Neom99 commited on
Commit
fc70f30
·
verified ·
1 Parent(s): 0a94f5e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -68
app.py CHANGED
@@ -14,6 +14,14 @@ import json
14
  import tempfile
15
  import pytz # Import pytz for timezone handling
16
 
 
 
 
 
 
 
 
 
17
  # --- Runtime / Environment Checks ---
18
  print(f"Gradio version at runtime: {gr.__version__}", file=sys.stderr)
19
  print(f"Python executable: {sys.executable}", file=sys.stderr)
@@ -821,33 +829,55 @@ def perform_ticket_analysis(file, user_query, selected_timezone, progress=gr.Pro
821
 
822
  # --- Output Download Functions (using global_analysis_df_for_export) ---
823
 
824
- # --- File Generation Libraries ---
825
- from fpdf import FPDF
826
- from docx import Document as DocxDocument
827
- from docx.shared import Inches, Pt
828
- from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_PARAGRAPH_ALIGNMENT
829
 
830
  def generate_pdf_report(selected_timezone):
831
  df = global_analysis_df_for_export
832
  if df.empty:
833
- return gr.update(value=None, visible=False) # Changed from gr.File.update()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
834
 
835
- pdf = FPDF()
836
  pdf.add_page()
837
 
838
- pdf.set_font("Arial", 'B', 16)
839
- pdf.cell(0, 10, "AI Customer Ticket Analysis Report", ln=True, align='C')
840
- pdf.ln(5)
 
 
 
 
841
 
842
  now_utc = datetime.utcnow()
843
  current_gen_time = format_time_for_display(now_utc, selected_timezone)
844
- pdf.set_font("Arial", size=10)
845
- pdf.cell(0, 10, f"Generated on: {current_gen_time}", ln=True, align='R')
846
- pdf.ln(10)
847
 
848
- pdf.set_font("Arial", 'B', 14)
849
- pdf.multi_cell(0, 10, "Overview & Key Insights")
850
- pdf.set_font("Arial", size=10)
851
  total_tickets_processed = df['Count'].sum() if 'Count' in df.columns else 0
852
  total_categories_identified = len(df['Category'].unique()) if 'Category' in df.columns else 0
853
 
@@ -857,102 +887,98 @@ def generate_pdf_report(selected_timezone):
857
  f"Total Tickets Summarized in Report: {total_tickets_processed}.\n"
858
  f"Total Categories Identified: {total_categories_identified}."
859
  )
860
- pdf.multi_cell(0, 7, overview_text)
861
- pdf.ln(10)
862
 
863
- pdf.set_font("Arial", 'B', 14)
864
- pdf.multi_cell(0, 10, "Aggregated Issue Summaries")
865
- pdf.ln(5)
866
 
867
- # Ensure required columns are present before iteration (handled in generate_summary_html_by_category)
868
- # The dataframe should already be prepared from the analysis step.
869
-
870
  for category, category_df in df.groupby('Category'):
871
  total_count = category_df['Count'].sum()
872
 
873
  pdf.set_fill_color(220, 237, 200) # Light Green
874
  pdf.set_text_color(76, 175, 80) # Dark Green
875
- pdf.set_font("Arial", 'B', 12)
876
- pdf.multi_cell(0, 8, f"{category} ({total_count})", 0, 'L', 1)
877
- pdf.ln(2)
878
 
879
  pdf.set_text_color(0, 0, 0) # Black
880
- pdf.set_font("Arial", 'B', 10)
881
- pdf.multi_cell(0, 7, "Summary:")
882
- pdf.set_font("Arial", size=9)
883
  unique_issues = category_df['Issue Description (Summary)'].astype(str).drop_duplicates().apply(lambda x: x.replace('*', '')).tolist()
884
  for issue in unique_issues:
885
- pdf.multi_cell(0, 6, f"• {issue}", 0, 'L')
886
- if not unique_issues: pdf.multi_cell(0, 6, "• No specific summary available.", 0, 'L')
887
- pdf.ln(2)
888
 
889
- pdf.set_font("Arial", 'B', 10)
890
- pdf.multi_cell(0, 7, "Sub-Categories:")
891
- pdf.set_font("Arial", size=9)
892
  if 'Sub-Category' in category_df.columns:
893
  sub_cat_counts = category_df.groupby('Sub-Category')['Count'].sum().sort_values(ascending=False)
894
  for sub_cat, count in sub_cat_counts.items():
895
- pdf.multi_cell(0, 6, f"• {sub_cat} (Count: {count})", 0, 'L')
896
- if 'Sub-Category' not in category_df.columns or sub_cat_counts.empty: pdf.multi_cell(0, 6, "• No sub-categories identified.", 0, 'L')
897
- pdf.ln(2)
898
 
