Download app.py from Aderaw/My_Bot: direct link, hf CLI and curl.
- Browser
- Download file 1.91 kB
-
https://huggingface.co/spaces/Aderaw/My_Bot/resolve/main/app.py
- Command line
-
hf download hf://spaces/Aderaw/My_Bot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Aderaw/My_Bot/resolve/main/app.py
1.91 kB
| import gradio as gr | |
| import numpy as np | |
| import faiss | |
| from sentence_transformers import SentenceTransformer | |
| from transformers import RagTokenizer, RagSequenceForGeneration | |
| # 1. Load Models | |
| tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq") | |
| model = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq") | |
| embedder = SentenceTransformer('all-MiniLM-L6-v2') | |
| # 2. Custom Knowledge Base (From CV) | |
| custom_knowledge = [ | |
| "Aderaw Molla is an ERP and Backend Developer specializing in Frappe, Django, and Node.js.", | |
| "He currently works at ERP Solutions Ethiopia and Devssinia Software Company.", | |
| "His skills include Python, JavaScript, Docker, AWS, and ERP system customization.", | |
| "Education: B.Sc in Software Engineering from Bahirdar University (GPA 3.9/4.0).", | |
| "Contact: mollaaderaw@gmail.com | Phone: +251-921-05-06-99 | GitHub: github.com/aderawmolla" | |
| ] | |
| # 3. Create Search Index | |
| knowledge_embeddings = embedder.encode(custom_knowledge) | |
| index = faiss.IndexFlatL2(knowledge_embeddings.shape[1]) | |
| index.add(knowledge_embeddings) | |
| def answer_question(question): | |
| # First check custom knowledge | |
| query_embed = embedder.encode([question]) | |
| distances, indices = index.search(query_embed, k=1) | |
| # Calculate cosine similarity (0 to 1) | |
| similarity = 1 - distances[0][0] / 2 # Convert L2 distance to approximate cosine | |
| if similarity > 0.6: # Threshold for custom answers | |
| return custom_knowledge[indices[0][0]] | |
| # Fallback to general knowledge | |
| inputs = tokenizer(question, return_tensors="pt") | |
| outputs = model.generate(input_ids=inputs["input_ids"]) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| # 4. Gradio Interface | |
| iface = gr.Interface( | |
| fn=answer_question, | |
| inputs="text", | |
| outputs="text", | |
| examples=["Where does Aderaw work?"], | |
| title="Aderaw Molla - Professional Q&A" | |
| ) | |
| iface.launch() | |