geethareddy commited on
Commit
40f86f1
·
verified ·
1 Parent(s): 578b499

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -7
app.py CHANGED
@@ -10,6 +10,7 @@ import torch
10
  from tenacity import retry, stop_after_attempt, wait_fixed
11
  import logging
12
  import tempfile
 
13
 
14
  # Set up logging
15
  logging.basicConfig(
@@ -88,6 +89,20 @@ def compute_file_hash(file_path):
88
  logger.error(f"Failed to compute file hash: {str(e)}")
89
  return "unknown"
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  def transcribe_audio(audio_file):
92
  """Transcribe audio using Whisper model."""
93
  if not whisper:
@@ -95,6 +110,9 @@ def transcribe_audio(audio_file):
95
  return "Error: Whisper model not loaded"
96
  try:
97
  logger.debug(f"Transcribing audio: {audio_file}")
 
 
 
98
  audio, sr = librosa.load(audio_file, sr=16000)
99
  if len(audio) < 1600:
100
  logger.error("Audio too short")
@@ -164,13 +182,24 @@ def analyze_voice(audio_file):
164
  logger.error(f"Audio file not found: {audio_file}")
165
  return "Error: Audio file not found"
166
 
 
 
 
 
 
 
 
167
  unique_path = os.path.join(
168
- tempfile.gettempdir(),
169
  f"gradio_{datetime.now().strftime('%Y%m%d%H%M%S%f')}_{os.path.basename(audio_file)}"
170
  )
171
- os.rename(audio_file, unique_path)
172
- audio_file = unique_path
173
- logger.debug(f"Renamed to: {audio_file}")
 
 
 
 
174
 
175
  file_hash = compute_file_hash(audio_file)
176
  logger.info(f"Processing audio, Hash: {file_hash}")
@@ -212,7 +241,12 @@ def analyze_voice(audio_file):
212
 
213
  def test_with_sample_audio():
214
  """Test with sample or synthetic audio."""
215
- sample_audio_path = "audio_samples/sample.wav"
 
 
 
 
 
216
  if not os.path.exists(sample_audio_path):
217
  logger.warning("Sample audio not found; generating synthetic audio")
218
  sr = 16000
@@ -221,8 +255,7 @@ def test_with_sample_audio():
221
  amplitude_mod = 0.5 + 0.1 * np.sin(2 * np.pi * 0.3 * t)
222
  noise = 0.01 * np.random.normal(0, 1, len(t))
223
  dummy_audio = amplitude_mod * np.sin(2 * np.pi * freq_mod * t) + noise
224
- sample_audio_path = os.path.join(tempfile.gettempdir(), "dummy_test.wav")
225
- os.makedirs(os.path.dirname(sample_audio_path), exist_ok=True)
226
  try:
227
  soundfile.write(dummy_audio, sr, sample_audio_path)
228
  logger.info(f"Generated synthetic audio: {sample_audio_path}")
@@ -230,6 +263,11 @@ def test_with_sample_audio():
230
  logger.error(f"Failed to write synthetic audio: {str(e)}")
231
  return f"Error: Failed to generate synthetic audio: {str(e)}"
232
 
 
 
 
 
 
233
  mock_transcription = "I have a cough and sore throat"
234
  logger.info(f"Mock transcription: {mock_transcription}")
235
  prediction, score = analyze_symptoms(mock_transcription)
 
10
  from tenacity import retry, stop_after_attempt, wait_fixed
11
  import logging
12
  import tempfile
13
+ import shutil
14
 
15
  # Set up logging
16
  logging.basicConfig(
 
89
  logger.error(f"Failed to compute file hash: {str(e)}")
90
  return "unknown"
91
 
92
+ def ensure_writable_dir(directory):
93
+ """Ensure directory exists and is writable."""
94
+ try:
95
+ os.makedirs(directory, exist_ok=True)
96
+ test_file = os.path.join(directory, "test_write")
97
+ with open(test_file, "w") as f:
98
+ f.write("test")
99
+ os.remove(test_file)
100
+ logger.debug(f"Directory {directory} is writable")
101
+ return True
102
+ except Exception as e:
103
+ logger.error(f"Directory {directory} not writable: {str(e)}")
104
+ return False
105
+
106
  def transcribe_audio(audio_file):
107
  """Transcribe audio using Whisper model."""
108
  if not whisper:
 
110
  return "Error: Whisper model not loaded"
111
  try:
112
  logger.debug(f"Transcribing audio: {audio_file}")
113
+ if not os.path.exists(audio_file):
114
+ logger.error(f"Audio file not found: {audio_file}")
115
+ return "Error: Audio file not found"
116
  audio, sr = librosa.load(audio_file, sr=16000)
117
  if len(audio) < 1600:
118
  logger.error("Audio too short")
 
182
  logger.error(f"Audio file not found: {audio_file}")
183
  return "Error: Audio file not found"
184
 
185
+ # Ensure temp directory is writable
186
+ temp_dir = os.path.join(tempfile.gettempdir(), "gradio")
187
+ if not ensure_writable_dir(temp_dir):
188
+ logger.error(f"Temp directory {temp_dir} not writable")
189
+ return f"Error: Temp directory {temp_dir} not writable"
190
+
191
+ # Rename file to unique path
192
  unique_path = os.path.join(
193
+ temp_dir,
194
  f"gradio_{datetime.now().strftime('%Y%m%d%H%M%S%f')}_{os.path.basename(audio_file)}"
195
  )
196
+ try:
197
+ shutil.move(audio_file, unique_path)
198
+ audio_file = unique_path
199
+ logger.debug(f"Moved to: {audio_file}")
200
+ except Exception as e:
201
+ logger.error(f"Failed to rename audio file: {str(e)}")
202
+ return f"Error: Failed to rename audio file: {str(e)}"
203
 
204
  file_hash = compute_file_hash(audio_file)
205
  logger.info(f"Processing audio, Hash: {file_hash}")
 
241
 
242
  def test_with_sample_audio():
243
  """Test with sample or synthetic audio."""
244
+ sample_audio_path = os.path.join("audio_samples", "sample.wav")
245
+ temp_dir = os.path.join(tempfile.gettempdir(), "audio_samples")
246
+ if not ensure_writable_dir(temp_dir):
247
+ logger.error(f"Temp directory {temp_dir} not writable")
248
+ return f"Error: Temp directory {temp_dir} not writable"
249
+
250
  if not os.path.exists(sample_audio_path):
251
  logger.warning("Sample audio not found; generating synthetic audio")
252
  sr = 16000
 
255
  amplitude_mod = 0.5 + 0.1 * np.sin(2 * np.pi * 0.3 * t)
256
  noise = 0.01 * np.random.normal(0, 1, len(t))
257
  dummy_audio = amplitude_mod * np.sin(2 * np.pi * freq_mod * t) + noise
258
+ sample_audio_path = os.path.join(temp_dir, "dummy_test.wav")
 
259
  try:
260
  soundfile.write(dummy_audio, sr, sample_audio_path)
261
  logger.info(f"Generated synthetic audio: {sample_audio_path}")
 
263
  logger.error(f"Failed to write synthetic audio: {str(e)}")
264
  return f"Error: Failed to generate synthetic audio: {str(e)}"
265
 
266
+ # Verify file existence
267
+ if not os.path.exists(sample_audio_path):
268
+ logger.error(f"Synthetic audio not created: {sample_audio_path}")
269
+ return f"Error: Synthetic audio not created: {sample_audio_path}"
270
+
271
  mock_transcription = "I have a cough and sore throat"
272
  logger.info(f"Mock transcription: {mock_transcription}")
273
  prediction, score = analyze_symptoms(mock_transcription)