norhan12 commited on
Commit
0ffccd7
·
1 Parent(s): 95ff6a9

project setup with multi-URL API

Browse files
Files changed (1) hide show
  1. process_interview.py +38 -18
process_interview.py CHANGED
@@ -19,12 +19,13 @@ from typing import Dict, List, Tuple
19
  import logging
20
  # --- Imports for enhanced PDF ---
21
  from reportlab.lib.pagesizes import letter
22
- from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
 
23
  from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
24
  from reportlab.lib.units import inch
25
  from reportlab.lib import colors
26
- import matplotlib.pyplot as plt # تم تفعيله للـ charts
27
- from reportlab.platypus import Image # تم تفعيله للـ charts
28
  # --- End Imports for enhanced PDF ---
29
  from transformers import AutoTokenizer, AutoModel
30
  import spacy
@@ -153,7 +154,7 @@ def extract_prosodic_features(audio_path: str, start_ms: int, end_ms: int) -> Di
153
  except Exception as e:
154
  logger.error(f"Feature extraction failed: {str(e)}")
155
  return {
156
- 'duration': (end_ms - start_ms) / 1000,
157
  'mean_pitch': 0.0,
158
  'min_pitch': 0.0,
159
  'max_pitch': 0.0,
@@ -488,10 +489,27 @@ def generate_voice_interpretation(analysis: Dict) -> str:
488
  return "\n".join(interpretation_lines)
489
 
490
 
491
- # --- Chart Generation Function (REMOVED) ---
492
- # This function is no longer included in this final version to avoid matplotlib/Image dependencies.
493
- # def generate_anxiety_confidence_chart(composite_scores: Dict, chart_path: str):
494
- # pass # Placeholder if function is called but not defined
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495
 
496
 
497
  # --- Acceptance Probability Calculation ---
@@ -758,23 +776,23 @@ def create_pdf_report(analysis_data: Dict, output_path: str, gemini_report_text:
758
  story.append(Spacer(1, 0.2 * inch))
759
 
760
  # --- Charts ---
761
- story.append(Paragraph("Score Visualization:", h3)) # Original placeholder for charts
762
  chart_path = os.path.join(OUTPUT_DIR, f"anxiety_confidence_{uuid.uuid4().hex[:8]}.png")
763
- # --- FIX: ensure matplotlib and Image are imported and generate_anxiety_confidence_chart is callable ---
764
  try:
765
- # This function call requires matplotlib and Image to be properly imported and generate_anxiety_confidence_chart to be defined.
766
- # If you want charts, make sure you have 'matplotlib' in requirements.txt.
767
- # For this response, I am assuming you DO want charts, as per your question.
768
- # The function definition is below, it will be added.
769
  generate_anxiety_confidence_chart(voice_analysis['composite_scores'], chart_path)
770
  if os.path.exists(chart_path):
771
  img = Image(chart_path, width=3.5 * inch, height=2.0 * inch)
772
  story.append(img)
773
  story.append(Spacer(1, 0.1 * inch))
774
  os.remove(chart_path)
775
- except Exception as chart_e:
776
  logger.warning(
777
- f"Could not add chart image to PDF: {chart_e}. Is matplotlib installed and the function defined correctly?")
 
 
778
  # --- End FIX ---
779
  # --- End Charts ---
780
 
@@ -800,8 +818,9 @@ def create_pdf_report(analysis_data: Dict, output_path: str, gemini_report_text:
800
  if 'Content Analysis & Strengths/Areas for Development' in sections:
801
  for line in sections['Content Analysis & Strengths/Areas for Development']:
802
  if line.strip():
 
803
  if line.strip().startswith('-'):
804
- story.append(Paragraph(line.strip(), bullet_style))
805
  else:
806
  story.append(Paragraph(line.strip(), body_text))
807
  story.append(Spacer(1, 0.2 * inch))
@@ -822,8 +841,9 @@ def create_pdf_report(analysis_data: Dict, output_path: str, gemini_report_text:
822
  if 'Actionable Recommendations' in sections:
823
  for line in sections['Actionable Recommendations']:
824
  if line.strip():
 
825
  if line.strip().startswith('-'):
826
- story.append(Paragraph(line.strip(), bullet_style))
827
  else:
828
  story.append(Paragraph(line.strip(), body_text))
829
  story.append(Spacer(1, 0.2 * inch))
 
19
  import logging
20
  # --- Imports for enhanced PDF ---
21
  from reportlab.lib.pagesizes import letter
22
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, ListFlowable, \
23
+ ListItem
24
  from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
25
  from reportlab.lib.units import inch
26
  from reportlab.lib import colors
27
+ import matplotlib.pyplot as plt # تم تفعيله
28
+ from reportlab.platypus import Image # تم تفعيله
29
  # --- End Imports for enhanced PDF ---
30
  from transformers import AutoTokenizer, AutoModel
31
  import spacy
 
154
  except Exception as e:
155
  logger.error(f"Feature extraction failed: {str(e)}")
156
  return {
157
+ 'duration': 0.0, # Return 0.0 for duration on error to prevent issues
158
  'mean_pitch': 0.0,
159
  'min_pitch': 0.0,
160
  'max_pitch': 0.0,
 
489
  return "\n".join(interpretation_lines)
490
 
491
 
492
+ # --- Chart Generation Function ---
493
+ def generate_anxiety_confidence_chart(composite_scores: Dict, chart_path: str):
494
+ try:
495
+ labels = ['Anxiety', 'Confidence']
496
+ scores = [composite_scores.get('anxiety', 0), composite_scores.get('confidence', 0)]
497
+
498
+ fig, ax = plt.subplots(figsize=(4, 2.5)) # Smaller size for embedding in PDF
499
+ ax.bar(labels, scores, color=['lightcoral', 'lightskyblue'])
500
+ ax.set_ylabel('Score')
501
+ ax.set_title('Anxiety vs. Confidence Scores')
502
+ ax.set_ylim(0, 1.0) # Assuming scores are normalized 0-1
503
+
504
+ for i, v in enumerate(scores):
505
+ ax.text(i, v + 0.05, f"{v:.2f}", color='black', ha='center', fontweight='bold')
506
+
507
+ # هذه الأوامر يجب أن تكون خارج الـ loop عشان يتم تنفيذها مرة واحدة بعد رسم كل العناصر
508
+ plt.tight_layout()
509
+ plt.savefig(chart_path)
510
+ plt.close(fig) # Close the figure to free up memory
511
+ except Exception as e:
512
+ logger.error(f"Error generating chart: {str(e)}")
513
 
514
 
515
  # --- Acceptance Probability Calculation ---
 
776
  story.append(Spacer(1, 0.2 * inch))
777
 
778
  # --- Charts ---
779
+ story.append(Paragraph("Score Visualization:", h3))
780
  chart_path = os.path.join(OUTPUT_DIR, f"anxiety_confidence_{uuid.uuid4().hex[:8]}.png")
781
+ # --- FIX: Call generate_anxiety_confidence_chart if it is defined and imports are correct ---
782
  try:
783
+ # The generate_anxiety_confidence_chart function is now expected to be defined.
784
+ # It relies on matplotlib and Image (from reportlab.platypus)
 
 
785
  generate_anxiety_confidence_chart(voice_analysis['composite_scores'], chart_path)
786
  if os.path.exists(chart_path):
787
  img = Image(chart_path, width=3.5 * inch, height=2.0 * inch)
788
  story.append(img)
789
  story.append(Spacer(1, 0.1 * inch))
790
  os.remove(chart_path)
791
+ except NameError: # Catch NameError if function is truly not defined
792
  logger.warning(
793
+ "Chart generation function 'generate_anxiety_confidence_chart' is not defined. Skipping chart.")
794
+ except Exception as chart_e:
795
+ logger.warning(f"Could not add chart image to PDF: {chart_e}. Please check matplotlib installation.")
796
  # --- End FIX ---
797
  # --- End Charts ---
798
 
 
818
  if 'Content Analysis & Strengths/Areas for Development' in sections:
819
  for line in sections['Content Analysis & Strengths/Areas for Development']:
820
  if line.strip():
821
+ # Handle bullet points from Gemini
822
  if line.strip().startswith('-'):
823
+ story.append(Paragraph(line.strip()[1:].strip(), bullet_style)) # Remove the '-' and strip
824
  else:
825
  story.append(Paragraph(line.strip(), body_text))
826
  story.append(Spacer(1, 0.2 * inch))
 
841
  if 'Actionable Recommendations' in sections:
842
  for line in sections['Actionable Recommendations']:
843
  if line.strip():
844
+ # Handle bullet points from Gemini
845
  if line.strip().startswith('-'):
846
+ story.append(Paragraph(line.strip()[1:].strip(), bullet_style)) # Remove the '-' and strip
847
  else:
848
  story.append(Paragraph(line.strip(), body_text))
849
  story.append(Spacer(1, 0.2 * inch))