Spaces:
Sleeping

GTKT_FAQ / app.py
fortify's picture
Update app.py
0641272 verified
Raw History Blame Contribute Delete
2.7 kB
import gradio as gr
import torch
import json
from sentence_transformers import SentenceTransformer, util
from huggingface_hub import hf_hub_download
# --- CONFIGURATION ---
# Point this to your MERGED MODEL repository
hf_username = "fortify"
repo_name = "gtkt-faq-gemma-merged"
repo_id = f"{hf_username}/{repo_name}"
faq_data_file = "faq_data.json"
faq_embeddings_file = "faq_embeddings.pt"
# --- LOAD THE KNOWLEDGE BASE FROM THE HUB ---
print("Loading knowledge base from the Hub...")
try:
# Download the files from the repository
faq_data_path = hf_hub_download(repo_id=repo_id, filename=faq_data_file)
faq_embeddings_path = hf_hub_download(repo_id=repo_id, filename=faq_embeddings_file)
# Load the Q&A data
with open(faq_data_path, 'r') as f:
faq_data = json.load(f)
# Load the embeddings tensor
faq_embeddings = torch.load(faq_embeddings_path)
print("Knowledge base loaded successfully.")
except Exception as e:
print(f"Error loading knowledge base: {e}")
faq_data = [] # Set empty defaults on failure
faq_embeddings = torch.Tensor([])
# --- LOAD THE SENTENCE TRANSFORMER MODEL ---
# This must be the same model used to create the embeddings
model = SentenceTransformer("all-MiniLM-L6-v2")
print("Sentence transformer model loaded.")
# --- DEFINE THE CORE SEARCH FUNCTION ---
def find_best_answer(user_question):
if not user_question or faq_embeddings.nelement() == 0:
return "Sorry, my knowledge base isn't loaded correctly. Please contact the site administrator."
# 1. Encode the user's question to get its embedding
question_embedding = model.encode(user_question, convert_to_tensor=True)
# 2. Compute cosine similarity between the user's question and all FAQ questions
cosine_scores = util.cos_sim(question_embedding, faq_embeddings)[0]
# 3. Find the index of the highest score
best_match_idx = torch.argmax(cosine_scores).item()
# 4. (Optional) Add a threshold to avoid irrelevant answers
if cosine_scores[best_match_idx] < 0.6: # You can tune this threshold
return "I'm sorry, I don't have a specific answer for that. Please try rephrasing your question or contact our support team."
# 5. Return the best-matching answer
return faq_data[best_match_idx]["answer"]
# --- CREATE THE GRADIO INTERFACE ---
demo = gr.Interface(
fn=find_best_answer,
inputs=gr.Textbox(label="Your Question", lines=3),
outputs=gr.Textbox(label="Answer", interactive=False),
title="FAQ Search Bot",
description="Ask a question and I will find the most relevant answer from our knowledge base."
)
# Launch the app
print("Launching Gradio Interface...")
demo.launch()