Spaces:
Runtime error
Runtime error
First_update
Browse files
app.py
CHANGED
@@ -1,64 +1,91 @@
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
"""
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
for val in history:
|
21 |
-
if val[0]:
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
response = ""
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
|
39 |
-
|
40 |
-
|
41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
-
""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
-
demo = gr.ChatInterface(
|
47 |
-
respond,
|
48 |
-
additional_inputs=[
|
49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
-
)
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import faiss
|
3 |
+
import numpy as np
|
4 |
+
import requests
|
5 |
+
import torch
|
6 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
7 |
+
from sentence_transformers import SentenceTransformer
|
8 |
|
9 |
+
class CustomRetriever:
|
10 |
+
def __init__(self, faiss_index_path: str):
|
11 |
+
"""Initializes the retriever by loading the FAISS index and setting up the embedding model."""
|
12 |
+
self.index = faiss.read_index(faiss_index_path)
|
13 |
+
self.embedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
14 |
+
|
15 |
+
def retrieve(self, query: str, top_k: int = 5):
|
16 |
+
"""Retrieve top-k relevant documents based on the query."""
|
17 |
+
query_embedding = self.embedder.encode([query])
|
18 |
+
distances, indices = self.index.search(np.array(query_embedding).astype('float32'), top_k)
|
19 |
+
return [(index, distance) for index, distance in zip(indices[0], distances[0])]
|
20 |
|
21 |
|
22 |
+
class CustomGenerator:
|
23 |
+
def __init__(self):
|
24 |
+
"""Initializes the generator by loading the HuggingFace model."""
|
25 |
+
self.tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.2")
|
26 |
+
self.model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.2")
|
27 |
+
|
28 |
+
def generate(self, user_input: str, retrieved_docs: list, max_length: int = 256):
|
29 |
+
"""Generate a response using the retrieved documents and the user input."""
|
30 |
+
context = "\n".join([f"Doc {i+1}: {doc}" for i, (doc, _) in enumerate(retrieved_docs)])
|
31 |
+
prompt = f"Context:\n{context}\n\nUser: {user_input}\nBot:"
|
32 |
+
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True)
|
33 |
+
with torch.no_grad():
|
34 |
+
outputs = self.model.generate(inputs.input_ids, max_length=max_length, pad_token_id=self.tokenizer.eos_token_id)
|
35 |
+
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
36 |
+
return response.split("Bot:")[-1].strip()
|
37 |
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
+
def rag_chatbot(user_input):
|
40 |
+
"""The main RAG chatbot function to retrieve documents and generate a response."""
|
41 |
+
top_k = 5 # Number of documents to retrieve
|
42 |
+
retrieved_doc_ids = retriever.retrieve(user_input, top_k)
|
43 |
+
retrieved_docs = [(f"Dummy content for doc {doc_id}", distance) for doc_id, distance in retrieved_doc_ids]
|
44 |
+
response = generator.generate(user_input, retrieved_docs)
|
45 |
+
return response
|
46 |
|
|
|
47 |
|
48 |
+
FAISS_INDEX_PATH = "path/to/your/faiss_index"
|
49 |
+
retriever = CustomRetriever(faiss_index_path=FAISS_INDEX_PATH)
|
50 |
+
generator = CustomGenerator()
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
+
# Gradio UI
|
53 |
+
app = gr.Blocks()
|
54 |
|
55 |
+
with app:
|
56 |
+
gr.Markdown(
|
57 |
+
"""
|
58 |
+
# Banking Regulations Compliance ChatBOT
|
59 |
+
Ask questions and get responses generated by a state-of-the-art AI model!
|
60 |
+
"""
|
61 |
+
)
|
62 |
|
63 |
+
chatbot = gr.Chatbot(label="Chat with the Bot")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
+
question_box = gr.Textbox(
|
66 |
+
label="Your Message",
|
67 |
+
placeholder="Type your message here...",
|
68 |
+
lines=1,
|
69 |
+
)
|
70 |
+
submit_button = gr.Button("Send")
|
71 |
|
72 |
+
gr.Examples(
|
73 |
+
examples=[
|
74 |
+
"What is Compliance?",
|
75 |
+
"Can you summarize the RBI Guidelines?",
|
76 |
+
"Can you summarize the RBI Guidelines related to gold loans?",
|
77 |
+
],
|
78 |
+
inputs=question_box,
|
79 |
+
)
|
80 |
+
|
81 |
+
submit_button.click(ask_model, inputs=[chatbot, question_box], outputs=chatbot)
|
82 |
+
|
83 |
+
footer_md = """
|
84 |
+
---
|
85 |
+
© 2024 by [Shashi Kiran, Karthik K, Venkara V V, Navin Kumar N, Jyoti Bavne]. All rights reserved.
|
86 |
+
This app was developed by **6505 Project Team** as part of Final Project.
|
87 |
+
For inquiries, please contact: [schandrappa@student.fairfield.edu](mailto:schandrappa@student.fairfield.edu)
|
88 |
+
"""
|
89 |
+
gr.Markdown(footer_md)
|
90 |
+
|
91 |
+
app.launch()
|