File size: 6,556 Bytes
d413c3a
 
0313d21
 
da8f4c4
 
 
 
 
d413c3a
 
 
 
 
da8f4c4
 
 
d413c3a
 
 
 
 
 
 
 
 
 
 
 
da8f4c4
 
d413c3a
 
 
 
 
 
 
 
 
 
 
da8f4c4
d413c3a
 
 
da8f4c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d413c3a
da8f4c4
 
 
 
 
 
d413c3a
 
da8f4c4
d413c3a
da8f4c4
d413c3a
 
da8f4c4
d413c3a
 
 
 
 
da8f4c4
d413c3a
da8f4c4
d413c3a
 
da8f4c4
d413c3a
 
da8f4c4
 
d413c3a
 
 
 
da8f4c4
 
d413c3a
 
 
 
 
da8f4c4
 
 
d413c3a
da8f4c4
d413c3a
 
da8f4c4
d413c3a
da8f4c4
 
d413c3a
 
 
da8f4c4
 
d413c3a
 
da8f4c4
0313d21
d413c3a
da8f4c4
 
 
 
 
 
 
 
 
 
 
 
d413c3a
da8f4c4
 
 
 
5e6af1a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
"""
Department 2 β€” Transcriber
Primary  : Groq API (Whisper large-v3 on H100) β€” free tier 14,400 s/day
Fallback : faster-whisper large-v3 int8 (local CPU) if Groq fails or limit reached

βœ… UPGRADED:
  - Chunking support β€” splits long audio into 60s pieces automatically
  - Groq limit is 25MB per file, chunking handles large files
  - Chunks rejoined seamlessly into full transcript
"""

import os
import time
import logging
import subprocess
import tempfile
import shutil

logger = logging.getLogger(__name__)

LANG_TO_WHISPER = {
    "auto": None,
    "en":   "en",
    "te":   "te",
    "hi":   "hi",
    "ta":   "ta",
    "kn":   "kn",
}

CHUNK_DURATION_SEC = 60  # Groq max is 25MB β€” 60s chunks stay safe


class Transcriber:
    def __init__(self):
        self.groq_key     = os.environ.get("GROQ_API_KEY", "")
        self._groq_client = None
        self._local_model = None

        if self.groq_key:
            print("[Transcriber] Groq API key found β€” primary = Groq Whisper large-v3")
            self._init_groq()
        else:
            print("[Transcriber] No GROQ_API_KEY β€” local Whisper loads on first use")

    def transcribe(self, audio_path: str, language: str = "auto"):
        lang_hint = LANG_TO_WHISPER.get(language, None)
        duration  = self._get_duration(audio_path)
        print(f"[Transcriber] Audio duration: {duration:.1f}s")

        if duration <= CHUNK_DURATION_SEC:
            return self._transcribe_single(audio_path, lang_hint)

        print(f"[Transcriber] Long audio β€” splitting into {CHUNK_DURATION_SEC}s chunks")
        return self._transcribe_chunked(audio_path, lang_hint, duration)

    def _transcribe_chunked(self, audio_path, language, duration):
        tmp_dir = tempfile.mkdtemp()
        chunks  = []
        start   = 0
        index   = 0

        while start < duration:
            chunk_path = os.path.join(tmp_dir, f"chunk_{index:03d}.wav")
            subprocess.run([
                "ffmpeg", "-y", "-i", audio_path,
                "-ss", str(start), "-t", str(CHUNK_DURATION_SEC),
                "-acodec", "pcm_s16le", "-ar", "16000", "-ac", "1",
                chunk_path
            ], capture_output=True)
            if os.path.exists(chunk_path):
                chunks.append(chunk_path)
            start += CHUNK_DURATION_SEC
            index += 1

        print(f"[Transcriber] Processing {len(chunks)} chunks...")
        transcripts   = []
        detected_lang = language or "en"
        method        = "unknown"

        for i, chunk in enumerate(chunks):
            print(f"[Transcriber] Chunk {i+1}/{len(chunks)}...")
            try:
                text, lang, m = self._transcribe_single(chunk, language)
                transcripts.append(text.strip())
                detected_lang = lang
                method        = m
            except Exception as e:
                logger.warning(f"Chunk {i+1} failed: {e}")

        shutil.rmtree(tmp_dir, ignore_errors=True)
        full = " ".join(t for t in transcripts if t)
        print(f"[Transcriber] Done β€” {len(full)} chars total")
        return full, detected_lang, f"{method} (chunked {len(chunks)}x)"

    def _transcribe_single(self, audio_path, language):
        if self._groq_client is not None:
            try:
                return self._transcribe_groq(audio_path, language)
            except Exception as e:
                logger.warning(f"Groq failed ({e}), falling back to local")
                if self._local_model is None:
                    self._init_local()
        return self._transcribe_local(audio_path, language)

    def _init_groq(self):
        try:
            from groq import Groq
            self._groq_client = Groq(api_key=self.groq_key)
            print("[Transcriber] Groq client initialised")
        except Exception as e:
            logger.warning(f"Groq init failed: {e}")
            self._groq_client = None

    def _transcribe_groq(self, audio_path, language=None):
        t0 = time.time()
        with open(audio_path, "rb") as f:
            kwargs = dict(file=f, model="whisper-large-v3",
                          response_format="verbose_json", temperature=0.0)
            if language:
                kwargs["language"] = language
            resp = self._groq_client.audio.transcriptions.create(**kwargs)
        transcript    = resp.text.strip()
        detected_lang = self._normalise_lang(getattr(resp, "language", language or "en") or "en")
        logger.info(f"Groq done in {time.time()-t0:.2f}s, lang={detected_lang}")
        return transcript, detected_lang, "Groq Whisper large-v3"

    def _init_local(self):
        try:
            from faster_whisper import WhisperModel
            print("[Transcriber] Loading faster-whisper large-v3 int8...")
            self._local_model = WhisperModel("large-v3", device="cpu", compute_type="int8")
            print("[Transcriber] faster-whisper ready")
        except Exception as e:
            logger.error(f"Local Whisper init failed: {e}")
            self._local_model = None

    def _transcribe_local(self, audio_path, language=None):
        t0 = time.time()
        if self._local_model is None:
            self._init_local()
        if self._local_model is None:
            raise RuntimeError("No transcription engine available.")
        segments, info = self._local_model.transcribe(
            audio_path, language=language, beam_size=5,
            vad_filter=True, vad_parameters=dict(min_silence_duration_ms=500))
        transcript    = " ".join(seg.text.strip() for seg in segments).strip()
        detected_lang = info.language or language or "en"
        logger.info(f"Local done in {time.time()-t0:.2f}s")
        return transcript, detected_lang, "faster-whisper large-v3 int8 (local)"

    def _get_duration(self, audio_path):
        try:
            result = subprocess.run([
                "ffprobe", "-v", "error",
                "-show_entries", "format=duration",
                "-of", "default=noprint_wrappers=1:nokey=1",
                audio_path
            ], capture_output=True, text=True)
            return float(result.stdout.strip())
        except Exception:
            return 0.0

    @staticmethod
    def _normalise_lang(raw):
        mapping = {"english":"en","telugu":"te","hindi":"hi",
                   "tamil":"ta","kannada":"kn","spanish":"es",
                   "french":"fr","german":"de","japanese":"ja","chinese":"zh"}
        return mapping.get(raw.lower(), raw[:2].lower() if len(raw) >= 2 else raw)