"""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": '', "text": '', "performance": '', "model": '', "sun": '', "moon": '', } # 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 = ('') MAIL_ICON = ('') # The LinkedIn mark is a solid glyph, so unlike the house stroke icons it is # painted with fill=currentColor and no outline. LINKEDIN_ICON = ('') # Small external-link arrow after the LinkedIn label: signals that the pill # opens a new tab without adding any text. EXTERNAL_ICON = ('') # 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 = ( '' ) MIC_UPLOAD_STATUS_HIDDEN = ( '' ) 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'' ) def icon(key, cls=""): cls_attr = f' class="{cls}"' if cls else "" return ( '' ) def heading(key, title): return f'
{icon(key)}

{title}

' def theme_button(): return ( '' ) 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@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(".", ".").replace("@", "@") return ( f'' ) def linkedin_link(url, label): """Pill-style link to a LinkedIn profile, opened in a new tab.""" href = escape(url, quote=True) return ( f'' f'{LINKEDIN_ICON}{escape(label)}{EXTERNAL_ICON}' '' ) def person_links(person): """Email pill and LinkedIn pill stacked under one person's details.""" return ( '' ) def person_detail(person): """Name, affiliation line and contact pills for one person.""" return ( f'

{person["name"]}

' f'

{person["affiliation"]}

' f'{person_links(person)}' ) def about_page(): logo = university_logo_url() logo_html = f'' if logo else "" return f'''
{theme_button()}

این سامانهٔ بازشناسی گفتار فارسی در دانشگاه اصفهان توسعه یافته است.

مجری طرح

{person_detail(PROJECT_LEAD)}

همکار

{person_detail(COLLABORATOR)}

اعضای تیم

{''.join( f'
{person_detail(member)}
' for member in TEAM_MEMBERS )}
{logo_html}

دانشگاه اصفهان

© تمامی حقوق محفوظ است · All rights reserved.

''' def header(preview): badge = 'Demo' if preview else "" return f'''
{theme_button()}
Persian Conformer ASR{badge}

بازشناسی گفتار فارسی

صدا را انتخاب کنید، متن بازشناسی‌شده را بخوانید و عملکرد مدل را بررسی کنید.

''' def entries(items, css="facts"): return '
' + "".join( '
' + escape(label) + '
' + escape(str(value)) + '
' for label, value in items ) + '
' 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'

این گفتار از مجموعهٔ {escape(dataset)} است

' return '

گفتارهای فارسی آمادهٔ انتخاب

' 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 += '

مقادیر پس از اجرای موفق بازشناسی نمایش داده می‌شوند.

' 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 = '

برای پخش، ابتدا یک صدا انتخاب یا ضبط کنید.

' 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('

انتخاب گفتار فارسی

', 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'

حداکثر مدت ورودی این مدل: {cfg.max_audio_seconds:g} ثانیه

' limit = gr.HTML(limit_text(default), container=False) gr.HTML('

پخش و بازشناسی

', 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)