RathodHarish commited on
Commit
a3fd656
·
verified ·
1 Parent(s): c3268d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -50
app.py CHANGED
@@ -160,20 +160,22 @@ def analyze_symptoms(text, features):
160
  text = text.lower() if text else ""
161
 
162
  # Voice-based health assessment
163
- if features["jitter"] > 2.0 or features["shimmer"] > 3.0:
164
- feedback.append("Your voice shows signs of irregularity (high jitter or shimmer), which may indicate respiratory or vocal strain. Consider a medical evaluation.")
 
 
165
  if features["energy"] < 0.01:
166
- feedback.append("Low vocal energy detected, which might suggest fatigue or low mood. Rest and professional consultation are recommended.")
167
  if features["pitch"] < 100 or features["pitch"] > 250:
168
- feedback.append(f"Unusual pitch range ({features['pitch']:.2f} Hz) detected, which could indicate vocal cord issues or emotional stress.")
169
  if features["spectral_centroid"] > 2000:
170
- feedback.append("High spectral centroid suggests tense or strained speech, possibly linked to stress or anxiety.")
171
 
172
  # Text-based symptom analysis
173
  if "cough" in text or "breath" in text:
174
  feedback.append("Your description suggests respiratory symptoms. Possible conditions include bronchitis or asthma. Please consult a doctor.")
175
  if "stress" in text or "anxious" in text:
176
- feedback.append("You mentioned stress or anxiety. Try deep breathing exercises or mindfulness. Consider speaking with a mental health professional.")
177
  if "pain" in text:
178
  feedback.append("Pain reported. For mild pain, consider Paracetamol; for inflammation, Ibuprofen may help. Consult a doctor before taking medication.")
179
  if not feedback:
@@ -215,56 +217,62 @@ def store_user_consent(language):
215
 
216
  def generate_pdf_report(feedback, transcription, features, language):
217
  try:
 
218
  feedback = feedback.replace('&', '\\&').replace('%', '\\%').replace('$', '\\$').replace('#', '\\#')
219
  transcription = transcription.replace('&', '\\&').replace('%', '\\%').replace('$', '\\$').replace('#', '\\#') if transcription else "None"
220
  email = DEFAULT_EMAIL.replace('&', '\\&').replace('%', '\\%').replace('$', '\\$').replace('#', '\\#')
221
- latex_content = f"""
222
- \\documentclass[a4paper,12pt]{{article}}
223
- \\usepackage[utf8]{{inputenc}}
224
- \\usepackage{{geometry}}
225
- \\usepackage{{parskip}}
226
- \\usepackage{{titlesec}}
227
- \\usepackage{{times}}
228
- \\geometry{{margin=1in}}
229
- \\titleformat{{\\section}}{{\\large\\bfseries}}{{\\thesection}}{{1em}}{{}}
230
- \\titleformat{{\\subsection}}{{\\bfseries}}{{\\thesubsection}}{{1em}}{{}}
231
- \\usepackage{{datetime}}
232
- \\newdateformat{{isodate}}{{\\THEDAY{ }\\shortmonthname[\\THEMONTH] \\THEYEAR}}
233
- \\begin{{document}}
234
- \\begin{{center}}
235
- \\textbf{{\\large MindCare Health Assistant Report}} \\\\
236
- \\vspace{{0.5cm}}
237
- Generated on \\isodate\\today\\ at \\currenttime
238
- \\end{{center}}
239
- \\section*{{User Information}}
240
- \\begin{{itemize}}
241
- \\item \\textbf{{Email}}: {email}
242
- \\item \\textbf{{Language}}: {SALESFORCE_LANGUAGE_MAP.get(language, "English")}
243
- \\end{{itemize}}
244
- \\section*{{Voice Analysis Results}}
245
- \\subsection*{{Health Assessment}}
246
- {feedback}
247
- \\subsection*{{Transcription}}
248
- {transcription}
249
- \\subsection*{{Voice Metrics}}
250
- \\begin{{itemize}}
251
- \\item \\textbf{{Pitch}}: {features['pitch']:.2f} Hz
252
- \\item \\textbf{{Jitter}}: {features['jitter']:.2f}\\%
253
- \\item \\textbf{{Shimmer}}: {features['shimmer']:.2f}\\%
254
- \\item \\textbf{{Energy}}: {features['energy']:.4f}
255
- \\item \\textbf{{MFCC Mean}}: {features['mfcc_mean']:.2f}
256
- \\item \\textbf{{Spectral Centroid}}: {features['spectral_centroid']:.2f} Hz
257
- \\end{{itemize}}
258
- \\section*{{Disclaimer}}
259
- This report is a preliminary analysis and not a medical diagnosis. Always consult a healthcare provider.
260
- \\end{{document}}
261
- """
 
 
 
