Trinoid commited on
Commit
ff3de11
·
verified ·
1 Parent(s): fed3e72

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -434
app.py CHANGED
@@ -1,172 +1,11 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
- import time
4
- import html
5
- import re
6
- import traceback
7
- import datetime
8
- import threading
9
- from collections import defaultdict
10
 
11
  """
12
  For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
13
  """
14
  client = InferenceClient("PlantWisdom/Data_Management_Mistral")
15
 
16
- # Rate limiting settings
17
- MAX_REQUESTS_PER_DAY = 100 # Maximum number of requests per IP per day (set to 1 for testing)
18
- ip_request_counters = defaultdict(int) # Tracks request count per IP
19
- ip_last_reset = {} # Tracks when counters were last reset for each IP
20
- rate_limit_lock = threading.Lock() # Lock for thread-safe counter access
21
-
22
- # Expanded comprehensive patterns to filter out thinking and meta-commentary
23
- THINKING_PATTERNS = [
24
- r"Okay, so I('m| am) (trying to|going to|attempting to)",
25
- r"I need to figure out",
26
- r"I'll start by",
27
- r"Let me try to",
28
- r"I'm trying to understand",
29
- r"First, I (know|think) that",
30
- r"I'll need to look into",
31
- r"I'm not entirely (sure|clear)",
32
- r"I believe this is",
33
- r"I imagine it involves",
34
- r"I think I understand",
35
- r"From what I (know|remember)",
36
- r"Let me think about",
37
- r"From my understanding",
38
- r"As I understand it",
39
- r"To answer this question",
40
- r"To address this",
41
- r"I'll approach this by",
42
- r"I think it's (important|worth) (to note|noting)",
43
- r"I (think|believe|wonder|should|also wonder|recall)",
44
- r"I also (think|believe|wonder|should|recall)",
45
- ]
46
-
47
- def get_client_ip():
48
- """Get the client's IP address from the request context"""
49
- try:
50
- # Try to get IP from Gradio's request context
51
- import contextvars
52
- request_context = contextvars.ContextVar("request").get()
53
- if hasattr(request_context, "client") and request_context.client:
54
- return request_context.client.host
55
- except:
56
- pass
57
-
58
- # Fallback if we can't get a real IP
59
- return "127.0.0.1"
60
-
61
- def check_rate_limit():
62
- """Check if the current IP has exceeded its daily limit"""
63
- current_ip = get_client_ip()
64
- current_date = datetime.datetime.now().date()
65
-
66
- with rate_limit_lock:
67
- # Reset counter if it's a new day
68
- if current_ip in ip_last_reset and ip_last_reset[current_ip] != current_date:
69
- ip_request_counters[current_ip] = 0
70
-
71
- # Update last reset date
72
- ip_last_reset[current_ip] = current_date
73
-
74
- # Check if limit is exceeded
75
- if ip_request_counters[current_ip] >= MAX_REQUESTS_PER_DAY:
76
- return False
77
-
78
- # Increment counter
79
- ip_request_counters[current_ip] += 1
80
- return True
81
-
82
- def process_final_response(response_text):
83
- """Comprehensive processing of the final response to ensure quality"""
84
-
85
- # Early return if response is too short
86
- if len(response_text) < 50:
87
- return response_text
88
-
89
- # 1. Remove thinking patterns more aggressively
90
- for pattern in THINKING_PATTERNS:
91
- response_text = re.sub(pattern, "", response_text, flags=re.IGNORECASE)
92
-
93
- # Remove first person references completely
94
- response_text = re.sub(r"\b(I|me|my|mine|myself)\b", "", response_text, flags=re.IGNORECASE)
95
-
96
- # 2. Split into paragraphs
97
- paragraphs = [p.strip() for p in response_text.split('\n\n') if p.strip()]
98
-
99
- # 3. Filter meaningless paragraphs
100
- filtered_paragraphs = []
101
- for para in paragraphs:
102
- # Skip too short paragraphs or those that are just meta-commentary
103
- if len(para) < 20 or re.search(r"^(In summary|To summarize|In conclusion)", para, re.IGNORECASE):
104
- continue
105
-
106
- # Skip paragraphs with thinking patterns
107
- skip = False
108
- for pattern in THINKING_PATTERNS:
109
- if re.search(pattern, para, re.IGNORECASE):
110
- skip = True
111
- break
112
-
113
- if not skip:
114
- filtered_paragraphs.append(para)
115
-
116
- # 4. Remove duplicates and similar paragraphs with stricter threshold
117
- unique_paragraphs = []
118
- for current in filtered_paragraphs:
119
- # Clean for comparison
120
- clean_current = re.sub(r'[^\w\s]', '', current.lower())
121
- words_current = set(clean_current.split())
122
-
123
- is_duplicate = False
124
- for existing in unique_paragraphs:
125
- clean_existing = re.sub(r'[^\w\s]', '', existing.lower())
126
- words_existing = set(clean_existing.split())
127
-
128
- if len(words_current) > 3 and len(words_existing) > 3: # Ignore very short paragraphs
129
- # Calculate word overlap as similarity measure
130
- overlap = len(words_current.intersection(words_existing))
131
- similarity = overlap / min(len(words_current), len(words_existing))
132
-
133
- if similarity > 0.5: # 50% threshold for similarity (stricter)
134
- is_duplicate = True
135
- break
136
-
137
- if not is_duplicate:
138
- unique_paragraphs.append(current)
139
-
140
- # 5. Structure the response based on detected content
141
- title = ""
142
- if "retention policies" in response_text.lower() and "retention labels" in response_text.lower():
143
- title = "# Retention Policies vs. Retention Labels in Microsoft 365"
144
- elif "onedrive" in response_text.lower() and "sharepoint" in response_text.lower():
145
- title = "# Key Differences Between OneDrive for Business and SharePoint Online"
146
- else:
147
- # Extract a title from the content
148
- first_para = unique_paragraphs[0] if unique_paragraphs else ""
149
- first_sentence = first_para.split('.')[0] if first_para else ""
150
- if len(first_sentence) > 10:
151
- title = f"# {first_sentence}"
152
- else:
153
- title = "# Microsoft 365 Information Management"
154
-
155
- # Build structured content with max 2-3 paragraphs
156
- final_paras = []
157
- if unique_paragraphs:
158
- # Limit to just 2-3 most relevant paragraphs
159
- final_paras = unique_paragraphs[:min(3, len(unique_paragraphs))]
160
-
161
- # Add a "Use cases" section if we have 3+ paragraphs
162
- if len(unique_paragraphs) > 2:
163
- final_text = f"{title}\n\n{final_paras[0]}\n\n{final_paras[1]}\n\n## Key Considerations\n\n{final_paras[2]}"
164
- else:
165
- final_text = f"{title}\n\n" + "\n\n".join(final_paras)
166
- else:
167
- final_text = f"{title}\n\nNo content available."
168
-
169
- return final_text.strip()
170
 