899
- pdf.set_font("Arial", 'B', 10)
900
- pdf.multi_cell(0, 7, "Root Cause:")
901
- pdf.set_font("Arial", size=9)
902
  unique_root_causes = category_df['Root Cause (Inferred)'].astype(str).drop_duplicates().apply(lambda x: x.replace('*', '')).tolist()
903
  for rc in unique_root_causes:
904
- pdf.multi_cell(0, 6, f"• {rc}", 0, 'L')
905
- if not unique_root_causes: pdf.multi_cell(0, 6, "• Undetermined.", 0, 'L')
906
- pdf.ln(2)
907
 
908
- pdf.set_font("Arial", 'B', 10)
909
- pdf.multi_cell(0, 7, "Resolution Steps:")
910
- pdf.set_font("Arial", size=9)
911
  unique_resolutions = category_df['Potential Resolution Steps'].astype(str).drop_duplicates().apply(lambda x: x.replace('*', '')).tolist()
912
  for res in unique_resolutions:
913
- pdf.multi_cell(0, 6, f"• {res}", 0, 'L')
914
- if not unique_resolutions: pdf.multi_cell(0, 6, "• No specific steps identified.", 0, 'L')
915
- pdf.ln(2)
916
 
917
- pdf.set_font("Arial", 'B', 10)
918
- pdf.multi_cell(0, 7, "Future Prediction & Proactive Measures:")
919
- pdf.set_font("Arial", size=9)
920
  future_predictions = category_df['Future Prediction'].astype(str).drop_duplicates().apply(lambda x: x.replace('*', '')).tolist()
921
  proactive_measures = category_df['Proactive Measures'].astype(str).drop_duplicates().apply(lambda x: x.replace('*', '')).tolist()
922
 
923
  if future_predictions:
924
  pdf.set_text_color(141, 110, 99) # Brownish
925
- pdf.multi_cell(0, 6, f"• Future Prediction: {'; '.join(future_predictions)}", 0, 'L')
926
  if proactive_measures:
927
  pdf.set_text_color(141, 110, 99) # Brownish
928
- pdf.multi_cell(0, 6, f"• Proactive Measures: {'; '.join(proactive_measures)}", 0, 'L')
929
  if not future_predictions and not proactive_measures:
930
  pdf.set_text_color(0, 0, 0) # Black
931
- pdf.multi_cell(0, 6, "• No future prediction or proactive measures identified.", 0, 'L')
932
- pdf.ln(5)
933
 
934
  pdf.set_text_color(0, 0, 0)
935
  pdf.set_fill_color(241, 248, 233)
936
- pdf.set_font("Arial", 'B', 12)
937
  pdf.multi_cell(0, 10, "Disclaimer", 0, 'L', 1)
938
- pdf.ln(2)
939
- pdf.set_font("Arial", size=9)
940
- pdf.multi_cell(0, 6, "*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.")
941
- pdf.ln(2)
942
- pdf.multi_cell(0, 6, f"Report generated on: {current_gen_time}")
943
-
944
 
945
  with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
946
  pdf.output(tmp_file.name)
947
  temp_file_path = tmp_file.name
948
 
949
- return gr.update(value=temp_file_path, visible=True, label="Download PDF Report") # Changed from gr.File.update()
950
 
951
 
952
  def generate_docx_report(selected_timezone):
953
  df = global_analysis_df_for_export
954
  if df.empty:
955
- return gr.update(value=None, visible=False) # Changed from gr.File.update()
956
 
957
  doc = DocxDocument()
958
 
@@ -1045,7 +1071,7 @@ def generate_docx_report(selected_timezone):
1045
  doc.save(tmp_file)
1046
  temp_file_path = tmp_file.name
1047
 
1048
- return gr.update(value=temp_file_path, visible=True, label="Download Word Report") # Changed from gr.File.update()
1049
 
1050
 
1051
  # --- Gradio Interface Setup ---
 
14
  import tempfile
15
  import pytz # Import pytz for timezone handling
16
 
17
+ # --- Import fpdf2 instead of fpdf ---
18
+ from fpdf2 import FPDF
19
+ # --- End fpdf2 import ---
20
+
21
+ from docx import Document as DocxDocument
22
+ from docx.shared import Inches, Pt
23
+ from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_PARAGRAPH_ALIGNMENT
24
+
25
  # --- Runtime / Environment Checks ---
26
  print(f"Gradio version at runtime: {gr.__version__}", file=sys.stderr)
27
  print(f"Python executable: {sys.executable}", file=sys.stderr)
 
829
 
830
  # --- Output Download Functions (using global_analysis_df_for_export) ---