262
  with tempfile.NamedTemporaryFile(delete=False, suffix=".tex") as tex_file:
263
  tex_file.write(latex_content.encode('utf-8'))
264
  tex_file_path = tex_file.name
265
  pdf_path = tex_file_path.replace('.tex', '.pdf')
266
- result = subprocess.run(['latexmk', '-pdf', '-pdflatex=pdflatex', '-interaction=nonstopmode', tex_file_path],
267
- capture_output=True, text=True, check=True)
 
 
268
  logger.info(f"PDF generation output: {result.stdout}")
269
  for ext in ['.aux', '.log', '.out', '.fls', '.fdb_latexmk']:
270
  try:
@@ -281,7 +289,7 @@ This report is a preliminary analysis and not a medical diagnosis. Always consul
281
  logger.error(f"PDF generation failed: {e.stderr}")
282
  return None
283
  except Exception as e:
284
- logger.error(f"PDF generation failed: {str(e)}")
285
  return None
286
 
287
  def store_in_salesforce(user_id, audio_file, feedback, respiratory_score, mental_health_score, features, transcription, language):
 
160
  text = text.lower() if text else ""
161
 
162
  # Voice-based health assessment
163
+ if features["jitter"] > 2.0:
164
+ feedback.append(f"Elevated jitter ({features['jitter']:.2f}%) detected, which may indicate respiratory strain or vocal cord issues. Consult a doctor.")
165
+ if features["shimmer"] > 3.0:
166
+ feedback.append(f"High shimmer ({features['shimmer']:.2f}%) suggests possible emotional stress or vocal fatigue. Consider professional evaluation.")
167
  if features["energy"] < 0.01:
168
+ feedback.append(f"Low vocal energy ({features['energy']:.4f}) detected, which might indicate fatigue or low mood. Rest and medical advice recommended.")
169
  if features["pitch"] < 100 or features["pitch"] > 250:
170
+ feedback.append(f"Unusual pitch ({features['pitch']:.2f} Hz) may indicate vocal cord issues or emotional stress.")
171
  if features["spectral_centroid"] > 2000:
172
+ feedback.append(f"High spectral centroid ({features['spectral_centroid']:.2f} Hz) suggests tense speech, possibly linked to stress or anxiety.")
173
 
174
  # Text-based symptom analysis
175
  if "cough" in text or "breath" in text:
176
  feedback.append("Your description suggests respiratory symptoms. Possible conditions include bronchitis or asthma. Please consult a doctor.")
177
  if "stress" in text or "anxious" in text:
178
+ feedback.append("You mentioned stress or anxiety. Try deep breathing or mindfulness. Consider speaking with a mental health professional.")
179
  if "pain" in text:
180
  feedback.append("Pain reported. For mild pain, consider Paracetamol; for inflammation, Ibuprofen may help. Consult a doctor before taking medication.")
181
  if not feedback:
 
217
 
218
  def generate_pdf_report(feedback, transcription, features, language):
219
  try:
220
+ # Sanitize inputs for LaTeX
221
  feedback = feedback.replace('&', '\\&').replace('%', '\\%').replace('$', '\\$').replace('#', '\\#')
222
  transcription = transcription.replace('&', '\\&').replace('%', '\\%').replace('$', '\\$').replace('#', '\\#') if transcription else "None"
