Spaces:
Running
Running
use "with" statement for more safety (it's my opinion)
Browse filesUsed with open(...) to ensure proper file handling and automatic closing of file descriptors.
Simplified and cleaned up conditionals for better readability.
Added exception handling to gracefully catch unexpected errors.
Used .get() with default fallbacks when accessing response JSON to prevent KeyError.
Returned API's reported inference time if available, otherwise used locally measured time as a fallback.
Improved naming and formatting for consistency with Python conventions.
app.py
CHANGED
@@ -11,26 +11,28 @@ def transcribe_audio(file_path):
|
|
11 |
if not ASR_API_URL or not AUTH_TOKEN:
|
12 |
return "Error: Missing ASR_API_URL or AUTH_TOKEN.", None
|
13 |
|
14 |
-
# Prepare headers and data
|
15 |
headers = {
|
16 |
-
'
|
17 |
'Authorization': f'Bearer {AUTH_TOKEN}',
|
18 |
}
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
34 |
|
35 |
|
36 |
# Set up the Gradio interface
|
|
|
11 |
if not ASR_API_URL or not AUTH_TOKEN:
|
12 |
return "Error: Missing ASR_API_URL or AUTH_TOKEN.", None
|
13 |
|
|
|
14 |
headers = {
|
15 |
+
'Accept': 'application/json',
|
16 |
'Authorization': f'Bearer {AUTH_TOKEN}',
|
17 |
}
|
18 |
+
|
19 |
+
try:
|
20 |
+
with open(file_path, 'rb') as audio_file:
|
21 |
+
files = {'file': (file_path, audio_file, 'audio/mpeg')}
|
22 |
+
start_time = time.time()
|
23 |
+
response = requests.post(ASR_API_URL, headers=headers, files=files)
|
24 |
+
elapsed_time = time.time() - start_time
|
25 |
+
|
26 |
+
if response.ok:
|
27 |
+
data = response.json()
|
28 |
+
transcription = data.get('transcription', 'No transcription returned.')
|
29 |
+
inference_time = f"{data.get('time', round(elapsed_time, 2))} seconds"
|
30 |
+
return transcription, inference_time
|
31 |
+
else:
|
32 |
+
return f"Error: {response.status_code}, {response.text}", None
|
33 |
+
|
34 |
+
except Exception as e:
|
35 |
+
return f"Exception occurred: {str(e)}", None
|
36 |
|
37 |
|
38 |
# Set up the Gradio interface
|