VectorV17 commited on
Commit
114fe80
·
verified ·
1 Parent(s): 86973d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -76
app.py CHANGED
@@ -1,63 +1,101 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  from datetime import datetime
 
4
 
5
- # Initialize the Hugging Face Serverless client
6
- client = InferenceClient("Qwen/Qwen2.5-7B-Instruct")
7
-
8
- # AI FAQ Agent Knowledge Base Context
9
- FAQ_CONTEXT = """
10
- An AI FAQ Agent can be adapted for almost any website where users have questions, need guidance, or require support. If people visit your site and need to find information, an FAQ agent can help. Here is a breakdown of the most common types of websites that benefit from an FAQ Agent, categorized by industry:
11
-
12
- 1. E-Commerce & Retail
13
- This is the most popular use case. Customers frequently have the same questions before and after buying.
14
- - What it answers: Shipping times, return policies, order tracking, product sizing, and payment methods.
15
- - Examples: Online clothing stores, gadget shops, dropshipping sites.
16
 
17
- 2. Service-Based & Agency Websites
18
- If your business provides a service, prospective clients usually need to understand your process, pricing, and capabilities before booking.
19
- - What it answers: Project timelines, custom quotes, what’s included in a package, and software requirements.
20
- - Examples: Marketing agencies, consulting firms, web design agencies, photography studios.
 
 
21
 
22
- 3. Software as a Service (SaaS) & Tech Products
23
- Tech users need quick answers to avoid churn. An FAQ agent can act as a 24/7 first-line technical support rep.
24
- - What it answers: Subscription tiers, API documentation, integrations, troubleshooting common errors, and feature requests.
25
- - Examples: Project management tools, CRM software, mobile app landing pages.
26
 
27
- 4. Educational & E-Learning Platforms
28
- Students, parents, and educators frequently need help navigating course structures, enrollment, and technical requirements.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- 5. Healthcare & Medical Websites
31
- Filters basic inquiries before booking an office appointment.
32
- - What it answers: Insurance accepted, clinic hours, prescription refill policies, and parking information.
33
- - Note: Always includes a disclaimer that it does not provide medical advice.
34
- - Examples: Dental clinics, therapy practices, local medical centers.
 
 
 
 
 
 
 
 
 
 
35
 
36
- 6. Hospitality, Travel & Events
37
- Travelers and event attendees are always looking for specific logistical details.
38
- - What it answers: Check-in/check-out times, hotel amenities, event agendas, venue rules, and ticket refund policies.
39
- - Examples: Hotels, Airbnb listings, music festivals, business conferences.
40
- """
 
 
 
 
 
 
 
 
 
 
41
 
42
  def get_thematic_datetime():
43
- """
44
- Generates precise, real-time updated date and running seconds strings.
45
- Returns complete styled HTML snippet to replace the header content dynamically.
46
- """
47
  now = datetime.now()
48
  day_int = now.day
49
-
50
- # Handle English ordinal suffixes smoothly
51
  if 11 <= day_int <= 13:
52
  suffix = "th"
53
  else:
54
- suffix = {1: "st", 2: "nd", 3: "rd"}.get(day_int % 10, "th")
55
 
56
  formatted_date = f"{now.strftime('%d')}{suffix} {now.strftime('%B %Y')} | Time: {now.strftime('%I:%M:%S %p').lower()}"
57
  return f"<div style='text-align: right; font-weight: 600; font-size: 14px; font-family: monospace; letter-spacing: 0.5px;'>{formatted_date}</div>"
58
 
59
  def extract_text(content):
60
- """Safely extracts plain string text from any Gradio message structure."""
61
  if isinstance(content, str):
62
  return content
63
  if isinstance(content, list):
@@ -71,10 +109,6 @@ def extract_text(content):
71
  if isinstance(content, dict):
72
  if "text" in content: return content["text"]
73
  if "content" in content: return content["content"]
74
- if hasattr(content, "text") and isinstance(content.text, str):
75
- return content.text
76
- if hasattr(content, "content") and isinstance(content.content, str):
77
- return content.content
78
  return str(content)
79
 
80
  def user_side(user_message, history):
@@ -93,33 +127,50 @@ def user_side(user_message, history):
93
  return "", clean_history
94
 
95
  def bot_side(history, system_message, max_tokens, temperature, top_p):
