Spaces:
Runtime error
Runtime error
Upload app.py with huggingface_hub
Browse files
app.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import faiss
|
| 4 |
+
import pickle
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 6 |
+
from sentence_transformers import SentenceTransformer
|
| 7 |
+
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained("tiny-gpt2-finetuned-ajem")
|
| 9 |
+
model = AutoModelForCausalLM.from_pretrained("tiny-gpt2-finetuned-ajem")
|
| 10 |
+
embedder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 11 |
+
|
| 12 |
+
index = faiss.read_index("rag_index.faiss")
|
| 13 |
+
with open("rag_texts.pkl", "rb") as f:
|
| 14 |
+
texts = pickle.load(f)
|
| 15 |
+
|
| 16 |
+
def get_context(query, top_k=3):
|
| 17 |
+
q_emb = embedder.encode([query])
|
| 18 |
+
D, I = index.search(q_emb, top_k)
|
| 19 |
+
return "\n".join([texts[i] for i in I[0]])
|
| 20 |
+
|
| 21 |
+
def chat(query):
|
| 22 |
+
context = get_context(query)
|
| 23 |
+
prompt = context + "\nUsuario: " + query + "\nAsistente:"
|
| 24 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 25 |
+
outputs = model.generate(**inputs, max_new_tokens=100, pad_token_id=tokenizer.eos_token_id)
|
| 26 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True).replace(prompt, "").strip()
|
| 27 |
+
return response
|
| 28 |
+
|
| 29 |
+
gr.ChatInterface(chat, title="Tiny Chat RAG").launch()
|