File size: 10,496 Bytes
abbbd7b
 
 
 
 
 
 
 
 
 
7d761b6
 
abbbd7b
 
8ae702a
 
abbbd7b
8ae702a
 
 
abbbd7b
 
7d761b6
abbbd7b
 
8ae702a
abbbd7b
 
 
8ae702a
abbbd7b
 
8ae702a
 
abbbd7b
 
 
 
 
 
 
 
 
 
5c9196d
8ae702a
abbbd7b
 
 
 
 
5c9196d
 
abbbd7b
 
 
5c9196d
abbbd7b
 
 
5c9196d
abbbd7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ae702a
 
abbbd7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ae702a
7d761b6
8ae702a
 
 
5c9196d
 
abbbd7b
8ae702a
 
 
abbbd7b
 
 
 
 
 
 
 
 
8ae702a
abbbd7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ae702a
abbbd7b
 
 
 
 
 
 
 
 
8ae702a
abbbd7b
 
 
 
 
8ae702a
abbbd7b
 
 
 
8ae702a
 
5c9196d
 
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""EchoScript v1.0 UI.

Implements the frozen v1.0 workflow:

    Upload Audio -> Generate Canonical Transcript -> Preview Results
                  -> Generate Outputs -> Copy / Download

Services are instantiated lazily (on first use) rather than at import time,
so the app can start up without needing model weights on disk yet, and so
this module stays import-safe in environments without network access.
"""

from __future__ import annotations

import tempfile
from pathlib import Path
from typing import Optional

import gradio as gr

from models.transcript import Transcript
from services.audio import AudioError, extract_window, resolve_window, validate_extension
from services.subtitles import generate_srt, generate_vtt
from services.transcription import SUPPORTED_LANGUAGES, TranscriptionService
from services.translation import SUPPORTED_TARGET_LANGUAGES, TranslationService

# ---------------------------------------------------------------------------
# Lazy service singletons
# ---------------------------------------------------------------------------

_transcription_service: Optional[TranscriptionService] = None
_translation_service: Optional[TranslationService] = None


def get_transcription_service() -> TranscriptionService:
    global _transcription_service
    if _transcription_service is None:
        _transcription_service = TranscriptionService(
            model_size="base",
            device="cpu",
            compute_type="int8",
            download_root="/tmp/whisper_models",
        )
    return _transcription_service


def get_translation_service() -> TranslationService:
    global _translation_service
    if _translation_service is None:
        _translation_service = TranslationService()
    return _translation_service


# ---------------------------------------------------------------------------
# UI <-> service-layer vocabulary
# ---------------------------------------------------------------------------

# "Source Language" dropdown: display name -> ISO 639-1 code (None = auto).
_NAME_TO_CODE = {name: code for code, name in SUPPORTED_LANGUAGES.items()}
SOURCE_LANGUAGE_CHOICES = ["Auto Detect"] + list(SUPPORTED_LANGUAGES.values())

# "Outputs" checkboxes: display label -> ISO 639-1 code for translations.
_TRANSLATION_LABEL_TO_CODE = {
    f"{name} Translation": code for code, name in SUPPORTED_TARGET_LANGUAGES.items()
}
OUTPUT_CHOICES = ["Transcript"] + list(_TRANSLATION_LABEL_TO_CODE.keys())
DEFAULT_OUTPUTS = ["Transcript", "English Translation"]

# Order in which translation tabs are laid out (fixed; visibility toggles).
_TRANSLATION_TAB_ORDER = ["English Translation", "German Translation", "Persian Translation", "Spanish Translation"]


def _format_duration(seconds: float) -> str:
    seconds = max(0, int(round(seconds)))
    hours, remainder = divmod(seconds, 3600)
    minutes, secs = divmod(remainder, 60)
    return f"{hours:02}:{minutes:02}:{secs:02}"


def _write_text_file(text: str, tmp_dir: Path, filename: str) -> str:
    path = tmp_dir / filename
    path.write_text(text, encoding="utf-8")
    return str(path)


# ---------------------------------------------------------------------------
# Main processing callback
# ---------------------------------------------------------------------------

def process_audio(
    audio_path: Optional[str],
    start_value: str,
    end_value: str,
    source_language_label: str,
    selected_outputs: list[str],
):
    if not audio_path:
        raise gr.Error("Please upload an audio file first.")

    try:
        validate_extension(audio_path)
        start, end = resolve_window(start_value, end_value)
    except AudioError as exc:
        raise gr.Error(str(exc)) from exc

    working_path = audio_path
    if start is not None or end is not None:
        try:
            working_path = extract_window(audio_path, start, end)
        except AudioError as exc:
            raise gr.Error(str(exc)) from exc

    language_code = _NAME_TO_CODE.get(source_language_label)  # None = auto-detect

    # Step 1: Audio -> canonical Transcript. This is the only step that
    # touches the audio; everything below works off `transcript`.
    transcript: Transcript = get_transcription_service().transcribe(
        working_path,
        source_filename=Path(audio_path).name,
        language=language_code,
        window_start=start,
        window_end=end,
    )

    tmp_dir = Path(tempfile.mkdtemp(prefix="echoscript_"))

    # --- Results dashboard ---
    detected_language = SUPPORTED_LANGUAGES.get(transcript.language, transcript.language)
    dashboard_md = (
        f"### \u2713 {detected_language} detected\n\n"
        f"**Confidence:** {transcript.language_probability:.0%}&nbsp;&nbsp;&nbsp;"
        f"**Duration:** {_format_duration(transcript.duration)}&nbsp;&nbsp;&nbsp;"
        f"**Words:** {transcript.word_count:,}"
    )

    # --- Transcript tab (always computed -- it's the source of truth --
    # but only exposed as a tab if the user kept "Transcript" checked) ---
    transcript_text = transcript.text
    transcript_file = _write_text_file(transcript_text, tmp_dir, "transcript.txt")
    transcript_tab_visible = "Transcript" in selected_outputs

    # --- Translation tabs ---
    translation_service = get_translation_service()
    translation_updates = {}  # label -> (text, file_path)
    for label in _TRANSLATION_TAB_ORDER:
        if label in selected_outputs:
            code = _TRANSLATION_LABEL_TO_CODE[label]
            translation = translation_service.translate(transcript, code)
            text = translation.text
            file_path = _write_text_file(text, tmp_dir, f"{code}.txt")
            translation_updates[label] = (text, file_path)
        else:
            translation_updates[label] = (None, None)

    # --- Subtitles (always derived from the transcript, the canonical
    # source of truth -- never regenerated from audio) ---
    srt_path = _write_text_file(generate_srt(transcript.segments), tmp_dir, "transcript.srt")
    vtt_path = _write_text_file(generate_vtt(transcript.segments), tmp_dir, "transcript.vtt")

    outputs = [dashboard_md, transcript_text, transcript_file, gr.update(visible=transcript_tab_visible)]

    for label in _TRANSLATION_TAB_ORDER:
        text, file_path = translation_updates[label]
        visible = text is not None
        outputs += [gr.update(visible=visible), text or "", file_path]

    outputs += [srt_path, vtt_path]

    return outputs


# ---------------------------------------------------------------------------
# UI layout
# ---------------------------------------------------------------------------

with gr.Blocks(title="EchoScript") as demo:

    gr.Markdown(
        """