96
- """Streams responses out to the layout without throwing Object mutation errors."""
97
  if not history:
98
  yield history
99
  return
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  full_system_prompt = (
102
  f"{system_message}\n\n"
103
- f"Use the following FAQ reference context to answer questions accurately:\n"
104
- f"{FAQ_CONTEXT}"
105
  )
106
 
107
  messages = [{"role": "system", "content": full_system_prompt}]
108
  clean_history = []
109
 
110
- for msg in history:
111
  if isinstance(msg, dict):
112
- role = msg.get("role")
113
- content = extract_text(msg.get("content"))
114
  else:
115
- role = getattr(msg, "role", None)
116
- content = extract_text(getattr(msg, "content", ""))
117
-
118
  if role and content:
119
  messages.append({"role": role, "content": content})
120
  clean_history.append({"role": role, "content": content})
121
 
122
- clean_history.append({"role": "assistant", "content": ""})
 
 
 
 
 
123
 
124
  try:
125
  for message_chunk in client.chat_completion(
@@ -134,7 +185,7 @@ def bot_side(history, system_message, max_tokens, temperature, top_p):
134
  clean_history[-1]["content"] += token
135
  yield clean_history
136
  except Exception as e:
137
- clean_history[-1]["content"] = f"An error occurred while connecting to the model API: {str(e)}"
138
  yield clean_history
139
 
140
  # Custom UI Theme Stylesheet
@@ -150,12 +201,8 @@ body.dark #header-container {
150
  background-color: #1f2937 !important;
151
  border-color: #374151 !important;
152
  }
153
- #header-container * {
154
- color: #1a1a1a !important;
155
- }
156
- body.dark #header-container * {
157
- color: #f9fafb !important;
158
- }
159
  #right-meta-card {
160
  background-color: #005f53 !important;
161
  border-radius: 12px !important;
@@ -163,9 +210,7 @@ body.dark #header-container * {
163
  color: white !important;
164
  text-align: center;
165
  }
166
- #right-meta-card * {
167
- color: white !important;
168
- }
169
  #send-btn {
170
  background-color: #ff6600 !important;
171
  color: white !important;
@@ -197,7 +242,7 @@ with gr.Blocks() as demo:
197
  gr.Markdown(
198
  """
199
  ### About Us
200
- At FAQ Agentic Hub, we are passionate about the power of structured, context-driven automation and its ability to transform customer workflows. We are leading a knowledge processing framework dedicated to helping businesses unlock the full potential of specialized, conversational AI support layers.
201
  """
202
  )
203
  with gr.Column(scale=1):
@@ -209,8 +254,8 @@ with gr.Blocks() as demo:
209
  with gr.Row():
210
  with gr.Column(scale=2):
211
  chatbot = gr.Chatbot(
212
- label="Lane AI Support Stream",
213
- value=[{"role": "assistant", "content": "Hello! I'm Lane, your FAQ Support Agent. How can I assist you with your platform infrastructure today?"}]
214
  )
215
 
216
  with gr.Row():
@@ -222,8 +267,8 @@ with gr.Blocks() as demo:
222
  send_btn = gr.Button("Send", variant="primary", scale=1, elem_id="send-btn")
223
 
224
  with gr.Row():
225
- suggest_btn1 = gr.Button("How do I update my profile?")
226
- suggest_btn2 = gr.Button("What is required to get certificate after course exam?")
227
 
228
  with gr.Column(scale=1):
229
  with gr.Group(elem_id="right-meta-card"):
@@ -234,12 +279,12 @@ with gr.Blocks() as demo:
234
  <img src='https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/robot/default/48px.svg' style='width: 70px; filter: invert(27%) sepia(91%) saturate(2853%) hue-rotate(152deg) brightness(93%) contrast(101%);'>
235
  </div>
236
  </div>
237
- <h2 style='margin: 5px 0 2px 0; font-size: 24px;'>Lane <span style='font-size: 11px; background: rgba(255,255,255,0.25); padding: 2px 7px; border-radius: 4px; vertical-align: middle;'>AI</span></h2>
238
- <p style='margin: 0; opacity: 0.85; font-size: 14px;'>Your Agentic FAQ Assistant</p>
239
 
240
  <div class='meta-status-text'>
241
- <p>🟢 Secure Session Activated</p>
242
- <p><strong>Operational Node:</strong> FAQ-Chroma-01</p>
243
  <p><strong>Processing Hardware:</strong> Base CPU Node</p>
