Spaces:
Running on Zero
Running on Zero
Download dashboard.py from DrBaradaran-ASR/ASR-Platform: direct link, hf CLI and curl.
- Browser
- Download file 37.7 kB
-
https://huggingface.co/spaces/DrBaradaran-ASR/ASR-Platform/resolve/main/dashboard.py
- Command line
-
hf download hf://spaces/DrBaradaran-ASR/ASR-Platform/dashboard.py
-
curl -L -o dashboard.py https://huggingface.co/spaces/DrBaradaran-ASR/ASR-Platform/resolve/main/dashboard.py
37.7 kB
| """Persian Gradio frontend. Importing this module never imports the ASR runtime.""" | |
| from base64 import b64encode | |
| from dataclasses import replace | |
| from html import escape | |
| from pathlib import Path | |
| import inspect | |
| import re | |
| import wave | |
| from uuid import uuid4 | |
| import gradio as gr | |
| # Gradio 6.0 moved the on-load JS from the Blocks constructor to launch(); | |
| # older releases only accept it on Blocks. Detect once and use the right one. | |
| LAUNCH_ACCEPTS_JS = "js" in inspect.signature(gr.Blocks.launch).parameters | |
| ASSETS = Path(__file__).resolve().parent / "dashboard_assets" | |
| # Samples shown in the "نمونههای آماده" tab: (title, filename, dataset). | |
| # A sample is listed only while its audio file actually exists inside | |
| # dashboard_assets, so a new sample appears automatically as soon as its file | |
| # is dropped into that folder. The dataset is deliberately kept out of the | |
| # radio label; it is shown in the caption under the list once a clip is | |
| # selected (see sample_note). To enable the PDID entry, add the clip as | |
| # dashboard_assets/pdid-sample.wav (or edit the filename below); wav, flac and | |
| # mp3 all work — without a duration only when the format is not plain wav. | |
| SAMPLES = [ | |
| ("مسابقهٔ چوگان", "polo.wav", "FLEURS"), | |
| ("قدرت و نفوذ", "travel.wav", "FLEURS"), | |
| ("رزرو هتل", "hotel.wav", "FLEURS"), | |
| ("خانواده شهید", "baradar_shahid.wav", "صامتی (PDID)"), | |
| ] | |
| ICONS = { | |
| "input": '<path d="M4 10v4m4-8v12m4-16v20m4-16v12m4-8v4"/>', | |
| "text": '<path d="M5 4h14v16H5zM8 8h8M8 12h8M11 16h5"/>', | |
| "performance": '<path d="M4 4v16h16M7 15l4-5 3 2 5-7"/>', | |
| "model": '<rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9 2v4m6-4v4M9 18v4m6-4v4M2 9h4m-4 6h4m12-6h4m-4 6h4"/><rect x="10" y="10" width="4" height="4"/>', | |
| "sun": '<circle cx="12" cy="12" r="4"/><path d="M12 2.6v2.5m0 13.8v2.5M2.6 12h2.5m13.8 0h2.5M5.1 5.1l1.8 1.8m10.2 10.2 1.8 1.8m0-13.8-1.8 1.8M6.9 17.1l-1.8 1.8"/>', | |
| "moon": '<path d="M20.3 13.3A8.3 8.3 0 1 1 10.7 3.7a6.6 6.6 0 0 0 9.6 9.6Z"/>', | |
| } | |
| # People shown on the درباره ما page. Every entry carries the affiliation | |
| # line, a click-to-copy email pill and a LinkedIn pill (icon + label) that | |
| # opens the real profile in a new tab. The LinkedIn label is the exact text | |
| # requested for each person and stays LTR/English inside the RTL page. | |
| PROJECT_LEAD = { | |
| "name": "دکتر حمیدرضا برادران کاشانی", | |
| "affiliation": "عضو هیأت علمی گروه هوش مصنوعی دانشکده مهندسی کامپیوتر دانشگاه اصفهان", | |
| "email": "hrb.kashani@eng.ui.ac.ir", | |
| "linkedin": "https://www.linkedin.com/in/hamidreza-baradaran-kashani-04396a334", | |
| "linkedin_label": "Dr. Hamidreza Baradaran Kashani", | |
| } | |
| COLLABORATOR = { | |
| "name": "پروفسور علیرضا درویشی", | |
| "affiliation": "عضو هیأت علمی دانشکده علوم کامپیوتر دانشگاه علوم کاربردی زوریخ (ZHAW)", | |
| "email": "darvishy@ifi.uzh.ch", | |
| "linkedin": "https://www.linkedin.com/in/alireza-darvishy-5643b8164", | |
| "linkedin_label": "Prof. Alireza Darvishy", | |
| } | |
| TEAM_MEMBERS = [ | |
| { | |
| "name": "هاجر مظاهری", | |
| "affiliation": "دانشآموختهی کارشناسی ارشد هوش مصنوعی دانشگاه اصفهان", | |
| "email": "hmazaheri817@gmail.com", | |
| "linkedin": "https://www.linkedin.com/in/hajar-mazaheri-a3125523b", | |
| "linkedin_label": "Hajar Mazaheri", | |
| }, | |
| { | |
| "name": "سیدمحمدسروش سجادی", | |
| "affiliation": "دانشجوی کارشناسی ارشد هوش مصنوعی دانشگاه اصفهان", | |
| "email": "sm.soroush.sajadi@gmail.com", | |
| "linkedin": "https://ir.linkedin.com/in/sms-sajadi", | |
| "linkedin_label": "Soroush Sajadi", | |
| }, | |
| { | |
| "name": "آیدا سرابی", | |
| "affiliation": "دانشجوی دکترا هوش مصنوعی دانشگاه اصفهان", | |
| "email": "ida.sarabi97@gmail.com", | |
| "linkedin": "https://www.linkedin.com/in/ida-sarabi-sarvarani-a37743205", | |
| "linkedin_label": "Ida Sarabi", | |
| }, | |
| ] | |
| CHECK_ICON = ('<svg class="ic-check" aria-hidden="true" viewBox="0 0 24 24" fill="none" ' | |
| 'stroke="currentColor" stroke-width="2" stroke-linejoin="round" ' | |
| 'stroke-linecap="round"><path d="M20 6 9 17l-5-5"/></svg>') | |
| MAIL_ICON = ('<svg class="ic-mail" aria-hidden="true" viewBox="0 0 24 24" fill="none" ' | |
| 'stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" ' | |
| 'stroke-linecap="round"><rect x="3" y="5" width="18" height="14" rx="2.5"/>' | |
| '<path d="m4.5 7.5 7.5 5.6 7.5-5.6"/></svg>') | |
| # The LinkedIn mark is a solid glyph, so unlike the house stroke icons it is | |
| # painted with fill=currentColor and no outline. | |
| LINKEDIN_ICON = ('<svg aria-hidden="true" viewBox="0 0 24 24" fill="currentColor">' | |
| '<path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037' | |
| '-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477' | |
| '-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337' | |
| ' 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 ' | |
| '1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 ' | |
| '13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542' | |
| 'C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729' | |
| 'C24 .774 23.2 0 22.225 0z"/></svg>') | |
| # Small external-link arrow after the LinkedIn label: signals that the pill | |
| # opens a new tab without adding any text. | |
| EXTERNAL_ICON = ('<svg class="ic-ext" aria-hidden="true" viewBox="0 0 24 24" fill="none" ' | |
| 'stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" ' | |
| 'stroke-linecap="round"><path d="M7 17 17 7"/><path d="M9 7h8v8"/></svg>') | |
| # The University of Isfahan logo is read straight from dashboard_assets. The | |
| # common filenames are tried first, then any single other image in the folder | |
| # (besides the masthead contours), so the page works whatever the file is | |
| # called. If no image exists at all the logo block simply hides itself. | |
| LOGO_CANDIDATES = ( | |
| "university-logo.png", "university_logo.png", "ui-logo.png", "ui_logo.png", | |
| "isfahan-university-logo.png", "isfahan-logo.png", "university-logo.jpg", | |
| "university-logo.jpeg", "university-logo.svg", "logo.png", "ui.png", | |
| ) | |
| LOGO_MIME = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", | |
| ".webp": "image/webp", ".svg": "image/svg+xml", ".gif": "image/gif"} | |
| # Runs once on page load (gr.Blocks js). Restores the saved theme or follows | |
| # the browser theme at first paint, wires the light/dark toggles, shows upload | |
| # indicators for both file uploads and microphone recordings, and copies each | |
| # person's email when its pill is clicked. | |
| THEME_JS = """() => { | |
| const root = document.documentElement; | |
| const KEY = 'asr-theme'; | |
| let stored = null; | |
| try { stored = localStorage.getItem(KEY); } catch (error) { stored = null; } | |
| const systemDark = !!(window.matchMedia && | |
| window.matchMedia('(prefers-color-scheme: dark)').matches); | |
| const apply = (theme, persist) => { | |
| root.dataset.theme = theme; | |
| const studio = document.getElementById('studio'); | |
| if (studio) studio.dataset.theme = theme; | |
| if (persist) { | |
| try { localStorage.setItem(KEY, theme); } catch (error) {} | |
| } | |
| }; | |
| // Follow the browser theme on every load; persist only explicit toggles. | |
| apply((stored === 'light' || stored === 'dark') | |
| ? stored : (systemDark ? 'dark' : 'light'), false); | |
| document.addEventListener('click', (event) => { | |
| const button = event.target && event.target.closest | |
| ? event.target.closest('.theme-toggle') : null; | |
| if (!button) return; | |
| apply(root.dataset.theme === 'dark' ? 'light' : 'dark', true); | |
| }); | |
| // Click-to-copy for every email pill on the درباره ما page: async clipboard | |
| // API first, execCommand fallback for non-secure contexts, and if both are | |
| // blocked the address is selected with a "متن انتخاب شد" hint instead. | |
| const legacyCopy = (text) => { | |
| try { | |
| const helper = document.createElement('textarea'); | |
| helper.value = text; | |
| helper.setAttribute('readonly', ''); | |
| helper.style.position = 'fixed'; | |
| helper.style.opacity = '0'; | |
| document.body.appendChild(helper); | |
| helper.select(); | |
| const ok = document.execCommand('copy'); | |
| document.body.removeChild(helper); | |
| return ok; | |
| } catch (error) { return false; } | |
| }; | |
| const selectText = (node) => { | |
| try { | |
| const range = document.createRange(); | |
| range.selectNodeContents(node); | |
| const selection = window.getSelection(); | |
| selection.removeAllRanges(); | |
| selection.addRange(range); | |
| return true; | |
| } catch (error) { return false; } | |
| }; | |
| document.addEventListener('click', (event) => { | |
| const button = event.target && event.target.closest | |
| ? event.target.closest('.copy-email') : null; | |
| if (!button) return; | |
| const email = button.getAttribute('data-email') || ''; | |
| const done = () => { | |
| button.classList.add('copied'); | |
| window.setTimeout(() => button.classList.remove('copied'), 1800); | |
| }; | |
| const fallback = () => { | |
| if (legacyCopy(email)) { done(); return; } | |
| const node = button.querySelector('bdi'); | |
| if (node) selectText(node); | |
| button.classList.add('copy-failed'); | |
| window.setTimeout(() => button.classList.remove('copy-failed'), 2400); | |
| }; | |
| if (navigator.clipboard && navigator.clipboard.writeText) { | |
| navigator.clipboard.writeText(email).then(done).catch(fallback); | |
| } else { | |
| fallback(); | |
| } | |
| }); | |
| const statusBox = () => document.getElementById('upload-status-box'); | |
| const micStatusBox = () => document.getElementById('mic-upload-status-box'); | |
| // File picker: show immediately after the user chooses a file, then let | |
| // the existing file-preview observer hide it once Gradio finishes upload. | |
| document.addEventListener('change', (event) => { | |
| const input = event.target; | |
| if (input && input.type === 'file' && input.closest && | |
| input.closest('#upload-audio')) { | |
| const box = statusBox(); | |
| if (box) box.removeAttribute('hidden'); | |
| } | |
| }); | |
| const hideWhenUploaded = () => { | |
| const box = statusBox(); | |
| const zone = document.getElementById('upload-audio'); | |
| if (!box || !zone) return; | |
| if (zone.querySelector('[data-testid="file"], .file-preview, .uploaded-file')) { | |
| box.setAttribute('hidden', ''); | |
| } | |
| }; | |
| // Microphone: show the status when the user stops recording. The Python | |
| // completion callback returns fresh hidden HTML after Gradio has delivered | |
| // the uploaded filepath; the data-cycle nonce forces a DOM replacement. | |
| let micIsRecording = false; | |
| document.addEventListener('click', (event) => { | |
| const button = event.target && event.target.closest | |
| ? event.target.closest('#record-audio button') : null; | |
| if (!button) return; | |
| const label = [ | |
| button.getAttribute('aria-label') || '', | |
| button.getAttribute('title') || '', | |
| button.getAttribute('data-testid') || '', | |
| button.className || '', | |
| button.textContent || '' | |
| ].join(' ').toLowerCase(); | |
| const isStart = button.classList.contains('record-button') || | |
| label.includes('start recording') || label.includes('record audio'); | |
| const isStop = button.classList.contains('stop-button') || | |
| label.includes('stop recording'); | |
| if (isStart) { | |
| micIsRecording = true; | |
| const box = micStatusBox(); | |
| if (box) box.setAttribute('hidden', ''); | |
| return; | |
| } | |
| if (isStop && micIsRecording) { | |
| micIsRecording = false; | |
| const box = micStatusBox(); | |
| if (box) box.removeAttribute('hidden'); | |
| } | |
| }, true); | |
| const attach = () => { | |
| const zone = document.getElementById('upload-audio'); | |
| if (!zone) { | |
| const studio = document.getElementById('studio'); | |
| if (studio && studio.dataset.theme !== root.dataset.theme) { | |
| studio.dataset.theme = root.dataset.theme; | |
| } | |
| window.setTimeout(attach, 400); | |
| return; | |
| } | |
| new MutationObserver(hideWhenUploaded) | |
| .observe(zone, { childList: true, subtree: true }); | |
| }; | |
| attach(); | |
| }""" | |
| UPLOAD_STATUS_HIDDEN = ( | |
| '<div class="upload-status" id="upload-status-box" hidden>' | |
| '<span class="dot" aria-hidden="true"></span>' | |
| '<span>در حال آپلود فایل…</span>' | |
| '</div>' | |
| ) | |
| MIC_UPLOAD_STATUS_HIDDEN = ( | |
| '<div class="upload-status" id="mic-upload-status-box" hidden>' | |
| '<span class="dot" aria-hidden="true"></span>' | |
| '<span>در حال آمادهسازی و آپلود صدای ضبطشده…</span>' | |
| '</div>' | |
| ) | |
| def hidden_status_markup(element_id: str, message: str) -> str: | |
| """Return a fresh hidden status element. | |
| The unique data-cycle value is intentional: JavaScript may show the current | |
| element by removing its `hidden` attribute. Returning the original static | |
| HTML string can be treated by Gradio as an unchanged component value, so | |
| React may leave the manually-shown DOM element visible. A fresh value forces | |
| Gradio to render a new hidden element after each completed upload. | |
| """ | |
| return ( | |
| f'<div class="upload-status" id="{element_id}" ' | |
| f'data-cycle="{uuid4().hex}" hidden>' | |
| '<span class="dot" aria-hidden="true"></span>' | |
| f'<span>{escape(message)}</span>' | |
| '</div>' | |
| ) | |
| def icon(key, cls=""): | |
| cls_attr = f' class="{cls}"' if cls else "" | |
| return ( | |
| '<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" ' | |
| f'stroke-width="1.55" stroke-linejoin="round" stroke-linecap="round"{cls_attr}>' | |
| f'{ICONS[key]}</svg>' | |
| ) | |
| def heading(key, title): | |
| return f'<div class="section-title"><span>{icon(key)}</span><h2>{title}</h2></div>' | |
| def theme_button(): | |
| return ( | |
| '<button class="theme-toggle" type="button" ' | |
| 'aria-label="تغییر حالت روشن و تاریک" title="تغییر حالت روشن و تاریک">' | |
| f'{icon("moon", "icon-moon")}{icon("sun", "icon-sun")}' | |
| '</button>' | |
| ) | |
| def data_url(filename, mime): | |
| encoded = b64encode((ASSETS / filename).read_bytes()).decode("ascii") | |
| return f"data:{mime};base64,{encoded}" | |
| def university_logo_url(): | |
| if ASSETS.is_dir(): | |
| for name in LOGO_CANDIDATES: | |
| path = ASSETS / name | |
| if path.is_file(): | |
| return data_url(name, LOGO_MIME.get(path.suffix.lower(), "image/png")) | |
| others = [p for p in ASSETS.iterdir() | |
| if p.is_file() and p.suffix.lower() in LOGO_MIME and p.name != "contours.png"] | |
| if len(others) == 1: | |
| return data_url(others[0].name, LOGO_MIME[others[0].suffix.lower()]) | |
| return "" | |
| def email_button(email): | |
| """Click-to-copy pill for one address; the envelope swaps to a check.""" | |
| # Word-break hints after the dots and the @ let long addresses wrap at | |
| # punctuation (e.g. "sajadi@<wbr>gmail.com") instead of mid-syllable when | |
| # a narrow column forces the pill to fold. data-email stays raw for the | |
| # clipboard handler wired in THEME_JS. | |
| printable = escape(email).replace(".", ".<wbr>").replace("@", "@<wbr>") | |
| return ( | |
| f'<button type="button" class="copy-email" data-email="{email}" ' | |
| 'title="برای رونوشت ایمیل کلیک کنید">' | |
| f'{MAIL_ICON}{CHECK_ICON}' | |
| f'<bdi dir="ltr">{printable}</bdi>' | |
| '<span class="copy-msg msg-ok">کپی شد</span>' | |
| '<span class="copy-msg msg-fail">متن انتخاب شد</span>' | |
| '</button>' | |
| ) | |
| def linkedin_link(url, label): | |
| """Pill-style link to a LinkedIn profile, opened in a new tab.""" | |
| href = escape(url, quote=True) | |
| return ( | |
| f'<a class="linkedin-link" href="{href}" target="_blank" ' | |
| 'rel="noopener noreferrer" title="مشاهدهٔ پروفایل در لینکدین">' | |
| f'{LINKEDIN_ICON}<bdi>{escape(label)}</bdi>{EXTERNAL_ICON}' | |
| '</a>' | |
| ) | |
| def person_links(person): | |
| """Email pill and LinkedIn pill stacked under one person's details.""" | |
| return ( | |
| '<div class="person-links">' | |
| f'{email_button(person["email"])}' | |
| f'{linkedin_link(person["linkedin"], person["linkedin_label"])}' | |
| '</div>' | |
| ) | |
| def person_detail(person): | |
| """Name, affiliation line and contact pills for one person.""" | |
| return ( | |
| f'<p class="person">{person["name"]}</p>' | |
| f'<p class="affiliation">{person["affiliation"]}</p>' | |
| f'{person_links(person)}' | |
| ) | |
| def about_page(): | |
| logo = university_logo_url() | |
| logo_html = f'<img class="univ-logo" src="{logo}" alt="نشان دانشگاه اصفهان">' if logo else "" | |
| return f'''<div class="about-wrap" lang="fa" dir="rtl"> | |
| <div class="about-topbar"> | |
| {theme_button()} | |
| </div> | |
| <p class="about-lead">این سامانهٔ بازشناسی گفتار فارسی در دانشگاه اصفهان توسعه یافته است.</p> | |
| <div class="about-grid"> | |
| <section class="about-card"> | |
| <h3>مجری طرح</h3> | |
| {person_detail(PROJECT_LEAD)} | |
| </section> | |
| <section class="about-card"> | |
| <h3>همکار</h3> | |
| {person_detail(COLLABORATOR)} | |
| </section> | |
| </div> | |
| <section class="about-card about-team"> | |
| <h3>اعضای تیم</h3> | |
| <div class="team-grid">{''.join( | |
| f'<div class="team-member">{person_detail(member)}</div>' | |
| for member in TEAM_MEMBERS | |
| )}</div> | |
| </section> | |
| <div class="univ-block"> | |
| {logo_html} | |
| <p class="univ-name">دانشگاه اصفهان</p> | |
| </div> | |
| <footer class="about-footer"> | |
| <p>© تمامی حقوق محفوظ است · <bdi dir="ltr">All rights reserved.</bdi></p> | |
| </footer> | |
| </div>''' | |
| def header(preview): | |
| badge = '<span class="demo-label" lang="en">Demo</span>' if preview else "" | |
| return f'''<header class="masthead" lang="fa" dir="rtl"> | |
| {theme_button()} | |
| <div class="intro"> | |
| <div class="brand"><i></i><bdi>Persian Conformer ASR</bdi>{badge}</div> | |
| <h1>بازشناسی گفتار فارسی</h1> | |
| <p>صدا را انتخاب کنید، متن بازشناسیشده را بخوانید و عملکرد مدل را بررسی کنید.</p> | |
| </div> | |
| <img alt="" class="contours" src="{data_url("contours.png", "image/png")}"> | |
| </header>''' | |
| def entries(items, css="facts"): | |
| return '<dl class="' + css + '">' + "".join( | |
| '<div><dt>' + escape(label) + '</dt><dd><bdi>' + escape(str(value)) + | |
| '</bdi></dd></div>' for label, value in items | |
| ) + '</dl>' | |
| def sample_files(): | |
| return {title: filename for title, filename, _ in SAMPLES if (ASSETS / filename).is_file()} | |
| def sample_choices(): | |
| # Radio choices with duration when the file is a plain wav (mp3/flac still | |
| # play fine, they just lack a duration). The dataset name is intentionally | |
| # left out of the label; sample_note() reports it after a clip is chosen. | |
| choices = [] | |
| for title, filename, _ in SAMPLES: | |
| path = ASSETS / filename | |
| if not path.is_file(): | |
| continue | |
| try: | |
| with wave.open(str(path)) as audio: | |
| seconds = audio.getnframes() / audio.getframerate() | |
| choices.append((f"{title} · {seconds:.1f} ثانیه", title)) | |
| except Exception: | |
| choices.append((title, title)) | |
| return choices | |
| def sample_note(selected=None): | |
| # Caption under the sample list: a neutral line until a clip is chosen, | |
| # then the dataset the selected clip comes from. Bound to sample.change so | |
| # programmatic resets (tab switches, پاک کردن, player.clear) restore it too. | |
| datasets = {title: dataset for title, _, dataset in SAMPLES} | |
| dataset = datasets.get(selected) | |
| if dataset: | |
| return f'<p class="note">این گفتار از مجموعهٔ <bdi>{escape(dataset)}</bdi> است</p>' | |
| return '<p class="note">گفتارهای فارسی آمادهٔ انتخاب</p>' | |
| def model_details(catalog, config, name, model_info): | |
| cfg = replace(config, **catalog[name].get("config", {})) | |
| # Keep native English API metadata intact, including measured parameter count. | |
| raw = model_info(name) if model_info else "" | |
| param = re.search(r"\*\*Parameters:\*\* ([\d.]+ M)", raw) | |
| items = [ | |
| ("معماری", catalog[name].get("description") or name), | |
| ("پارامترها", param.group(1) if param else "پس از بارگیری مدل"), | |
| ("بُعد رمزگذار", cfg.encoder_dim), ("سرهای توجه", cfg.nhead), | |
| ("رمزگذار بازگشتی", "بله" if cfg.use_recurrence else "خیر"), | |
| ] | |
| if cfg.use_recurrence: | |
| items.append(("تعداد تکرار", cfg.max_loops if cfg.max_loops > 0 else cfg.num_loops)) | |
| items.extend([ | |
| ("بازخورد CTC", "فعال" if cfg.use_ctc_feedback else "غیرفعال"), | |
| ("رمزگشا", f"k2 · {cfg.method}"), ("پردازندهٔ پیکربندیشده", "CPU"), | |
| ]) | |
| return entries(items) | |
| def performance(report=""): | |
| fields = dict(line.split(": ", 1) for line in (report or "").splitlines() if ": " in line) | |
| # Only the total numbers: input duration, total processing time and RTF. | |
| metrics = [ | |
| ("مدت صوت", "Audio duration"), | |
| ("زمان پردازش کل", "End-to-end processing"), | |
| ("RTF کل", "End-to-end RTF"), | |
| ] | |
| html = entries([(label, fields.get(key, "—")) for label, key in metrics], "metrics") | |
| if fields: | |
| secondary = [ | |
| ("مدل", "Model"), ("پردازنده", "Device"), | |
| ("نرخ نمونهبرداری ورودی", "Original sample rate"), ("تعداد کانال", "Channels"), | |
| ] | |
| html += entries([(label, fields[key]) for label, key in secondary if key in fields]) | |
| else: | |
| html += '<p class="note">مقادیر پس از اجرای موفق بازشناسی نمایش داده میشوند.</p>' | |
| return html | |
| def build_dashboard(catalog, config, *, select_model=None, model_info=None, | |
| transcribe=None, gpu_handler=None): | |
| preview = transcribe is None | |
| default = next(iter(catalog)) | |
| empty_report = performance() | |
| selection_hint = "مدل هنگام اجرای بازشناسی در حافظه بارگیری میشود." | |
| if preview: | |
| selection_hint = "پیشنمایش Demo فعال است. میتوانید ورودی و پخش صدا را بررسی کنید." | |
| empty_hint = '<p class="player-empty">برای پخش، ابتدا یک صدا انتخاب یا ضبط کنید.</p>' | |
| blocks_kwargs = {} if LAUNCH_ACCEPTS_JS else {"js": THEME_JS} | |
| with gr.Blocks(title="بازشناسی گفتار فارسی · Persian Conformer ASR", | |
| **blocks_kwargs) as demo: | |
| with gr.Column(elem_id="studio"): | |
| with gr.Tabs(elem_id="main-tabs"): | |
| with gr.Tab("خانه", elem_id="tab-home"): | |
| gr.HTML(header(preview), container=False) | |
| with gr.Column(elem_classes=["surface", "settings"]): | |
| with gr.Row(elem_classes=["model-row"]): | |
| with gr.Column(min_width=220): | |
| gr.HTML(heading("model", "مدل بازشناسی"), container=False) | |
| status = gr.Markdown(selection_hint, elem_classes=["model-note"]) | |
| model = gr.Dropdown(list(catalog), value=default, label="انتخاب مدل", interactive=True, | |
| filterable=False, elem_id="model-select", min_width=210) | |
| with gr.Accordion("مشخصات فنی مدل", open=False, elem_id="technical"): | |
| info = gr.HTML(model_details(catalog, config, default, model_info), container=False) | |
| with gr.Row(elem_id="desk", equal_height=False): | |
| with gr.Column(scale=11, min_width=320, elem_classes=["surface", "source-card"]): | |
| gr.HTML(heading("input", "ورودی صوتی"), container=False) | |
| source_tabs_kwargs = {"elem_id": "sources"} | |
| if "overflow_behavior" in inspect.signature(gr.Tabs.__init__).parameters: | |
| source_tabs_kwargs["overflow_behavior"] = "wrap" | |
| with gr.Tabs(**source_tabs_kwargs): | |
| with gr.Tab("بارگذاری فایل") as upload_tab: | |
| uploaded = gr.File(file_types=["audio"], type="filepath", label="انتخاب فایل صوتی", | |
| show_label=False, height=118, elem_id="upload-audio") | |
| upload_status = gr.HTML(UPLOAD_STATUS_HIDDEN, container=False, | |
| elem_id="upload-status") | |
| with gr.Tab("ضبط صدا") as mic_tab: | |
| recorded = gr.Audio(sources=["microphone"], type="filepath", label="ضبط با میکروفون", | |
| show_label=False, interactive=True, elem_id="record-audio") | |
| mic_upload_status = gr.HTML(MIC_UPLOAD_STATUS_HIDDEN, container=False, | |
| elem_id="mic-upload-status") | |
| with gr.Tab("نمونههای آماده") as examples_tab: | |
| gr.HTML('<p class="radio-head">انتخاب گفتار فارسی</p>', container=False) | |
| sample = gr.Radio(choices=sample_choices(), label="انتخاب گفتار فارسی", | |
| show_label=False, value=None, elem_id="sample-list") | |
| sample_caption = gr.HTML(sample_note(), container=False) | |
| def limit_text(name): | |
| cfg = replace(config, **catalog[name].get("config", {})) | |
| return f'<p class="note">حداکثر مدت ورودی این مدل: {cfg.max_audio_seconds:g} ثانیه</p>' | |
| limit = gr.HTML(limit_text(default), container=False) | |
| gr.HTML('<h3 class="subhead">پخش و بازشناسی</h3>', container=False) | |
| placeholder = gr.HTML(empty_hint, container=False) | |
| # Automatically show the selected audio in the player. | |
| # The original server filepath is also kept in gr.State | |
| # and passed directly to inference (no browser re-upload). | |
| player = gr.Audio(type="filepath", sources=[], label="صدای انتخابشده", | |
| show_label=False, interactive=False, visible=False, | |
| elem_id="shared-player") | |
| with gr.Row(elem_classes=["actions"]): | |
| run = gr.Button("اجرای بازشناسی", variant="primary", interactive=False, scale=3) | |
| clear = gr.Button("پاک کردن", interactive=False, scale=1) | |
| with gr.Column(scale=10, min_width=310, elem_id="results"): | |
| with gr.Column(elem_classes=["surface"]): | |
| gr.HTML(heading("text", "متن بازشناسیشده"), container=False) | |
| text = gr.Textbox(lines=3, rtl=True, label="متن بازشناسیشده", show_label=False, | |
| interactive=False, elem_id="transcript", | |
| placeholder="متن فارسی پس از بازشناسی اینجا نمایش داده میشود.") | |
| with gr.Column(elem_classes=["surface"]): | |
| gr.HTML(heading("performance", "عملکرد مدل"), container=False) | |
| report = gr.HTML(empty_report, container=False) | |
| with gr.Tab("درباره ما", elem_id="tab-about"): | |
| gr.HTML(about_page(), container=False) | |
| audio_state = gr.State(None) | |
| last_tab = gr.State(None) | |
| # Transcription stays on the single serial queue; light UI updates run | |
| # without queueing so the input menus never freeze behind a running job. | |
| events = dict(concurrency_id="asr-dashboard", concurrency_limit=1, api_visibility="private", | |
| show_progress="hidden") | |
| ui_events = dict(api_visibility="private", show_progress="hidden", queue=False) | |
| outputs = [player, placeholder, run, clear, text, report, audio_state] | |
| def choose_audio(path): | |
| ready = bool(path) | |
| # Always populate the player when a file is ready, while retaining | |
| # the original server filepath in gr.State for direct inference. | |
| return (gr.update(value=path, visible=ready), gr.update(visible=not ready), | |
| gr.update(interactive=ready and not preview), | |
| gr.update(interactive=ready), "", empty_report, path) | |
| def choose_sample(title): | |
| files = sample_files() | |
| return choose_audio(str(ASSETS / files[title]) if title in files else None) | |
| def on_upload(path): | |
| # Gradio calls this after the uploaded file has reached the server. | |
| # Return a fresh hidden status markup so a prior JS visibility change | |
| # cannot leave the uploading message stuck on screen. | |
| return (*choose_audio(path), gr.update(value=None), | |
| gr.update(value=hidden_status_markup( | |
| "upload-status-box", "در حال آپلود فایل…"))) | |
| def on_record(path): | |
| # stop_recording supplies the completed server-side filepath. The | |
| # fresh hidden markup forces the microphone status to disappear. | |
| return (*choose_audio(path), gr.update(value=None), | |
| gr.update(value=hidden_status_markup( | |
| "mic-upload-status-box", "در حال آمادهسازی و آپلود صدای ضبطشده…"))) | |
| uploaded.upload(on_upload, uploaded, outputs + [uploaded, upload_status], **ui_events) | |
| recorded.stop_recording( | |
| on_record, recorded, outputs + [recorded, mic_upload_status], **ui_events | |
| ) | |
| def hide_mic_status_when_value_arrives(path): | |
| # Some Gradio/browser combinations update the Audio value in a | |
| # separate input event after stop_recording. Only hide the status | |
| # when a real filepath has arrived; ignore empty/reset events. | |
| if path: | |
| return gr.update(value=hidden_status_markup( | |
| "mic-upload-status-box", | |
| "در حال آمادهسازی و آپلود صدای ضبطشده…", | |
| )) | |
| return gr.skip() | |
| recorded.input( | |
| hide_mic_status_when_value_arrives, | |
| recorded, | |
| mic_upload_status, | |
| **ui_events, | |
| ) | |
| sample.input(choose_sample, sample, outputs, **ui_events) | |
| # .change (not .input) so the caption also resets when the selection is | |
| # cleared programmatically by the tab switches and the reset flows. | |
| sample.change(sample_note, sample, sample_caption, **ui_events) | |
| def make_tab_switch(name): | |
| def switch(last): | |
| if last == name: | |
| # Clicking the already-active tab keeps the current selection. | |
| return [gr.skip()] * len(outputs) + [gr.update()] * 6 | |
| # Switching tabs clears the selected audio, results and both | |
| # upload indicators to avoid leaving a stale status visible. | |
| return (*choose_audio(None), gr.update(value=None), gr.update(value=None), | |
| gr.update(value=None), name, | |
| gr.update(value=hidden_status_markup( | |
| "upload-status-box", "در حال آپلود فایل…")), | |
| gr.update(value=hidden_status_markup( | |
| "mic-upload-status-box", "در حال آمادهسازی و آپلود صدای ضبطشده…"))) | |
| return switch | |
| for tab, name in ((upload_tab, "upload"), (mic_tab, "record"), (examples_tab, "samples")): | |
| tab.select( | |
| make_tab_switch(name), last_tab, | |
| outputs + [uploaded, recorded, sample, last_tab, upload_status, mic_upload_status], | |
| **ui_events, | |
| ) | |
| def reset(): | |
| return (*choose_audio(None), None, None, None, | |
| gr.update(value=hidden_status_markup( | |
| "upload-status-box", "در حال آپلود فایل…")), | |
| gr.update(value=hidden_status_markup( | |
| "mic-upload-status-box", "در حال آمادهسازی و آپلود صدای ضبطشده…"))) | |
| clear.click( | |
| reset, None, | |
| outputs + [uploaded, recorded, sample, upload_status, mic_upload_status], | |
| **ui_events, | |
| ) | |
| recorded.clear( | |
| reset, None, | |
| outputs + [uploaded, recorded, sample, upload_status, mic_upload_status], | |
| **ui_events, | |
| ) | |
| def change_model(name): | |
| # Instant, local-only refresh: the hub download happens lazily on the | |
| # first transcription, so switching models never blocks the interface. | |
| if preview: | |
| message = selection_hint | |
| else: | |
| message = f"مدل «{name}» انتخاب شد؛ در اولین اجرای بازشناسی بارگیری میشود." | |
| return message, model_details(catalog, config, name, model_info), limit_text(name), "", empty_report | |
| model.input(change_model, model, [status, info, limit, text, report], **ui_events) | |
| if not preview: | |
| def recognize(path, name): | |
| yield "", empty_report, gr.skip(), gr.skip() | |
| words, stats = transcribe(path, name) | |
| yield (words, performance(stats), model_details(catalog, config, name, model_info), | |
| "مدل انتخابشده در حافظه آمادهٔ بازشناسی است.") | |
| run.click(recognize, [audio_state, model], [text, report, info, status], | |
| **{**events, "show_progress": "minimal"}) | |
| # Preserve the original Gradio client endpoints and their two string outputs. | |
| api_text = gr.Textbox(visible=False) | |
| api_report = gr.Textbox(visible=False) | |
| for handler in (transcribe, gpu_handler): | |
| if handler: | |
| gr.Button(visible=False).click(handler, [audio_state, model], [api_text, api_report], | |
| api_name=handler.__name__, concurrency_id="asr-dashboard", concurrency_limit=1) | |
| gr.Button(visible=False).click(select_model, model, [api_text, api_report], | |
| api_name="select_model", concurrency_id="asr-dashboard", concurrency_limit=1) | |
| return demo.queue(default_concurrency_limit=1) | |
| def launch_dashboard(demo, **kwargs): | |
| css = (ASSETS / "studio.css").read_text("utf-8").replace( | |
| "__FONT__", data_url("Vazirmatn.ttf", "font/ttf")) | |
| # Use Gradio Font objects for every fallback. Some Gradio versions compare | |
| # custom themes against built-in themes during launch; mixing Font objects | |
| # and plain strings in the internal font lists can raise | |
| # AttributeError: 'str' object has no attribute 'name'. | |
| # The actual Vazirmatn font is still supplied by studio.css via __FONT__. | |
| theme = gr.themes.Base( | |
| primary_hue="teal", | |
| neutral_hue="slate", | |
| font=[ | |
| gr.themes.Font("Vazirmatn"), | |
| gr.themes.Font("Tahoma"), | |
| gr.themes.Font("sans-serif"), | |
| ], | |
| font_mono=[ | |
| gr.themes.Font("Consolas"), | |
| gr.themes.Font("monospace"), | |
| ], | |
| ) | |
| if LAUNCH_ACCEPTS_JS: | |
| demo.launch(theme=theme, css=css, allowed_paths=[str(ASSETS)], js=THEME_JS, **kwargs) | |
| else: | |
| demo.launch(theme=theme, css=css, allowed_paths=[str(ASSETS)], **kwargs) | |