Consulawtech commited on
Commit
e2ef3c4
·
1 Parent(s): 00c7ba2

initial: modular ASR system v2

Browse files
.dockerignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ *.pyc
3
+ .git
4
+ .gitignore
5
+ README.md
6
+ temp/
7
+ model_cache/
8
+ .DS_Store
9
+ .vscode/
10
+ .idea/
11
+ *.wav
12
+ *.mp3
13
+ *.m4a
.gitignore ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ env/
8
+ venv/
9
+ ENV/
10
+ env.bak/
11
+ venv.bak/
12
+
13
+ # Audio files
14
+ *.wav
15
+ *.mp3
16
+ *.m4a
17
+ *.ogg
18
+ *.flac
19
+ *.aac
20
+ temp/
21
+ temp_*/
22
+
23
+ # Model cache
24
+ model_cache/
25
+ .huggingface/
26
+
27
+ # IDE
28
+ .vscode/
29
+ .idea/
30
+ *.swp
31
+ *.swo
32
+ *~
33
+
34
+ # OS
35
+ .DS_Store
36
+ Thumbs.db
37
+
38
+ # Logs
39
+ *.log
40
+ logs/
41
+
42
+ # Output
43
+ *.srt
44
+ *.vtt
45
+ *.json
Dockerfile ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ # System deps — ffmpeg for pydub, libsndfile for soundfile
4
+ RUN apt-get update && apt-get install -y --no-install-recommends \
5
+ ffmpeg \
6
+ libsndfile1 \
7
+ build-essential \
8
+ git \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ WORKDIR /app
12
+
13
+ # Layer-cache trick: copy only requirements first so this layer only
14
+ # rebuilds when dependencies actually change, not on every code edit.
15
+ COPY requirements.txt .
16
+
17
+ # Use pip cache mount for faster rebuilds (BuildKit).
18
+ # --no-cache-dir is intentionally omitted here to benefit from the mount.
19
+ RUN --mount=type=cache,target=/root/.cache/pip \
20
+ pip install --upgrade pip setuptools wheel && \
21
+ pip install -r requirements.txt
22
+
23
+ # Copy rest of project
24
+ COPY . .
25
+
26
+ # Create runtime directories
27
+ RUN mkdir -p /app/temp /app/model_cache
28
+
29
+ # Force matplotlib to use non-interactive Agg backend (no display needed)
30
+ ENV MPLBACKEND=Agg
31
+ # Respect HF_HOME for model caching across restarts
32
+ ENV HF_HOME=/app/model_cache
33
+ # Gradio telemetry off
34
+ ENV GRADIO_ANALYTICS_ENABLED=false
35
+
36
+ EXPOSE 7860
37
+
38
+ CMD ["python", "gradio_app.py"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Maaldeens
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,11 +1,102 @@
1
  ---
2
- title: Asr System
3
- emoji: 🔥
4
- colorFrom: yellow
5
- colorTo: yellow
6
  sdk: docker
 
 
7
  pinned: false
8
- license: mit
 
 
 
 
 
 
 
 
 
 
 
 
9
  ---
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Modular ASR System
3
+ emoji: 🎙
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: docker
7
+ sdk_version: "20.10"
8
+ app_file: gradio_app.py
9
  pinned: false
10
+ short_description: Production-ready speech-to-text — Whisper · waveforms · SRT/VTT export
11
+ suggested_hardware: "t4-small"
12
+ tags:
13
+ - asr
14
+ - speech-to-text
15
+ - whisper
16
+ - gradio
17
+ models:
18
+ - openai/whisper-tiny
19
+ - openai/whisper-small
20
+ - openai/whisper-medium
21
+ - openai/whisper-large-v3
22
+ fullWidth: true
23
  ---
24
 
25
+ # 🎙 Modular ASR System
26
+
27
+ Production-ready speech-to-text with a split-screen Gradio UI, live waveform visualisation, and export to TXT / JSON / SRT / VTT.
28
+
29
+ ## Features
30
+
31
+ - **Four Whisper models** — tiny → large-v3, switchable at runtime
32
+ - **Live waveform + segment timeline** rendered after every transcription
33
+ - **Segment table** — scrollable view of every timestamped chunk
34
+ - **Download in four formats** — TXT, JSON, SRT, VTT
35
+ - **100+ languages** — auto-detect or manually specify
36
+ - **Translate mode** — transcribe any language → English
37
+ - **Long audio** — automatic chunking with overlap for files > 30 s
38
+ - **FastAPI REST API** — `/transcribe`, `/models`, `/health` endpoints via `app.py`
39
+
40
+ ## Project structure
41
+
42
+ ```
43
+ asr_system/
44
+ ├── gradio_app.py # Gradio UI (primary entrypoint)
45
+ ├── app.py # FastAPI REST API (optional)
46
+ ├── config/
47
+ │ └── settings.yaml
48
+ ├── src/
49
+ │ ├── audio_processor/
50
+ │ │ ├── validator.py # File validation & metadata
51
+ │ │ ├── converter.py # Format conversion & normalisation
52
+ │ │ └── chunker.py # Long-audio chunking with overlap
53
+ │ ├── models/
54
+ │ │ ├── registry.py # Model loading & caching
55
+ │ │ └── asr_pipeline.py
56
+ │ ├── transcription/
57
+ │ │ └── engine.py # Orchestration layer
58
+ │ └── output/
59
+ │ └── formatter.py # TXT / JSON / SRT / VTT output
60
+ ├── Dockerfile
61
+ ├── requirements.txt
62
+ └── test.py # pytest suite
63
+ ```
64
+
65
+ ## Running locally
66
+
67
+ ```bash
68
+ pip install -r requirements.txt
69
+
70
+ # Gradio UI
71
+ python gradio_app.py
72
+
73
+ # FastAPI REST API
74
+ python app.py --api --port 7860
75
+ ```
76
+
77
+ ## REST API
78
+
79
+ ```bash
80
+ # Transcribe
81
+ curl -X POST http://localhost:7860/transcribe \
82
+ -F "file=@audio.mp3" \
83
+ -F "language=en" \
84
+ -F "task=transcribe" \
85
+ -F "output_format=srt"
86
+
87
+ # List models
88
+ curl http://localhost:7860/models
89
+
90
+ # Health
91
+ curl http://localhost:7860/health
92
+ ```
93
+
94
+ ## Running tests
95
+
96
+ ```bash
97
+ python -m pytest test.py -v
98
+ ```
99
+
100
+ ## License
101
+
102
+ MIT — see LICENSE
app.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Main application entry point for Hugging Face Space
3
+ Author: Maaldeens
4
+ License: MIT
5
+ """
6
+
7
+ import os
8
+ import argparse
9
+ from pathlib import Path
10
+ import logging
11
+ from typing import Optional
12
+ import uvicorn
13
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException
14
+ from fastapi.responses import JSONResponse
15
+ from fastapi.middleware.cors import CORSMiddleware
16
+ import json
17
+
18
+ from src.transcription.engine import TranscriptionEngine
19
+ from src.output.formatter import OutputFormatter
20
+
21
+ # Setup logging
22
+ logging.basicConfig(
23
+ level=logging.INFO,
24
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
25
+ )
26
+ logger = logging.getLogger(__name__)
27
+
28
+ # Initialize FastAPI app
29
+ app = FastAPI(
30
+ title="Modular ASR System",
31
+ description="Upgradable speech-to-text transcription system",
32
+ version="1.0.0"
33
+ )
34
+
35
+ # Add CORS middleware
36
+ app.add_middleware(
37
+ CORSMiddleware,
38
+ allow_origins=["*"],
39
+ allow_credentials=True,
40
+ allow_methods=["*"],
41
+ allow_headers=["*"],
42
+ )
43
+
44
+ # Initialize transcription engine
45
+ engine = None
46
+
47
+ @app.on_event("startup")
48
+ async def startup_event():
49
+ """Initialize engine on startup"""
50
+ global engine
51
+ config_path = os.getenv("CONFIG_PATH", "config/settings.yaml")
52
+ engine = TranscriptionEngine(config_path)
53
+ logger.info(f"Transcription engine initialized with model: {engine.current_model_key}")
54
+
55
+ @app.get("/")
56
+ async def root():
57
+ """Root endpoint with system info"""
58
+ return {
59
+ "name": "Modular ASR System",
60
+ "version": "1.0.0",
61
+ "owner": "Maaldeens",
62
+ "license": "MIT",
63
+ "status": "operational",
64
+ "available_models": list(engine.get_available_models().keys()) if engine else [],
65
+ "current_model": engine.current_model_key if engine else None
66
+ }
67
+
68
+ @app.get("/models")
69
+ async def list_models():
70
+ """List available models"""
71
+ if not engine:
72
+ raise HTTPException(status_code=503, detail="Engine not initialized")
73
+
74
+ return {
75
+ "available_models": engine.get_available_models(),
76
+ "current_model": engine.current_model_key
77
+ }
78
+
79
+ @app.post("/transcribe")
80
+ async def transcribe(
81
+ file: UploadFile = File(...),
82
+ language: Optional[str] = Form(None),
83
+ task: str = Form("transcribe"),
84
+ return_timestamps: bool = Form(True),
85
+ output_format: str = Form("json"),
86
+ model: Optional[str] = Form(None)
87
+ ):
88
+ """
89
+ Transcribe an audio file
90
+ """
91
+ if not engine:
92
+ raise HTTPException(status_code=503, detail="Engine not initialized")
93
+
94
+ if not file.filename:
95
+ raise HTTPException(status_code=400, detail="No file provided")
96
+
97
+ # Read file
98
+ content = await file.read()
99
+
100
+ # Switch model if specified
101
+ original_model = None
102
+ if model and model != engine.current_model_key:
103
+ original_model = engine.current_model_key
104
+ try:
105
+ engine.set_model(model)
106
+ except ValueError as e:
107
+ raise HTTPException(status_code=400, detail=str(e))
108
+
109
+ try:
110
+ # Prepare transcription parameters
111
+ transcription_kwargs = {
112
+ "language": language if language != "auto" else None,
113
+ "task": task,
114
+ "return_timestamps": return_timestamps
115
+ }
116
+
117
+ # Transcribe
118
+ result = engine.transcribe_bytes(
119
+ content,
120
+ filename=file.filename,
121
+ **transcription_kwargs
122
+ )
123
+
124
+ # Format output
125
+ formatted_output = OutputFormatter.format(result.to_dict(), output_format)
126
+
127
+ # Prepare response
128
+ response = {
129
+ "success": True,
130
+ "filename": file.filename,
131
+ "model_used": result.model_used,
132
+ "processing_time": result.processing_time,
133
+ "audio_duration": result.audio_duration,
134
+ "language": result.language,
135
+ "output_format": output_format,
136
+ "result": formatted_output if output_format in ["txt", "srt", "vtt"] else json.loads(formatted_output)
137
+ }
138
+
139
+ return JSONResponse(content=response)
140
+
141
+ except Exception as e:
142
+ logger.error(f"Transcription failed: {e}")
143
+ raise HTTPException(status_code=500, detail=f"Transcription failed: {str(e)}")
144
+
145
+ finally:
146
+ # Restore original model if switched
147
+ if original_model:
148
+ engine.set_model(original_model)
149
+
150
+ @app.get("/health")
151
+ async def health_check():
152
+ """Health check endpoint"""
153
+ return {
154
+ "status": "healthy",
155
+ "engine_initialized": engine is not None
156
+ }
157
+
158
+ def main():
159
+ """Command line interface"""
160
+ parser = argparse.ArgumentParser(description="Modular ASR Transcription System")
161
+ parser.add_argument("--api", action="store_true", help="Run as API server")
162
+ parser.add_argument("--host", default="0.0.0.0", help="API host")
163
+ parser.add_argument("--port", type=int, default=7860, help="API port")
164
+ parser.add_argument("--config", "-c", help="Config file path")
165
+
166
+ args = parser.parse_args()
167
+
168
+ # Set config path
169
+ if args.config:
170
+ os.environ["CONFIG_PATH"] = args.config
171
+
172
+ # Run API server
173
+ if args.api:
174
+ uvicorn.run(app, host=args.host, port=args.port)
175
+ return
176
+
177
+ if __name__ == "__main__":
178
+ main()
config/settings.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ system:
2
+ name: "Modular ASR System"
3
+ version: "2.0.0"
4
+ temp_dir: "/app/temp"
5
+ max_file_size_mb: 500
6
+
7
+ audio:
8
+ target_sample_rate: 16000
9
+ target_channels: 1
10
+ normalize_volume: true
11
+ target_dbfs: -20
12
+ # Disabled — noisereduce not in requirements; set true only if you add it
13
+ noise_reduction: false
14
+ chunk_duration_sec: 30
15
+ chunk_overlap_sec: 2
16
+
17
+ models:
18
+ default: "whisper-medium"
19
+ # cache_dir is overridden at runtime by HF_HOME env var (set in Dockerfile)
20
+ cache_dir: "/app/model_cache"
21
+ available:
22
+ whisper-tiny:
23
+ path: "openai/whisper-tiny"
24
+ type: "whisper"
25
+ size: "39M"
26
+ speed: "~32x"
27
+ whisper-small:
28
+ path: "openai/whisper-small"
29
+ type: "whisper"
30
+ size: "244M"
31
+ speed: "~8x"
32
+ whisper-medium:
33
+ path: "openai/whisper-medium"
34
+ type: "whisper"
35
+ size: "769M"
36
+ speed: "~2x"
37
+ whisper-large-v3:
38
+ path: "openai/whisper-large-v3"
39
+ type: "whisper"
40
+ size: "1.55B"
41
+ speed: "1x"
42
+
43
+ transcription:
44
+ language: null
45
+ task: "transcribe"
46
+ return_timestamps: true
47
+ beam_size: 5
gradio_app.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Modular ASR System — Gradio UI
3
+ Author: Maaldeens
4
+ License: MIT
5
+ """
6
+
7
+ import os
8
+ import json
9
+ import tempfile
10
+ import numpy as np
11
+ import gradio as gr
12
+ import soundfile as sf
13
+ import matplotlib
14
+ matplotlib.use("Agg")
15
+ import matplotlib.pyplot as plt
16
+ import matplotlib.patches as mpatches
17
+ from matplotlib.collections import BrokenBarHCollection
18
+ from pathlib import Path
19
+ from typing import Optional
20
+
21
+ from src.transcription.engine import TranscriptionEngine
22
+ from src.output.formatter import OutputFormatter
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Engine
26
+ # ---------------------------------------------------------------------------
27
+ CONFIG_PATH = os.getenv("CONFIG_PATH", "config/settings.yaml")
28
+ engine = TranscriptionEngine(CONFIG_PATH)
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Model metadata (for info cards in UI)
32
+ # ---------------------------------------------------------------------------
33
+ MODEL_INFO = {
34
+ "whisper-tiny": {"size": "39 M", "speed": "~32×", "langs": "99", "note": "Fastest — good for drafts"},
35
+ "whisper-small": {"size": "244 M", "speed": "~8×", "langs": "99", "note": "Good accuracy/speed balance"},
36
+ "whisper-medium": {"size": "769 M", "speed": "~2×", "langs": "99", "note": "Recommended default"},
37
+ "whisper-large-v3": {"size": "1.55 B", "speed": "1×", "langs": "100", "note": "Best accuracy"},
38
+ }
39
+
40
+ LANGUAGES = [
41
+ ("Auto-detect", None),
42
+ ("English", "en"),
43
+ ("Arabic", "ar"),
44
+ ("Chinese", "zh"),
45
+ ("French", "fr"),
46
+ ("German", "de"),
47
+ ("Hindi", "hi"),
48
+ ("Indonesian", "id"),
49
+ ("Italian", "it"),
50
+ ("Japanese", "ja"),
51
+ ("Korean", "ko"),
52
+ ("Malay", "ms"),
53
+ ("Portuguese", "pt"),
54
+ ("Russian", "ru"),
55
+ ("Spanish", "es"),
56
+ ("Swahili", "sw"),
57
+ ("Turkish", "tr"),
58
+ ("Ukrainian", "uk"),
59
+ ("Yoruba", "yo"),
60
+ ("Hausa", "ha"),
61
+ ("Igbo", "ig"),
62
+ ]
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # Waveform + segment timeline plot
66
+ # ---------------------------------------------------------------------------
67
+
68
+ def _make_waveform_plot(audio_path: str, segments: Optional[list]) -> plt.Figure:
69
+ """Return a matplotlib Figure with waveform + optional segment timeline."""
70
+ y, sr = sf.read(audio_path, dtype="float32")
71
+ if y.ndim > 1:
72
+ y = y.mean(axis=1)
73
+
74
+ duration = len(y) / sr
75
+ t = np.linspace(0, duration, num=len(y))
76
+
77
+ # Down-sample for plotting (max 4000 points)
78
+ step = max(1, len(y) // 4000)
79
+ t_ds, y_ds = t[::step], y[::step]
80
+
81
+ has_segs = bool(segments)
82
+ fig_h = 3.6 if has_segs else 2.4
83
+ fig, axes = plt.subplots(
84
+ 2 if has_segs else 1, 1,
85
+ figsize=(10, fig_h),
86
+ gridspec_kw={"height_ratios": [3, 1]} if has_segs else {},
87
+ facecolor="#0f0f11",
88
+ )
89
+ ax_wave = axes[0] if has_segs else axes
90
+
91
+ # -- Waveform --
92
+ ax_wave.set_facecolor("#0f0f11")
93
+ ax_wave.fill_between(t_ds, y_ds, 0, color="#7c6af7", alpha=0.55)
94
+ ax_wave.fill_between(t_ds, -y_ds, 0, color="#7c6af7", alpha=0.55)
95
+ ax_wave.plot(t_ds, y_ds, color="#a99ff8", linewidth=0.4, alpha=0.8)
96
+ ax_wave.axhline(0, color="#3a3650", linewidth=0.5)
97
+ ax_wave.set_xlim(0, duration)
98
+ ax_wave.set_ylim(-1.1, 1.1)
99
+ ax_wave.set_ylabel("Amplitude", color="#8b85b8", fontsize=8)
100
+ ax_wave.tick_params(colors="#8b85b8", labelsize=7)
101
+ for spine in ax_wave.spines.values():
102
+ spine.set_edgecolor("#2d2845")
103
+
104
+ # -- Segment timeline --
105
+ if has_segs:
106
+ ax_seg = axes[1]
107
+ ax_seg.set_facecolor("#0f0f11")
108
+ palette = ["#7c6af7", "#5cc8a8", "#f0875a", "#e86fa0", "#f5c842"]
109
+ for i, seg in enumerate(segments):
110
+ s, e = seg.get("start", 0), seg.get("end", 0)
111
+ ax_seg.barh(
112
+ 0, e - s, left=s, height=0.5,
113
+ color=palette[i % len(palette)], alpha=0.85,
114
+ edgecolor="#0f0f11", linewidth=0.6,
115
+ )
116
+ ax_seg.set_xlim(0, duration)
117
+ ax_seg.set_ylim(-0.5, 0.5)
118
+ ax_seg.set_yticks([])
119
+ ax_seg.set_xlabel("Time (s)", color="#8b85b8", fontsize=8)
120
+ ax_seg.tick_params(colors="#8b85b8", labelsize=7, axis="x")
121
+ ax_seg.set_ylabel("Segs", color="#8b85b8", fontsize=7)
122
+ for spine in ax_seg.spines.values():
123
+ spine.set_edgecolor("#2d2845")
124
+
125
+ fig.tight_layout(pad=0.5)
126
+ return fig
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # Download helpers
131
+ # ---------------------------------------------------------------------------
132
+
133
+ def _write_temp(content: str, suffix: str) -> str:
134
+ fd, path = tempfile.mkstemp(suffix=suffix)
135
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
136
+ f.write(content)
137
+ return path
138
+
139
+
140
+ # ---------------------------------------------------------------------------
141
+ # Core transcription function
142
+ # ---------------------------------------------------------------------------
143
+
144
+ def transcribe(
145
+ audio_file,
146
+ model_key: str,
147
+ language_label: str,
148
+ task: str,
149
+ return_timestamps: bool,
150
+ ):
151
+ if audio_file is None:
152
+ raise gr.Error("Please upload an audio file first.")
153
+
154
+ # Map language label → code
155
+ lang_map = {label: code for label, code in LANGUAGES}
156
+ language = lang_map.get(language_label)
157
+
158
+ # Switch model if needed
159
+ if model_key != engine.current_model_key:
160
+ engine.set_model(model_key)
161
+
162
+ result = engine.transcribe_file(
163
+ audio_file,
164
+ language=language,
165
+ task=task,
166
+ return_timestamps=return_timestamps,
167
+ )
168
+
169
+ # --- stats bar ---
170
+ duration_str = f"{result.audio_duration:.1f}s" if result.audio_duration else "—"
171
+ proc_str = f"{result.processing_time:.1f}s" if result.processing_time else "—"
172
+ lang_str = (result.language or "auto").upper()
173
+ segs_str = str(len(result.segments)) if result.segments else "0"
174
+ stats_html = f"""
175
+ <div style="display:flex;gap:16px;flex-wrap:wrap;padding:10px 0">
176
+ <span style="background:#1e1b36;color:#a99ff8;padding:4px 12px;border-radius:20px;font-size:13px">
177
+ ⏱ Audio: {duration_str}
178
+ </span>
179
+ <span style="background:#1e1b36;color:#5cc8a8;padding:4px 12px;border-radius:20px;font-size:13px">
180
+ ⚡ Processed: {proc_str}
181
+ </span>
182
+ <span style="background:#1e1b36;color:#f0875a;padding:4px 12px;border-radius:20px;font-size:13px">
183
+ 🌐 Language: {lang_str}
184
+ </span>
185
+ <span style="background:#1e1b36;color:#e86fa0;padding:4px 12px;border-radius:20px;font-size:13px">
186
+ 📝 Segments: {segs_str}
187
+ </span>
188
+ </div>"""
189
+
190
+ # --- waveform ---
191
+ fig = _make_waveform_plot(audio_file, result.segments)
192
+
193
+ # --- segment table html ---
194
+ seg_html = ""
195
+ if result.segments:
196
+ rows = ""
197
+ for i, seg in enumerate(result.segments):
198
+ s = seg.get("start", 0)
199
+ e = seg.get("end", 0)
200
+ txt = seg.get("text", "")
201
+ bg = "#18162e" if i % 2 == 0 else "#100f22"
202
+ rows += f"""<tr style="background:{bg}">
203
+ <td style="padding:6px 10px;color:#8b85b8;font-size:12px;white-space:nowrap">{s:.2f}s</td>
204
+ <td style="padding:6px 10px;color:#8b85b8;font-size:12px;white-space:nowrap">{e:.2f}s</td>
205
+ <td style="padding:6px 10px;color:#e0dcff;font-size:13px">{txt}</td>
206
+ </tr>"""
207
+ seg_html = f"""
208
+ <div style="max-height:280px;overflow-y:auto;border-radius:8px;border:1px solid #2d2845">
209
+ <table style="width:100%;border-collapse:collapse">
210
+ <thead>
211
+ <tr style="background:#1e1b36;position:sticky;top:0">
212
+ <th style="padding:8px 10px;color:#a99ff8;font-size:12px;text-align:left">Start</th>
213
+ <th style="padding:8px 10px;color:#a99ff8;font-size:12px;text-align:left">End</th>
214
+ <th style="padding:8px 10px;color:#a99ff8;font-size:12px;text-align:left">Text</th>
215
+ </tr>
216
+ </thead>
217
+ <tbody>{rows}</tbody>
218
+ </table>
219
+ </div>"""
220
+
221
+ # --- download files ---
222
+ rd = result.to_dict()
223
+ txt_path = _write_temp(OutputFormatter.format(rd, "txt"), ".txt")
224
+ json_path = _write_temp(OutputFormatter.format(rd, "json"), ".json")
225
+ srt_path = _write_temp(OutputFormatter.format(rd, "srt"), ".srt")
226
+ vtt_path = _write_temp(OutputFormatter.format(rd, "vtt"), ".vtt")
227
+
228
+ return (
229
+ result.text,
230
+ stats_html,
231
+ fig,
232
+ seg_html,
233
+ txt_path,
234
+ json_path,
235
+ srt_path,
236
+ vtt_path,
237
+ gr.update(visible=True), # download_row
238
+ )
239
+
240
+
241
+ # ---------------------------------------------------------------------------
242
+ # Model info card
243
+ # ---------------------------------------------------------------------------
244
+
245
+ def update_model_card(model_key: str) -> str:
246
+ info = MODEL_INFO.get(model_key, {})
247
+ return f"""
248
+ <div style="background:#1e1b36;border:1px solid #2d2845;border-radius:10px;padding:14px 16px">
249
+ <div style="font-size:15px;font-weight:600;color:#a99ff8;margin-bottom:8px">{model_key}</div>
250
+ <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px">
251
+ <div style="background:#131126;border-radius:6px;padding:8px;text-align:center">
252
+ <div style="font-size:11px;color:#5c5882;margin-bottom:2px">Parameters</div>
253
+ <div style="font-size:14px;font-weight:600;color:#e0dcff">{info.get('size','—')}</div>
254
+ </div>
255
+ <div style="background:#131126;border-radius:6px;padding:8px;text-align:center">
256
+ <div style="font-size:11px;color:#5c5882;margin-bottom:2px">Speed</div>
257
+ <div style="font-size:14px;font-weight:600;color:#5cc8a8">{info.get('speed','—')}</div>
258
+ </div>
259
+ <div style="background:#131126;border-radius:6px;padding:8px;text-align:center">
260
+ <div style="font-size:11px;color:#5c5882;margin-bottom:2px">Languages</div>
261
+ <div style="font-size:14px;font-weight:600;color:#f0875a">{info.get('langs','—')}</div>
262
+ </div>
263
+ </div>
264
+ <div style="margin-top:10px;font-size:12px;color:#8b85b8">{info.get('note','')}</div>
265
+ </div>"""
266
+
267
+
268
+ # ---------------------------------------------------------------------------
269
+ # UI
270
+ # ---------------------------------------------------------------------------
271
+
272
+ THEME = gr.themes.Base(
273
+ primary_hue=gr.themes.colors.purple,
274
+ secondary_hue=gr.themes.colors.indigo,
275
+ neutral_hue=gr.themes.colors.slate,
276
+ ).set(
277
+ body_background_fill="#0a0914",
278
+ body_background_fill_dark="#0a0914",
279
+ block_background_fill="#13112a",
280
+ block_background_fill_dark="#13112a",
281
+ block_border_color="#2d2845",
282
+ block_border_color_dark="#2d2845",
283
+ input_background_fill="#0f0d1f",
284
+ input_background_fill_dark="#0f0d1f",
285
+ button_primary_background_fill="#6b5de8",
286
+ button_primary_background_fill_hover="#7c6af7",
287
+ button_primary_text_color="#ffffff",
288
+ )
289
+
290
+ CSS = """
291
+ #title { text-align:center; padding: 2rem 0 0.5rem; }
292
+ #title h1 { font-size:2rem; font-weight:700; color:#a99ff8; letter-spacing:-0.5px; margin:0 }
293
+ #title p { color:#5c5882; font-size:14px; margin:6px 0 0 }
294
+ .transcription-box textarea { font-size:15px !important; line-height:1.7 !important; color:#e0dcff !important; }
295
+ .segment-table { border-radius:8px; overflow:hidden; }
296
+ footer { display:none !important; }
297
+ """
298
+
299
+ with gr.Blocks(theme=THEME, css=CSS, title="ASR System") as demo:
300
+
301
+ # Header
302
+ gr.HTML("""
303
+ <div id="title">
304
+ <h1>🎙 Modular ASR System</h1>
305
+ <p>Production-grade speech-to-text · Whisper · 100+ languages · Multiple export formats</p>
306
+ </div>""")
307
+
308
+ with gr.Row(equal_height=False):
309
+ # ── LEFT: inputs ─────────────────────────────────────────────────
310
+ with gr.Column(scale=4, min_width=320):
311
+ gr.Markdown("### Upload")
312
+ audio_input = gr.Audio(
313
+ type="filepath",
314
+ label="Audio file",
315
+ show_label=False,
316
+ )
317
+
318
+ gr.Markdown("### Model")
319
+ model_dropdown = gr.Dropdown(
320
+ choices=list(MODEL_INFO.keys()),
321
+ value="whisper-medium",
322
+ label="Model",
323
+ show_label=False,
324
+ )
325
+ model_card_html = gr.HTML(update_model_card("whisper-medium"))
326
+ model_dropdown.change(update_model_card, model_dropdown, model_card_html)
327
+
328
+ gr.Markdown("### Options")
329
+ with gr.Row():
330
+ lang_dropdown = gr.Dropdown(
331
+ choices=[l for l, _ in LANGUAGES],
332
+ value="Auto-detect",
333
+ label="Language",
334
+ )
335
+ task_radio = gr.Radio(
336
+ ["transcribe", "translate"],
337
+ value="transcribe",
338
+ label="Task",
339
+ )
340
+ timestamps_toggle = gr.Checkbox(
341
+ value=True,
342
+ label="Return word timestamps",
343
+ )
344
+
345
+ transcribe_btn = gr.Button(
346
+ "▶ Transcribe",
347
+ variant="primary",
348
+ size="lg",
349
+ )
350
+
351
+ # ── RIGHT: outputs ────────────────────────────────────────────────
352
+ with gr.Column(scale=6, min_width=400):
353
+ gr.Markdown("### Transcription")
354
+ stats_out = gr.HTML("")
355
+ text_out = gr.Textbox(
356
+ label="",
357
+ lines=8,
358
+ show_copy_button=True,
359
+ elem_classes=["transcription-box"],
360
+ placeholder="Transcription will appear here…",
361
+ interactive=False,
362
+ )
363
+
364
+ gr.Markdown("### Waveform")
365
+ waveform_out = gr.Plot(label="", show_label=False)
366
+
367
+ gr.Markdown("### Segments")
368
+ segment_html = gr.HTML("")
369
+
370
+ gr.Markdown("### Download")
371
+ with gr.Row(visible=False) as download_row:
372
+ dl_txt = gr.File(label="TXT", file_count="single")
373
+ dl_json = gr.File(label="JSON", file_count="single")
374
+ dl_srt = gr.File(label="SRT", file_count="single")
375
+ dl_vtt = gr.File(label="VTT", file_count="single")
376
+
377
+ # Wire up
378
+ transcribe_btn.click(
379
+ fn=transcribe,
380
+ inputs=[audio_input, model_dropdown, lang_dropdown, task_radio, timestamps_toggle],
381
+ outputs=[text_out, stats_out, waveform_out, segment_html,
382
+ dl_txt, dl_json, dl_srt, dl_vtt, download_row],
383
+ )
384
+
385
+ if __name__ == "__main__":
386
+ demo.launch(
387
+ server_name="0.0.0.0",
388
+ server_port=int(os.getenv("GRADIO_SERVER_PORT", 7860)),
389
+ show_error=True,
390
+ )
requirements.txt ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core
2
+ setuptools==69.0.2
3
+ wheel==0.42.0
4
+
5
+ # Audio processing
6
+ librosa==0.10.1
7
+ soundfile==0.12.1
8
+ pydub==0.25.1
9
+ audioread==3.0.1
10
+ pooch==1.8.0
11
+ platformdirs==4.1.0
12
+
13
+ # ML/AI
14
+ torch==2.1.0
15
+ transformers==4.35.2
16
+ accelerate==0.24.1
17
+ # NOTE: safetensors is kept as a dep but we no longer force use_safetensors=True
18
+ # in from_pretrained — transformers will use it automatically when available.
19
+ safetensors==0.4.1
20
+ tokenizers==0.15.0
21
+
22
+ # Visualization
23
+ matplotlib==3.8.2
24
+
25
+ # API server (app.py)
26
+ fastapi==0.104.1
27
+ uvicorn==0.24.0
28
+ python-multipart==0.0.6
29
+
30
+ # UI
31
+ gradio==4.7.1
32
+
33
+ # Utilities
34
+ pyyaml==6.0.1
35
+ numpy==1.24.3
36
+ scipy==1.11.4
37
+ typing-extensions==4.9.0
38
+ packaging==23.2
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Module initialization
src/audio_processor/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .validator import AudioValidator, AudioMetadata
2
+ from .converter import AudioConverter
3
+ from .chunker import AudioChunker, AudioChunk
4
+
5
+ __all__ = ['AudioValidator', 'AudioMetadata', 'AudioConverter', 'AudioChunker', 'AudioChunk']
src/audio_processor/chunker.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Long audio chunking module
3
+ Author: Maaldeens
4
+ License: MIT
5
+ """
6
+
7
+ import numpy as np
8
+ import librosa
9
+ from typing import List, Tuple, Generator
10
+ import logging
11
+ from dataclasses import dataclass
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ @dataclass
16
+ class AudioChunk:
17
+ """Audio chunk with metadata"""
18
+ audio: np.ndarray
19
+ start_time: float
20
+ end_time: float
21
+ index: int
22
+ overlap_with_prev: bool = False
23
+
24
+ class AudioChunker:
25
+ """
26
+ Splits long audio files into manageable chunks
27
+ Maintains context through overlap
28
+ """
29
+
30
+ def __init__(self, chunk_duration: int = 30, overlap_duration: int = 2,
31
+ target_sr: int = 16000):
32
+ self.chunk_samples = chunk_duration * target_sr
33
+ self.overlap_samples = overlap_duration * target_sr
34
+ self.target_sr = target_sr
35
+ self.chunk_duration = chunk_duration
36
+ self.overlap_duration = overlap_duration
37
+
38
+ def should_chunk(self, duration: float) -> bool:
39
+ """Determine if audio needs chunking"""
40
+ return duration > self.chunk_duration
41
+
42
+ def create_chunks(self, audio: np.ndarray, sample_rate: int) -> List[AudioChunk]:
43
+ """Split audio into overlapping chunks"""
44
+ if sample_rate != self.target_sr:
45
+ audio = librosa.resample(audio, orig_sr=sample_rate, target_sr=self.target_sr)
46
+
47
+ total_samples = len(audio)
48
+
49
+ if total_samples <= self.chunk_samples:
50
+ return [
51
+ AudioChunk(
52
+ audio=audio,
53
+ start_time=0,
54
+ end_time=total_samples / self.target_sr,
55
+ index=0,
56
+ overlap_with_prev=False
57
+ )
58
+ ]
59
+
60
+ chunks = []
61
+ step = self.chunk_samples - self.overlap_samples
62
+ num_chunks = (total_samples - self.overlap_samples) // step + 1
63
+
64
+ for i in range(num_chunks):
65
+ start = i * step
66
+ end = min(start + self.chunk_samples, total_samples)
67
+ chunk_audio = audio[start:end]
68
+
69
+ if len(chunk_audio) < self.chunk_samples // 2:
70
+ break
71
+
72
+ chunk = AudioChunk(
73
+ audio=chunk_audio,
74
+ start_time=start / self.target_sr,
75
+ end_time=end / self.target_sr,
76
+ index=i,
77
+ overlap_with_prev=(i > 0)
78
+ )
79
+ chunks.append(chunk)
80
+ logger.info(f"Created chunk {i}: {chunk.start_time:.1f}s - {chunk.end_time:.1f}s")
81
+
82
+ return chunks
83
+
84
+ def merge_chunk_results(self, chunk_results: List[Tuple[AudioChunk, dict]]) -> dict:
85
+ """Merge transcription results from chunks"""
86
+ if not chunk_results:
87
+ return {"text": "", "segments": [], "chunks": 0}
88
+
89
+ merged_text = []
90
+ merged_segments = []
91
+ last_end_time = 0
92
+ overlap_region = self.overlap_duration / 2
93
+
94
+ for i, (chunk, result) in enumerate(chunk_results):
95
+ if i == 0:
96
+ merged_text.append(result.get("text", ""))
97
+ merged_segments.extend(result.get("segments", []))
98
+ if result.get("segments"):
99
+ last_end_time = result["segments"][-1].get("end", 0)
100
+ else:
101
+ segments = result.get("segments", [])
102
+ trimmed_segments = []
103
+
104
+ for seg in segments:
105
+ seg_start = seg.get("start", 0) + chunk.start_time
106
+ if seg_start > last_end_time - overlap_region:
107
+ adjusted_seg = seg.copy()
108
+ adjusted_seg["start"] = seg_start
109
+ adjusted_seg["end"] = seg.get("end", 0) + chunk.start_time
110
+ trimmed_segments.append(adjusted_seg)
111
+ last_end_time = max(last_end_time, adjusted_seg["end"])
112
+
113
+ if trimmed_segments:
114
+ chunk_text = " ".join([seg.get("text", "") for seg in trimmed_segments])
115
+ merged_text.append(chunk_text)
116
+ merged_segments.extend(trimmed_segments)
117
+
118
+ merged_segments.sort(key=lambda x: x.get("start", 0))
119
+
120
+ return {
121
+ "text": " ".join(merged_text),
122
+ "segments": merged_segments,
123
+ "chunks": len(chunk_results)
124
+ }
src/audio_processor/converter.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Audio conversion and normalization module - Simplified without noisereduce
3
+ Author: Maaldeens
4
+ License: MIT
5
+ """
6
+
7
+ import os
8
+ import numpy as np
9
+ import librosa
10
+ import soundfile as sf
11
+ from pydub import AudioSegment
12
+ from pathlib import Path
13
+ import tempfile
14
+ import logging
15
+ from typing import Optional
16
+ import uuid
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ class AudioConverter:
21
+ """
22
+ Converts audio to standard format for ASR processing
23
+ Target: 16kHz mono WAV with normalized volume
24
+ """
25
+
26
+ def __init__(self, target_sr: int = 16000, target_channels: int = 1,
27
+ target_dbfs: int = -20, apply_noise_reduction: bool = False): # Disabled by default
28
+ self.target_sr = target_sr
29
+ self.target_channels = target_channels
30
+ self.target_dbfs = target_dbfs
31
+ self.apply_noise_reduction = False # Force disable
32
+ self.temp_dir = Path(tempfile.gettempdir()) / "asr_temp"
33
+ self.temp_dir.mkdir(exist_ok=True)
34
+
35
+ def convert_to_wav(self, input_path: str, output_path: Optional[str] = None) -> str:
36
+ """Convert any audio format to WAV using pydub"""
37
+ if not output_path:
38
+ output_path = str(self.temp_dir / f"{uuid.uuid4()}.wav")
39
+
40
+ try:
41
+ audio = AudioSegment.from_file(input_path)
42
+ audio.export(output_path, format="wav")
43
+ logger.info(f"Converted {input_path} to WAV: {output_path}")
44
+ return output_path
45
+ except Exception as e:
46
+ logger.error(f"Conversion failed for {input_path}: {e}")
47
+ raise
48
+
49
+ def resample(self, input_path: str, target_sr: int = None) -> np.ndarray:
50
+ """Resample audio to target sample rate"""
51
+ target_sr = target_sr or self.target_sr
52
+
53
+ try:
54
+ audio, sr = librosa.load(input_path, sr=None, mono=False)
55
+ if sr != target_sr:
56
+ audio = librosa.resample(audio, orig_sr=sr, target_sr=target_sr)
57
+ logger.info(f"Resampled from {sr}Hz to {target_sr}Hz")
58
+ return audio
59
+ except Exception as e:
60
+ logger.error(f"Resampling failed: {e}")
61
+ raise
62
+
63
+ def convert_to_mono(self, audio: np.ndarray) -> np.ndarray:
64
+ """Convert stereo to mono by averaging channels"""
65
+ if audio.ndim > 1 and audio.shape[0] == 2:
66
+ mono = np.mean(audio, axis=0)
67
+ logger.info("Converted stereo to mono")
68
+ return mono
69
+ return audio
70
+
71
+ def normalize_volume(self, audio: np.ndarray, sr: int, target_dbfs: int = None) -> np.ndarray:
72
+ """Normalize audio volume to target dBFS"""
73
+ target_dbfs = target_dbfs or self.target_dbfs
74
+
75
+ # Simple peak normalization
76
+ max_val = np.max(np.abs(audio))
77
+ if max_val > 0:
78
+ # Target max amplitude of 0.95 to avoid clipping
79
+ target_amplitude = 0.95
80
+ audio = audio * (target_amplitude / max_val)
81
+ logger.info(f"Normalized volume (peak: {max_val:.3f} -> {target_amplitude:.3f})")
82
+
83
+ return audio
84
+
85
+ def preprocess(self, input_path: str, output_path: Optional[str] = None) -> str:
86
+ """Complete preprocessing pipeline without noise reduction"""
87
+ if not output_path:
88
+ output_path = str(self.temp_dir / f"processed_{uuid.uuid4()}.wav")
89
+
90
+ # Step 1: Convert to WAV if needed
91
+ wav_path = self.convert_to_wav(input_path) if not input_path.lower().endswith('.wav') else input_path
92
+
93
+ # Step 2: Load and resample
94
+ audio = self.resample(wav_path)
95
+
96
+ # Step 3: Convert to mono
97
+ audio = self.convert_to_mono(audio)
98
+
99
+ # Step 4: Normalize volume
100
+ audio = self.normalize_volume(audio, self.target_sr)
101
+
102
+ # Step 5: Save processed audio
103
+ sf.write(output_path, audio, self.target_sr)
104
+ logger.info(f"Saved processed audio to {output_path}")
105
+
106
+ # Cleanup temporary WAV if created
107
+ if wav_path != input_path and Path(wav_path).exists():
108
+ Path(wav_path).unlink()
109
+
110
+ return output_path
111
+
112
+ def cleanup(self):
113
+ """Clean up temporary files"""
114
+ for file in self.temp_dir.glob("*.wav"):
115
+ try:
116
+ file.unlink()
117
+ except Exception as e:
118
+ logger.warning(f"Failed to delete {file}: {e}")
src/audio_processor/validator.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Audio file validator and metadata extractor
3
+ Author: Maaldeens
4
+ License: MIT
5
+ """
6
+
7
+ from pathlib import Path
8
+ from typing import Dict, Tuple, Optional
9
+ import logging
10
+ from dataclasses import dataclass
11
+ import librosa
12
+ import soundfile as sf
13
+
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ @dataclass
19
+ class AudioMetadata:
20
+ """Audio file metadata container."""
21
+ filename: str
22
+ format: str
23
+ sample_rate: int
24
+ channels: int
25
+ duration: float
26
+ file_size: int
27
+ # FIX: subtype from soundfile is a string like "PCM_16", not an int.
28
+ bit_depth: Optional[str] = None
29
+ bit_rate: Optional[int] = None
30
+
31
+
32
+ class AudioValidator:
33
+ """Validates audio files and extracts metadata. Supports mp3, wav, m4a, ogg, flac, aac."""
34
+
35
+ EXTENSION_MAP = {
36
+ ".mp3": "mp3",
37
+ ".wav": "wav",
38
+ ".m4a": "m4a",
39
+ ".ogg": "ogg",
40
+ ".flac": "flac",
41
+ ".aac": "aac",
42
+ ".mp4": "m4a",
43
+ ".aiff": "aiff",
44
+ ".wma": "wma",
45
+ }
46
+
47
+ def __init__(self, max_file_size_mb: int = 500):
48
+ self.max_file_size_bytes = max_file_size_mb * 1024 * 1024
49
+
50
+ def validate_file(self, file_path: str) -> Tuple[bool, str]:
51
+ path = Path(file_path)
52
+ if not path.exists():
53
+ return False, f"File not found: {file_path}"
54
+ if not path.is_file():
55
+ return False, f"Path is not a file: {file_path}"
56
+ size = path.stat().st_size
57
+ if size > self.max_file_size_bytes:
58
+ return False, f"File size ({size/1024/1024:.1f} MB) exceeds limit ({self.max_file_size_bytes/1024/1024:.0f} MB)"
59
+ if size == 0:
60
+ return False, "File is empty"
61
+ return True, ""
62
+
63
+ def detect_format(self, file_path: str) -> Optional[str]:
64
+ return self.EXTENSION_MAP.get(Path(file_path).suffix.lower())
65
+
66
+ def extract_metadata(self, file_path: str) -> Optional[AudioMetadata]:
67
+ try:
68
+ info = sf.info(file_path)
69
+ stats = Path(file_path).stat()
70
+ return AudioMetadata(
71
+ filename=Path(file_path).name,
72
+ format=self.detect_format(file_path) or "unknown",
73
+ sample_rate=int(info.samplerate),
74
+ channels=info.channels,
75
+ duration=float(info.duration),
76
+ file_size=stats.st_size,
77
+ # subtype is a string e.g. "PCM_16" — stored as-is
78
+ bit_depth=str(info.subtype) if hasattr(info, "subtype") and info.subtype else None,
79
+ )
80
+ except Exception as e:
81
+ logger.warning(f"soundfile metadata extraction failed ({e}), trying librosa fallback")
82
+ try:
83
+ y, sr = librosa.load(file_path, sr=None, mono=False, duration=5)
84
+ stats = Path(file_path).stat()
85
+ channels = 2 if y.ndim > 1 and y.shape[0] == 2 else 1
86
+ duration = librosa.get_duration(y=y, sr=sr)
87
+ return AudioMetadata(
88
+ filename=Path(file_path).name,
89
+ format=self.detect_format(file_path) or "unknown",
90
+ sample_rate=int(sr),
91
+ channels=channels,
92
+ duration=float(duration),
93
+ file_size=stats.st_size,
94
+ )
95
+ except Exception as e2:
96
+ logger.error(f"Librosa fallback also failed: {e2}")
97
+ return None
98
+
99
+ def is_valid_audio(self, file_path: str) -> Tuple[bool, Optional[AudioMetadata], str]:
100
+ is_valid, error = self.validate_file(file_path)
101
+ if not is_valid:
102
+ return False, None, error
103
+
104
+ if not self.detect_format(file_path):
105
+ return False, None, f"Unsupported audio format: {Path(file_path).suffix}"
106
+
107
+ metadata = self.extract_metadata(file_path)
108
+ if not metadata:
109
+ return False, None, "Failed to extract audio metadata"
110
+
111
+ if metadata.duration < 0.1:
112
+ return False, metadata, "Audio too short (< 0.1 s)"
113
+
114
+ return True, metadata, ""
src/models/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .registry import ModelRegistry
2
+ from .asr_pipeline import ASRPipeline, TranscriptionResult
3
+
4
+ __all__ = ['ModelRegistry', 'ASRPipeline', 'TranscriptionResult']
src/models/asr_pipeline.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Standardized ASR pipeline wrapper
3
+ Author: Maaldeens
4
+ License: MIT
5
+ """
6
+
7
+ import io
8
+ import time
9
+ import numpy as np
10
+ import soundfile as sf
11
+ from typing import Optional, Dict, Any, Union, List
12
+ import logging
13
+ from dataclasses import dataclass, asdict
14
+ import json
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ @dataclass
20
+ class TranscriptionResult:
21
+ """Standardized transcription result."""
22
+ text: str
23
+ language: Optional[str] = None
24
+ segments: Optional[List[Dict]] = None
25
+ confidence: Optional[float] = None
26
+ word_timestamps: Optional[List[Dict]] = None
27
+ model_used: Optional[str] = None
28
+ processing_time: Optional[float] = None
29
+ audio_duration: Optional[float] = None
30
+
31
+ def to_dict(self) -> Dict:
32
+ return {k: v for k, v in asdict(self).items() if v is not None}
33
+
34
+ def to_json(self) -> str:
35
+ return json.dumps(self.to_dict(), indent=2, ensure_ascii=False)
36
+
37
+ def to_merge_dict(self) -> Dict:
38
+ """Shape expected by AudioChunker.merge_chunk_results."""
39
+ return {
40
+ "text": self.text or "",
41
+ "segments": self.segments or [],
42
+ "language": self.language,
43
+ }
44
+
45
+
46
+ class ASRPipeline:
47
+ """Standardized ASR pipeline that works with Whisper models."""
48
+
49
+ def __init__(self, model_key: str, registry, config: Dict):
50
+ self.model_key = model_key
51
+ self.registry = registry
52
+ self.config = config
53
+ self.pipeline = None
54
+
55
+ def _initialize_pipeline(self):
56
+ if self.pipeline is None:
57
+ self.pipeline = self.registry.create_pipeline(self.model_key)
58
+
59
+ def transcribe(self, audio: Union[str, np.ndarray, bytes], **kwargs) -> "TranscriptionResult":
60
+ start_time = time.time()
61
+ self._initialize_pipeline()
62
+
63
+ generate_kwargs = {
64
+ "task": kwargs.get("task", self.config.get("task", "transcribe")),
65
+ "language": kwargs.get("language", self.config.get("language")),
66
+ }
67
+ generate_kwargs = {k: v for k, v in generate_kwargs.items() if v is not None}
68
+
69
+ return_timestamps = kwargs.get(
70
+ "return_timestamps", self.config.get("return_timestamps", True)
71
+ )
72
+
73
+ try:
74
+ if isinstance(audio, (str, np.ndarray)):
75
+ result = self.pipeline(
76
+ audio,
77
+ return_timestamps=return_timestamps,
78
+ generate_kwargs=generate_kwargs,
79
+ )
80
+ elif isinstance(audio, bytes):
81
+ audio_array, _ = sf.read(io.BytesIO(audio))
82
+ result = self.pipeline(
83
+ audio_array,
84
+ return_timestamps=return_timestamps,
85
+ generate_kwargs=generate_kwargs,
86
+ )
87
+ else:
88
+ raise ValueError(f"Unsupported audio type: {type(audio)}")
89
+
90
+ transcription = self._format_result(result)
91
+ transcription.processing_time = time.time() - start_time
92
+ transcription.model_used = self.model_key
93
+ return transcription
94
+
95
+ except Exception as e:
96
+ logger.error(f"Transcription failed: {e}")
97
+ raise
98
+
99
+ def _format_result(self, result: Dict) -> "TranscriptionResult":
100
+ text = result.get("text", "").strip()
101
+
102
+ segments = []
103
+ for chunk in result.get("chunks", []):
104
+ ts = chunk.get("timestamp", [0, 0])
105
+ if isinstance(ts, (list, tuple)) and len(ts) >= 2:
106
+ segments.append({
107
+ "start": float(ts[0]) if ts[0] is not None else 0.0,
108
+ "end": float(ts[1]) if ts[1] is not None else 0.0,
109
+ "text": chunk.get("text", "").strip(),
110
+ })
111
+
112
+ return TranscriptionResult(
113
+ text=text,
114
+ language=result.get("language"),
115
+ segments=segments if segments else None,
116
+ )
src/models/registry.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Model registry for dynamic model loading
3
+ Author: Maaldeens
4
+ License: MIT
5
+ """
6
+
7
+ import torch
8
+ from transformers import (
9
+ WhisperProcessor,
10
+ WhisperForConditionalGeneration,
11
+ pipeline
12
+ )
13
+ from typing import Dict, Any, Optional, Tuple
14
+ import logging
15
+ import yaml
16
+ from pathlib import Path
17
+ import gc
18
+ import os
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ class ModelRegistry:
23
+ """Registry for managing ASR models with caching and device management."""
24
+
25
+ def __init__(self, config_path: Optional[str] = None):
26
+ self.models = {}
27
+ self.processors = {}
28
+ self.pipelines = {}
29
+ self.config = self._load_config(config_path)
30
+ self.device = self._get_device()
31
+ self.current_model = None
32
+ # Respect HF_HOME env var for persistent model caching across restarts
33
+ self.cache_dir = os.getenv(
34
+ "HF_HOME",
35
+ self.config.get("models", {}).get("cache_dir", "/app/model_cache")
36
+ )
37
+
38
+ def _load_config(self, config_path: Optional[str] = None) -> Dict:
39
+ if config_path and Path(config_path).exists():
40
+ with open(config_path, 'r') as f:
41
+ return yaml.safe_load(f)
42
+ return {"models": {"available": {}}}
43
+
44
+ def _get_device(self) -> torch.device:
45
+ if torch.cuda.is_available():
46
+ return torch.device("cuda")
47
+ elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
48
+ return torch.device("mps")
49
+ return torch.device("cpu")
50
+
51
+ def load_model(self, model_key: str, force_reload: bool = False) -> Tuple[Any, Any]:
52
+ if not force_reload and model_key in self.models:
53
+ logger.info(f"Using cached model: {model_key}")
54
+ return self.models[model_key], self.processors[model_key]
55
+
56
+ available_models = self.config.get("models", {}).get("available", {})
57
+
58
+ if model_key not in available_models:
59
+ default = self.config.get("models", {}).get("default", "whisper-medium")
60
+ if default in available_models:
61
+ logger.warning(f"Model {model_key} not found, using default: {default}")
62
+ model_key = default
63
+ else:
64
+ logger.warning(f"Using fallback model path: openai/whisper-{model_key}")
65
+ return self._load_whisper_model(f"openai/whisper-{model_key}", model_key, force_reload)
66
+
67
+ model_config = available_models.get(model_key, {})
68
+ model_path = model_config.get("path", f"openai/whisper-{model_key}")
69
+ return self._load_whisper_model(model_path, model_key, force_reload)
70
+
71
+ def _load_whisper_model(self, model_path: str, model_key: str, force_reload: bool) -> Tuple[Any, Any]:
72
+ logger.info(f"Loading Whisper model: {model_key} from {model_path}")
73
+ try:
74
+ if force_reload and model_key in self.models:
75
+ del self.models[model_key]
76
+ del self.processors[model_key]
77
+ gc.collect()
78
+ if torch.cuda.is_available():
79
+ torch.cuda.empty_cache()
80
+
81
+ processor = WhisperProcessor.from_pretrained(
82
+ model_path,
83
+ cache_dir=self.cache_dir
84
+ )
85
+
86
+ # FIX: Do NOT pass use_safetensors=True — many Whisper checkpoints
87
+ # only ship .bin weights; safetensors would raise FileNotFoundError.
88
+ # transformers auto-selects the best available format.
89
+ model = WhisperForConditionalGeneration.from_pretrained(
90
+ model_path,
91
+ torch_dtype=torch.float16 if self.device.type == "cuda" else torch.float32,
92
+ low_cpu_mem_usage=True,
93
+ cache_dir=self.cache_dir
94
+ )
95
+
96
+ model = model.to(self.device)
97
+ model.eval()
98
+
99
+ self.models[model_key] = model
100
+ self.processors[model_key] = processor
101
+ self.current_model = model_key
102
+
103
+ logger.info(f"Successfully loaded {model_key} on {self.device}")
104
+ return model, processor
105
+
106
+ except Exception as e:
107
+ logger.error(f"Failed to load model {model_key}: {e}")
108
+ raise
109
+
110
+ def create_pipeline(self, model_key: str, **kwargs) -> Any:
111
+ if model_key in self.pipelines and not kwargs.get("force_reload", False):
112
+ return self.pipelines[model_key]
113
+
114
+ model, processor = self.load_model(model_key)
115
+
116
+ pipe = pipeline(
117
+ task="automatic-speech-recognition",
118
+ model=model,
119
+ tokenizer=processor.tokenizer,
120
+ feature_extractor=processor.feature_extractor,
121
+ device=self.device
122
+ )
123
+
124
+ self.pipelines[model_key] = pipe
125
+ return pipe
126
+
127
+ def list_available_models(self) -> Dict[str, Dict]:
128
+ available = self.config.get("models", {}).get("available", {})
129
+ if not available:
130
+ available = {
131
+ "whisper-tiny": {"path": "openai/whisper-tiny", "type": "whisper", "size": "39M", "speed": "~32x"},
132
+ "whisper-small": {"path": "openai/whisper-small", "type": "whisper", "size": "244M", "speed": "~8x"},
133
+ "whisper-medium": {"path": "openai/whisper-medium", "type": "whisper", "size": "769M", "speed": "~2x"},
134
+ "whisper-large-v3": {"path": "openai/whisper-large-v3", "type": "whisper", "size": "1.5B", "speed": "1x"},
135
+ }
136
+ return available
137
+
138
+ def get_current_model(self) -> Optional[str]:
139
+ return self.current_model
src/output/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .formatter import OutputFormatter
2
+
3
+ __all__ = ['OutputFormatter']
src/output/formatter.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Output formatter for transcription results
3
+ Author: Maaldeens
4
+ License: MIT
5
+ """
6
+
7
+ from typing import Dict, Optional
8
+ import json
9
+ import logging
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class OutputFormatter:
15
+ """Formats transcription results into plain text, JSON, SRT, and WebVTT."""
16
+
17
+ @staticmethod
18
+ def to_text(result: Dict) -> str:
19
+ return result.get("text", "")
20
+
21
+ @staticmethod
22
+ def to_json(result: Dict, pretty: bool = True) -> str:
23
+ return json.dumps(result, indent=2 if pretty else None, ensure_ascii=False)
24
+
25
+ @staticmethod
26
+ def _format_timestamp(total_seconds: float, fmt: str = "srt") -> str:
27
+ """
28
+ Convert a float number of seconds to a subtitle timestamp string.
29
+
30
+ FIX: Previously used timedelta.seconds which caps at 86399 and drops days.
31
+ Now derived from the raw float — correct for any duration.
32
+ """
33
+ total_seconds = max(0.0, total_seconds)
34
+ hours = int(total_seconds) // 3600
35
+ minutes = (int(total_seconds) % 3600) // 60
36
+ secs = int(total_seconds) % 60
37
+ millis = round((total_seconds - int(total_seconds)) * 1000)
38
+
39
+ if fmt == "srt":
40
+ return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
41
+ else: # vtt
42
+ if hours > 0:
43
+ return f"{hours:02d}:{minutes:02d}:{secs:02d}.{millis:03d}"
44
+ return f"{minutes:02d}:{secs:02d}.{millis:03d}"
45
+
46
+ @staticmethod
47
+ def to_srt(result: Dict) -> str:
48
+ segments = result.get("segments", [])
49
+ if not segments:
50
+ return ""
51
+ lines = []
52
+ for i, seg in enumerate(segments, 1):
53
+ start = OutputFormatter._format_timestamp(seg.get("start", 0), "srt")
54
+ end = OutputFormatter._format_timestamp(seg.get("end", 0), "srt")
55
+ text = seg.get("text", "").strip()
56
+ lines += [str(i), f"{start} --> {end}", text, ""]
57
+ return "\n".join(lines)
58
+
59
+ @staticmethod
60
+ def to_vtt(result: Dict) -> str:
61
+ segments = result.get("segments", [])
62
+ if not segments:
63
+ return "WEBVTT\n\n"
64
+ lines = ["WEBVTT", ""]
65
+ for seg in segments:
66
+ start = OutputFormatter._format_timestamp(seg.get("start", 0), "vtt")
67
+ end = OutputFormatter._format_timestamp(seg.get("end", 0), "vtt")
68
+ lines += [f"{start} --> {end}", seg.get("text", "").strip(), ""]
69
+ return "\n".join(lines)
70
+
71
+ @staticmethod
72
+ def format(result: Dict, output_format: str, **kwargs) -> str:
73
+ formatters = {
74
+ "txt": OutputFormatter.to_text,
75
+ "json": lambda r: OutputFormatter.to_json(r, kwargs.get("pretty", True)),
76
+ "srt": OutputFormatter.to_srt,
77
+ "vtt": OutputFormatter.to_vtt,
78
+ }
79
+ fn = formatters.get(output_format.lower())
80
+ if not fn:
81
+ raise ValueError(f"Unsupported output format: {output_format}. Choose from: txt, json, srt, vtt")
82
+ return fn(result)
83
+
84
+ @staticmethod
85
+ def save_to_file(result: Dict, output_path: str, fmt: Optional[str] = None):
86
+ if fmt is None:
87
+ fmt = output_path.rsplit(".", 1)[-1].lower()
88
+ content = OutputFormatter.format(result, fmt)
89
+ with open(output_path, 'w', encoding='utf-8') as f:
90
+ f.write(content)
91
+ logger.info(f"Saved transcription to {output_path}")
src/transcription/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .engine import TranscriptionEngine
2
+
3
+ __all__ = ['TranscriptionEngine']
src/transcription/engine.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Main transcription engine orchestrating all components
3
+ Author: Maaldeens
4
+ License: MIT
5
+ """
6
+
7
+ import os
8
+ from pathlib import Path
9
+ from typing import Optional, Dict, Any, Union
10
+ import logging
11
+ import yaml
12
+ import soundfile as sf
13
+
14
+ from ..audio_processor.validator import AudioValidator
15
+ from ..audio_processor.converter import AudioConverter
16
+ from ..audio_processor.chunker import AudioChunker
17
+ from ..models.registry import ModelRegistry
18
+ from ..models.asr_pipeline import ASRPipeline, TranscriptionResult
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class TranscriptionEngine:
24
+ """Main transcription engine orchestrating the entire pipeline."""
25
+
26
+ def __init__(self, config_path: Optional[str] = None):
27
+ self.config = self._load_config(config_path)
28
+ self.temp_dir = Path(self.config.get("system", {}).get("temp_dir", "/app/temp"))
29
+ self.temp_dir.mkdir(exist_ok=True, parents=True)
30
+
31
+ self.validator = AudioValidator(
32
+ max_file_size_mb=self.config.get("system", {}).get("max_file_size_mb", 500)
33
+ )
34
+
35
+ audio_cfg = self.config.get("audio", {})
36
+ # FIX: default noise_reduction to False — consistent with settings.yaml
37
+ self.converter = AudioConverter(
38
+ target_sr=audio_cfg.get("target_sample_rate", 16000),
39
+ target_channels=audio_cfg.get("target_channels", 1),
40
+ target_dbfs=audio_cfg.get("target_dbfs", -20),
41
+ apply_noise_reduction=audio_cfg.get("noise_reduction", False),
42
+ )
43
+
44
+ self.chunker = AudioChunker(
45
+ chunk_duration=audio_cfg.get("chunk_duration_sec", 30),
46
+ overlap_duration=audio_cfg.get("chunk_overlap_sec", 2),
47
+ target_sr=audio_cfg.get("target_sample_rate", 16000),
48
+ )
49
+
50
+ self.registry = ModelRegistry(config_path)
51
+ self._pipeline: Optional[ASRPipeline] = None
52
+ self.current_model_key = self.config.get("models", {}).get("default", "whisper-medium")
53
+
54
+ def _load_config(self, config_path: Optional[str]) -> Dict:
55
+ if config_path and Path(config_path).exists():
56
+ with open(config_path, 'r') as f:
57
+ return yaml.safe_load(f)
58
+ return {}
59
+
60
+ def set_model(self, model_key: str):
61
+ available = self.registry.list_available_models()
62
+ if model_key not in available:
63
+ raise ValueError(f"Model '{model_key}' not available. Options: {list(available.keys())}")
64
+ self.current_model_key = model_key
65
+ self._pipeline = None
66
+ logger.info(f"Model changed to: {model_key}")
67
+
68
+ def _get_pipeline(self) -> ASRPipeline:
69
+ if self._pipeline is None:
70
+ self._pipeline = ASRPipeline(
71
+ self.current_model_key,
72
+ self.registry,
73
+ self.config.get("transcription", {}),
74
+ )
75
+ return self._pipeline
76
+
77
+ def transcribe_file(self, file_path: str, **kwargs) -> TranscriptionResult:
78
+ logger.info(f"Processing file: {file_path}")
79
+
80
+ is_valid, metadata, error = self.validator.is_valid_audio(file_path)
81
+ if not is_valid:
82
+ raise ValueError(f"Invalid audio file: {error}")
83
+
84
+ processed_path = self.converter.preprocess(file_path)
85
+ audio, sr = sf.read(processed_path)
86
+
87
+ try:
88
+ if self.chunker.should_chunk(metadata.duration):
89
+ logger.info(f"Long audio ({metadata.duration:.1f}s) — chunking...")
90
+ chunks = self.chunker.create_chunks(audio, sr)
91
+ chunk_results = []
92
+
93
+ for chunk in chunks:
94
+ chunk_path = self.temp_dir / f"chunk_{chunk.index}.wav"
95
+ sf.write(chunk_path, chunk.audio, sr)
96
+ chunk_result = self._get_pipeline().transcribe(str(chunk_path), **kwargs)
97
+ # FIX: use to_merge_dict() which returns the shape merge_chunk_results expects
98
+ chunk_results.append((chunk, chunk_result.to_merge_dict()))
99
+ chunk_path.unlink(missing_ok=True)
100
+
101
+ merged = self.chunker.merge_chunk_results(chunk_results)
102
+ result = TranscriptionResult(
103
+ text=merged["text"],
104
+ language=merged.get("language"),
105
+ segments=merged.get("segments") or None,
106
+ audio_duration=metadata.duration,
107
+ model_used=self.current_model_key,
108
+ )
109
+ else:
110
+ result = self._get_pipeline().transcribe(processed_path, **kwargs)
111
+ result.audio_duration = metadata.duration
112
+
113
+ finally:
114
+ Path(processed_path).unlink(missing_ok=True)
115
+
116
+ return result
117
+
118
+ def transcribe_bytes(self, audio_bytes: bytes, filename: str = "audio", **kwargs) -> TranscriptionResult:
119
+ temp_path = self.temp_dir / f"upload_{filename}"
120
+ with open(temp_path, 'wb') as f:
121
+ f.write(audio_bytes)
122
+ try:
123
+ return self.transcribe_file(str(temp_path), **kwargs)
124
+ finally:
125
+ temp_path.unlink(missing_ok=True)
126
+
127
+ def get_available_models(self) -> Dict:
128
+ return self.registry.list_available_models()
129
+
130
+ def get_current_model_info(self) -> Dict:
131
+ return self.registry.list_available_models().get(self.current_model_key, {})
test.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unit tests for pure-function modules: formatter and chunker.
3
+ Run with: python -m pytest test.py -v
4
+ """
5
+
6
+ import sys
7
+ import numpy as np
8
+ import pytest
9
+
10
+ # ---------------------------------------------------------------------------
11
+ # Basic import smoke test
12
+ # ---------------------------------------------------------------------------
13
+
14
+ def test_imports():
15
+ try:
16
+ import pkg_resources
17
+ import setuptools
18
+ import yaml
19
+ import gradio
20
+ import torch
21
+ import transformers
22
+ import librosa
23
+ import soundfile
24
+ import matplotlib
25
+ except ImportError as e:
26
+ pytest.fail(f"Missing dependency: {e}")
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # OutputFormatter
31
+ # ---------------------------------------------------------------------------
32
+
33
+ from src.output.formatter import OutputFormatter
34
+
35
+ class TestTimestamp:
36
+ def test_zero(self):
37
+ assert OutputFormatter._format_timestamp(0, "srt") == "00:00:00,000"
38
+
39
+ def test_sub_minute(self):
40
+ assert OutputFormatter._format_timestamp(5.5, "srt") == "00:00:05,500"
41
+
42
+ def test_over_one_hour(self):
43
+ # 3661.25 s = 1h 1m 1.25s
44
+ result = OutputFormatter._format_timestamp(3661.25, "srt")
45
+ assert result == "01:01:01,250"
46
+
47
+ def test_vtt_under_one_hour(self):
48
+ result = OutputFormatter._format_timestamp(90.0, "vtt")
49
+ assert result == "01:30.000"
50
+
51
+ def test_vtt_over_one_hour(self):
52
+ result = OutputFormatter._format_timestamp(3700.0, "vtt")
53
+ assert result == "01:01:40.000"
54
+
55
+
56
+ class TestSRT:
57
+ def test_empty_segments(self):
58
+ assert OutputFormatter.to_srt({"segments": []}) == ""
59
+
60
+ def test_basic_srt(self):
61
+ result = {"segments": [{"start": 0.0, "end": 2.5, "text": "Hello world"}]}
62
+ srt = OutputFormatter.to_srt(result)
63
+ assert "1" in srt
64
+ assert "00:00:00,000 --> 00:00:02,500" in srt
65
+ assert "Hello world" in srt
66
+
67
+ def test_multi_segment(self):
68
+ result = {"segments": [
69
+ {"start": 0.0, "end": 1.0, "text": "First"},
70
+ {"start": 1.0, "end": 2.0, "text": "Second"},
71
+ ]}
72
+ srt = OutputFormatter.to_srt(result)
73
+ assert "First" in srt
74
+ assert "Second" in srt
75
+
76
+
77
+ class TestVTT:
78
+ def test_empty_returns_webvtt_header(self):
79
+ assert OutputFormatter.to_vtt({"segments": []}).startswith("WEBVTT")
80
+
81
+ def test_basic_vtt(self):
82
+ result = {"segments": [{"start": 0.0, "end": 3.0, "text": "Test"}]}
83
+ vtt = OutputFormatter.to_vtt(result)
84
+ assert vtt.startswith("WEBVTT")
85
+ assert "00:03.000" in vtt
86
+
87
+
88
+ class TestFormatDispatch:
89
+ def test_txt(self):
90
+ assert OutputFormatter.format({"text": "hi"}, "txt") == "hi"
91
+
92
+ def test_unsupported_raises(self):
93
+ with pytest.raises(ValueError, match="Unsupported"):
94
+ OutputFormatter.format({}, "docx")
95
+
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # AudioChunker
99
+ # ---------------------------------------------------------------------------
100
+
101
+ from src.audio_processor.chunker import AudioChunker, AudioChunk
102
+
103
+ class TestChunker:
104
+ SR = 16000
105
+
106
+ def _make_audio(self, seconds: float) -> np.ndarray:
107
+ return np.random.rand(int(seconds * self.SR)).astype(np.float32)
108
+
109
+ def test_short_audio_no_chunk(self):
110
+ chunker = AudioChunker(chunk_duration=30, overlap_duration=2, target_sr=self.SR)
111
+ audio = self._make_audio(10)
112
+ chunks = chunker.create_chunks(audio, self.SR)
113
+ assert len(chunks) == 1
114
+ assert chunks[0].index == 0
115
+ assert not chunks[0].overlap_with_prev
116
+
117
+ def test_long_audio_multiple_chunks(self):
118
+ chunker = AudioChunker(chunk_duration=30, overlap_duration=2, target_sr=self.SR)
119
+ audio = self._make_audio(90)
120
+ chunks = chunker.create_chunks(audio, self.SR)
121
+ assert len(chunks) > 1
122
+
123
+ def test_should_chunk(self):
124
+ chunker = AudioChunker(chunk_duration=30, overlap_duration=2, target_sr=self.SR)
125
+ assert not chunker.should_chunk(20)
126
+ assert chunker.should_chunk(60)
127
+
128
+ def test_merge_empty(self):
129
+ chunker = AudioChunker(chunk_duration=30, overlap_duration=2, target_sr=self.SR)
130
+ result = chunker.merge_chunk_results([])
131
+ assert result["text"] == ""
132
+ assert result["segments"] == []
133
+
134
+ def test_merge_single_chunk(self):
135
+ chunker = AudioChunker(chunk_duration=30, overlap_duration=2, target_sr=self.SR)
136
+ audio = self._make_audio(5)
137
+ chunk = AudioChunk(audio=audio, start_time=0, end_time=5, index=0)
138
+ mock_result = {"text": "Hello", "segments": [{"start": 0, "end": 1, "text": "Hello"}]}
139
+ merged = chunker.merge_chunk_results([(chunk, mock_result)])
140
+ assert "Hello" in merged["text"]
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Run directly
145
+ # ---------------------------------------------------------------------------
146
+
147
+ if __name__ == "__main__":
148
+ print("Running basic import check...")
149
+ test_imports()
150
+ print("✓ All imports OK")
151
+ print("\nRun 'python -m pytest test.py -v' for full test suite.")