Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
-
|
26 |
-
messages.append({"role": "user", "content": message})
|
27 |
-
|
28 |
-
response = ""
|
29 |
-
|
30 |
-
for message in client.chat_completion(
|
31 |
-
messages,
|
32 |
-
max_tokens=max_tokens,
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
-
|
39 |
-
response += token
|
40 |
-
yield response
|
41 |
-
|
42 |
-
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
demo = gr.ChatInterface(
|
47 |
respond,
|
48 |
-
additional_inputs=[
|
49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
)
|
61 |
|
62 |
-
|
63 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
demo.launch()
|
|
|
1 |
+
# app.py
|
2 |
+
|
3 |
+
import pandas as pd
|
4 |
+
from fastapi import FastAPI
|
5 |
+
from pydantic import BaseModel
|
6 |
+
from sentence_transformers import SentenceTransformer
|
7 |
+
import faiss
|
8 |
+
from datasets import load_dataset
|
9 |
+
|
10 |
+
# Load the dataset
|
11 |
+
support_data = load_dataset("rjac/e-commerce-customer-support-qa")
|
12 |
+
faq_data = pd.read_csv("Ecommerce_FAQs.csv")
|
13 |
+
|
14 |
+
# Data preparation
|
15 |
+
faq_data.rename(columns={'prompt': 'Question', 'response': 'Answer'}, inplace=True)
|
16 |
+
faq_data = faq_data[['Question', 'Answer']]
|
17 |
+
support_data_df = pd.DataFrame(support_data['train'])
|
18 |
+
|
19 |
+
def extract_conversation(data):
|
20 |
+
try:
|
21 |
+
parts = data.split("\n\n")
|
22 |
+
question = parts[1].split(": ", 1)[1] if len(parts) > 1 else ""
|
23 |
+
answer = parts[2].split(": ", 1)[1] if len(parts) > 2 else ""
|
24 |
+
return pd.Series({"Question": question, "Answer": answer})
|
25 |
+
except IndexError:
|
26 |
+
return pd.Series({"Question": "", "Answer": ""})
|
27 |
+
|
28 |
+
support_data_df[['Question', 'Answer']] = support_data_df['conversation'].apply(extract_conversation)
|
29 |
+
combined_data = pd.concat([faq_data, support_data_df[['Question', 'Answer']]], ignore_index=True)
|
30 |
+
|
31 |
+
# Initialize SBERT Model
|
32 |
+
model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')
|
33 |
+
|
34 |
+
# Generate and Index Embeddings
|
35 |
+
questions = combined_data['Question'].tolist()
|
36 |
+
embeddings = model.encode(questions, convert_to_tensor=True)
|
37 |
+
index = faiss.IndexFlatL2(embeddings.shape[1])
|
38 |
+
index.add(embeddings.cpu().numpy())
|
39 |
+
|
40 |
+
# Define FastAPI app and model
|
41 |
+
app = FastAPI()
|
42 |
+
|
43 |
+
class Query(BaseModel):
|
44 |
+
question: str
|
45 |
+
|
46 |
+
@app.post("/ask")
|
47 |
+
def ask_bot(query: Query):
|
48 |
+
question_embedding = model.encode([query.question], convert_to_tensor=True)
|
49 |
+
question_embedding_np = question_embedding.cpu().numpy()
|
50 |
+
_, closest_index = index.search(question_embedding_np, k=1)
|
51 |
+
best_match_idx = closest_index[0][0]
|
52 |
+
answer = combined_data.iloc[best_match_idx]['Answer']
|
53 |
+
return {"answer": answer}
|
54 |
+
|
55 |
+
# Gradio Interface
|
56 |
+
|
57 |
import gradio as gr
|
58 |
+
import requests
|
59 |
+
|
60 |
+
# Define the URL of your FastAPI endpoint
|
61 |
+
API_URL = "http://localhost:8000/ask" # Update to your deployed FastAPI URL if needed
|
62 |
+
|
63 |
+
def respond(message, history: list[tuple[str, str]]):
|
64 |
+
payload = {"question": message}
|
65 |
+
|
66 |
+
try:
|
67 |
+
response = requests.post(API_URL, json=payload)
|
68 |
+
response.raise_for_status()
|
69 |
+
response_data = response.json()
|
70 |
+
answer = response_data.get("answer", "Sorry, I didn't get that.")
|
71 |
+
except requests.exceptions.RequestException as e:
|
72 |
+
answer = f"Request Error: {str(e)}"
|
73 |
+
|
74 |
+
# Update history
|
75 |
+
history.append((message, answer))
|
76 |
+
return answer, history
|
77 |
+
|
78 |
+
# Gradio Chat Interface
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
demo = gr.ChatInterface(
|
80 |
respond,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
)
|
82 |
|
|
|
83 |
if __name__ == "__main__":
|
84 |
+
import threading
|
85 |
+
import uvicorn
|
86 |
+
|
87 |
+
# Run FastAPI in a separate thread
|
88 |
+
threading.Thread(target=uvicorn.run, args=(app,), kwargs={"host": "0.0.0.0", "port": 8000}).start()
|
89 |
+
|
90 |
+
# Launch Gradio interface
|
91 |
demo.launch()
|