"""Gradio UI β€” layout orchestrator.""" from pathlib import Path from types import SimpleNamespace import gradio as gr from config import ( ANIM_DISPLAY_MODE_DEFAULT, ANIM_DISPLAY_MODES, ANIM_GRANULARITIES, ANIM_GRANULARITY_DEFAULT, ANIM_STYLE_ROW_SCALES, ANIM_WORD_COLOR, DEFAULT_INPUT_MODE, DELETE_CACHE_AGE, DELETE_CACHE_FREQUENCY, LEFT_COLUMN_SCALE, PAD_LEFT_DEFAULT, PRELOAD_MODE_ENABLED, RIGHT_COLUMN_SCALE, VISIBLE_ASR_MODEL_DEFAULT, VISIBLE_ASR_MODELS, ) from gradio_rangeslider import RangeSlider from src.ui.brand import title_html from src.ui.changelog import latest_entry_date, load_changelog_text from src.ui.event_wiring import wire_events from src.ui.faq import load_faq_text from src.ui.handlers import create_segmentation_settings from src.ui.js_config import build_js_head from src.ui.styles import build_css def build_interface(): """Build the Gradio interface.""" c = SimpleNamespace() css = build_css() _changelog = load_changelog_text() js = build_js_head(latest_entry_date(_changelog)) with gr.Blocks(title="Quranic Universal Aligner", css=css, head=js, delete_cache=(DELETE_CACHE_FREQUENCY, DELETE_CACHE_AGE)) as app: # Title, then the account and theme controls beside it. The right of the # row is deliberately left empty: on the direct *.hf.space URL the # Hugging Face mini header floats there (see js_config). with gr.Row(elem_id="header-row"): gr.HTML(title_html("Quranic Universal Aligner"), elem_id="app-title") # HF OAuth pill \u2014 token cached for ~30 days (see README hf_oauth_expiration_minutes). # Required for Save Session / Load Saved Session. c.login_button = gr.LoginButton(value="Sign in", size="sm", scale=0, min_width=0, elem_id="hf-login-btn") # Light/dark switch. Driven entirely by static/theme-toggle.js \u2014 no # Gradio event, so nothing can leak onto the public API surface and the # icon can follow the class Gradio actually set. gr.Button("\U0001f319", size="sm", scale=0, min_width=0, elem_id="theme-toggle") # FAQ accordion β€” the first thing under the header now that the About # bullets are gone. The API doc below it is for the smaller technical # audience. with gr.Accordion("❓ FAQ", open=False, elem_id="faq-accordion"): gr.Markdown(load_faq_text()) # API Usage accordion β€” the hand-written guide. The generated reference # it links to is always current; this covers what a schema cannot. _api_doc = (Path(__file__).parent.parent.parent / "docs" / "client_api.md") with gr.Accordion("\U0001f4e1 API Usage", open=False): gr.Markdown(_api_doc.read_text(encoding="utf-8")) # Changelog accordion (reuse already-loaded _changelog) with gr.Accordion("πŸ“‹ Changelog", open=False, elem_id="changelog-accordion"): gr.Markdown(_changelog) with gr.Row(elem_id="main-row"): _build_left_column(c) _build_right_column(c) # State components for caching segmentation data between runs c.cached_speech_intervals = gr.State(value=None) c.cached_is_complete = gr.State(value=None) c.cached_audio = gr.State(value=None) c.cached_sample_rate = gr.State(value=None) c.cached_intervals = gr.State(value=None) c.cached_model_name = gr.State(value=None) c.cached_segment_dir = gr.State(value=None) c.cached_full_audio_url = gr.State(value=None) c.audio_source = gr.State(value="preload") c.view_mode = gr.State(value="segment") c.split_panel_visible = gr.State(value=False) # Saved-sessions state carriers c.session_id_state = gr.State(value="") # current session id; "" if not yet saved c.session_meta_state = gr.State(value=None) # full meta dict for the active session # Legacy Gradio API components (hidden, API-only). # Argument ORDER here is production's frozen contract β€” see # src/api/session_api.py. New parameters belong on /api/v1. c.api_audio = gr.Audio(visible=False, type="numpy") c.api_audio_id = gr.Textbox(visible=False) c.api_url = gr.Textbox(visible=False) # Accepted and ignored: the VAD these configured no longer exists. c.api_legacy_min_silence = gr.Number(visible=False, precision=0) c.api_legacy_min_speech = gr.Number(visible=False, precision=0) # Single symmetric pad, applied to both segment edges. c.api_legacy_pad = gr.Number(value=PAD_LEFT_DEFAULT, visible=False, precision=0) c.api_model = gr.Textbox(visible=False) c.api_device = gr.Textbox(visible=False) c.api_split_max_verses = gr.Number(visible=False, precision=0) c.api_split_max_words = gr.Number(visible=False, precision=0) c.api_split_max_duration = gr.Number(visible=False) c.api_split_require_stop_sign = gr.Checkbox(visible=False, value=False) c.api_timestamps = gr.JSON(visible=False) c.api_mfa_segments = gr.JSON(visible=False) c.api_mfa_granularity = gr.Textbox(visible=False) # Operator-only pool controls. c.api_pool_status_token = gr.Textbox(visible=False) c.api_pool_worker_id = gr.Textbox(visible=False) # Preload API (catalog + pre-aligned segment fetch) c.api_preload_slug = gr.Textbox(visible=False) c.api_preload_chapter = gr.Number(visible=False, precision=0) c.api_preload_verse_from = gr.Number(visible=False, precision=0) c.api_preload_verse_to = gr.Number(visible=False, precision=0) c.api_preload_include_ts = gr.Checkbox(visible=False, value=True) c.api_result = gr.JSON(visible=False) # Inline ref editing bridge (JS β†’ Python) # Must be visible=True + CSS hide (visible=False removes from DOM in Gradio 6) with gr.Row(visible=True, elem_id="ref-edit-bridge"): c.ref_edit_payload = gr.Textbox(elem_id="ref-edit-payload", show_label=False, container=False) c.ref_edit_trigger = gr.Button("", elem_id="ref-edit-trigger", size="sm") # Manual split bridge (JS β†’ Python) with gr.Row(visible=True, elem_id="manual-split-bridge"): c.manual_split_payload = gr.Textbox(elem_id="manual-split-payload", show_label=False, container=False) c.manual_split_trigger = gr.Button("", elem_id="manual-split-trigger", size="sm") # Undo split bridge (JS β†’ Python) with gr.Row(visible=True, elem_id="undo-split-bridge"): c.undo_split_payload = gr.Textbox(elem_id="undo-split-payload", show_label=False, container=False) c.undo_split_trigger = gr.Button("", elem_id="undo-split-trigger", size="sm") # Merge bridge (JS β†’ Python) with gr.Row(visible=True, elem_id="merge-bridge"): c.merge_payload = gr.Textbox(elem_id="merge-payload", show_label=False, container=False) c.merge_trigger = gr.Button("", elem_id="merge-trigger", size="sm") # Undo merge bridge (JS β†’ Python) with gr.Row(visible=True, elem_id="undo-merge-bridge"): c.undo_merge_payload = gr.Textbox(elem_id="undo-merge-payload", show_label=False, container=False) c.undo_merge_trigger = gr.Button("", elem_id="undo-merge-trigger", size="sm") # Partial merge bridge (JS β†’ Python) with gr.Row(visible=True, elem_id="partial-merge-bridge"): c.partial_merge_payload = gr.Textbox(elem_id="partial-merge-payload", show_label=False, container=False) c.partial_merge_trigger = gr.Button("", elem_id="partial-merge-trigger", size="sm") # Edit patch channel (Python β†’ JS, carries surgical patch instructions) with gr.Row(visible=True, elem_id="edit-patch"): c.edit_patch = gr.Textbox(elem_id="edit-patch-data", show_label=False, container=False) wire_events(app, c) return app def _build_left_column(c): """Build the left input column.""" _is_preload = DEFAULT_INPUT_MODE == "Preload" _is_link = DEFAULT_INPUT_MODE == "Link" _is_upload = DEFAULT_INPUT_MODE == "Upload" _is_record = DEFAULT_INPUT_MODE == "Record" with gr.Column(scale=LEFT_COLUMN_SCALE, elem_id="left-col"): # Stack mode switchers in a compact column: Gradio "compact" = no internal gap # between children (see Column variant in Gradio docs). Fixes HF layout without # fragile CSS overrides on .gr-block wrappers. with gr.Column( scale=1, variant="compact", min_width=0, elem_id="mode-rows-stack", elem_classes=["mode-rows-stack"], ): # Row 1: Preload + Load Saved Session (the two "browse"-style modes). with gr.Row( elem_id="preload-pill-row", elem_classes=[] if PRELOAD_MODE_ENABLED else ["preload-disabled"], ): c.mode_preload = gr.Button( "Preload", size="sm", min_width=0, visible=PRELOAD_MODE_ENABLED, elem_classes=(["mode-active"] if _is_preload else []) + ["preload-main-pill"], ) c.mode_saved = gr.Button( "Load Saved Session / JSON", size="sm", min_width=0, elem_classes=["preload-main-pill"], elem_id="mode-saved-btn", ) with gr.Row(elem_id="input-mode-row"): c.mode_link = gr.Button("Link", size="sm", min_width=0, elem_classes=["mode-active"] if _is_link else []) c.mode_upload = gr.Button("Upload", size="sm", min_width=0, elem_classes=["mode-active"] if _is_upload else []) c.mode_record = gr.Button("Record", size="sm", min_width=0, elem_classes=["mode-active"] if _is_record else []) with gr.Column(visible=_is_preload, elem_id="preload-panel", elem_classes=["preload-panel-tight"]) as c.preload_panel: # Preload callout β€” single line inside a quiet brand-tinted box. c.preload_caption = gr.HTML( """
Pre-computed alignments, human-verified. Contribute at Quranic Universal Audio →
""", elem_id="preload-caption", ) # One flat dropdown: [(label, delivery_slug)]. Every delivery is a # self-describing row labelled "Reciter Β· Riwayah Β· Style Β· Source" # so the collapsed box shows everything. Choices are precomputed at # app load so opening it never waits. c.preload_content_mode = gr.Radio( choices=["Audio only", "Audio + segments"], value="Audio + segments", show_label=False, container=False, elem_id="preload-content-mode", ) c.preload_recitation = gr.Dropdown( label="Recitation", choices=[], allow_custom_value=False, filterable=True, elem_id="preload-recitation", ) c.preload_surah = gr.Dropdown( label="Surah", choices=[], allow_custom_value=False, elem_id="preload-surah", ) c.preload_ayah_range = RangeSlider( label="Ayah range", minimum=1, maximum=1, value=(1, 1), step=1, visible=False, elem_id="preload-ayah-range", ) # Left column is content selection only. View toggle (Segments / # Verses) and Repeats toggle (Show / Hide) live in the right # column above the segment list. # The render-ready chapter, built once per surah/ayah load. View # switches re-render purely from this cached state. c.preload_chapter_state = gr.State(value=None) # Link panel with gr.Column(visible=_is_link, elem_id="link-panel") as c.link_panel: with gr.Row(elem_id="link-example-row"): c.btn_site_tiktok = gr.Button("TikTok - Al-Qasas", size="sm", min_width=0) c.btn_site_soundcloud = gr.Button("SoundCloud - Maryam", size="sm", min_width=0) c.btn_site_mp3quran = gr.Button("MP3Quran - An-Naml", size="sm", min_width=0) c.url_input = gr.Textbox( label="Paste a link", info='[all supported sites](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md)', lines=1, ) c.url_download_btn = gr.Button("Download", size="sm", variant="secondary", interactive=False) c.url_audio_player = gr.Audio( label="Downloaded Audio", visible=False, sources=[], type="filepath", interactive=False, show_download_button=True, ) # Upload panel with gr.Column(visible=_is_upload, elem_id="upload-panel") as c.upload_panel: with gr.Row(elem_id="example-row"): c.btn_ex_84 = gr.Button("84 - Al-Inshiqaq", size="sm", min_width=0) c.btn_ex_67 = gr.Button("67 - Al-Mulk", size="sm", min_width=0) c.btn_ex_7 = gr.Button("7 - Al-A'raf", size="sm", min_width=0) c.btn_ex_juz30 = gr.Button("Juz 'Amma", size="sm", min_width=0) c.audio_upload = gr.Audio( label="Upload Recitation", sources=["upload"], type="filepath", interactive=True, show_download_button=True, ) # Record panel with gr.Column(visible=_is_record, elem_id="record-panel") as c.record_panel: c.audio_record = gr.Audio( label="Record Recitation", sources=["microphone"], type="filepath", interactive=True, show_download_button=True, ) # Saved Sessions panel β€” shown when "Load Saved Session" mode is active. with gr.Column(visible=False, elem_id="saved-panel") as c.saved_panel: c.saved_storage_html = gr.HTML(value="", elem_id="saved-storage-html") c.saved_sessions_html = gr.HTML(value="", elem_id="saved-sessions-html") c.saved_footer_html = gr.HTML(value="", elem_id="saved-footer-html") # Load an exported segments JSON (export-only β€” no bucket write, no # session). Renders the cards audio-less; attach audio afterwards # to enable playback / animate / per-card split. c.json_upload_file = gr.File( label="…or load an exported segments JSON", file_types=[".json"], type="filepath", elem_id="json-upload-file", ) # Shown only after a JSON is loaded. Attaching audio is a separate, # non-destructive path (preserves output_json) β€” NOT the normal # upload input, whose .input() handler would wipe the loaded cards. c.json_attach_audio = gr.Audio( label="Attach audio (optional) β€” enables playback, animate, per-card split", sources=["upload"], type="filepath", interactive=True, visible=False, elem_id="json-attach-audio", ) # JS bridge β€” list-row clicks (delete/rename) flow through here. with gr.Row(visible=True, elem_id="saved-action-bridge"): c.saved_action_payload = gr.Textbox(elem_id="saved-action-payload", show_label=False, container=False) c.saved_action_trigger = gr.Button("", elem_id="saved-action-trigger", size="sm") with gr.Row(visible=True, elem_id="saved-load-bridge"): c.saved_load_payload = gr.Textbox(elem_id="saved-load-payload", show_label=False, container=False) c.saved_load_trigger = gr.Button("", elem_id="saved-load-trigger", size="sm") # Pre-signin stash bridge. ``pending_stash_id`` receives a stash id # from ``open_save_panel`` when an unsigned user clicks Save β€” # client JS picks the value up and writes it to sessionStorage # so it survives the HF OAuth redirect. ``saved_promote_*`` is # the reverse trip: after sign-in, JS dispatches a promote payload # through here and ``handle_promote_action`` restores the session. with gr.Row(visible=True, elem_id="saved-promote-bridge"): c.pending_stash_id = gr.Textbox( value="", elem_id="pending-stash-id", show_label=False, container=False, ) c.saved_promote_payload = gr.Textbox( elem_id="saved-promote-payload", show_label=False, container=False, ) c.saved_promote_trigger = gr.Button( "", elem_id="saved-promote-trigger", size="sm", ) # Hidden unified audio state (fed by upload, record, or URL download) # gr.State avoids cascading .change events that gr.Audio would fire c.audio_input = gr.State(value=None) # Save Session controls + Download JSON β€” all three buttons live in a # single Row inside ``save_session_group`` so they vertically align by # default flex. The name-input row sits BELOW that row inside the same # wrapper Column, hidden until the user clicks Save. # Visibility: # - Saved-browse mode: whole ``save_session_group`` is hidden. # - Preload mode: wrapper visible, ``session_save_btn`` hidden # (only Download shows). # - Input modes (Upload/Record/URL): everything visible. Readiness is # conveyed via dim-grey ↔ orange light-up CSS classes, not flicker. with gr.Column(visible=True, elem_id="save-session-group", min_width=0) as c.save_session_group: with gr.Row(elem_id="save-download-row"): # Chapter audio (preload mode only). Streams from the bucket mount # via the same ``/preload-audio//.mp3`` route that the # per-segment cards use under the hood (Range-served, kernel # sendfile, 24h cache). We use ``gr.HTML`` + a raw ``