File size: 889 Bytes
8f3289d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()