Spaces:
Runtime error
Runtime error
File size: 5,486 Bytes
d411ac6 |
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 |
#!/usr/bin/env python3
"""
Gradio app for ASR model with support for:
- Microphone input
- File upload
- Word-level timestamps
- Speaker diarization
"""
import os
# Fix OpenMP environment variable if invalid
if not os.environ.get("OMP_NUM_THREADS", "").isdigit():
os.environ["OMP_NUM_THREADS"] = "1"
# Set matplotlib config dir to avoid warning in Hugging Face Spaces
os.environ["MPLCONFIGDIR"] = "/tmp/matplotlib"
# Disable tokenizer parallelism warning
os.environ["TOKENIZERS_PARALLELISM"] = "false"
import gradio as gr
import torch
from transformers import pipeline
def format_timestamp(seconds):
"""Format seconds as MM:SS.ms"""
mins = int(seconds // 60)
secs = seconds % 60
return f"{mins:02d}:{secs:05.2f}"
def format_words_with_timestamps(words):
"""Format word timestamps as readable text."""
if not words:
return ""
lines = []
for w in words:
start = format_timestamp(w["start"])
end = format_timestamp(w["end"])
speaker = w.get("speaker", "")
if speaker:
lines.append(f"[{start} - {end}] ({speaker}) {w['word']}")
else:
lines.append(f"[{start} - {end}] {w['word']}")
return "\n".join(lines)
def format_speaker_segments(segments):
"""Format speaker segments as readable text."""
if not segments:
return ""
lines = []
for seg in segments:
start = format_timestamp(seg["start"])
end = format_timestamp(seg["end"])
lines.append(f"[{start} - {end}] {seg['speaker']}")
return "\n".join(lines)
def create_demo(model_path="mazesmazes/tiny-audio"):
"""Create Gradio demo interface using transformers pipeline."""
# Determine device
if torch.cuda.is_available():
device = 0
elif torch.backends.mps.is_available():
device = "mps"
else:
device = -1
# Load pipeline - uses custom ASRPipeline from the model repo
pipe = pipeline(
"automatic-speech-recognition",
model=model_path,
trust_remote_code=True,
device=device,
)
def process_audio(audio, show_timestamps, show_diarization):
"""Process audio file for transcription."""
if audio is None:
return "Please provide audio input", "", ""
# Build kwargs
kwargs = {}
if show_timestamps:
kwargs["return_timestamps"] = True
if show_diarization:
kwargs["return_speakers"] = True
# Transcribe the audio
result = pipe(audio, **kwargs)
# Format outputs
transcript = result.get("text", "")
# Format timestamps
if show_timestamps and "words" in result:
timestamps_text = format_words_with_timestamps(result["words"])
elif "timestamp_error" in result:
timestamps_text = f"Error: {result['timestamp_error']}"
else:
timestamps_text = ""
# Format diarization
if show_diarization and "speaker_segments" in result:
diarization_text = format_speaker_segments(result["speaker_segments"])
elif "diarization_error" in result:
diarization_text = f"Error: {result['diarization_error']}"
else:
diarization_text = ""
return transcript, timestamps_text, diarization_text
# Create Gradio interface
with gr.Blocks(title="Tiny Audio") as demo:
gr.Markdown("# Tiny Audio")
gr.Markdown("Speech recognition with optional word timestamps and speaker diarization.")
with gr.Row():
with gr.Column(scale=2):
audio_input = gr.Audio(
sources=["microphone", "upload"],
type="filepath",
label="Audio Input",
)
with gr.Row():
show_timestamps = gr.Checkbox(
label="Word Timestamps",
value=False,
)
show_diarization = gr.Checkbox(
label="Speaker Diarization",
value=False,
)
process_btn = gr.Button("Transcribe", variant="primary")
with gr.Column(scale=3):
output_text = gr.Textbox(
label="Transcript",
lines=5,
)
timestamps_output = gr.Textbox(
label="Word Timestamps",
lines=8,
)
diarization_output = gr.Textbox(
label="Speaker Segments",
lines=5,
)
# Wire up events
process_btn.click(
fn=process_audio,
inputs=[audio_input, show_timestamps, show_diarization],
outputs=[output_text, timestamps_output, diarization_output],
)
return demo
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="ASR Gradio Demo")
parser.add_argument(
"--model",
type=str,
default=os.environ.get("MODEL_ID", "mazesmazes/tiny-audio"),
help="HuggingFace Hub model ID",
)
parser.add_argument("--port", type=int, default=7860)
parser.add_argument("--share", action="store_true")
args = parser.parse_args()
demo = create_demo(args.model)
demo.launch(server_port=args.port, share=args.share, server_name="0.0.0.0")
|