feat(spaces): add whisper persian v4 speech recognition demo space
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: Whisper Persian v4 - Speech Recognition Demo
|
||||
emoji: 🎙️
|
||||
colorFrom: indigo
|
||||
colorTo: purple
|
||||
sdk: gradio
|
||||
sdk_version: 5.50.0
|
||||
app_file: app.py
|
||||
pinned: false
|
||||
license: apache-2.0
|
||||
short_description: Persian ASR with Whisper Large v3 (WER 8.73%)
|
||||
tags:
|
||||
- audio
|
||||
- speech-recognition
|
||||
- whisper
|
||||
- persian
|
||||
- farsi
|
||||
- asr
|
||||
---
|
||||
|
||||
# 🎙️ Whisper Persian v4 - Automatic Speech Recognition Demo
|
||||
### دمو بازشناسی گفتار فارسی با مدل Whisper Persian v4
|
||||
|
||||
این فضا یک دموی پیشرفته و بهینهشده برای مدل **[nezamisafa/whisper-persian-v4](https://huggingface.co/nezamisafa/whisper-persian-v4)** است.
|
||||
|
||||
## 📌 ویژگیهای مدل (Model Highlights)
|
||||
- **مدل پایه (Base Model):** `openai/whisper-large-v3` (~1.54 میلیارد پارامتر)
|
||||
- **مجموعه داده آموزش (Training Dataset):** `nezamisafa/ASR_fa_v1`
|
||||
- **معیار خطای کلمه (Word Error Rate - WER):** **8.73%** روی مجموعه تست
|
||||
- **بهینهسازی:** پشتیبانی از ZeroGPU برای اجرای بلادرنگ، ورودی صوتی زنده (میکروفون) و فایل، تولید زمانبندی (Timestamps) و خروجی زیرنویس (SRT).
|
||||
|
||||
## 🚀 قابلیتهای دمو
|
||||
1. **تایپ خودکار گفتار:** تبدیل گفتار فارسی به متن با دقت بسیار بالا و نگارش صحیح.
|
||||
2. **برچسبگذاری زمانی (Timestamps):** استخراج بازههای زمانی کلمات و عبارات.
|
||||
3. **پشتیبانی از فرمتهای صوتی مختلف:** MP3, WAV, M4A, FLAC, OGG و ضبط زنده میکروفون.
|
||||
4. **رابط کاربری مدرن:** پشتیبانی کامل از چینش راستبهچپ (RTL)، کپی سریع متن و دانلود زیرنویس.
|
||||
|
||||
---
|
||||
Built with ❤️ using [Gradio](https://github.com/gradio-app/gradio) and [Transformers](https://github.com/huggingface/transformers).
|
||||
@@ -0,0 +1,297 @@
|
||||
import os
|
||||
import time
|
||||
|
||||
# ZeroGPU requires spaces to be imported before any CUDA-dependent libraries
|
||||
try:
|
||||
import spaces
|
||||
except ImportError:
|
||||
class spaces:
|
||||
@staticmethod
|
||||
def GPU(duration=60):
|
||||
def decorator(fn):
|
||||
return fn
|
||||
return decorator
|
||||
|
||||
import gradio as gr
|
||||
import torch
|
||||
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
|
||||
|
||||
# Model configuration
|
||||
MODEL_ID = "nezamisafa/whisper-persian-v4"
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
||||
|
||||
print(f"Loading model {MODEL_ID} on device: {device} (dtype: {torch_dtype})...")
|
||||
|
||||
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
||||
MODEL_ID,
|
||||
torch_dtype=torch_dtype,
|
||||
low_cpu_mem_usage=True,
|
||||
use_safetensors=True,
|
||||
)
|
||||
if torch.cuda.is_available():
|
||||
model = model.to("cuda")
|
||||
|
||||
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
||||
|
||||
pipe = pipeline(
|
||||
"automatic-speech-recognition",
|
||||
model=model,
|
||||
tokenizer=processor.tokenizer,
|
||||
feature_extractor=processor.feature_extractor,
|
||||
chunk_length_s=30,
|
||||
stride_length_s=5,
|
||||
batch_size=8,
|
||||
torch_dtype=torch_dtype,
|
||||
ignore_warning=True,
|
||||
device="cuda" if torch.cuda.is_available() else "cpu",
|
||||
)
|
||||
|
||||
def format_timestamp(seconds: float) -> str:
|
||||
"""Format seconds into SRT timestamp HH:MM:SS,mmm."""
|
||||
hrs = int(seconds // 3600)
|
||||
mins = int((seconds % 3600) // 60)
|
||||
secs = int(seconds % 60)
|
||||
millis = int((seconds - int(seconds)) * 1000)
|
||||
return f"{hrs:02d}:{mins:02d}:{secs:02d},{millis:03d}"
|
||||
|
||||
def generate_srt(chunks: list[dict]) -> str:
|
||||
"""Convert chunk list with timestamps to standard SRT format."""
|
||||
srt_lines = []
|
||||
for i, chunk in enumerate(chunks, 1):
|
||||
timestamp = chunk.get("timestamp", (0.0, 0.0))
|
||||
start = timestamp[0] if timestamp and timestamp[0] is not None else 0.0
|
||||
end = timestamp[1] if timestamp and timestamp[1] is not None else (start + 2.0)
|
||||
text = chunk.get("text", "").strip()
|
||||
srt_lines.append(f"{i}\n{format_timestamp(start)} --> {format_timestamp(end)}\n{text}\n")
|
||||
return "\n".join(srt_lines)
|
||||
|
||||
def generate_segments_html(chunks: list[dict]) -> str:
|
||||
"""Generate a clean and responsive HTML table for timestamped segments."""
|
||||
if not chunks:
|
||||
return """
|
||||
<div style="padding: 30px; text-align: center; color: #94a3b8; font-size: 0.95rem;">
|
||||
هنوز فایلی پردازش نشده یا گزینهی زمانبندی غیرفعال بوده است.
|
||||
</div>
|
||||
"""
|
||||
|
||||
rows = []
|
||||
for i, chunk in enumerate(chunks, 1):
|
||||
ts = chunk.get("timestamp", (0.0, 0.0))
|
||||
s = round(ts[0], 2) if ts and ts[0] is not None else 0.0
|
||||
e = round(ts[1], 2) if ts and ts[1] is not None else s
|
||||
text = chunk.get("text", "").strip()
|
||||
rows.append(f"""
|
||||
<tr style="border-bottom: 1px solid #f1f5f9; transition: background 0.2s;">
|
||||
<td style="padding: 10px 14px; font-weight: 700; color: #6366f1; width: 45px;">#{i}</td>
|
||||
<td style="padding: 10px 14px; direction: ltr; text-align: center; width: 140px;">
|
||||
<span style="background: #eef2ff; color: #4338ca; padding: 3px 8px; border-radius: 6px; font-family: monospace; font-size: 0.85rem; font-weight: 600;">
|
||||
{s:.2f}s - {e:.2f}s
|
||||
</span>
|
||||
</td>
|
||||
<td style="padding: 10px 14px; font-size: 1rem; line-height: 1.7; text-align: right; color: #1e293b;">{text}</td>
|
||||
</tr>
|
||||
""")
|
||||
|
||||
return f"""
|
||||
<div style="max-height: 380px; overflow-y: auto; border: 1px solid #e2e8f0; border-radius: 10px; background: #ffffff;">
|
||||
<table style="width: 100%; border-collapse: collapse; text-align: right; direction: rtl;">
|
||||
<thead>
|
||||
<tr style="background: #f8fafc; border-bottom: 2px solid #e2e8f0; color: #475569; font-size: 0.88rem;">
|
||||
<th style="padding: 10px 14px;">ردیف</th>
|
||||
<th style="padding: 10px 14px; text-align: center;">بازه زمانی</th>
|
||||
<th style="padding: 10px 14px;">متن پیادهسازی شده</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{''.join(rows)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
"""
|
||||
|
||||
@spaces.GPU(duration=60)
|
||||
def transcribe(audio_path, return_timestamps=True):
|
||||
"""
|
||||
Transcribe Persian speech audio to text with timestamps using Whisper Persian v4.
|
||||
"""
|
||||
if not audio_path:
|
||||
return (
|
||||
"لطفاً ابتدا یک فایل صوتی آپلود کنید یا صدایتان را ضبط نمایید.",
|
||||
generate_segments_html([]),
|
||||
"",
|
||||
"⚠️ لطفاً ورودی صوتی را مشخص کنید."
|
||||
)
|
||||
|
||||
start_time = time.perf_counter()
|
||||
|
||||
try:
|
||||
generate_kwargs = {
|
||||
"language": "persian",
|
||||
"task": "transcribe"
|
||||
}
|
||||
|
||||
result = pipe(
|
||||
audio_path,
|
||||
return_timestamps=return_timestamps,
|
||||
generate_kwargs=generate_kwargs
|
||||
)
|
||||
|
||||
elapsed = round(time.perf_counter() - start_time, 2)
|
||||
full_text = result.get("text", "").strip()
|
||||
chunks = result.get("chunks", [])
|
||||
|
||||
segments_html = generate_segments_html(chunks)
|
||||
srt_content = generate_srt(chunks) if chunks else ""
|
||||
metrics = f"✅ پردازش موفق در {elapsed} ثانیه | مدل: nezamisafa/whisper-persian-v4"
|
||||
|
||||
return full_text, segments_html, srt_content, metrics
|
||||
|
||||
except Exception as e:
|
||||
error_msg = str(e)
|
||||
return (
|
||||
f"خطا در پردازش صوت: {error_msg}",
|
||||
generate_segments_html([]),
|
||||
"",
|
||||
f"❌ خطای سیستم: {error_msg}"
|
||||
)
|
||||
|
||||
|
||||
CUSTOM_CSS = """
|
||||
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
|
||||
|
||||
body, .gradio-container {
|
||||
font-family: 'Vazirmatn', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
|
||||
direction: rtl;
|
||||
}
|
||||
|
||||
.persian-title {
|
||||
text-align: center;
|
||||
background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #db2777 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
font-size: 2.2rem;
|
||||
font-weight: 800;
|
||||
margin-bottom: 0.2rem;
|
||||
}
|
||||
|
||||
.persian-subtitle {
|
||||
text-align: center;
|
||||
color: #64748b;
|
||||
font-size: 1.05rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.metric-badge-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.metric-badge {
|
||||
background: #f1f5f9;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 9999px;
|
||||
padding: 6px 14px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.dark .metric-badge {
|
||||
background: #1e293b;
|
||||
border-color: #334155;
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
.rtl-text-box textarea {
|
||||
direction: rtl !important;
|
||||
text-align: right !important;
|
||||
font-size: 1.15rem !important;
|
||||
line-height: 1.8 !important;
|
||||
font-family: 'Vazirmatn', sans-serif !important;
|
||||
}
|
||||
|
||||
.srt-text-box textarea {
|
||||
direction: ltr !important;
|
||||
text-align: left !important;
|
||||
font-family: monospace !important;
|
||||
font-size: 0.9rem !important;
|
||||
}
|
||||
|
||||
footer {
|
||||
display: none !important;
|
||||
}
|
||||
"""
|
||||
|
||||
with gr.Blocks(title="Whisper Persian v4 🎙️ دمو بازشناسی گفتار فارسی", css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="indigo")) as demo:
|
||||
gr.HTML("""
|
||||
<div style="padding: 10px 0;">
|
||||
<h1 class="persian-title">مدل بازشناسی گفتار فارسی ویسپر (نسخه ۴)</h1>
|
||||
<p class="persian-subtitle">تبدیل گفتار و صوت فارسی به متن دقیق با بهرهگیری از مدل بهینهشده Whisper Large v3</p>
|
||||
<div class="metric-badge-container">
|
||||
<span class="metric-badge">🏆 مدل پایه: Whisper Large v3</span>
|
||||
<span class="metric-badge">🎯 نرخ خطا (WER): ۸.۷۳٪</span>
|
||||
<span class="metric-badge">📦 دیتاست آموزش: ASR_fa_v1</span>
|
||||
<span class="metric-badge">⚡ سختافزار: ZeroGPU شتابیافته</span>
|
||||
</div>
|
||||
</div>
|
||||
""")
|
||||
|
||||
with gr.Row():
|
||||
with gr.Column(scale=5):
|
||||
audio_input = gr.Audio(
|
||||
sources=["microphone", "upload"],
|
||||
type="filepath",
|
||||
label="ورودی صوت (میکروفون یا فایل صوتی)",
|
||||
)
|
||||
return_ts_checkbox = gr.Checkbox(
|
||||
value=True,
|
||||
label="استخراج زمانبندی دقیق بخشها (Timestamps)",
|
||||
info="ایجاد برچسب زمانی و ساخت زیرنویس خودکار"
|
||||
)
|
||||
transcribe_btn = gr.Button("🚀 شروع بازشناسی گفتار", variant="primary", size="lg")
|
||||
metrics_display = gr.Markdown("آماده دریافت فایل یا صدای شما...")
|
||||
|
||||
with gr.Column(scale=6):
|
||||
output_text = gr.Textbox(
|
||||
label="متن استخراجشده (فارسی)",
|
||||
lines=7,
|
||||
elem_classes=["rtl-text-box"],
|
||||
show_copy_button=True,
|
||||
placeholder="متن پیادهسازی شده در اینجا نمایش داده خواهد شد..."
|
||||
)
|
||||
with gr.Tabs():
|
||||
with gr.TabItem("📋 بخشها و زمانبندی"):
|
||||
segments_html_view = gr.HTML(
|
||||
value=generate_segments_html([]),
|
||||
label="جدول زمانبندی بخشها"
|
||||
)
|
||||
with gr.TabItem("📄 فرمت زیرنویس (SRT)"):
|
||||
srt_output = gr.Textbox(
|
||||
label="فایل زیرنویس SRT",
|
||||
lines=7,
|
||||
elem_classes=["srt-text-box"],
|
||||
show_copy_button=True
|
||||
)
|
||||
|
||||
transcribe_btn.click(
|
||||
fn=transcribe,
|
||||
inputs=[audio_input, return_ts_checkbox],
|
||||
outputs=[output_text, segments_html_view, srt_output, metrics_display],
|
||||
api_name=False
|
||||
)
|
||||
|
||||
gr.HTML("""
|
||||
<div style="margin-top: 30px; padding: 15px; border-radius: 12px; background: rgba(99, 102, 241, 0.05); border: 1px solid rgba(99, 102, 241, 0.2); direction: rtl; text-align: right;">
|
||||
<h4 style="margin-top: 0; color: #4338ca;">درباره مدل nezamisafa/whisper-persian-v4</h4>
|
||||
<p style="font-size: 0.95rem; line-height: 1.7; margin-bottom: 0;">
|
||||
این مدل نسخه بهبودیافته و fine-tune شده از مدل بزرگ <code>openai/whisper-large-v3</code> بر روی دیتاست جامع فارسی <code>nezamisafa/ASR_fa_v1</code> است که توانسته در ارزیابی نهایی به WER کمنظیر <strong>۸.۷۳٪</strong> دست یابد. این فضا مجهز به ساختار بهینهسازیشده ZeroGPU میباشد.
|
||||
</p>
|
||||
</div>
|
||||
""")
|
||||
|
||||
if __name__ == "__main__":
|
||||
demo.launch()
|
||||
@@ -0,0 +1,6 @@
|
||||
transformers>=4.40.0
|
||||
torchaudio
|
||||
accelerate
|
||||
soundfile
|
||||
librosa
|
||||
pandas
|
||||
Reference in New Issue
Block a user