Spaces:
Paused

ASTRA / app.py
Denis
Add Gradio password gate via env-var credentials
6898093
Raw History Blame Contribute Delete
8.37 kB
"""
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)