Neom99 commited on
Commit
8abbfeb
·
verified ·
1 Parent(s): 089bb71

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -38
app.py CHANGED
@@ -4,6 +4,7 @@ from dotenv import load_dotenv
4
  import pandas as pd
5
  from datetime import datetime
6
  import io # For in-memory file operations
 
7
 
8
  # --- RAG Libraries ---
9
  from langchain.text_splitter import RecursiveCharacterTextSplitter
@@ -28,22 +29,23 @@ llm = None # Initialize llm to None
28
  embeddings = None # Initialize embeddings to None
29
 
30
  try:
31
- llm_model_id = "gemini-1.5-flash" # Store the intended model ID here for printing
32
  llm = ChatGoogleGenerativeAI(model=llm_model_id, temperature=0.7)
33
  embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
34
  rag_initialized = True
35
- # Print the model ID we intended to use, not relying on llm.model_name attribute
36
  print(f"Google Generative AI LLM ({llm_model_id}) and embeddings initialized successfully.")
37
  except Exception as e:
38
  rag_initialized = False
39
  print(f"Error initializing Google Generative AI components: {e}")
40
  print("Please ensure GOOGLE_API_KEY is correctly set in your environment or Hugging Face Space secrets.")
41
- # Provide the model ID in the error message for clarity
42
  print(f"Also, verify that the specified AI model ('{llm_model_id}' for LLM) is available to your API key.")
43
  print("RAG functionality will not work without a valid Google API key and accessible model.")
44
 
45
- # Global variable to store the last analysis result for download
46
- last_analysis_result_text = ""
 
 
 
47
 
48
  def get_document_content_from_tickets(file_path, file_extension, filename):
49
  """
@@ -106,25 +108,32 @@ def get_document_content_from_tickets(file_path, file_extension, filename):
106
 
107
  def perform_ticket_analysis(file, query):
108
  """
109
- Main function to analyze customer tickets using RAG.
110
- Updates a global variable with the result for download functions.
111
  """
112
- global last_analysis_result_text # Declare global to modify it
113
 
114
- if not rag_initialized:
115
- last_analysis_result_text = "RAG system not initialized. Please ensure your **GOOGLE_API_KEY** is configured correctly in Hugging Face Space secrets and the specified AI model is accessible."
116
- return last_analysis_result_text
117
 
118
- # Ensure llm and embeddings are not None before use, even if rag_initialized is True
119
- # This might happen if 'rag_initialized' is True but 'llm' or 'embeddings'
120
- # assignment failed but did not raise an exception caught by try-except
 
 
 
121
  if llm is None or embeddings is None:
122
- last_analysis_result_text = "RAG components (LLM/Embeddings) were not fully initialized. Please check startup logs."
123
- return last_analysis_result_text
 
 
124
 
125
  if file is None:
126
- last_analysis_result_text = "Please upload a customer ticket file."
127
- return last_analysis_result_text
 
 
128
 
129
  # Default comprehensive analysis if query is empty
130
  if not query.strip():
@@ -134,6 +143,9 @@ def perform_ticket_analysis(file, query):
134
  filename = os.path.basename(file_path)
135
  file_extension = os.path.splitext(filename)[1].lower()
136
 
 
 
 
137
  try:
138
  documents = get_document_content_from_tickets(file_path, file_extension, filename)
139
 
@@ -141,8 +153,10 @@ def perform_ticket_analysis(file, query):
141
  texts = text_splitter.split_documents(documents)
142
 
143
  if not texts:
144
- last_analysis_result_text = "No usable text extracted from the ticket data after splitting."
145
- return last_analysis_result_text
 
 
146
 
147
  vectorstore = FAISS.from_documents(texts, embeddings)
148
 
@@ -180,25 +194,175 @@ def perform_ticket_analysis(file, query):
180
  chain_type_kwargs={"prompt": QA_CHAIN_PROMPT}
181
  )
182
 
183
- result = qa_chain.run(query)
184
-
185
- disclaimer = "\n\n**Note:** 'Root Cause', 'Future Prediction', and 'Proactive Measures' are AI-inferred based on descriptions provided. For critical decisions, human expert review is essential."
186
- final_result = result + disclaimer
187
-
188
- last_analysis_result_text = final_result # Store the result
189
- return final_result
190
 
191
  except ValueError as e:
192
- last_analysis_result_text = f"Ticket Analysis Error: {e}"
193
- return last_analysis_result_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  except Exception as e:
195
- last_analysis_result_text = f"An unexpected error occurred during analysis: {e}. Check logs for details."
196
- print(f"Error: {e}")
197
- return last_analysis_result_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
- # --- Output Download Functions ---
200
 
201
- def generate_pdf_report(markdown_text):
 
202
  if not markdown_text or "RAG system not initialized" in markdown_text or "Error:" in markdown_text:
203
  return None # Return None if no valid text to generate
204
 
@@ -243,7 +407,8 @@ def generate_pdf_report(markdown_text):
243
  return temp_file_path
244
 
245
 
246
- def generate_docx_report(markdown_text):
 
247
  if not markdown_text or "RAG system not initialized" in markdown_text or "Error:" in markdown_text:
248
  return None # Return None if no valid text to generate
249
 
@@ -401,8 +566,9 @@ with gr.Blocks(theme=gr.themes.Soft(), css="""
401
  output_text = gr.Textbox(
402
  label="AI Ticket Analysis Result",
403
  show_copy_button=True,
404
- lines=15,
405
  interactive=False,
 
406
  )
