File size: 8,367 Bytes
d422f47 6898093 d422f47 6898093 d422f47 6898093 | 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 | """
ASTRA — Serbian STT bake-off Space.
Compares multiple Whisper variants on Serbian audio (both Cyrillic and Latin
output scripts). Runs on HF ZeroGPU.
"""
from __future__ import annotations
import os
import time
from dataclasses import dataclass
from typing import Optional
import gradio as gr
import spaces
import torch
from transformers import pipeline
@dataclass(frozen=True)
class Model:
label: str
model_id: str
family: str
notes: str = ""
# Model registry. Add or remove rows freely; the dropdown reads from this.
# Serbian fine-tunes are community-contributed — verify access before relying on them.
MODELS: list[Model] = [
Model(
label="Whisper large-v3-turbo (multilingual baseline, fast)",
model_id="openai/whisper-large-v3-turbo",
family="openai",
notes="809M params. Fast, good Serbian out-of-the-box. Recommended starting point.",
),
Model(
label="Whisper large-v3 (multilingual, quality ceiling)",
model_id="openai/whisper-large-v3",
family="openai",
notes="1.55B params. Slower than Turbo, marginally better quality.",
),
Model(
label="Whisper small (multilingual, fast/lower-quality)",
model_id="openai/whisper-small",
family="openai",
notes="244M params. Mostly here as a speed/quality lower bound.",
),
Model(
label="DigitLib whisper-large-v2-sr (Serbian fine-tune)",
model_id="DigitLib/whisper-large-v2-sr",
family="serbian-finetune",
notes="Community Serbian fine-tune by DigitLib. Verify license/availability.",
),
Model(
label="Sagicc whisper-large-sr-cmb (Serbian fine-tune)",
model_id="Sagicc/whisper-large-sr-cmb",
family="serbian-finetune",
notes="Community Serbian fine-tune by Sagicc. Verify license/availability.",
),
]
LANGUAGES = [
("Serbian (sr)", "serbian"),
("Croatian (hr)", "croatian"),
("Bosnian (bs)", "bosnian"),
("English (en)", "english"),
("Auto-detect", None),
]
SCRIPTS = ["Model default", "Cyrillic (ћирилица)", "Latin (latinica)", "Both"]
# Lazy-loaded pipelines, keyed by model_id. Loaded inside the GPU-decorated
# function on first use; stays resident across calls until ZeroGPU swaps us out.
_pipelines: dict[str, object] = {}
def _detect_script(text: str) -> str:
"""Heuristic: if any Cyrillic letter appears, treat as Cyrillic; else Latin."""
return "cyrillic" if any("Ѐ" <= ch <= "ӿ" for ch in text) else "latin"
def _convert_script(text: str, target: str) -> str:
"""Transliterate using cyrtranslit. Returns text unchanged if already target."""
try:
import cyrtranslit
except ImportError:
return text
src = _detect_script(text)
if target == "cyrillic" and src == "latin":
return cyrtranslit.to_cyrillic(text, "sr")
if target == "latin" and src == "cyrillic":
return cyrtranslit.to_latin(text, "sr")
return text
def _format_output(text: str, script_choice: str) -> str:
if script_choice == "Cyrillic (ћирилица)":
return _convert_script(text, "cyrillic")
if script_choice == "Latin (latinica)":
return _convert_script(text, "latin")
if script_choice == "Both":
cyr = _convert_script(text, "cyrillic")
lat = _convert_script(text, "latin")
return f"**Cyrillic:**\n{cyr}\n\n**Latin:**\n{lat}"
return text
@spaces.GPU(duration=180)
def transcribe(
audio_path: Optional[str],
model_label: str,
language_label: str,
script_choice: str,
) -> tuple[str, str]:
"""Run STT. Returns (transcript, status_line)."""
if not audio_path:
return "", "No audio provided."
model = next((m for m in MODELS if m.label == model_label), None)
if model is None:
return "", f"Unknown model: {model_label}"
language = next((code for label, code in LANGUAGES if label == language_label), None)
t_load_start = time.perf_counter()
if model.model_id not in _pipelines:
_pipelines[model.model_id] = pipeline(
task="automatic-speech-recognition",
model=model.model_id,
torch_dtype=torch.float16,
device="cuda",
chunk_length_s=30,
)
pipe = _pipelines[model.model_id]
t_load = time.perf_counter() - t_load_start
generate_kwargs: dict = {"task": "transcribe"}
if language is not None:
generate_kwargs["language"] = language
t_infer_start = time.perf_counter()
result = pipe(audio_path, generate_kwargs=generate_kwargs, return_timestamps=False)
t_infer = time.perf_counter() - t_infer_start
raw_text = result["text"].strip() if isinstance(result, dict) else str(result)
formatted = _format_output(raw_text, script_choice)
status = (
f"Model: `{model.model_id}` | Language: `{language or 'auto'}` | "
f"Load: {t_load:.1f}s | Inference: {t_infer:.1f}s | "
f"Output script (raw): `{_detect_script(raw_text)}`"
)
return formatted, status
def build_ui() -> gr.Blocks:
with gr.Blocks(title="ASTRA — Serbian STT bake-off") as demo:
gr.Markdown(
"# ASTRA — Serbian Speech-to-Text bake-off\n"
"Compare Whisper variants on Serbian audio. Upload a clip or record from "
"your microphone, pick a model, and check the transcript. Use the same "
"audio across multiple models to compare quality and speed.\n\n"
"*Cyrillic / Latin output is transliterated post-hoc when the model's "
"output script differs from your selection — the underlying recognition "
"is the same.*"
)
with gr.Row():
with gr.Column(scale=1):
audio = gr.Audio(
sources=["microphone", "upload"],
type="filepath",
label="Audio (microphone or upload — wav/mp3/m4a)",
)
model_dd = gr.Dropdown(
choices=[m.label for m in MODELS],
value=MODELS[0].label,
label="Model",
)
language_dd = gr.Dropdown(
choices=[label for label, _ in LANGUAGES],
value=LANGUAGES[0][0],
label="Language hint",
)
script_dd = gr.Dropdown(
choices=SCRIPTS,
value="Both",
label="Output script",
)
run_btn = gr.Button("Transcribe", variant="primary")
with gr.Column(scale=2):
output = gr.Markdown(label="Transcript", value="*Transcript will appear here.*")
status = gr.Markdown(label="Status", value="")
with gr.Accordion("Model notes", open=False):
gr.Markdown(
"\n".join(f"- **{m.label}** — `{m.model_id}` — {m.notes}" for m in MODELS)
)
run_btn.click(
fn=transcribe,
inputs=[audio, model_dd, language_dd, script_dd],
outputs=[output, status],
)
return demo
def _load_credentials() -> Optional[list[tuple[str, str]]]:
"""Read auth credentials from env. Supports either a single shared pair
(SPACE_USER / SPACE_PASS) or a JSON array in SPACE_AUTH for per-person
tracking. Returns None if no credentials are configured (no auth gate)."""
import json
raw = os.environ.get("SPACE_AUTH")
if raw:
try:
pairs = json.loads(raw)
return [(p["user"], p["pass"]) for p in pairs]
except (ValueError, KeyError, TypeError):
print("[auth] SPACE_AUTH set but failed to parse as JSON; ignoring.")
user = os.environ.get("SPACE_USER")
pw = os.environ.get("SPACE_PASS")
if user and pw:
return [(user, pw)]
return None
if __name__ == "__main__":
demo = build_ui()
creds = _load_credentials()
launch_kwargs: dict = {}
if creds:
launch_kwargs["auth"] = creds
launch_kwargs["auth_message"] = (
"ASTRA — Serbian STT bake-off (private). Credentials shared by Denis."
)
else:
print("[auth] No credentials configured — Space will be unprotected.")
demo.launch(**launch_kwargs)
|