Spaces:
Runtime error
Runtime error
Update to app.py to rag system
Browse files
app.py
CHANGED
@@ -1,64 +1,81 @@
|
|
1 |
import gradio as gr
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
yield response
|
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 |
if __name__ == "__main__":
|
64 |
-
|
|
|
1 |
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
from datasets import load_dataset
|
6 |
+
import torch
|
7 |
+
|
8 |
+
# Initialize models
|
9 |
+
retriever = SentenceTransformer("all-MiniLM-L6-v2")
|
10 |
+
generator = AutoModelForCausalLM.from_pretrained("distilgpt2")
|
11 |
+
tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
|
12 |
+
|
13 |
+
|
14 |
+
# Simple vector store
|
15 |
+
class VectorStore:
|
16 |
+
def __init__(self):
|
17 |
+
self.documents = []
|
18 |
+
self.embeddings = []
|
19 |
+
|
20 |
+
def add_document(self, document):
|
21 |
+
self.documents.append(document)
|
22 |
+
embedding = retriever.encode(document)
|
23 |
+
self.embeddings.append(embedding)
|
24 |
+
|
25 |
+
def search(self, query, k=3):
|
26 |
+
query_embedding = retriever.encode(query)
|
27 |
+
similarities = np.dot(self.embeddings, query_embedding) / (
|
28 |
+
np.linalg.norm(self.embeddings, axis=1) * np.linalg.norm(query_embedding)
|
29 |
+
)
|
30 |
+
top_k_indices = np.argsort(similarities)[-k:][::-1]
|
31 |
+
return [self.documents[i] for i in top_k_indices]
|
32 |
+
|
33 |
+
|
34 |
+
# Initialize vector store
|
35 |
+
vector_store = VectorStore()
|
36 |
+
|
37 |
+
# Load sample dataset (e.g., Wikipedia snippets)
|
38 |
+
dataset = load_dataset(
|
39 |
+
"wikipedia", "20220301.simple", split="train[:1000]", trust_remote_code=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
)
|
41 |
+
for doc in dataset["text"]:
|
42 |
+
vector_store.add_document(doc)
|
43 |
+
|
44 |
|
45 |
+
# RAG function
|
46 |
+
def rag_query(query, max_length=100):
|
47 |
+
# Retrieve relevant documents
|
48 |
+
retrieved_docs = vector_store.search(query)
|
49 |
+
context = " ".join(retrieved_docs)
|
50 |
+
|
51 |
+
# Generate response
|
52 |
+
input_text = f"Context: {context}\n\nQuestion: {query}\nAnswer:"
|
53 |
+
inputs = tokenizer(input_text, return_tensors="pt", truncation=True, max_length=512)
|
54 |
+
|
55 |
+
with torch.no_grad():
|
56 |
+
outputs = generator.generate(
|
57 |
+
inputs.input_ids,
|
58 |
+
max_length=max_length + len(inputs.input_ids[0]),
|
59 |
+
num_return_sequences=1,
|
60 |
+
pad_token_id=tokenizer.eos_token_id,
|
61 |
+
)
|
62 |
+
|
63 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
64 |
+
return response.split("Answer:")[-1].strip()
|
65 |
+
|
66 |
+
|
67 |
+
# Gradio interface
|
68 |
+
def gradio_interface(query):
|
69 |
+
return rag_query(query)
|
70 |
+
|
71 |
+
|
72 |
+
iface = gr.Interface(
|
73 |
+
fn=gradio_interface,
|
74 |
+
inputs=gr.Textbox(label="Enter your question"),
|
75 |
+
outputs=gr.Textbox(label="Answer"),
|
76 |
+
title="RAG System with Hugging Face and Gradio",
|
77 |
+
description="Ask questions based on a Wikipedia-based knowledge base.",
|
78 |
+
)
|
79 |
|
80 |
if __name__ == "__main__":
|
81 |
+
iface.launch()
|