Debdeep30 commited on
Commit
d797bdc
·
verified ·
1 Parent(s): 28de674

Upload pipeline/stt.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. pipeline/stt.py +66 -0
pipeline/stt.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Whisper STT wrapper — ROCm-compatible.
3
+
4
+ Two modes:
5
+ 1. Local Whisper (runs on the same MI300X, via openai-whisper or faster-whisper)
6
+ 2. Remote endpoint (OpenAI-compatible /v1/audio/transcriptions)
7
+
8
+ Set STT_MODE env var to "local" or "remote". Defaults to "remote" in HF Space.
9
+ """
10
+
11
+ import os
12
+ import tempfile
13
+ from pathlib import Path
14
+
15
+ STT_MODE = os.getenv("STT_MODE", "remote")
16
+ STT_URL = os.getenv("STT_URL", "")
17
+ WHISPER_SIZE = os.getenv("WHISPER_SIZE", "base") # tiny/base/small/medium
18
+
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Remote path (OpenAI-compatible endpoint — used in HF Space)
22
+ # ---------------------------------------------------------------------------
23
+
24
+ def _transcribe_remote(audio_path: str) -> str:
25
+ from openai import OpenAI
26
+ client = OpenAI(base_url=STT_URL.rstrip("/"), api_key="not-required")
27
+ with open(audio_path, "rb") as f:
28
+ result = client.audio.transcriptions.create(model="whisper-1", file=f)
29
+ return result.text.strip()
30
+
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Local path (runs on MI300X with ROCm)
34
+ # ---------------------------------------------------------------------------
35
+
36
+ _whisper_model = None
37
+
38
+ def _load_whisper():
39
+ global _whisper_model
40
+ if _whisper_model is None:
41
+ import whisper
42
+ _whisper_model = whisper.load_model(WHISPER_SIZE)
43
+ return _whisper_model
44
+
45
+
46
+ def _transcribe_local(audio_path: str) -> str:
47
+ model = _load_whisper()
48
+ result = model.transcribe(audio_path, fp16=True, language="en")
49
+ return result["text"].strip()
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # Public API
54
+ # ---------------------------------------------------------------------------
55
+
56
+ def transcribe(audio_path: str) -> str:
57
+ """Transcribe audio file to text. Returns empty string on failure."""
58
+ if not audio_path or not Path(audio_path).exists():
59
+ return ""
60
+ try:
61
+ if STT_MODE == "local":
62
+ return _transcribe_local(audio_path)
63
+ return _transcribe_remote(audio_path)
64
+ except Exception as e:
65
+ print(f"[STT] Error: {e}")
66
+ return ""