171
  def respond(
172
  message,
@@ -176,51 +15,8 @@ def respond(
176
  temperature,
177
  top_p,
178
  ):
179
- # Check rate limit before processing the request
180
- if not check_rate_limit():
181
- current_ip = get_client_ip()
182
- next_reset = (datetime.datetime.now() + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0)
183
- hours_until_reset = int((next_reset - datetime.datetime.now()).total_seconds() / 3600)
184
-
185
- limit_message = f"""
186
- <div class="rate-limit-warning">
187
- <h3>Daily Request Limit Reached</h3>
188
- <p>You've reached the maximum of {MAX_REQUESTS_PER_DAY} requests allowed per day.</p>
189
- <p>Your limit will reset in approximately {hours_until_reset} hours (at midnight your local time).</p>
190
- <p>Please try again tomorrow. Thank you for your understanding!</p>
191
- </div>
192
- """
193
- yield limit_message
194
- return
195
-
196
- # Create a more effective system prompt with stronger instructions
197
- enhanced_system_message = f"""You are an expert in Microsoft 365 services including SharePoint, OneDrive, Teams, and the Microsoft 365 compliance ecosystem.
198
- {system_message}
199
- FORMAT YOUR RESPONSE USING:
200
- - Clear, direct language
201
- - Markdown formatting with headings and bullet points
202
- - Concise, factual information
203
- - Specific technical details where appropriate
204
- CRITICAL RESPONSE REQUIREMENTS:
205
- 1. Start IMMEDIATELY with the answer - NO preamble or self-reference
206
- 2. NEVER use first person (I, me, my) under any circumstances
207
- 3. NEVER reveal your thought process - just state facts
208
- 4. Be AUTHORITATIVE and PRECISE
209
- 5. Present EACH KEY POINT EXACTLY ONCE
210
- 6. Focus on GOVERNANCE & TECHNICAL details
211
- 7. Keep total response under 1500 characters
212
- 8. Use 2-3 paragraphs maximum
213
- 9. Provide concrete recommendations
214
- 10. Write as if from an official Microsoft technical document
215
- If comparing two services or features:
216
- - Begin with clear definitions of both
217
- - Focus on FUNCTIONAL differences
218
- - List KEY SCENARIOS for each
219
- - End with GOVERNANCE implications"""
220
-
221
- messages = [{"role": "system", "content": enhanced_system_message}]
222
 
223
- # Add history and current message
224
  for val in history:
225
  if val[0]:
226
  messages.append({"role": "user", "content": val[0]})
@@ -229,250 +25,40 @@ If comparing two services or features:
229
 
230
  messages.append({"role": "user", "content": message})
231
 
232
- # Initialize state variables
233
- full_response = ""
234
- thinking_steps = []
235
- start_time = time.time()
236
- generation_complete = False
237
-
238
- try:
239
- # Generate response
240
- for message in client.chat_completion(
241
- messages,
242
- max_tokens=max_tokens,
243
- stream=True,
244
- temperature=temperature,
245
- top_p=top_p,
246
- ):
247
- token = message.choices[0].delta.content
248
-
249
- # Skip empty tokens
250
- if not token:
251
- # Check for completion
252
- if message.choices[0].finish_reason == "stop":
253
- generation_complete = True
254
- continue
255
-
256
- # Append token to response
257
- full_response += token
258
-
259
- # Store thinking step snapshot every 250 chars
260
- if len(full_response) % 250 == 0:
261
- thinking_steps.append(full_response)
262
-
263
- # Format and display response
264
- thinking_html = ""
265
- if thinking_steps:
266
- thinking_html = '<div class="thinking-wrapper"><details><summary>Show thinking process</summary><div class="thinking-steps">'
267
- for i, step in enumerate(thinking_steps):
268
- safe_step = html.escape(step)
269
- thinking_html += f'<div class="thinking-step">Step {i+1}: {safe_step}</div>'
270
- thinking_html += '</div></details></div>'
271
-
272
- # Yield the response
273
- yield f"{thinking_html}{full_response}"
274
-
275
- # Check if we need to post-process the response
276
- processed_response = process_final_response(full_response)
277
-
278
- # If the processing made significant changes, show both versions
279
- if len(processed_response) < len(full_response) * 0.8 or len(processed_response) > 100:
280
- thinking_html = '<div class="thinking-wrapper"><details><summary>Show original response</summary><div class="thinking-steps">'
281
- thinking_html += f'<div class="thinking-step">{html.escape(full_response)}</div>'
282
- thinking_html += '</div></details></div>'
283
- yield f"{thinking_html}{processed_response}"
284
-
285
- except Exception as e:
286
- error_msg = f"I apologize, but I encountered an error while generating a response. Error details: {str(e)}"
287
- yield error_msg
288
 
289
- # Custom CSS for Plant Wisdom.AI styling
290
- custom_css = """
291
- .gradio-container {
292
- font-family: 'Source Sans Pro', 'Helvetica Neue', Arial, sans-serif;
293
- max-width: 1000px;
294
- margin: 0 auto;
295
- background-color: #ffffff;
296
- }
297
- .contain {
298
- background-color: #ffffff;
299
- border-radius: 12px;
300
- box-shadow: 0 4px 6px rgba(0,0,0,0.05);
301
- padding: 20px;
302
- }
303
- .message {
304
- padding: 16px 20px;
305
- border-radius: 12px;
306
- margin: 12px 0;
307
- font-size: 16px;
308
- line-height: 1.5;
309
- }
310
- .message.user {
311
- background-color: #f5f7fa;
312
- margin-left: 15%;
313
- border: 1px solid #e8eef7;
314
- }
315
- .message.assistant {
316
- background-color: #f0f7f0;
317
- margin-right: 15%;
318
- border: 1px solid #e0ede0;
319
- color: #2c3338;
320
- }
321
- .message.assistant p {
322
- margin-bottom: 12px;
323
- }
324
- .message.assistant h1 {
325
- font-size: 1.4em;
326
- margin-top: 0;
327
- margin-bottom: 16px;
328
- color: #2e7d32;
329
- }
330
- .message.assistant h2 {
331
- font-size: 1.2em;
332
- margin-top: 16px;
333
- margin-bottom: 12px;
334
- color: #2e7d32;
335
- }
336
- .message.assistant ul, .message.assistant ol {
337
- margin: 12px 0;
338
- padding-left: 24px;
339
- }
340
- .message.assistant li {
341
- margin-bottom: 6px;
342
- }
343
- .thinking-wrapper {
344
- margin-bottom: 12px;
345
- }
346
- details {
347
- background-color: #f8faf8;
348
- border: 1px solid #e0ede0;
349
- border-radius: 8px;
350
- padding: 8px;
351
- margin-bottom: 16px;
352
- }
353
- summary {
354
- cursor: pointer;
355
- color: #2e7d32;
356
- font-weight: 500;
357
- padding: 4px 8px;
358
- }
359
- summary:hover {
360
- background-color: rgba(46,125,50,0.1);
361
- border-radius: 4px;
362
- }
363
- .thinking-steps {
364
- margin-top: 8px;
365
- padding: 8px;
366
- border-top: 1px solid #e0ede0;
367
- max-height: 200px;
368
- overflow-y: auto;
369
- }
370
- .thinking-step {
371
- padding: 4px 8px;
372
- font-size: 14px;
373
- color: #666;
374
- border-bottom: 1px dashed #eee;
375
- }
376
- .thinking-step:last-child {
377
- border-bottom: none;
378
- }
379
- /* Rate limit warning styling */
380
- .rate-limit-warning {
381
- background-color: #fff3cd;
382
- color: #856404;
383
- border: 1px solid #ffeeba;
384
- border-radius: 8px;
385
- padding: 16px;
386
- margin: 16px 0;
387
- text-align: center;
388
- font-weight: 500;
389
- }
390
- """
391
 
392
  """
393
  For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
394
  """
395
- # Main chat interface
396
- chat_interface = gr.ChatInterface(
397
  respond,
398
- title="AI Data Management Expert",
399
- description="Hello! I am your Data Management Expert, specialized in Microsoft 365. I'm here to help you with guidance on Data Management procedures. How can I assist you today?",
400
- theme=gr.themes.Base(
401
- primary_hue=gr.themes.Color(
402
- c50="#f3f7f3",
403
- c100="#e0ede0",
404
- c200="#b5d4b5",
405
- c300="#8abb8a",
406
- c400="#5fa25f",
407
- c500="#2e7d32",
408
- c600="#1b5e20",
409
- c700="#154a19",
410
- c800="#0e3511",
411
- c900="#082108",
412
- c950="#041104"
413
- ),
414
- secondary_hue=gr.themes.Color(
415
- c50="#f3f7f3",
416
- c100="#e0ede0",
417
- c200="#b5d4b5",
418
- c300="#8abb8a",
419
- c400="#5fa25f",
420
- c500="#2e7d32",
421
- c600="#1b5e20",
422
- c700="#154a19",
423
- c800="#0e3511",
424
- c900="#082108",
425
- c950="#041104"
426
- ),
427
- neutral_hue="slate",
428
- spacing_size="lg",
429
- radius_size="lg",
430
- font=["Source Sans Pro", "Helvetica Neue", "Arial", "sans-serif"],
431
- ),
432
- css=custom_css,
433
  additional_inputs=[
434
- gr.Textbox(
435
- value="""You are a specialized AI assistant made by Plant Wisdom.AI with deep knowledge of Microsoft 365 services—including SharePoint Online, OneDrive, Teams, Exchange, and the Microsoft Purview (Compliance) ecosystem—as well as general records management and data governance best practices.
436
- Your primary objectives are:
437
- Provide accurate, detailed, and practical answers about:
438
- Microsoft 365's features, capabilities, and architecture.
439
- Document and records management (e.g., retention labels, policies, disposition reviews).
440
- Compliance and information governance (e.g., data loss prevention, eDiscovery, retention schedules).
441
- SharePoint Online configuration, site management, and usage best practices.
442
- Integration points across Microsoft 365 (Teams, Outlook, Power Platform, etc.).
443
- Address user questions in a clear, direct manner without simply directing them to official documentation. Instead, share concise explanations and relevant examples.
444
- When applicable, highlight best practices, common pitfalls, and recommended solutions based on real-world usage.
445
- If you are not certain about an answer or lack enough context, say so clearly rather than guess.
446
- Tone and Style:
447
- Strive for clarity and helpfulness; avoid excessive jargon.
448
- Avoid generic references like "refer to the documentation." Instead, explain or paraphrase relevant information whenever possible.
449
- Cite Microsoft's recommended or well-known practices when beneficial, but do so in your own words.
450
- Keep responses concise yet sufficiently detailed.
451
- Additional Guidelines:
452
- Where necessary, provide step-by-step instructions for configurations or troubleshooting.
453
- Distinguish between official Microsoft 365 functionalities and custom solutions or third-party tools.
454
- If the user's request includes advanced or niche scenarios, do your best to provide an overview, while acknowledging any areas that may require deeper research.
455
- Maintain professionalism in all responses; be polite, solution-focused, and proactive.
456
- Follow any privacy or ethical guidelines, and do not disclose personally identifiable information about real people.
457
- IMPORTANT: If a question has been asked before in the conversation, acknowledge this and either refer back to the previous answer or provide additional context. Do not simply repeat the same answer verbatim.""",
458
- label="System message"
459
- ),
460
- gr.Slider(minimum=1, maximum=2048, value=1000, step=1, label="Max new tokens"),
461
- gr.Slider(minimum=0.1, maximum=2.0, value=0.35, step=0.05, label="Temperature"),
462
  gr.Slider(
463
  minimum=0.1,
464
  maximum=1.0,
465
- value=0.6,
466
  step=0.05,
467
  label="Top-p (nucleus sampling)",
468
  ),
469
  ],
470
  )
471
 
472
- # Create Gradio Blocks app with chat interface
473
- with gr.Blocks(theme=gr.themes.Base()) as demo:
474
- # Main chat interface
475
- chat_interface.render()
476
 
477
  if __name__ == "__main__":
478
- demo.launch(server_name="0.0.0.0")
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
3
 
4
  """
5
  For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
  """
7
  client = InferenceClient("PlantWisdom/Data_Management_Mistral")
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  def respond(
11
  message,
 
15
  temperature,
16
  top_p,
17
  ):
18
+ messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
 
20
  for val in history:
21
  if val[0]:
22
  messages.append({"role": "user", "content": val[0]})
 
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()