831
 
 
 
 
 
 
832
 
833
  def generate_pdf_report(selected_timezone):
834
  df = global_analysis_df_for_export
835
  if df.empty:
836
+ return gr.update(value=None, visible=False)
837
+
838
+ # Initialize FPDF with UTF-8 encoding (fpdf2 handles this implicitly better)
839
+ pdf = FPDF(unit="pt", format="A4")
840
+
841
+ # Add a Unicode font (DejaVuSans.ttf is a good choice for broad character support)
842
+ # Make sure 'DejaVuSans.ttf' is in the same directory as your script
843
+ # Or provide the full path to the .ttf file
844
+ try:
845
+ pdf.add_font('DejaVu', '', 'DejaVuSans.ttf', uni=True)
846
+ # Verify font was added
847
+ if 'DejaVu' not in pdf.fonts:
848
+ raise RuntimeError("DejaVu font not registered properly.")
849
+ except RuntimeError as e:
850
+ print(f"Warning: Problem loading DejaVuSans.ttf: {e}. Falling back to Arial for PDF generation.", file=sys.stderr)
851
+ # Fallback for font if DejaVu fails
852
+ def set_default_font():
853
+ pdf.set_font("Arial", size=12)
854
+ pdf.set_font_method = set_default_font # Override set_font to use Arial fallback
855
+ except Exception as e:
856
+ print(f"An unexpected error occurred while adding font: {e}. Falling back to Arial.", file=sys.stderr)
857
+ def set_default_font():
858
+ pdf.set_font("Arial", size=12)
859
+ pdf.set_font_method = set_default_font # Override set_font to use Arial fallback
860
+
861
 
 
862
  pdf.add_page()
863
 
864
+ # Use the Unicode font if it was successfully loaded, otherwise Arial
865
+ font_name_bold = "DejaVu" if 'DejaVu' in pdf.fonts else "Arial"
866
+ font_name_regular = "DejaVu" if 'DejaVu' in pdf.fonts else "Arial"
867
+
868
+ pdf.set_font(font_name_bold, 'B', 16)
869
+ pdf.cell(0, 20, "AI Customer Ticket Analysis Report", ln=True, align='C')
870
+ pdf.ln(10)
871
 
872
  now_utc = datetime.utcnow()
873
  current_gen_time = format_time_for_display(now_utc, selected_timezone)
874
+ pdf.set_font(font_name_regular, size=10)
875
+ pdf.cell(0, 15, f"Generated on: {current_gen_time}", ln=True, align='R')
876
+ pdf.ln(15)
877
 
878
+ pdf.set_font(font_name_bold, 'B', 14)
879
+ pdf.multi_cell(0, 15, "Overview & Key Insights")
880
+ pdf.set_font(font_name_regular, size=10)
881
  total_tickets_processed = df['Count'].sum() if 'Count' in df.columns else 0
882
  total_categories_identified = len(df['Category'].unique()) if 'Category' in df.columns else 0
883
 
 
887
  f"Total Tickets Summarized in Report: {total_tickets_processed}.\n"
888
  f"Total Categories Identified: {total_categories_identified}."
889
  )
890
+ pdf.multi_cell(0, 10, overview_text)
891
+ pdf.ln(15)
892
 
893
+ pdf.set_font(font_name_bold, 'B', 14)
894
+ pdf.multi_cell(0, 15, "Aggregated Issue Summaries")
895
+ pdf.ln(10)
896
 
 
 
 
897
  for category, category_df in df.groupby('Category'):
898
  total_count = category_df['Count'].sum()
899
 
900
  pdf.set_fill_color(220, 237, 200) # Light Green
901
  pdf.set_text_color(76, 175, 80) # Dark Green
902
+ pdf.set_font(font_name_bold, 'B', 12)
903
+ pdf.multi_cell(0, 12, f"{category} ({total_count})", 0, 'L', 1)
904
+ pdf.ln(5)
905
 
906
  pdf.set_text_color(0, 0, 0) # Black
907
+ pdf.set_font(font_name_bold, 'B', 10)
908
+ pdf.multi_cell(0, 10, "Summary:")
909
+ pdf.set_font(font_name_regular, size=9)
910
  unique_issues = category_df['Issue Description (Summary)'].astype(str).drop_duplicates().apply(lambda x: x.replace('*', '')).tolist()
911
  for issue in unique_issues:
912
+ pdf.multi_cell(0, 9, f"\u2022 {issue}", 0, 'L')
913
+ if not unique_issues: pdf.multi_cell(0, 9, "\u2022 No specific summary available.", 0, 'L')
914
+ pdf.ln(5)
915
 