407
 
408
  with gr.Group(elem_id="download-buttons"):
@@ -428,7 +594,6 @@ with gr.Blocks(theme=gr.themes.Soft(), css="""
428
 
429
  pdf_btn.click(
430
  fn=generate_pdf_report,
431
- inputs=output_text,
432
  outputs=pdf_output_file,
433
  api_name="download_pdf"
434
  ).then(
@@ -439,7 +604,6 @@ with gr.Blocks(theme=gr.themes.Soft(), css="""
439
 
440
  docx_btn.click(
441
  fn=generate_docx_report,
442
- inputs=output_text,
443
  outputs=docx_output_file,
444
  api_name="download_docx"
445
  ).then(
 
4
  import pandas as pd
5
  from datetime import datetime
6
  import io # For in-memory file operations
7
+ import re # For regex to clean markdown
8
 
9
  # --- RAG Libraries ---
10
  from langchain.text_splitter import RecursiveCharacterTextSplitter
 
29
  embeddings = None # Initialize embeddings to None
30
 
31
  try:
32
+ llm_model_id = "gemini-1.5-flash" # The intended model ID
33
  llm = ChatGoogleGenerativeAI(model=llm_model_id, temperature=0.7)
34
  embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
35
  rag_initialized = True
 
36
  print(f"Google Generative AI LLM ({llm_model_id}) and embeddings initialized successfully.")
37
  except Exception as e:
38
  rag_initialized = False
39
  print(f"Error initializing Google Generative AI components: {e}")
40
  print("Please ensure GOOGLE_API_KEY is correctly set in your environment or Hugging Face Space secrets.")
 
41
  print(f"Also, verify that the specified AI model ('{llm_model_id}' for LLM) is available to your API key.")
42
  print("RAG functionality will not work without a valid Google API key and accessible model.")
43
 
44
+
45
+ # Global variable to store the RAW MARKDOWN for download functions
46
+ # The on-page output will be rich HTML, but PDF/Word needs simpler markdown/text.
47
+ global_raw_markdown_for_export = ""
48
+
49
 
50
  def get_document_content_from_tickets(file_path, file_extension, filename):
51
  """
 
108
 
109
  def perform_ticket_analysis(file, query):
110
  """
111
+ Main function to analyze customer tickets using RAG and format output as rich HTML.
112
+ Updates a global variable with the raw markdown result for download functions.
113
  """
114
+ global global_raw_markdown_for_export # Declare global to modify it
115
 
116
+ # Default output if RAG not initialized or file missing
117
+ default_output_html = "" # This will be the HTML if an error occurs
118
+ error_message_markdown = "" # This will be markdown for export if an error occurs
119
 
120
+ if not rag_initialized:
121
+ error_message_markdown = "RAG system not initialized. Please ensure your **GOOGLE_API_KEY** is configured correctly in Hugging Face Space secrets and the specified AI model is accessible."
122
+ default_output_html = f"<p style='color:red;'>{error_message_markdown}</p>"
123
+ global_raw_markdown_for_export = error_message_markdown
124
+ return default_output_html
125
+
126
  if llm is None or embeddings is None:
127
+ error_message_markdown = "RAG components (LLM/Embeddings) were not fully initialized. Please check startup logs."
128
+ default_output_html = f"<p style='color:red;'>{error_message_markdown}</p>"
129
+ global_raw_markdown_for_export = error_message_markdown
130
+ return default_output_html
131
 
132
  if file is None:
133
+ error_message_markdown = "Please upload a customer ticket file."
134
+ default_output_html = f"<p style='color:red;'>{error_message_markdown}</p>"
135
+ global_raw_markdown_for_export = error_message_markdown
136
+ return default_output_html
137
 
138
  # Default comprehensive analysis if query is empty
139
  if not query.strip():
 
143
  filename = os.path.basename(file_path)
144
  file_extension = os.path.splitext(filename)[1].lower()
145
 
146
+ raw_rag_output = "" # This will hold the raw markdown table from the LLM
147
+ disclaimer_text = "\n\n**Note:** 'Root Cause', 'Future Prediction', and 'Proactive Measures' are AI-inferred based on descriptions provided. For critical decisions, human expert review is essential."
148
+
149
  try:
150
  documents = get_document_content_from_tickets(file_path, file_extension, filename)
151
 
 
153
  texts = text_splitter.split_documents(documents)
154
 
155
  if not texts:
156
+ error_message_markdown = "No usable text extracted from the ticket data after splitting."
157
+ default_output_html = f"<p style='color:red;'>{error_message_markdown}</p>"
158
+ global_raw_markdown_for_export = error_message_markdown
159
+ return default_output_html
160
 
161
  vectorstore = FAISS.from_documents(texts, embeddings)
162
 
 
194
  chain_type_kwargs={"prompt": QA_CHAIN_PROMPT}
195
  )
196
 
197
+ raw_rag_output = qa_chain.run(query)
 
 
 
 
 
 
198
 
199
  except ValueError as e:
200
+ raw_rag_output = f"Ticket Analysis Error: {e}"
201
+ except Exception as e:
202
+ raw_rag_output = f"An unexpected error occurred during analysis: {e}. Check logs for details."
203
+ print(f"Error during RAG analysis: {e}")
204
+
205
+ # Store the raw markdown with disclaimer for PDF/Word export
206
+ global_raw_markdown_for_export = raw_rag_output + disclaimer_text
207
+
208
+ # --- HTML Formatting for On-Page Display ---
209
+ analysis_df = None
210
+ detailed_table_html = ""
211
+
212
+ # Attempt to parse the raw RAG markdown output into a pandas DataFrame
213
+ try:
214
+ # Clean markdown: remove starting/ending pipes, extra spaces, and markdown bolding/italics
215
+ cleaned_markdown_lines = []
216
+ is_table_section = False
217
+ for line in raw_rag_output.split('\n'):
218
+ if line.strip().startswith('|') and '|---' not in line:
219
+ is_table_section = True
220
+ cleaned_line = line.strip('|') # Remove leading/trailing pipes
221
+ # Replace markdown bold/italic inside cells for easier parsing
222
+ cleaned_line = re.sub(r'\*\*(.*?)\*\*', r'\1', cleaned_line) # Remove bold
223
+ cleaned_line = re.sub(r'\*(.*?)\*', r'\1', cleaned_line) # Remove italics
224
+ cleaned_markdown_lines.append(cleaned_line)
225
+ elif '|---' in line:
226
+ # This is the separator line, we'll handle column names directly
227
+ continue
228
+ elif is_table_section and not line.strip(): # End of table if empty line after table content
229
+ is_table_section = False
230
+ elif not is_table_section: # Non-table content at start/end
231
+ pass # We are only interested in parsing the table part
232
+
233
+ if len(cleaned_markdown_lines) > 1: # At least header and one data row
234
+ header_str = cleaned_markdown_lines[0]
235
+ data_str = "\n".join(cleaned_markdown_lines[1:])
236
+
237
+ # Use io.StringIO and read_csv with regex for flexible splitting (handles varying spaces)
238
+ # The regex `\s*\|\s*` means "any whitespace, then a pipe, then any whitespace"
239
+ analysis_df = pd.read_csv(io.StringIO(header_str + '\n' + data_str), sep='\s*\|\s*', engine='python')
240
+
241
+ analysis_df = analysis_df.dropna(axis=1, how='all') # Drop columns that are entirely NaN
242
+ analysis_df.columns = analysis_df.columns.str.strip() # Strip whitespace from column names
243
+
244
+ if 'Count' in analysis_df.columns:
245
+ analysis_df['Count'] = pd.to_numeric(analysis_df['Count'], errors='coerce').fillna(0).astype(int)
246
+ else:
247
+ analysis_df['Count'] = 1 # Default to 1 if no count column found
248
+ print("Warning: 'Count' column not found in RAG output. Defaulting counts to 1.")
249
+
250
  except Exception as e:
251
+ print(f"Failed to parse RAG markdown table into DataFrame for HTML display: {e}")
252
+ analysis_df = None # Reset if parsing fails
253
+
254
+ # --- Construct HTML Output ---
255
+ html_output = f"""
256
+ <div style="font-family: Arial, sans-serif; padding: 20px; background-color: #f9f9f9; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
257
+ <h1 style="color: #1A237E; text-align: center; margin-bottom: 25px;">Executive Summary: Customer Ticket Analysis</h1>
258
+
259
+ <div style="background-color: #E8EAF6; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
260
+ <h2 style="color: #3F51B5; margin-top: 0;">Overview & Key Insights</h2>
261
+ <p style="font-size: 1.1em; line-height: 1.6; color: #424242;">
262
+ This report provides a data-driven analysis of recent customer support tickets, leveraging advanced AI to identify trends, root causes, and actionable insights.
263
+ Below is a summary of identified issues and a detailed breakdown.
264
+ </p>
265
+ </div>
266
+ """
267
+
268
+ category_counts_html = ""
269
+ sub_category_counts_html = ""
270
+
271
+ if analysis_df is not None and not analysis_df.empty:
272
+ # Aggregate counts for Categories
273
+ if 'Category' in analysis_df.columns and 'Count' in analysis_df.columns:
274
+ category_summary = analysis_df.groupby('Category')['Count'].sum().sort_values(ascending=False)
275
+ category_counts_html = """
276
+ <div style="background-color: #FFFDE7; border: 1px solid #FFEB3B; border-radius: 8px; padding: 15px; flex: 1; min-width: 250px; box-shadow: 0 1px 5px rgba(0,0,0,0.05);">
277
+ <h4 style="color: #FFC107; margin-top: 0;">Categories Breakdown</h4>
278
+ <ul style="list-style: none; padding-left: 0;">
279
+ """
280
+ for category, count in category_summary.items():
281
+ category_counts_html += f"""<li><strong>{category}:</strong> {count} tickets</li>"""
282
+ category_counts_html += "</ul></div>"
283
+
284
+ # Aggregate counts for Sub-Categories
285
+ if 'Sub-Category' in analysis_df.columns and 'Count' in analysis_df.columns:
286
+ sub_category_summary = analysis_df.groupby('Sub-Category')['Count'].sum().sort_values(ascending=False).head(5) # Top 5
287
+ sub_category_counts_html = """
288
+ <div style="background-color: #E0F2F7; border: 1px solid #00BCD4; border-radius: 8px; padding: 15px; flex: 1; min-width: 250px; box-shadow: 0 1px 5px rgba(0,0,0,0.05);">
289
+ <h4 style="color: #0097A7; margin-top: 0;">Top Sub-Categories</h4>
290
+ <ul style="list-style: none; padding-left: 0;">
291
+ """
292
+ for sub_category, count in sub_category_summary.items():
293
+ sub_category_counts_html += f"""<li><strong>{sub_category}:</strong> {count} tickets</li>"""
294
+ sub_category_counts_html += "</ul></div>"
295
+
296
+ html_output += f"""
297
+ <div style="margin-bottom: 20px;">
298
+ <h3 style="color: #3F51B5;">Issue Categorization & Volume</h3>
299
+ <div style="display: flex; flex-wrap: wrap; gap: 20px; justify-content: space-around;">
300
+ {category_counts_html}
301
+ {sub_category_counts_html}
302
+ </div>
303
+ </div>
304
+ """
305
+
306
+ # Re-generate the detailed table with HTML styling
307
+ detailed_table_html = """
308
+ <div style="margin-bottom: 20px;">
309
+ <h3 style="color: #3F51B5;">Detailed Analysis Table</h3>
310
+ <div style="overflow-x: auto;">
311
+ <table style="width: 100%; border-collapse: collapse; margin-top: 10px; background-color: white; font-size: 0.9em;">
312
+ <thead>
313
+ <tr style="background-color: #E0E0E0;">
314
+ """
315
+ for col in analysis_df.columns:
316
+ detailed_table_html += f"""<th style="padding: 12px; border: 1px solid #CCC; text-align: left; color: #333;">{col}</th>"""
317
+ detailed_table_html += """
318
+ </tr>
319
+ </thead>
320
+ <tbody>
321
+ """
322
+ for index, row in analysis_df.iterrows():
323
+ detailed_table_html += """<tr style="background-color: white;">"""
324
+ for col_data in row.values:
325
+ # Basic HTML escaping for table cells to prevent issues with special characters
326
+ escaped_data = str(col_data).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
327
+ detailed_table_html += f"""<td style="padding: 10px; border: 1px solid #DDD; text-align: left; vertical-align: top;">{escaped_data}</td>"""
328
+ detailed_table_html += """</tr>"""
329
+ detailed_table_html += """
330
+ </tbody>
331
+ </table>
332
+ </div>
333
+ </div>
334
+ """
335
+ else:
336
+ # If parsing failed or no data, display raw output with an error message
337
+ detailed_table_html = f"""
338
+ <div style="margin-bottom: 20px;">
339
+ <h3 style="color: #3F51B5;">Detailed Analysis Table</h3>
340
+ <p style="color: #D32F2F;">Could not generate structured report from AI output. Raw AI output or parsing error:</p>
341
+ <pre style="background-color: #EEE; padding: 15px; border: 1px solid #DDD; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word;">{raw_rag_output}</pre>
342
+ </div>
343
+ """
344
+
345
+ html_output += detailed_table_html
346
+
347
+ html_output += f"""
348
+ <div style="background-color: #F1F8E9; padding: 15px; border-radius: 8px; margin-top: 20px;">
349
+ <h3 style="color: #689F38; margin-top: 0;">Disclaimer</h3>
350
+ <p style="font-size: 0.9em; color: #555;">
351
+ *Note: AI-generated insights, especially 'Root Cause', 'Future Prediction', and 'Proactive Measures', are inferred based on the provided ticket descriptions. These are educated guesses by the AI and should be used for **guidance only**. For critical business decisions, human expert validation is highly recommended.*
352
+ </p>
353
+ <p style="font-size: 0.8em; color: #777;">
354
+ Report generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
355
+ </p>
356
+ </div>
357
+ </div>
358
+ """
359
+ return html_output # Return the rich HTML for display
360
+
361
 
362
+ # --- Output Download Functions (updated to use global_raw_markdown_for_export) ---
363
 
364
+ def generate_pdf_report(): # No input needed as it uses global_raw_markdown_for_export
365
+ markdown_text = global_raw_markdown_for_export
366
  if not markdown_text or "RAG system not initialized" in markdown_text or "Error:" in markdown_text:
367
  return None # Return None if no valid text to generate
368
 
 
407
  return temp_file_path
408
 
409
 
410
+ def generate_docx_report(): # No input needed as it uses global_raw_markdown_for_export
411
+ markdown_text = global_raw_markdown_for_export
412
  if not markdown_text or "RAG system not initialized" in markdown_text or "Error:" in markdown_text:
413
  return None # Return None if no valid text to generate
414
 
 
566
  output_text = gr.Textbox(
567
  label="AI Ticket Analysis Result",
568
  show_copy_button=True,
569
+ lines=20,
570
  interactive=False,
571
+ render_as="markdown" # Ensure it renders as markdown/HTML
572
  )
573
 
574
  with gr.Group(elem_id="download-buttons"):
 
594
 
595
  pdf_btn.click(
596
  fn=generate_pdf_report,
 
597
  outputs=pdf_output_file,
598
  api_name="download_pdf"
599
  ).then(
 
604
 
605
  docx_btn.click(
606
  fn=generate_docx_report,
 
607
  outputs=docx_output_file,
608
  api_name="download_docx"
609
  ).then(