File size: 1,911 Bytes
14849e4 e5ac714 8178590 14849e4 8178590 7bbfbfb 8178590 7bbfbfb 8178590 e5ac714 8178590 e5ac714 14849e4 8178590 e5ac714 14849e4 e5ac714 7bbfbfb e5ac714 8178590 7bbfbfb e5ac714 8178590 e5ac714 8178590 e5ac714 14849e4 8178590 e5ac714 8178590 7bbfbfb 14849e4 8178590 | 1 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 41 42 43 44 45 46 47 48 49 50 | 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()
|