916
+ pdf.set_font(font_name_bold, 'B', 10)
917
+ pdf.multi_cell(0, 10, "Sub-Categories:")
918
+ pdf.set_font(font_name_regular, size=9)
919
  if 'Sub-Category' in category_df.columns:
920
  sub_cat_counts = category_df.groupby('Sub-Category')['Count'].sum().sort_values(ascending=False)
921
  for sub_cat, count in sub_cat_counts.items():
922
+ pdf.multi_cell(0, 9, f"\u2022 {sub_cat} (Count: {count})", 0, 'L')
923
+ if 'Sub-Category' not in category_df.columns or sub_cat_counts.empty: pdf.multi_cell(0, 9, "\u2022 No sub-categories identified.", 0, 'L')
924
+ pdf.ln(5)
925
 
926
+ pdf.set_font(font_name_bold, 'B', 10)
927
+ pdf.multi_cell(0, 10, "Root Cause:")
928
+ pdf.set_font(font_name_regular, size=9)
929
  unique_root_causes = category_df['Root Cause (Inferred)'].astype(str).drop_duplicates().apply(lambda x: x.replace('*', '')).tolist()
930
  for rc in unique_root_causes:
931
+ pdf.multi_cell(0, 9, f"\u2022 {rc}", 0, 'L')
932
+ if not unique_root_causes: pdf.multi_cell(0, 9, "\u2022 Undetermined.", 0, 'L')
933
+ pdf.ln(5)
934
 
935
+ pdf.set_font(font_name_bold, 'B', 10)
936
+ pdf.multi_cell(0, 10, "Resolution Steps:")
937
+ pdf.set_font(font_name_regular, size=9)
938
  unique_resolutions = category_df['Potential Resolution Steps'].astype(str).drop_duplicates().apply(lambda x: x.replace('*', '')).tolist()
939
  for res in unique_resolutions:
940
+ pdf.multi_cell(0, 9, f"\u2022 {res}", 0, 'L')
941
+ if not unique_resolutions: pdf.multi_cell(0, 9, "\u2022 No specific steps identified.", 0, 'L')
942
+ pdf.ln(5)
943
 
944
+ pdf.set_font(font_name_bold, 'B', 10)
945
+ pdf.multi_cell(0, 10, "Future Prediction & Proactive Measures:")
946
+ pdf.set_font(font_name_regular, size=9)
947
  future_predictions = category_df['Future Prediction'].astype(str).drop_duplicates().apply(lambda x: x.replace('*', '')).tolist()
948
  proactive_measures = category_df['Proactive Measures'].astype(str).drop_duplicates().apply(lambda x: x.replace('*', '')).tolist()
949
 
950
  if future_predictions:
951
  pdf.set_text_color(141, 110, 99) # Brownish
952
+ pdf.multi_cell(0, 9, f"\u2022 Future Prediction: {'; '.join(future_predictions)}", 0, 'L')
953
  if proactive_measures:
954
  pdf.set_text_color(141, 110, 99) # Brownish
955
+ pdf.multi_cell(0, 9, f"\u2022 Proactive Measures: {'; '.join(proactive_measures)}", 0, 'L')
956
  if not future_predictions and not proactive_measures:
957
  pdf.set_text_color(0, 0, 0) # Black
958
+ pdf.multi_cell(0, 9, "\u2022 No future prediction or proactive measures identified.", 0, 'L')
959
+ pdf.ln(10)
960
 
961
  pdf.set_text_color(0, 0, 0)
962
  pdf.set_fill_color(241, 248, 233)
963
+ pdf.set_font(font_name_bold, 'B', 12)
964
  pdf.multi_cell(0, 10, "Disclaimer", 0, 'L', 1)
965
+ pdf.ln(5)
966
+ pdf.set_font(font_name_regular, size=9)
967
+ pdf.multi_cell(0, 8, "*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.")
968
+ pdf.ln(5)
969
+ pdf.multi_cell(0, 8, f"Report generated on: {current_gen_time}")
 
970
 
971
  with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
972
  pdf.output(tmp_file.name)
973
  temp_file_path = tmp_file.name
974
 
975
+ return gr.update(value=temp_file_path, visible=True, label="Download PDF Report")
976
 
977
 
978
  def generate_docx_report(selected_timezone):
979
  df = global_analysis_df_for_export
980
  if df.empty:
981
+ return gr.update(value=None, visible=False)
982
 
983
  doc = DocxDocument()
984
 
 
1071
  doc.save(tmp_file)
1072
  temp_file_path = tmp_file.name
1073
 
1074
+ return gr.update(value=temp_file_path, visible=True, label="Download Word Report")
1075
 
1076
 
1077
  # --- Gradio Interface Setup ---