Neom99 commited on
Commit
8585ec5
·
verified ·
1 Parent(s): 1bd6c94

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -40
app.py CHANGED
@@ -9,7 +9,9 @@ import google.generativeai as genai
9
  import faiss
10
  import numpy as np
11
  import time
12
- import json # For saving intermediate results if no DB is used, or for larger JSON processing
 
 
13
 
14
  # --- File Generation Libraries ---
15
  from fpdf import FPDF
@@ -372,7 +374,7 @@ def parse_markdown_table_to_df(markdown_string):
372
  lines = markdown_string.strip().split('\n')
373
 
374
  header_line = None
375
- separator_line_index = -1 # Corrected variable name
376
 
377
  for i, line in enumerate(lines):
378
  if '|' in line and '---' not in line and not line.strip().startswith('|---'):
@@ -385,7 +387,6 @@ def parse_markdown_table_to_df(markdown_string):
385
  return pd.DataFrame(), "No valid Markdown table header or separator found."
386
 
387
  data_lines = []
388
- # CORRECTED: Use separator_line_index here
389
  for line in lines[separator_line_index + 1:]:
390
  if line.strip().startswith('|') and '|' in line.strip():
391
  data_lines.append(line.strip())
@@ -417,8 +418,23 @@ def parse_markdown_table_to_df(markdown_string):
417
 
418
  return df, None
419
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
 
421
- def perform_ticket_analysis(file, user_query, progress=gr.Progress()):
 
422
  """
423
  Main function to analyze customer tickets using custom RAG implementation and format output as rich HTML.
424
  Implements a two-phase iterative approach to handle large ticket sets robustly.
@@ -431,8 +447,12 @@ def perform_ticket_analysis(file, user_query, progress=gr.Progress()):
431
  error_message_markdown = ""
432
  log_messages = [] # Initialize log messages list
433
 
 
 
 
 
434
  def append_log_message(message):
435
- timestamp = datetime.now().strftime("%H:%M:%S")
436
  log_messages.append(f"[{timestamp}] {message}")
437
  # Yield update to the log every time a message is appended
438
  yield gr.update(value=None), "\n".join(log_messages)
@@ -733,7 +753,7 @@ def perform_ticket_analysis(file, user_query, progress=gr.Progress()):
733
 
734
  html_output = f"""
735
  <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});">
736
- <h1 style="color: #1A237E; text-align: center; margin-bottom: 25px;">Executive Summary: Customer Ticket Analysis</h1>
737
 
738
  <div style="background-color: #E8EAF6; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
739
  <h2 style="color: #3F51B5; margin-top: 0;">Overview & Key Insights</h2>
@@ -761,10 +781,10 @@ def perform_ticket_analysis(file, user_query, progress=gr.Progress()):
761
  <div style="background-color: #F1F8E9; padding: 15px; border-radius: 8px; margin-top: 20px;">
762
  <h3 style="color: #689F38; margin-top: 0;">Disclaimer</h3>
763
  <p style="font-size: 0.9em; color: #555;'>
764
- *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.*
765
  </p>
766
  <p style="font-size: 0.8em; color: #777;'>
767
- Report generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
768
  </p>
769
  </div>
770
  </div>
@@ -778,7 +798,7 @@ def perform_ticket_analysis(file, user_query, progress=gr.Progress()):
778
 
779
  # --- Output Download Functions (using global_analysis_df_for_export) ---
780
 
781
- def generate_pdf_report():
782
  df = global_analysis_df_for_export
783
  if df.empty:
784
  # Return an update that hides the file component if no data
@@ -793,7 +813,8 @@ def generate_pdf_report():
793
  pdf.ln(5)
794
 
795
  # Generated on timestamp
796
- current_gen_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
 
797
  pdf.set_font("Arial", size=10)
798
  pdf.cell(0, 10, f"Generated on: {current_gen_time}", ln=True, align='R')
799
  pdf.ln(10)
@@ -898,22 +919,17 @@ def generate_pdf_report():
898
  pdf.multi_cell(0, 6, f"Report generated on: {current_gen_time}")
899
 
900
 
901
- pdf_output = io.BytesIO()
902
- pdf.output(pdf_output)
903
- pdf_output.seek(0)
904
-
905
- file_name = f"ticket_analysis_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
906
- temp_dir = os.path.join(os.getcwd(), "temp_files")
907
- os.makedirs(temp_dir, exist_ok=True)
908
- temp_file_path = os.path.join(temp_dir, file_name)
909
- with open(temp_file_path, "wb") as f:
910
- f.write(pdf_output.read())
911
 