244
  </div>
245
  """
@@ -247,11 +292,11 @@ with gr.Blocks() as demo:
247
 
248
  with gr.Accordion("Advanced Agent Parameter Configurations", open=False):
249
  system_msg = gr.Textbox(
250
- value="You are an expert AI FAQ Agent assistant. Help users understand how websites use FAQ agents across various industries.",
251
  label="System Prompt Context Injection"
252
  )
253
  max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
254
- temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
255
  top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (Nucleus Sampling)")
256
 
257
  # 3. Components Event Wiring
@@ -279,9 +324,9 @@ with gr.Blocks() as demo:
279
  bot_side, inputs=[chatbot, system_msg, max_tokens, temperature, top_p], outputs=[chatbot]
280
  )
281
 
282
- # FIXED: Pass interval as a positional argument (value=1.0)
283
  clock_timer = gr.Timer(1.0)
284
  clock_timer.tick(fn=get_thematic_datetime, outputs=time_display, queue=False)
285
 
286
  if __name__ == "__main__":
287
- demo.launch(css=custom_css, theme=gr.themes.Default())
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  from datetime import datetime
4
+ import re
5
 
6
+ # Import localized NLP and Math Matching frameworks
7
+ import nltk
8
+ from sklearn.feature_extraction.text import TfidfVectorizer
9
+ from sklearn.metrics.pairwise import cosine_similarity
 
 
 
 
 
 
 
10
 
11
+ # Initialize NLTK tokenization assets safely on basic CPU bootup
12
+ try:
13
+ nltk.download('punkt', quiet=True)
14
+ nltk.download('punkt_tab', quiet=True)
15
+ except Exception:
16
+ pass # Fallback to standard regex splitting if environment is strictly offline
17
 
18
+ # Initialize the Hugging Face Serverless client
19
+ client = InferenceClient("Qwen/Qwen2.5-7B-Instruct")
 
 
20
 
21
+ # 1. Collect FAQs related to topics/products into a structured corpus
22
+ FAQ_DATA = [
23
+ {
24
+ "q": "What are your shipping times and policies?",
25
+ "a": "Shipping times vary by location. Typically, local retail deliveries take 2-3 business days, while international dropshipping options take 7-14 business days. All tracking codes are sent via email."
26
+ },
27
+ {
28
+ "q": "What is the return policy for products?",
29
+ "a": "We offer a flexible 30-day return policy. Items must be unworn, in their original packaging layout, and accompanied by the checkout receipt."
30
+ },
31
+ {
32
+ "q": "What are your service project timelines and quotes?",
33
+ "a": "Standard design and consulting project timelines range between 2 to 6 weeks. You can request a personalized pricing quote directly via our booking panel."
34
+ },
35
+ {
36
+ "q": "What are the differences between your software subscription tiers?",
37
+ "a": "We offer Free, Pro, and Enterprise tiers. Pro unlocks comprehensive API documentation access, and Enterprise unlocks custom third-party platform integrations."
38
+ },
39
+ {
40
+ "q": "How do I unlock my course completion certificate?",
41
+ "a": "Completion certificates unlock automatically on your student profile dashboard as soon as all video modules and the final evaluation quiz are marked 100% complete."
42
+ },
43
+ {
44
+ "q": "What insurance providers do you accept at the clinic?",
45
+ "a": "We accept major national medical insurance providers. Please contact our front office coordinator to verify your specific policy layout before scheduling appointments."
46
+ },
47
+ {
48
+ "q": "What are your standard check-in and check-out times?",
49
+ "a": "Standard hospitality check-in opens at 3:00 PM, and checkout must be finalized by 11:00 AM. Early check-in requests can be accommodated based on live room availability."
50
+ }
51
+ ]
52
 
53
+ def perform_nlp_cosine_matching(user_query):
54
+ """
55
+ Fulfills NLP Requirements: Preprocesses text with tokenization
56
+ and applies Cosine Similarity matching over TF-IDF vectors.
57
+ """
58
+ # Step 2: Preprocess text using NLP approaches (Lowercase + NLTK Tokenization)
59
+ try:
60
+ tokens = nltk.word_tokenize(user_query.lower())
61
+ cleaned_query = " ".join([w for w in tokens if re.match(r'^\w+$', w)])
62
+ except Exception:
63
+ # Secure fallback text parsing if NLTK files fail initialization on basic CPU
64
+ cleaned_query = " ".join(re.findall(r'\w+', user_query.lower()))
65
+
66
+ if not cleaned_query.strip():
67
+ return None, 0.0
68
 
69
+ # Extract our collected question list text array
70
+ questions_corpus = [faq["q"] for faq in FAQ_DATA]
71
+
72
+ # Step 3: Compute mathematical similarity matrices
73
+ vectorizer = TfidfVectorizer(stop_words='english')
74
+ tfidf_matrix = vectorizer.fit_transform(questions_corpus)
75
+
76
+ query_vector = vectorizer.transform([cleaned_query])
77
+ similarity_scores = cosine_similarity(query_vector, tfidf_matrix)[0]
78
+
79
+ # Find highest matching index score
80
+ best_match_idx = similarity_scores.argmax()
81
+ highest_score = similarity_scores[best_match_idx]
82
+
83
+ return FAQ_DATA[best_match_idx], float(highest_score)
84
 
85
  def get_thematic_datetime():
86
+ """Generates precise, real-time updated date and running seconds strings."""
 
 
 
87
  now = datetime.now()
88
  day_int = now.day
 
 
89
  if 11 <= day_int <= 13:
90
  suffix = "th"
91
  else:
92
+ suffix = {1: "st", 2: "nd", 3: "rd"}._get(day_int % 10, "th")
93
 
94
  formatted_date = f"{now.strftime('%d')}{suffix} {now.strftime('%B %Y')} | Time: {now.strftime('%I:%M:%S %p').lower()}"
95
  return f"<div style='text-align: right; font-weight: 600; font-size: 14px; font-family: monospace; letter-spacing: 0.5px;'>{formatted_date}</div>"
96
 
97
  def extract_text(content):
98
+ """Safely extracts plain string text from any Gradio 6 message structure."""
99
  if isinstance(content, str):
100
  return content
101
  if isinstance(content, list):
 
109
  if isinstance(content, dict):
110
  if "text" in content: return content["text"]
111
  if "content" in content: return content["content"]
 
 
 
 
112
  return str(content)
113
 
114
  def user_side(user_message, history):
 
127
  return "", clean_history
128
 
129
  def bot_side(history, system_message, max_tokens, temperature, top_p):
130
+ """Streams responses out, embedding the NLP similarity match directly into context."""
131
  if not history:
132
  yield history
133
  return
134
 
135
+ # Extract the fresh user input message text
136
+ user_query = extract_text(history[-1]["content"])
137
+
138
+ # Run our NLP Cosine Matcher over our collected database
139
+ matched_faq, match_score = perform_nlp_cosine_matching(user_query)
140
+
141
+ # Format a visible dynamic tag noting the similarity result inside the UI panel
142
+ nlp_metadata_prefix = ""
143
+ faq_context_injection = ""
144
+
145
+ if matched_faq and match_score > 0.15:
146
+ nlp_metadata_prefix = f"🔍 *NLP Match Found (Cosine Similarity Confidence: {match_score*100:.1f}%):*\n> **Q: {matched_faq['q']}**\n> A: {matched_faq['a']}\n\n---\n"
147
+ faq_context_injection = f"Use this highly relevant matched FAQ data to build your answer: Question: {matched_faq['q']} | Answer: {matched_faq['a']}"
148
+ else:
149
+ nlp_metadata_prefix = "🔍 *NLP Search Notice: No direct close FAQ match found. Defaulting to general system inference knowledge.*\n\n---\n"
150
+
151
  full_system_prompt = (
152
  f"{system_message}\n\n"
153
+ f"{faq_context_injection}"
 
154
  )
155
 
156
  messages = [{"role": "system", "content": full_system_prompt}]
157
  clean_history = []
158
 
159
+ for msg in history[:-1]:
160
  if isinstance(msg, dict):
161
+ role, content = msg.get("role"), extract_text(msg.get("content"))
 
162
  else:
163
+ role, content = getattr(msg, "role", None), extract_text(getattr(msg, "content", ""))
 
 
164
  if role and content:
165
  messages.append({"role": role, "content": content})
166
  clean_history.append({"role": role, "content": content})
167
 
168
+ # Append user question to system message array
169
+ messages.append({"role": "user", "content": user_query})
170
+ clean_history.append({"role": "user", "content": user_query})
171
+
172
+ # Initialize assistant output streaming sequence
173
+ clean_history.append({"role": "assistant", "content": nlp_metadata_prefix})
174
 
175
  try:
176
  for message_chunk in client.chat_completion(
 
185
  clean_history[-1]["content"] += token
186
  yield clean_history
187
  except Exception as e:
188
+ clean_history[-1]["content"] += f"\nAn error occurred while connecting to the model API: {str(e)}"
189
  yield clean_history
190
 
191
  # Custom UI Theme Stylesheet
 
201
  background-color: #1f2937 !important;
202
  border-color: #374151 !important;
203
  }
204
+ #header-container * { color: #1a1a1a !important; }
205
+ body.dark #header-container * { color: #f9fafb !important; }
 
 
 
 
206
  #right-meta-card {
207
  background-color: #005f53 !important;
208
  border-radius: 12px !important;
 
210
  color: white !important;
211
  text-align: center;
212
  }
213
+ #right-meta-card * { color: white !important; }
 
 
214
  #send-btn {
215
  background-color: #ff6600 !important;
216
  color: white !important;
 
242
  gr.Markdown(
243
  """
