similiarity / app.py
KiranRand's picture
Create app.py
8f3289d verified
raw
history blame contribute delete
889 Bytes
import gradio as gr
import numpy as np
import json
from sentence_transformers import SentenceTransformer, util
# Load precomputed QA pairs and embeddings
with open("qa.json", encoding="utf-8") as f:
QA_PAIRS = json.load(f)
QA_EMBEDDINGS = np.load("qa.npy")
hf_model = SentenceTransformer('all-MiniLM-L6-v2')
def find_similar(question):
user_embedding = hf_model.encode(question, convert_to_tensor=True)
similarities = util.cos_sim(user_embedding, QA_EMBEDDINGS)[0]
best_score = float(similarities.max())
best_index = int(similarities.argmax())
if best_score >= 0.6:
return QA_PAIRS[best_index]["answer"]
else:
return "Sorry, I could not find a relevant answer."
iface = gr.Interface(
fn=find_similar,
inputs=gr.Textbox(label="Your Question"),
outputs=gr.Textbox(label="Answer"),
title="Similarity Service"
)
iface.launch()