RathodHarish commited on
Commit
432d77e
·
verified ·
1 Parent(s): a6dea81

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -13
app.py CHANGED
@@ -8,10 +8,10 @@ from datetime import datetime
8
  from simple_salesforce import Salesforce
9
 
10
  # Salesforce credentials (store securely in environment variables)
11
- SF_USERNAME = os.getenv("SF_USERNAME", "your_salesforce_username")
12
- SF_PASSWORD = os.getenv("SF_PASSWORD", "your_salesforce_password")
13
- SF_SECURITY_TOKEN = os.getenv("SF_SECURITY_TOKEN", "your_salesforce_security_token")
14
- SF_INSTANCE_URL = os.getenv("SF_INSTANCE_URL", "https://your-salesforce-instance.salesforce.com")
15
 
16
  # Hugging Face Inference API token (store in environment variables)
17
  HF_TOKEN = os.getenv("HF_TOKEN", "your_huggingface_token")
@@ -49,16 +49,23 @@ def transcribe_audio(audio_file):
49
  response = requests.post(WHISPER_API_URL, headers=HEADERS, data=data)
50
  response.raise_for_status()
51
  result = response.json()
52
- transcription = result.get("text", "")
 
 
53
  print(f"Transcription: {transcription}")
54
  return transcription
 
 
 
 
55
  except Exception as e:
56
- print(f"Whisper API error: {str(e)}")
57
  return f"Error transcribing audio: {str(e)}"
58
 
59
  def analyze_symptoms(text):
60
  """Analyze symptoms using Symptom-2-Disease API."""
61
  try:
 
 
62
  payload = {"inputs": text}
63
  response = requests.post(SYMPTOM_API_URL, headers=HEADERS, json=payload)
64
  response.raise_for_status()
@@ -69,13 +76,21 @@ def analyze_symptoms(text):
69
  print(f"Health Prediction: {prediction}, Score: {score:.4f}")
70
  return prediction, score
71
  return "No health condition predicted", 0.0
 
 
 
 
72
  except Exception as e:
73
- print(f"Symptom API error: {str(e)}")
74
  return f"Error analyzing symptoms: {str(e)}", 0.0
75
 
76
  def analyze_voice(audio_file):
77
  """Analyze voice for health indicators."""
78
  try:
 
 
 
 
 
79
  # Log audio file info
80
  file_hash = compute_file_hash(audio_file)
81
  print(f"Processing audio file: {audio_file}, Hash: {file_hash}")
@@ -133,11 +148,15 @@ def store_in_salesforce(audio_file, feedback, transcription, prediction, score):
133
  print(f"Failed to store in Salesforce: {str(e)}")
134
 
135
  def test_with_sample_audio():
136
- """Test the app with a sample audio file."""
137
- sample_audio_path = "audio_samples/sample.wav"
138
- if os.path.exists(sample_audio_path):
139
- return analyze_voice(sample_audio_path)
140
- return "Sample audio file not found."
 
 
 
 
141
 
142
  # Gradio interface
143
  iface = gr.Interface(
@@ -145,7 +164,7 @@ iface = gr.Interface(
145
  inputs=gr.Audio(type="filepath", label="Record or Upload Voice"),
146
  outputs=gr.Textbox(label="Health Assessment Feedback"),
147
  title="Health Voice Analyzer",
148
- description="Record or upload a voice sample describing symptoms for preliminary health assessment. Supports English (transcription), with symptom analysis in English."
149
  )
150
 
151
  if __name__ == "__main__":
 
8
  from simple_salesforce import Salesforce
9
 
10
  # Salesforce credentials (store securely in environment variables)
11
+ SF_USERNAME = os.getenv("SF_USERNAME", "[email protected]")
12
+ SF_PASSWORD = os.getenv("SF_PASSWORD", "voicebot1")
13
+ SF_SECURITY_TOKEN = os.getenv("SF_SECURITY_TOKEN", "jq4VVHUFti6TmzJDjjegv2h6b")
14
+ SF_INSTANCE_URL = os.getenv("SF_INSTANCE_URL", "https://voicebot-dev-ed.my.salesforce.com") # Verify correct API URL
15
 
16
  # Hugging Face Inference API token (store in environment variables)
17
  HF_TOKEN = os.getenv("HF_TOKEN", "your_huggingface_token")
 
49
  response = requests.post(WHISPER_API_URL, headers=HEADERS, data=data)
50
  response.raise_for_status()
51
  result = response.json()
52
+ transcription = result.get("text", "").strip()
53
+ if not transcription:
54
+ return "Transcription empty. Please provide clear audio describing symptoms."
55
  print(f"Transcription: {transcription}")
56
  return transcription
57
+ except requests.exceptions.HTTPError as e:
58
+ if e.response.status_code == 401:
59
+ return "Error transcribing audio: Unauthorized. Please check HF_TOKEN in Space secrets at https://huggingface.co/spaces/your-username/HealthVoiceAnalyzer/settings."
60
+ return f"Error transcribing audio: {str(e)}"
61
  except Exception as e:
 
62
  return f"Error transcribing audio: {str(e)}"
63
 
64
  def analyze_symptoms(text):
65
  """Analyze symptoms using Symptom-2-Disease API."""
66
  try:
67
+ if not text or "Error transcribing" in text:
68
+ return "No valid transcription for analysis.", 0.0
69
  payload = {"inputs": text}
70
  response = requests.post(SYMPTOM_API_URL, headers=HEADERS, json=payload)
71
  response.raise_for_status()
 
76
  print(f"Health Prediction: {prediction}, Score: {score:.4f}")
77
  return prediction, score
78
  return "No health condition predicted", 0.0
79
+ except requests.exceptions.HTTPError as e:
80
+ if e.response.status_code == 401:
81
+ return "Error analyzing symptoms: Unauthorized. Please check HF_TOKEN in Space secrets at https://huggingface.co/spaces/your-username/HealthVoiceAnalyzer/settings.", 0.0
82
+ return f"Error analyzing symptoms: {str(e)}", 0.0
83
  except Exception as e:
 
84
  return f"Error analyzing symptoms: {str(e)}", 0.0
85
 
86
  def analyze_voice(audio_file):
87
  """Analyze voice for health indicators."""
88
  try:
89
+ # Ensure unique file name to avoid Gradio reuse
90
+ unique_path = f"/tmp/gradio/{datetime.now().strftime('%Y%m%d%H%M%S%f')}_{os.path.basename(audio_file)}"
91
+ os.rename(audio_file, unique_path)
92
+ audio_file = unique_path
93
+
94
  # Log audio file info
95
  file_hash = compute_file_hash(audio_file)
96
  print(f"Processing audio file: {audio_file}, Hash: {file_hash}")
 
148
  print(f"Failed to store in Salesforce: {str(e)}")
149
 
150
  def test_with_sample_audio():
151
+ """Test the app with sample audio files."""
152
+ samples = ["audio_samples/sample.wav", "audio_samples/common_voice_en.wav"]
153
+ results = []
154
+ for sample in samples:
155
+ if os.path.exists(sample):
156
+ results.append(analyze_voice(sample))
157
+ else:
158
+ results.append(f"Sample not found: {sample}")
159
+ return "\n".join(results)
160
 
161
  # Gradio interface
162
  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 at https://huggingface.co/spaces/your-username/HealthVoiceAnalyzer/settings."
168
  )
169
 
170
  if __name__ == "__main__":