223
  email = DEFAULT_EMAIL.replace('&', '\\&').replace('%', '\\%').replace('$', '\\$').replace('#', '\\#')
224
+ language_display = SALESFORCE_LANGUAGE_MAP.get(language, "English")
225
+
226
+ latex_content = (
227
+ "\\documentclass[a4paper,12pt]{article}\n"
228
+ "\\usepackage[utf8]{inputenc}\n"
229
+ "\\usepackage{geometry}\n"
230
+ "\\usepackage{parskip}\n"
231
+ "\\usepackage{titlesec}\n"
232
+ "\\usepackage{times}\n"
233
+ "\\usepackage{datetime}\n"
234
+ "\\newdateformat{isodate}{\\THEDAY{} \\shortmonthname[\\THEMONTH] \\THEYEAR}\n"
235
+ "\\geometry{margin=1in}\n"
236
+ "\\titleformat{\\section}{\\large\\bfseries}{\\thesection}{1em}{}\n"
237
+ "\\titleformat{\\subsection}{\\bfseries}{\\thesubsection}{1em}{}\n"
238
+ "\\begin{document}\n"
239
+ "\\begin{center}\n"
240
+ " \\textbf{\\large MindCare Health Assistant Report} \\\\\n"
241
+ " \\vspace{0.5cm}\n"
242
+ " Generated on \\isodate\\today\\ at \\currenttime\n"
243
+ "\\end{center}\n"
244
+ "\\section*{User Information}\n"
245
+ "\\begin{itemize}\n"
246
+ f" \\item \\textbf{{Email}}: {email}\n"
247
+ f" \\item \\textbf{{Language}}: {language_display}\n"
248
+ "\\end{itemize}\n"
249
+ "\\section*{Voice Analysis Results}\n"
250
+ "\\subsection*{Health Assessment}\n"
251
+ f"{feedback}\n"
252
+ "\\subsection*{Transcription}\n"
253
+ f"{transcription}\n"
254
+ "\\subsection*{Voice Metrics}\n"
255
+ "\\begin{itemize}\n"
256
+ f" \\item \\textbf{{Pitch}}: {features['pitch']:.2f} Hz\n"
257
+ f" \\item \\textbf{{Jitter}}: {features['jitter']:.2f}\\%\n"
258
+ f" \\item \\textbf{{Shimmer}}: {features['shimmer']:.2f}\\%\n"
259
+ f" \\item \\textbf{{Energy}}: {features['energy']:.4f}\n"
260
+ f" \\item \\textbf{{MFCC Mean}}: {features['mfcc_mean']:.2f}\n"
261
+ f" \\item \\textbf{{Spectral Centroid}}: {features['spectral_centroid']:.2f} Hz\n"
262
+ "\\end{itemize}\n"
263
+ "\\section*{Disclaimer}\n"
264
+ "This report is a preliminary analysis and not a medical diagnosis. Always consult a healthcare provider.\n"
265
+ "\\end{document}\n"
266
+ )
267
+
268
  with tempfile.NamedTemporaryFile(delete=False, suffix=".tex") as tex_file:
269
  tex_file.write(latex_content.encode('utf-8'))
270
  tex_file_path = tex_file.name
271
  pdf_path = tex_file_path.replace('.tex', '.pdf')
272
+ result = subprocess.run(
273
+ ['latexmk', '-pdf', '-pdflatex=pdflatex', '-interaction=nonstopmode', tex_file_path],
274
+ capture_output=True, text=True, check=True
275
+ )
276
  logger.info(f"PDF generation output: {result.stdout}")
277
  for ext in ['.aux', '.log', '.out', '.fls', '.fdb_latexmk']:
278
  try:
 
289
  logger.error(f"PDF generation failed: {e.stderr}")
290
  return None
291
  except Exception as e:
292
+ logger.error(f"PDF generation failed: { five(str(e))}")
293
  return None
294
 
295
  def store_in_salesforce(user_id, audio_file, feedback, respiratory_score, mental_health_score, features, transcription, language):