File size: 7,503 Bytes
df2fada
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""
Audio Processor
Extracts audio from video and transcribes using Whisper
Optimized for Arabic Quran recitation
"""

import os
import subprocess
import tempfile
from pathlib import Path
from typing import Optional, List, Dict
import json

# Try to import whisper
try:
    import whisper
    WHISPER_AVAILABLE = True
except ImportError:
    WHISPER_AVAILABLE = False
    print("Warning: Whisper not installed. Install with: pip install openai-whisper")


class AudioProcessor:
    def __init__(self, model_size: str = "medium"):
        """
        Initialize the audio processor

        Args:
            model_size: Whisper model size
                - "tiny": Fastest, least accurate
                - "base": Fast, basic accuracy
                - "small": Good balance
                - "medium": Recommended for Arabic (best balance)
                - "large": Most accurate, slowest (requires more VRAM)
        """
        self.model_size = model_size
        self.model = None
        self.temp_dir = Path(tempfile.gettempdir()) / "quran_srt"
        self.temp_dir.mkdir(exist_ok=True)

    def load_model(self):
        """Load Whisper model (lazy loading)"""
        if not WHISPER_AVAILABLE:
            raise RuntimeError("Whisper is not installed. Run: pip install openai-whisper")

        if self.model is None:
            print(f"Loading Whisper {self.model_size} model...")
            self.model = whisper.load_model(self.model_size)
            print("Model loaded successfully!")

        return self.model

    def extract_audio(self, video_path: str, output_path: Optional[str] = None) -> str:
        """
        Extract audio from video file using FFmpeg

        Args:
            video_path: Path to the video file
            output_path: Optional output path for audio file

        Returns:
            Path to the extracted audio file
        """
        video_path = Path(video_path)

        if not video_path.exists():
            raise FileNotFoundError(f"Video file not found: {video_path}")

        if output_path is None:
            output_path = self.temp_dir / f"{video_path.stem}_audio.wav"
        else:
            output_path = Path(output_path)

        # FFmpeg command to extract audio as WAV (16kHz for Whisper)
        cmd = [
            "ffmpeg",
            "-i", str(video_path),
            "-vn",                    # No video
            "-acodec", "pcm_s16le",   # PCM format
            "-ar", "16000",           # 16kHz sample rate (Whisper optimal)
            "-ac", "1",               # Mono
            "-y",                     # Overwrite output
            str(output_path)
        ]

        try:
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                check=True
            )
            print(f"Audio extracted to: {output_path}")
            return str(output_path)

        except subprocess.CalledProcessError as e:
            raise RuntimeError(f"FFmpeg error: {e.stderr}")
        except FileNotFoundError:
            raise RuntimeError("FFmpeg not found. Please install FFmpeg.")

    def transcribe(
        self,
        audio_path: str,
        language: str = "ar",
        task: str = "transcribe"
    ) -> Dict:
        """
        Transcribe audio using Whisper

        Args:
            audio_path: Path to audio file
            language: Language code ("ar" for Arabic)
            task: "transcribe" for same language, "translate" for English

        Returns:
            Transcription result with segments and timestamps
        """
        model = self.load_model()

        print(f"Transcribing audio: {audio_path}")
        print("This may take a few minutes depending on the video length...")

        result = model.transcribe(
            audio_path,
            language=language,
            task=task,
            word_timestamps=True,      # Get word-level timestamps
            verbose=False,
            initial_prompt="ุจุณู… ุงู„ู„ู‡ ุงู„ุฑุญู…ู† ุงู„ุฑุญูŠู…",  # Help with Quran context
        )

        return result

    def transcribe_video(
        self,
        video_path: str,
        language: str = "ar"
    ) -> Dict:
        """
        Full pipeline: extract audio and transcribe

        Args:
            video_path: Path to video file
            language: Language code

        Returns:
            Transcription result with segments
        """
        # Extract audio
        audio_path = self.extract_audio(video_path)

        # Transcribe
        result = self.transcribe(audio_path, language=language)

        # Clean up temp audio file
        try:
            os.remove(audio_path)
        except:
            pass

        return result

    def get_segments_with_timing(self, transcription: Dict) -> List[Dict]:
        """
        Extract segments with precise timing from transcription

        Args:
            transcription: Whisper transcription result

        Returns:
            List of segments with start, end, and text
        """
        segments = []

        for segment in transcription.get("segments", []):
            segments.append({
                "id": segment.get("id", len(segments)),
                "start": segment.get("start", 0),
                "end": segment.get("end", 0),
                "text": segment.get("text", "").strip(),
                "words": segment.get("words", []),
                "confidence": segment.get("avg_logprob", 0)
            })

        return segments


class MockAudioProcessor:
    """
    Mock processor for testing without Whisper installed
    """

    def __init__(self, model_size: str = "medium"):
        self.model_size = model_size

    def transcribe_video(self, video_path: str, language: str = "ar") -> Dict:
        """Return mock transcription for testing"""
        return {
            "text": "ุจุณู… ุงู„ู„ู‡ ุงู„ุฑุญู…ู† ุงู„ุฑุญูŠู… ุงู„ุญู…ุฏ ู„ู„ู‡ ุฑุจ ุงู„ุนุงู„ู…ูŠู†",
            "segments": [
                {
                    "id": 0,
                    "start": 0.0,
                    "end": 3.5,
                    "text": "ุจุณู… ุงู„ู„ู‡ ุงู„ุฑุญู…ู† ุงู„ุฑุญูŠู…",
                    "words": []
                },
                {
                    "id": 1,
                    "start": 3.5,
                    "end": 6.0,
                    "text": "ุงู„ุญู…ุฏ ู„ู„ู‡ ุฑุจ ุงู„ุนุงู„ู…ูŠู†",
                    "words": []
                }
            ],
            "language": "ar"
        }

    def get_segments_with_timing(self, transcription: Dict) -> List[Dict]:
        return transcription.get("segments", [])


def get_processor(model_size: str = "medium") -> AudioProcessor:
    """
    Get appropriate processor based on Whisper availability
    """
    if WHISPER_AVAILABLE:
        return AudioProcessor(model_size)
    else:
        print("Using mock processor (Whisper not installed)")
        return MockAudioProcessor(model_size)


# For testing
if __name__ == "__main__":
    processor = get_processor()
    print(f"Whisper available: {WHISPER_AVAILABLE}")
    print(f"Processor type: {type(processor).__name__}")

    # Test with mock data
    if not WHISPER_AVAILABLE:
        result = processor.transcribe_video("test.mp4")
        segments = processor.get_segments_with_timing(result)

        print("\nMock transcription result:")
        for seg in segments:
            print(f"[{seg['start']:.2f} - {seg['end']:.2f}] {seg['text']}")