912
  # Return update object for Gradio
913
  return gr.File.update(value=temp_file_path, visible=True, label="Download PDF Report")
914
 
915
 
916
- def generate_docx_report():
917
  df = global_analysis_df_for_export
918
  if df.empty:
919
  # Return an update that hides the file component if no data
@@ -926,7 +942,8 @@ def generate_docx_report():
926
  heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
927
 
928
  # Generated on timestamp
929
- current_gen_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
 
930
  p = doc.add_paragraph(f"Generated on: {current_gen_time}")
931
  p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
932
  doc.add_paragraph("") # Spacer
@@ -1015,17 +1032,11 @@ def generate_docx_report():
1015
  )
1016
  doc.add_paragraph(f"Report generated on: {current_gen_time}")
1017
 
1018
- docx_output = io.BytesIO()
1019
- doc.save(docx_output)
1020
- docx_output.seek(0)
 
1021
 
1022
- file_name = f"ticket_analysis_summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
1023
- temp_dir = os.path.join(os.getcwd(), "temp_files")
1024
- os.makedirs(temp_dir, exist_ok=True)
1025
- temp_file_path = os.path.join(temp_dir, file_name)
1026
- with open(temp_file_path, "wb") as f:
1027
- f.write(docx_output.read())
1028
-
1029
  # Return update object for Gradio
1030
  return gr.File.update(value=temp_file_path, visible=True, label="Download Word Report")
1031
 
@@ -1100,6 +1111,9 @@ with gr.Blocks(theme=gr.themes.Soft(), css="""
1100
  interactive=True
1101
  )
1102
 
 
 
 
1103
  submit_btn = gr.Button("Analyze Tickets", variant="primary")
1104
 
1105
  # New Textbox for detailed processing log
@@ -1116,12 +1130,11 @@ with gr.Blocks(theme=gr.themes.Soft(), css="""
1116
  )
1117
 
1118
  with gr.Group(elem_id="download-buttons"):
 
 
1119
  pdf_btn = gr.Button("Download as PDF Report", elem_classes="download-button")
1120
  docx_btn = gr.Button("Download as Word Document", elem_classes="download-button")
1121
 
1122
- # These outputs are initially hidden and will become visible when a file is ready for download
1123
- pdf_output_file = gr.File(label="Download PDF", visible=False)
1124
- docx_output_file = gr.File(label="Download Word Doc", visible=False)
1125
 