244
  ### About Us
245
+ At FAQ Agentic Hub, we are passionate about the power of structured, NLP-driven automation and its ability to transform customer workflows. This engine utilizes real-time Tokenization and Cosine Similarity computations.
246
  """
247
  )
248
  with gr.Column(scale=1):
 
254
  with gr.Row():
255
  with gr.Column(scale=2):
256
  chatbot = gr.Chatbot(
257
+ label="Lane NLP AI Support Stream",
258
+ value=[{"role": "assistant", "content": "Hello! I'm Lane, your upgraded NLP FAQ Support Agent. Ask me questions about shipping, returns, or certificates, and watch the cosine-similarity system extract matches in real-time."}]
259
  )
260
 
261
  with gr.Row():
 
267
  send_btn = gr.Button("Send", variant="primary", scale=1, elem_id="send-btn")
268
 
269
  with gr.Row():
270
+ suggest_btn1 = gr.Button("What are your shipping times and policies?")
271
+ suggest_btn2 = gr.Button("How do I unlock my course completion certificate?")
272
 
273
  with gr.Column(scale=1):
274
  with gr.Group(elem_id="right-meta-card"):
 
279
  <img src='https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/robot/default/48px.svg' style='width: 70px; filter: invert(27%) sepia(91%) saturate(2853%) hue-rotate(152deg) brightness(93%) contrast(101%);'>
280
  </div>
281
  </div>
282
+ <h2 style='margin: 5px 0 2px 0; font-size: 24px;'>Lane <span style='font-size: 11px; background: rgba(255,255,255,0.25); padding: 2px 7px; border-radius: 4px; vertical-align: middle;'>NLP AI</span></h2>
283
+ <p style='margin: 0; opacity: 0.85; font-size: 14px;'>Similarity-Augmented Assistant</p>
284
 
285
  <div class='meta-status-text'>
286
+ <p>🟢 NLP Match Engine Online</p>
287
+ <p><strong>Vectorization Model:</strong> Text TF-IDF Vectorizer</p>
288
  <p><strong>Processing Hardware:</strong> Base CPU Node</p>
289
  </div>
290
  """
 
292
 
293
  with gr.Accordion("Advanced Agent Parameter Configurations", open=False):
294
  system_msg = gr.Textbox(
295
+ value="You are an expert AI FAQ Agent assistant. Answer user queries concisely, expanding intelligently upon matched context summaries when available.",
296
  label="System Prompt Context Injection"
297
  )
298
  max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
299
+ temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.4, step=0.1, label="Temperature")
300
  top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (Nucleus Sampling)")
301
 
302
  # 3. Components Event Wiring
 
324
  bot_side, inputs=[chatbot, system_msg, max_tokens, temperature, top_p], outputs=[chatbot]
325
  )
326
 
327
+ # Initialize continuous running digital time clock loop
328
  clock_timer = gr.Timer(1.0)
329
  clock_timer.tick(fn=get_thematic_datetime, outputs=time_display, queue=False)
330
 
331
  if __name__ == "__main__":
332
+ demo.launch(theme=gr.themes.Default())