whynotasif commited on
Commit
52a4da2
·
verified ·
1 Parent(s): 7db5ca1

Upload 2 files

Browse files
Files changed (1) hide show
  1. main.py +24 -7
main.py CHANGED
@@ -9,7 +9,13 @@ from typing import Optional
9
 
10
  app = FastAPI(title="VocalizeAPI")
11
 
 
 
 
 
 
12
  def get_audio_info(file_path):
 
13
  size_mb = os.path.getsize(file_path) / (1024 * 1024)
14
  audio = AudioSegment.from_file(file_path)
15
  duration_sec = len(audio) / 1000.0
@@ -21,19 +27,25 @@ async def audio_to_text(
21
  lang: Optional[str] = Form(None)
22
  ):
23
  temp_dir = tempfile.mkdtemp()
24
- input_ext = Path(file.filename).suffix.lower() or ".ogg"
 
 
 
25
  input_path = os.path.join(temp_dir, f"input{input_ext}")
26
  wav_path = os.path.join(temp_dir, "converted.wav")
27
 
28
  try:
 
29
  with open(input_path, "wb") as buffer:
30
  shutil.copyfileobj(file.file, buffer)
31
 
 
32
  audio = AudioSegment.from_file(input_path)
33
  audio = audio.set_channels(1).set_frame_rate(16000)
34
  audio.export(wav_path, format="wav")
35
  target_path = wav_path
36
 
 
37
  size_mb, duration = get_audio_info(target_path)
38
 
39
  if duration > 60:
@@ -41,18 +53,19 @@ async def audio_to_text(
41
  elif size_mb > 10:
42
  return {"status": False, "error": "Error: File is too large (>10MB).", "result": ""}
43
 
 
44
  r = sr.Recognizer()
45
  with sr.AudioFile(target_path) as source:
46
  r.adjust_for_ambient_noise(source, duration=0.5)
47
  audio_data = r.record(source)
48
 
49
  try:
50
- # --- FIXED LOGIC HERE ---
51
- if lang and lang.strip():
52
- # Use specific language if provided
53
- text = r.recognize_google(audio_data, language=lang)
 
54
  else:
55
- # Use default (English/Auto) if lang is None or empty string
56
  text = r.recognize_google(audio_data)
57
 
58
  return {"status": True, "error": None, "result": text}
@@ -64,7 +77,11 @@ async def audio_to_text(
64
 
65
  except Exception as e:
66
  print(f"Server Log Error: {e}")
67
- return {"status": False, "error": "System Error: Processing failed.", "result": ""}
68
  finally:
 
69
  shutil.rmtree(temp_dir, ignore_errors=True)
70
 
 
 
 
 
9
 
10
  app = FastAPI(title="VocalizeAPI")
11
 
12
+ # --- LINUX FFMPEG FIX ---
13
+ # On some HF containers, we need to explicitly tell pydub where ffmpeg is
14
+ if shutil.which("ffmpeg"):
15
+ AudioSegment.converter = shutil.which("ffmpeg")
16
+
17
  def get_audio_info(file_path):
18
+ """Returns size in MB and duration in seconds."""
19
  size_mb = os.path.getsize(file_path) / (1024 * 1024)
20
  audio = AudioSegment.from_file(file_path)
21
  duration_sec = len(audio) / 1000.0
 
27
  lang: Optional[str] = Form(None)
28
  ):
29
  temp_dir = tempfile.mkdtemp()
30
+ # Ensure filename exists to avoid suffix errors
31
+ filename = file.filename if file.filename else "input.ogg"
32
+ input_ext = Path(filename).suffix.lower() or ".ogg"
33
+
34
  input_path = os.path.join(temp_dir, f"input{input_ext}")
35
  wav_path = os.path.join(temp_dir, "converted.wav")
36
 
37
  try:
38
+ # 1. Save uploaded file
39
  with open(input_path, "wb") as buffer:
40
  shutil.copyfileobj(file.file, buffer)
41
 
42
+ # 2. Convert to WAV (Standardized for Google)
43
  audio = AudioSegment.from_file(input_path)
44
  audio = audio.set_channels(1).set_frame_rate(16000)
45
  audio.export(wav_path, format="wav")
46
  target_path = wav_path
47
 
48
+ # 3. Validate
49
  size_mb, duration = get_audio_info(target_path)
50
 
51
  if duration > 60:
 
53
  elif size_mb > 10:
54
  return {"status": False, "error": "Error: File is too large (>10MB).", "result": ""}
55
 
56
+ # 4. Transcribe
57
  r = sr.Recognizer()
58
  with sr.AudioFile(target_path) as source:
59
  r.adjust_for_ambient_noise(source, duration=0.5)
60
  audio_data = r.record(source)
61
 
62
  try:
63
+ # Use provided lang if it exists and isn't just whitespace
64
+ actual_lang = lang.strip() if (lang and lang.strip()) else None
65
+
66
+ if actual_lang:
67
+ text = r.recognize_google(audio_data, language=actual_lang)
68
  else:
 
69
  text = r.recognize_google(audio_data)
70
 
71
  return {"status": True, "error": None, "result": text}
 
77
 
78
  except Exception as e:
79
  print(f"Server Log Error: {e}")
80
+ return {"status": False, "error": f"System Error: {str(e)}", "result": ""}
81
  finally:
82
+ # 5. Cleanup
83
  shutil.rmtree(temp_dir, ignore_errors=True)
84
 
85
+ if __name__ == "__main__":
86
+ import uvicorn
87
+ uvicorn.run(app, host="0.0.0.0", port=7860)