1126
  gr.HTML("""
1127
  <hr>
@@ -1130,28 +1143,52 @@ with gr.Blocks(theme=gr.themes.Soft(), css="""
1130
  </p>
1131
  """)
1132
 
1133
- # Modified submit_btn.click to update both HTML display and the new progress_log
1134
- # Gradio automatically handles generator functions when passed to `fn`
1135
  submit_btn.click(
1136
  fn=perform_ticket_analysis,
1137
- inputs=[file_input, query_input],
1138
- outputs=[output_html_display, progress_log], # Now receives updates incrementally
1139
  queue=True
1140
  )
1141
 
1142
- # Updated click handlers for download buttons
1143
  pdf_btn.click(
1144
  fn=generate_pdf_report,
 
1145
  outputs=pdf_output_file,
1146
  api_name="download_pdf"
1147
  )
1148
 
1149
  docx_btn.click(
1150
  fn=generate_docx_report,
 
1151
  outputs=docx_output_file,
1152
  api_name="download_docx"
1153
  )
1154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1155
 
1156
  if __name__ == "__main__":
1157
  if not os.getenv("GOOGLE_API_KEY"):
 
9
  import faiss
10
  import numpy as np
11
  import time
12
+ import json
13
+ import tempfile
14
+ import pytz # <--- NEW: Import pytz for timezone handling
15
 
16
  # --- File Generation Libraries ---
17
  from fpdf import FPDF
 
374
  lines = markdown_string.strip().split('\n')
375
 
376
  header_line = None
377
+ separator_line_index = -1
378
 
379
  for i, line in enumerate(lines):
380
  if '|' in line and '---' not in line and not line.strip().startswith('|---'):
 
387
  return pd.DataFrame(), "No valid Markdown table header or separator found."
388
 
389
  data_lines = []
 
390
  for line in lines[separator_line_index + 1:]:
391
  if line.strip().startswith('|') and '|' in line.strip():
392
  data_lines.append(line.strip())
 
418
 
419
  return df, None
420
 
421
+ # --- Helper function for timezone formatting ---
422
+ def format_time_for_display(dt_utc, user_timezone_str):
423
+ if not user_timezone_str:
424
+ return dt_utc.strftime('%Y-%m-%d %H:%M:%S UTC (No timezone detected)')
425
+
426
+ try:
427
+ user_tz = pytz.timezone(user_timezone_str)
428
+ # Make the UTC datetime timezone-aware and then convert
429
+ dt_user_tz = dt_utc.replace(tzinfo=pytz.utc).astimezone(user_tz)
430
+ return dt_user_tz.strftime('%Y-%m-%d %H:%M:%S %Z%z')
431
+ except pytz.UnknownTimeZoneError:
432
+ return dt_utc.strftime(f'%Y-%m-%d %H:%M:%S UTC (Unknown Timezone: {user_timezone_str})')
433
+ except Exception as e:
434
+ return dt_utc.strftime(f'%Y-%m-%d %H:%M:%S UTC (Timezone Error: {e})')
435
 
436
+
437
+ def perform_ticket_analysis(file, user_query, user_timezone_str, progress=gr.Progress()): # <--- NEW: Added user_timezone_str
438
  """
439
  Main function to analyze customer tickets using custom RAG implementation and format output as rich HTML.
440
  Implements a two-phase iterative approach to handle large ticket sets robustly.
 
447
  error_message_markdown = ""
448
  log_messages = [] # Initialize log messages list
449
 
450
+ # Get the current time in UTC
451
+ now_utc = datetime.utcnow()
452
+ display_time = format_time_for_display(now_utc, user_timezone_str) # <--- NEW: Format for display
453
+
454
  def append_log_message(message):
455
+ timestamp = datetime.now().strftime("%H:%M:%S") # Log messages use server's local time for simplicity
456
  log_messages.append(f"[{timestamp}] {message}")
457
  # Yield update to the log every time a message is appended
458
  yield gr.update(value=None), "\n".join(log_messages)
 
753
 
754
  html_output = f"""
755
  <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});">
756
+ <h1 align="center">🕵️‍♀️ Executive Summary: Customer Ticket Analysis 🕵️‍♀️</h1>
757
 
758
  <div style="background-color: #E8EAF6; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
759
  <h2 style="color: #3F51B5; margin-top: 0;">Overview & Key Insights</h2>
 
781
  <div style="background-color: #F1F8E9; padding: 15px; border-radius: 8px; margin-top: 20px;">
782
  <h3 style="color: #689F38; margin-top: 0;">Disclaimer</h3>
783
  <p style="font-size: 0.9em; color: #555;'>
784
+ *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.*
785
  </p>
786
  <p style="font-size: 0.8em; color: #777;'>
787
+ Report generated on: {display_time} # <--- NEW: Using user-timezone formatted time here
788
  </p>
789
  </div>
790
  </div>
 
798
 
799
  # --- Output Download Functions (using global_analysis_df_for_export) ---
800
 
801
+ def generate_pdf_report(user_timezone_str): # <--- NEW: Added user_timezone_str
802
  df = global_analysis_df_for_export
803
  if df.empty:
804
  # Return an update that hides the file component if no data
 
813
  pdf.ln(5)
814
 
815
  # Generated on timestamp
816
+ now_utc = datetime.utcnow()
817
+ current_gen_time = format_time_for_display(now_utc, user_timezone_str) # <--- NEW: Format for display
818
  pdf.set_font("Arial", size=10)
819
  pdf.cell(0, 10, f"Generated on: {current_gen_time}", ln=True, align='R')
820
  pdf.ln(10)
 
919
  pdf.multi_cell(0, 6, f"Report generated on: {current_gen_time}")
920
 
921
 
922
+ # Create a temporary file managed by the system
923
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
924
+ # Get the value from the BytesIO object and write it to the temporary file
925
+ pdf.output(tmp_file.name) # FPDF can write directly to a file path
926
+ temp_file_path = tmp_file.name # Get the path to the temporary file
 
 
 
 
 
927
 
928
  # Return update object for Gradio
929
  return gr.File.update(value=temp_file_path, visible=True, label="Download PDF Report")
930
 
931
 
932
+ def generate_docx_report(user_timezone_str): # <--- NEW: Added user_timezone_str
933
  df = global_analysis_df_for_export
934
  if df.empty:
935
  # Return an update that hides the file component if no data
 
942
  heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
943
 
944
  # Generated on timestamp
945
+ now_utc = datetime.utcnow()
946
+ current_gen_time = format_time_for_display(now_utc, user_timezone_str) # <--- NEW: Format for display
947
  p = doc.add_paragraph(f"Generated on: {current_gen_time}")
948
  p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
949
  doc.add_paragraph("") # Spacer
 
1032
  )
1033
  doc.add_paragraph(f"Report generated on: {current_gen_time}")
1034
 
1035
+ # Create a temporary file managed by the system
1036
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as tmp_file:
1037
+ doc.save(tmp_file) # Save directly to the temporary file object
1038
+ temp_file_path = tmp_file.name
1039
 
 
 
 
 
 
 
 
1040
  # Return update object for Gradio
1041
  return gr.File.update(value=temp_file_path, visible=True, label="Download Word Report")
1042
 
 
1111
  interactive=True
1112
  )
1113
 
1114
+ # <--- NEW: Hidden Textbox for user's timezone
1115
+ timezone_textbox = gr.Textbox(label="User Timezone", visible=False, interactive=False, elem_id="user-timezone-input")
1116
+
1117
  submit_btn = gr.Button("Analyze Tickets", variant="primary")
1118
 
1119
  # New Textbox for detailed processing log
 
1130
  )
1131
 
1132
  with gr.Group(elem_id="download-buttons"):
1133
+ pdf_output_file = gr.File(label="Download PDF", visible=False)
1134
+ docx_output_file = gr.File(label="Download Word Doc", visible=False)
1135
  pdf_btn = gr.Button("Download as PDF Report", elem_classes="download-button")
1136
  docx_btn = gr.Button("Download as Word Document", elem_classes="download-button")
1137
 
 
 
 
1138
 
1139
  gr.HTML("""
1140
  <hr>
 
1143
  </p>
1144
  """)
1145
 
1146
+ # Modified submit_btn.click to pass user_timezone_str
 
1147
  submit_btn.click(
1148
  fn=perform_ticket_analysis,
1149
+ inputs=[file_input, query_input, timezone_textbox], # <--- NEW: Pass timezone_textbox
1150
+ outputs=[output_html_display, progress_log],
1151
  queue=True
1152
  )
1153
 
1154
+ # Updated click handlers for download buttons to pass user_timezone_str
1155
  pdf_btn.click(
1156
  fn=generate_pdf_report,
1157
+ inputs=[timezone_textbox], # <--- NEW: Pass timezone_textbox
1158
  outputs=pdf_output_file,
1159
  api_name="download_pdf"
1160
  )
1161
 
1162
  docx_btn.click(
1163
  fn=generate_docx_report,
1164
+ inputs=[timezone_textbox], # <--- NEW: Pass timezone_textbox
1165
  outputs=docx_output_file,
1166
  api_name="download_docx"
1167
  )
1168
 
1169
+ # <--- NEW: JavaScript to detect and set user timezone on page load
1170
+ demo.load(
1171
+ fn=None, # No Python function needed for this part
1172
+ _js="""
1173
+ () => {
1174
+ const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
1175
+ const timezoneInput = document.getElementById('user-timezone-input');
1176
+ if (timezoneInput) {
1177
+ // Set the value directly for Gradio's internal state
1178
+ // This might require more advanced Gradio internal methods for direct binding.
1179
+ // For a simpler approach, we rely on Gradio's automatic value capture on click.
1180
+ // The key is that the input element 'user-timezone-input' itself has its value attribute updated.
1181
+ timezoneInput.value = userTimeZone;
1182
+ // For immediate visual feedback or if Gradio's internal state needs explicit update:
1183
+ // If Gradio version is new enough to support this pattern:
1184
+ // timezoneInput.dispatchEvent(new Event('input', { bubbles: true })); // Trigger change event
1185
+ }
1186
+ }
1187
+ """,
1188
+ inputs=None,
1189
+ outputs=None,
1190
+ queue=False # This JavaScript should run immediately on load
1191
+ )
1192
 
1193
  if __name__ == "__main__":
1194
  if not os.getenv("GOOGLE_API_KEY"):