jacob-c commited on
Commit
5b86980
·
1 Parent(s): 3b06717
Files changed (1) hide show
  1. app.py +42 -4
app.py CHANGED
@@ -2,6 +2,7 @@ import requests
2
  import gradio as gr
3
  import os
4
  import torch
 
5
 
6
  # Check if CUDA is available and set the device accordingly
7
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
@@ -9,26 +10,63 @@ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
9
  API_URL = "https://api-inference.huggingface.co/models/MIT/ast-finetuned-audioset-10-10-0.4593"
10
  headers = {"Authorization": f"Bearer {os.environ.get('HF_TOKEN')}"}
11
 
 
 
 
 
12
  def classify_audio(audio_file):
13
  """
14
  Classify the uploaded audio file using Hugging Face AST model
15
  """
16
  if audio_file is None:
17
- return "Please upload an audio file."
18
 
19
  try:
 
 
 
 
 
 
 
 
 
 
20
  with open(audio_file.name, "rb") as f:
21
  data = f.read()
 
 
22
  response = requests.post(API_URL, headers=headers, data=data)
23
 
 
 
 
 
 
24
  if response.status_code == 200:
25
  results = response.json()
26
- return results
 
 
 
 
 
 
 
 
 
 
 
27
  else:
28
- return f"Error: API returned status code {response.status_code}"
 
 
 
29
 
30
  except Exception as e:
31
- return f"Error processing audio: {str(e)}"
 
 
32
 
33
  # Create Gradio interface
34
  iface = gr.Interface(
 
2
  import gradio as gr
3
  import os
4
  import torch
5
+ import json
6
 
7
  # Check if CUDA is available and set the device accordingly
8
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
 
10
  API_URL = "https://api-inference.huggingface.co/models/MIT/ast-finetuned-audioset-10-10-0.4593"
11
  headers = {"Authorization": f"Bearer {os.environ.get('HF_TOKEN')}"}
12
 
13
+ def format_error(message):
14
+ """Helper function to format error messages as JSON"""
15
+ return [{"error": message}]
16
+
17
  def classify_audio(audio_file):
18
  """
19
  Classify the uploaded audio file using Hugging Face AST model
20
  """
21
  if audio_file is None:
22
+ return format_error("Please upload an audio file.")
23
 
24
  try:
25
+ # Debug: Print token status (masked)
26
+ token = os.environ.get('HF_TOKEN')
27
+ if not token:
28
+ return format_error("Error: HF_TOKEN environment variable is not set. Please set your Hugging Face API token.")
29
+ print(f"Token present: {'Yes' if token else 'No'}, Token length: {len(token) if token else 0}")
30
+
31
+ # Debug: Print audio file info
32
+ print(f"Audio file path: {audio_file.name}")
33
+ print(f"Audio file size: {os.path.getsize(audio_file.name)} bytes")
34
+
35
  with open(audio_file.name, "rb") as f:
36
  data = f.read()
37
+
38
+ print("Sending request to Hugging Face API...")
39
  response = requests.post(API_URL, headers=headers, data=data)
40
 
41
+ # Print response for debugging
42
+ print(f"Response status code: {response.status_code}")
43
+ print(f"Response headers: {dict(response.headers)}")
44
+ print(f"Response content: {response.content.decode('utf-8', errors='ignore')}")
45
+
46
  if response.status_code == 200:
47
  results = response.json()
48
+ # Format results for better readability
49
+ formatted_results = []
50
+ for result in results:
51
+ formatted_results.append({
52
+ 'label': result['label'],
53
+ 'score': f"{result['score']*100:.2f}%"
54
+ })
55
+ return formatted_results
56
+ elif response.status_code == 401:
57
+ return format_error("Error: Invalid or missing API token. Please check your Hugging Face API token.")
58
+ elif response.status_code == 503:
59
+ return format_error("Error: Model is loading. Please try again in a few seconds.")
60
  else:
61
+ error_msg = f"Error: API returned status code {response.status_code}\n"
62
+ error_msg += f"Response headers: {dict(response.headers)}\n"
63
+ error_msg += f"Response: {response.text}"
64
+ return format_error(error_msg)
65
 
66
  except Exception as e:
67
+ import traceback
68
+ error_details = traceback.format_exc()
69
+ return format_error(f"Error processing audio: {str(e)}\nDetails:\n{error_details}")
70
 
71
  # Create Gradio interface
72
  iface = gr.Interface(