Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,83 +1,65 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import os
|
3 |
-
import json
|
4 |
import faiss
|
5 |
import numpy as np
|
6 |
import torch
|
7 |
from sentence_transformers import SentenceTransformer
|
8 |
-
from
|
|
|
|
|
9 |
|
10 |
# πΉ Hugging Face Credentials
|
11 |
HF_REPO = "Futuresony/future_ai_12_10_2024.gguf"
|
12 |
-
HF_TOKEN = os.getenv('HUGGINGFACEHUB_API_TOKEN')
|
13 |
|
14 |
-
# πΉ
|
15 |
FAISS_PATH = "asa_faiss.index"
|
|
|
16 |
|
17 |
-
# πΉ Load
|
18 |
-
|
19 |
-
|
20 |
-
# πΉ Load FAISS Index from Hugging Face
|
21 |
-
faiss_local_path = hf_hub_download(HF_REPO, "asa_faiss.index", token=HF_TOKEN)
|
22 |
faiss_index = faiss.read_index(faiss_local_path)
|
|
|
23 |
|
24 |
-
# πΉ
|
25 |
-
|
|
|
|
|
26 |
|
27 |
-
# πΉ
|
28 |
-
|
29 |
-
|
30 |
-
distances, indices = faiss_index.search(query_embedding, top_k)
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
if idx != -1: # Ensure valid index
|
35 |
-
retrieved_texts.append(f"Example {idx}: (Extracted FAISS Data)")
|
36 |
-
|
37 |
-
return "\n".join(retrieved_texts) if retrieved_texts else "**No relevant FAISS data found.**"
|
38 |
-
|
39 |
-
# πΉ Chatbot Response Function (Forcing FAISS Context)
|
40 |
-
def respond(message, history, system_message, max_tokens, temperature, top_p):
|
41 |
-
faiss_context = retrieve_faiss_knowledge(message)
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
You MUST use the provided FAISS data to generate your response.
|
46 |
-
If no FAISS data is found, return "I don't have enough information."
|
47 |
|
48 |
-
### Retrieved FAISS Data:
|
49 |
-
{faiss_context}
|
50 |
|
51 |
-
|
52 |
-
|
|
|
53 |
|
54 |
-
### Response:
|
55 |
-
"""
|
56 |
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
top_p=top_p,
|
62 |
-
)
|
63 |
|
64 |
-
|
65 |
-
cleaned_response = response.split("### Response:")[-1].strip()
|
66 |
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
-
|
70 |
|
71 |
-
# πΉ Gradio Chat Interface
|
72 |
-
demo = gr.ChatInterface(
|
73 |
-
respond,
|
74 |
-
additional_inputs=[
|
75 |
-
gr.Textbox(value="You are a knowledge assistant that must use FAISS context.", label="System message"),
|
76 |
-
gr.Slider(minimum=1, maximum=250, value=128, step=1, label="Max new tokens"),
|
77 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.9, step=0.1, label="Temperature"),
|
78 |
-
gr.Slider(minimum=0.1, maximum=1.0, value=0.99, step=0.01, label="Top-p (nucleus sampling)"),
|
79 |
-
],
|
80 |
-
)
|
81 |
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
|
|
|
1 |
import faiss
|
2 |
import numpy as np
|
3 |
import torch
|
4 |
from sentence_transformers import SentenceTransformer
|
5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
6 |
+
import gradio as gr
|
7 |
+
from huggingface_hub import hf_hub_download
|
8 |
|
9 |
# πΉ Hugging Face Credentials
|
10 |
HF_REPO = "Futuresony/future_ai_12_10_2024.gguf"
|
11 |
+
HF_TOKEN = os.getenv('HUGGINGFACEHUB_API_TOKEN')
|
12 |
|
13 |
+
# πΉ Paths
|
14 |
FAISS_PATH = "asa_faiss.index"
|
15 |
+
DATASET_PATH = "responses.txt"
|
16 |
|
17 |
+
# πΉ Load FAISS Index
|
18 |
+
faiss_local_path = hf_hub_download(HF_REPO, FAISS_PATH, token=HF_TOKEN)
|
|
|
|
|
|
|
19 |
faiss_index = faiss.read_index(faiss_local_path)
|
20 |
+
print("β
FAISS index loaded successfully!")
|
21 |
|
22 |
+
# πΉ Load Dataset Responses
|
23 |
+
with open(DATASET_PATH, "r", encoding="utf-8") as f:
|
24 |
+
dataset = f.readlines()
|
25 |
+
print("β
Responses dataset loaded!")
|
26 |
|
27 |
+
# πΉ Load Model & Tokenizer Correctly
|
28 |
+
tokenizer = AutoTokenizer.from_pretrained(HF_REPO, token=HF_TOKEN)
|
29 |
+
model = AutoModelForCausalLM.from_pretrained(HF_REPO, token=HF_TOKEN)
|
|
|
30 |
|
31 |
+
# πΉ Load Sentence Transformer (Ensures proper FAISS embedding match)
|
32 |
+
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
+
# πΉ Adjust FAISS Threshold
|
35 |
+
THRESHOLD = 100 # Adjust based on actual FAISS distances
|
|
|
|
|
36 |
|
|
|
|
|
37 |
|
38 |
+
def embed(text):
|
39 |
+
"""Convert text into FAISS-compatible vector using the same method as training."""
|
40 |
+
return embedder.encode([text], convert_to_tensor=True).cpu().numpy()
|
41 |
|
|
|
|
|
42 |
|
43 |
+
def chatbot_response(user_query):
|
44 |
+
"""Fetch response from FAISS or generate with model if needed."""
|
45 |
+
query_vector = embed(user_query) # Convert input to vector
|
46 |
+
D, I = faiss_index.search(query_vector, k=1) # Search FAISS index
|
|
|
|
|
47 |
|
48 |
+
print(f"Closest FAISS match index: {I[0][0]}, Distance: {D[0][0]}") # Debugging info
|
|
|
49 |
|
50 |
+
if D[0][0] < THRESHOLD: # If FAISS match is good
|
51 |
+
response = dataset[I[0][0]].strip() # Retrieve FAISS response
|
52 |
+
print("β
FAISS response used!")
|
53 |
+
else:
|
54 |
+
# π₯ Fallback: Generate response with model
|
55 |
+
print("β οΈ FAISS match too weak, using model instead.")
|
56 |
+
inputs = tokenizer(user_query, return_tensors="pt")
|
57 |
+
outputs = model.generate(**inputs, max_new_tokens=150)
|
58 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
59 |
|
60 |
+
return response
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
+
# πΉ Gradio UI
|
64 |
+
iface = gr.Interface(fn=chatbot_response, inputs="text", outputs="text", title="ASA Microfinance Chatbot")
|
65 |
+
iface.launch()
|