funlifew commited on
Commit
b36a0c9
·
verified ·
1 Parent(s): 2c53232

use "with" statement for more safety (it's my opinion)

Browse files

Used 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.

Files changed (1) hide show
  1. app.py +19 -17
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
- 'accept': 'application/json',
17
  'Authorization': f'Bearer {AUTH_TOKEN}',
18
  }
19
- files = {
20
- 'file': (file_path, open(file_path, 'rb'), 'audio/mpeg'),
21
- }
22
- start_time = time.time()
23
- # Send POST request
24
- response = requests.post(ASR_API_URL, headers=headers, files=files)
25
- inference_time = time.time() - start_time # in seconds
26
-
27
- # Check if response is successful
28
- if response.status_code == 200:
29
- transcription = response.json().get("transcription", "No transcription returned.")
30
- inference_time_str = f"{response.json().get('time', 'No inference time returned.')} seconds"
31
- return transcription, inference_time_str
32
- else:
33
- return f"Error: {response.status_code}, {response.text}", None
 
 
 
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