# EchoScript

**Upload Audio &rarr; Generate Canonical Transcript &rarr; Preview Results &rarr; Generate Outputs &rarr; Copy / Download**
        """
    )

    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### Upload Audio")
            audio_input = gr.Audio(
                label="Drop audio file here or click to browse",
                sources=["upload"],
                type="filepath",
            )
            gr.Markdown("Supported: mp3 &middot; wav &middot; m4a &middot; flac")

            gr.Markdown("### Processing Window")
            with gr.Row():
                start_input = gr.Textbox(label="Start Time (optional)", placeholder="HH:MM:SS")
                end_input = gr.Textbox(label="End Time (optional)", placeholder="HH:MM:SS")
            gr.Markdown("Leave blank: entire file")

            gr.Markdown("### Processing Options")
            language_input = gr.Dropdown(
                choices=SOURCE_LANGUAGE_CHOICES,
                value="Auto Detect",
                label="Source Language",
            )

            outputs_input = gr.CheckboxGroup(
                choices=OUTPUT_CHOICES,
                value=DEFAULT_OUTPUTS,
                label="Outputs",
            )

            process_button = gr.Button("Generate Outputs", variant="primary")

        with gr.Column(scale=2):
            gr.Markdown("### Results Dashboard")
            dashboard_output = gr.Markdown("Upload an audio file and click **Generate Outputs** to begin.")

            with gr.Tabs():
                with gr.Tab("Transcript") as transcript_tab:
                    transcript_box = gr.Textbox(
                        label="Transcript",
                        lines=16,
                        interactive=True,
                        buttons=["copy"],
                    )
                    transcript_download = gr.DownloadButton("Download TXT")

                translation_tabs = {}
                translation_boxes = {}
                translation_downloads = {}
                for label in _TRANSLATION_TAB_ORDER:
                    short_name = label.replace(" Translation", "")
                    with gr.Tab(short_name, visible=False) as tab:
                        box = gr.Textbox(
                            label=short_name,
                            lines=16,
                            interactive=True,
                            buttons=["copy"],
                        )
                        download = gr.DownloadButton("Download TXT")
                    translation_tabs[label] = tab
                    translation_boxes[label] = box
                    translation_downloads[label] = download

                with gr.Tab("Subtitles"):
                    gr.Markdown(
                        "Subtitles are generated from the transcript "
                        "(source language), so they stay in sync no matter "
                        "which translations are also generated."
                    )
                    with gr.Row():
                        srt_download = gr.DownloadButton("Download SRT")
                        vtt_download = gr.DownloadButton("Download VTT")

    # Build the flat outputs list in the exact order process_audio() returns.
    click_outputs = [dashboard_output, transcript_box, transcript_download, transcript_tab]
    for label in _TRANSLATION_TAB_ORDER:
        click_outputs += [translation_tabs[label], translation_boxes[label], translation_downloads[label]]
    click_outputs += [srt_download, vtt_download]

    process_button.click(
        fn=process_audio,
        inputs=[audio_input, start_input, end_input, language_input, outputs_input],
        outputs=click_outputs,
    )

if __name__ == "__main__":
    demo.launch()