RathodHarish commited on
Commit
573cc21
·
verified ·
1 Parent(s): 5963146

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -69
app.py CHANGED
@@ -1,21 +1,29 @@
1
  import gradio as gr
2
- import requests
3
  import librosa
4
  import numpy as np
5
  import os
6
  import hashlib
7
  from datetime import datetime
 
 
 
8
 
9
- # Hugging Face Inference API token (store in environment variables)
10
- HF_TOKEN = os.getenv("HF_TOKEN") # Must be set in Space secrets
 
 
 
 
 
 
11
 
12
- # Log HF_TOKEN status at startup
13
- print(f"HF_TOKEN status: {'Set' if HF_TOKEN else 'Not set'}")
14
-
15
- # Hugging Face API endpoints
16
- WHISPER_API_URL = "https://api-inference.huggingface.co/models/openai/whisper-tiny.en"
17
- SYMPTOM_API_URL = "https://api-inference.huggingface.co/models/abhirajeshbhai/symptom-2-disease-net"
18
- HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
19
 
20
  def compute_file_hash(file_path):
21
  """Compute MD5 hash of a file to check uniqueness."""
@@ -26,80 +34,49 @@ def compute_file_hash(file_path):
26
  return hash_md5.hexdigest()
27
 
28
  def transcribe_audio(audio_file):
29
- """Transcribe audio using Whisper API."""
30
- if not HF_TOKEN:
31
- error_msg = (
32
- "Error transcribing audio: HF_TOKEN not set. Please set HF_TOKEN in Space secrets at "
33
- "https://huggingface.co/spaces/your-username/HealthVoiceAnalyzer/settings. "
34
- "Generate a token with Inference API access at https://huggingface.co/settings/tokens."
35
- )
36
- print(error_msg)
37
- return error_msg
38
  try:
39
- with open(audio_file, "rb") as f:
40
- data = f.read()
41
- response = requests.post(WHISPER_API_URL, headers=HEADERS, data=data)
42
- response.raise_for_status()
43
- result = response.json()
44
- print(f"Whisper API response: {result}")
 
 
45
  transcription = result.get("text", "").strip()
 
 
 
 
 
 
 
 
46
  if not transcription:
47
  return "Transcription empty. Please provide clear audio describing symptoms in English."
48
- print(f"Transcription: {transcription}")
49
  return transcription
50
- except requests.exceptions.HTTPError as e:
51
- error_msg = f"Error transcribing audio: {str(e)}"
52
- if e.response.status_code == 401:
53
- error_msg = (
54
- "Error transcribing audio: Unauthorized. Please check HF_TOKEN in Space secrets at "
55
- "https://huggingface.co/spaces/your-username/HealthVoiceAnalyzer/settings. "
56
- "Ensure token has Inference API access (get at https://huggingface.co/settings/tokens)."
57
- )
58
- print(f"Whisper API error: {error_msg}, Status: {e.response.status_code}")
59
- return error_msg
60
  except Exception as e:
61
- error_msg = f"Error transcribing audio: {str(e)}"
62
- print(error_msg)
63
- return error_msg
64
 
65
  def analyze_symptoms(text):
66
- """Analyze symptoms using Symptom-2-Disease API."""
67
- if not HF_TOKEN:
68
- error_msg = (
69
- "Error analyzing symptoms: HF_TOKEN not set. Please set HF_TOKEN in Space secrets at "
70
- "https://huggingface.co/spaces/your-username/HealthVoiceAnalyzer/settings. "
71
- "Generate a token with Inference API access at https://huggingface.co/settings/tokens."
72
- )
73
- print(error_msg)
74
- return error_msg, 0.0
75
  try:
76
  if not text or "Error transcribing" in text:
77
  return "No valid transcription for analysis.", 0.0
78
- payload = {"inputs": text}
79
- response = requests.post(SYMPTOM_API_URL, headers=HEADERS, json=payload)
80
- response.raise_for_status()
81
- result = response.json()
82
- print(f"Symptom API response: {result}")
83
  if result and isinstance(result, list) and len(result) > 0:
84
- prediction = result[0][0]["label"]
85
- score = result[0][0]["score"]
86
  print(f"Health Prediction: {prediction}, Score: {score:.4f}")
87
  return prediction, score
88
  return "No health condition predicted", 0.0
89
- except requests.exceptions.HTTPError as e:
90
- error_msg = f"Error analyzing symptoms: {str(e)}"
91
- if e.response.status_code == 401:
92
- error_msg = (
93
- "Error analyzing symptoms: Unauthorized. Please check HF_TOKEN in Space secrets at "
94
- "https://huggingface.co/spaces/your-username/HealthVoiceAnalyzer/settings. "
95
- "Ensure token has Inference API access (get at https://huggingface.co/settings/tokens)."
96
- )
97
- print(f"Symptom API error: {error_msg}, Status: {e.response.status_code}")
98
- return error_msg, 0.0
99
  except Exception as e:
100
- error_msg = f"Error analyzing symptoms: {str(e)}"
101
- print(error_msg)
102
- return error_msg, 0.0
103
 
104
  def analyze_voice(audio_file):
105
  """Analyze voice for health indicators."""
@@ -164,7 +141,7 @@ iface = gr.Interface(
164
  inputs=gr.Audio(type="filepath", label="Record or Upload Voice"),
165
  outputs=gr.Textbox(label="Health Assessment Feedback"),
166
  title="Health Voice Analyzer",
167
- description="Record or upload a voice sample describing symptoms for preliminary health assessment. Supports English (transcription), with symptom analysis in English. Ensure HF_TOKEN is set in Space secrets."
168
  )
169
 
170
  if __name__ == "__main__":
 
1
  import gradio as gr
 
2
  import librosa
3
  import numpy as np
4
  import os
5
  import hashlib
6
  from datetime import datetime
7
+ from transformers import pipeline
8
+ import soundfile as sf
9
+ import torch
10
 
11
+ # Initialize local models
12
+ try:
13
+ # Whisper for speech-to-text (English-only)
14
+ whisper = pipeline("automatic-speech-recognition", model="openai/whisper-tiny.en", device=-1) # CPU; use device=0 for GPU
15
+ print("Whisper model loaded successfully.")
16
+ except Exception as e:
17
+ print(f"Failed to load Whisper model: {str(e)}")
18
+ whisper = None
19
 
20
+ try:
21
+ # Symptom-2-Disease for health analysis
22
+ symptom_classifier = pipeline("text-classification", model="abhirajeshbhai/symptom-2-disease-net", device=-1) # CPU
23
+ print("Symptom-2-Disease model loaded successfully.")
24
+ except Exception as e:
25
+ print(f"Failed to load Symptom-2-Disease model: {str(e)}")
26
+ symptom_classifier = None
27
 
28
  def compute_file_hash(file_path):
29
  """Compute MD5 hash of a file to check uniqueness."""
 
34
  return hash_md5.hexdigest()
35
 
36
  def transcribe_audio(audio_file):
37
+ """Transcribe audio using local Whisper model."""
38
+ if not whisper:
39
+ return "Error: Whisper model not loaded. Check logs for details."
 
 
 
 
 
 
40
  try:
41
+ # Load and resample audio to 16,000 Hz
42
+ audio, sr = librosa.load(audio_file, sr=16000)
43
+ # Save as WAV for Whisper compatibility
44
+ temp_wav = f"/tmp/{os.path.basename(audio_file)}.wav"
45
+ sf.write(temp_wav, audio, sr)
46
+
47
+ # Transcribe
48
+ result = whisper(temp_wav)
49
  transcription = result.get("text", "").strip()
50
+ print(f"Transcription: {transcription}")
51
+
52
+ # Clean up temp file
53
+ try:
54
+ os.remove(temp_wav)
55
+ except Exception:
56
+ pass
57
+
58
  if not transcription:
59
  return "Transcription empty. Please provide clear audio describing symptoms in English."
 
60
  return transcription
 
 
 
 
 
 
 
 
 
 
61
  except Exception as e:
62
+ return f"Error transcribing audio: {str(e)}"
 
 
63
 
64
  def analyze_symptoms(text):
65
+ """Analyze symptoms using local Symptom-2-Disease model."""
66
+ if not symptom_classifier:
67
+ return "Error: Symptom-2-Disease model not loaded. Check logs for details.", 0.0
 
 
 
 
 
 
68
  try:
69
  if not text or "Error transcribing" in text:
70
  return "No valid transcription for analysis.", 0.0
71
+ result = symptom_classifier(text)
 
 
 
 
72
  if result and isinstance(result, list) and len(result) > 0:
73
+ prediction = result[0]["label"]
74
+ score = result[0]["score"]
75
  print(f"Health Prediction: {prediction}, Score: {score:.4f}")
76
  return prediction, score
77
  return "No health condition predicted", 0.0
 
 
 
 
 
 
 
 
 
 
78
  except Exception as e:
79
+ return f"Error analyzing symptoms: {str(e)}", 0.0
 
 
80
 
81
  def analyze_voice(audio_file):
82
  """Analyze voice for health indicators."""
 
141
  inputs=gr.Audio(type="filepath", label="Record or Upload Voice"),
142
  outputs=gr.Textbox(label="Health Assessment Feedback"),
143
  title="Health Voice Analyzer",
144
+ description="Record or upload a voice sample describing symptoms for preliminary health assessment. Supports English (transcription), with symptom analysis in English."
145
  )
146
 
147
  if __name__ == "__main__":