File size: 29,716 Bytes
35d8fb6
 
 
 
 
 
003b05a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35d8fb6
003b05a
 
3ce422a
003b05a
 
35d8fb6
 
003b05a
 
 
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
3ce422a
35d8fb6
bc49622
 
 
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc49622
 
 
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1f9249
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
003b05a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d6ae90
 
 
35d8fb6
 
 
 
 
3d6ae90
 
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef8a4c9
 
 
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
003b05a
 
 
 
 
 
 
 
 
 
35d8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
"""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(
                """

                <div class="preload-callout">

                  Pre-computed alignments, human-verified.

                  <a class="preload-callout-link"

                     href="https://huggingface.co/spaces/QUD-Technologies/quranic-universal-audio"

                     target="_blank" rel="noopener"

                  >Contribute at Quranic Universal Audio &rarr;</a>

                </div>

                """,
                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/<slug>/<ch>.mp3`` route that the
                # per-segment cards use under the hood (Range-served, kernel
                # sendfile, 24h cache). We use ``gr.HTML`` + a raw ``<audio>`` tag
                # rather than ``gr.Audio`` because Gradio's Audio postprocess
                # treats any string with a leading ``/`` as a local filesystem
                # path and runs ``_check_allowed`` against it — which rejects the
                # Space-route URL with ``InvalidPathError``. ``FileData`` dicts
                # are also rejected by ``Audio.postprocess``. Hidden until a
                # chapter loads; cleared on mode switches / recitation change so
                # it never bleeds into the Upload/Record/Link panels. Lives
                # inside the row so in preload mode it sits side-by-side with
                # Download JSON at equal width.
                c.preload_audio_player = gr.HTML(
                    value="",
                    visible=False,
                    elem_id="preload-chapter-audio",
                    elem_classes=["preload-chapter-audio"],
                )
                c.preload_align_btn = gr.Button(
                    "Align recitation", visible=False, variant="primary",
                    elem_id="preload-align-btn", min_width=0,
                )
                c.session_save_btn = gr.Button(
                    "💾 Save Session", size="sm", variant="secondary",
                    interactive=False, min_width=0,
                    visible=not _is_preload,
                    elem_id="session-save-btn",
                    elem_classes=["session-save-btn"],
                )
                c.session_saved_status = gr.Button(
                    "Saved · just now", size="sm", variant="secondary",
                    visible=False, interactive=False, min_width=0,
                    elem_id="session-saved-status",
                    elem_classes=["session-saved-status"],
                )
                c.export_file = gr.DownloadButton(
                    label="\U0001f4e5 Download JSON",
                    interactive=False, value=None,
                    size="sm",
                    elem_id="export-json-btn",
                    elem_classes=["download-json-btn"],
                )
            with gr.Row(visible=False, elem_id="session-name-row") as c.session_name_row:
                c.session_name_input = gr.Textbox(
                    placeholder=f"Session name (max {80} chars)",
                    show_label=False, container=False, scale=3,
                    elem_id="session-name-input", max_length=80,
                )
                c.session_confirm_btn = gr.Button(
                    "Confirm", size="sm", variant="secondary",
                    interactive=False, scale=1,
                    elem_id="session-confirm-btn",
                )

        c.anim_cached_settings = gr.JSON(value=None, visible=False)
        with gr.Accordion("Alignment Settings", open=True, visible=not _is_preload, elem_id="alignment-settings-accordion") as c.alignment_accordion:
            from src.core.editions import RIWAYAH_CHOICES
            c.riwayah_radio = gr.Radio(
                choices=list(RIWAYAH_CHOICES),
                value="hafs",
                label="Riwayah",
                elem_id="riwayah-radio",
            )
            with gr.Row():
                c.model_radio = gr.Radio(
                    choices=list(VISIBLE_ASR_MODELS.keys()),
                    value=VISIBLE_ASR_MODEL_DEFAULT,
                    label="ASR Model",
                    info="Large: more robust to noisy/non-studio recitations but slower"
                )
            c.pad_left_slider, c.pad_right_slider = create_segmentation_settings()

        _build_animation_settings(c, preload_mode=_is_preload)



def _build_animation_settings(c, *, preload_mode: bool = False):
    """Build the animation settings accordion."""
    with gr.Accordion(
        "Animation Settings",
        open=False,
        elem_id="anim-settings-accordion",
        visible=not preload_mode,
    ) as c.anim_settings_accordion, gr.Row(elem_id="anim-style-row"):
        c.anim_granularity_radio = gr.Radio(
            choices=ANIM_GRANULARITIES,
            value=ANIM_GRANULARITY_DEFAULT,
            label="Granularity",
            scale=ANIM_STYLE_ROW_SCALES[0],
        )
        c.anim_mode_radio = gr.Radio(
            choices=ANIM_DISPLAY_MODES,
            value=ANIM_DISPLAY_MODE_DEFAULT,
            label="Animation Style",
            scale=ANIM_STYLE_ROW_SCALES[1],
        )
        c.anim_color_picker = gr.ColorPicker(
            value=ANIM_WORD_COLOR,
            label="Color",
            scale=ANIM_STYLE_ROW_SCALES[2],
        )


def _build_right_column(c):
    """Build the right output column."""
    with gr.Column(scale=RIGHT_COLUMN_SCALE):
        _build_results_content(c)


def _build_results_content(c):
    """Build the main results content (extract/output)."""
    _is_preload = DEFAULT_INPUT_MODE == "Preload"
    with gr.Row(elem_id="primary-actions-row"):
        c.extract_btn = gr.Button(
            "Align Recitation",
            variant="secondary",
            size="lg",
            interactive=False,
            visible=not _is_preload,
        )
        c.pipeline_progress = gr.HTML(
            value="", visible=False, elem_id="pipeline-progress",
            container=False, padding=False, min_height=0,
        )
    with gr.Row(elem_id="action-btns-row"):

        c.retranscribe_btn = gr.Button(
            "Retranscribe with Large Model", variant="primary", size="lg", visible=False
        )
        c.split_toggle_btn = gr.Button(
            "Split Segments", variant="primary", size="lg", visible=False
        )
    with gr.Row(elem_id="ts-row"):
        c.animate_all_btn = gr.Button(
            "Animate All", variant="secondary", size="lg", interactive=False, visible=False,
            elem_classes=["animate-all-btn"],
        )
        c.compute_ts_progress = gr.HTML(
            value="", visible=False, elem_id="compute-ts-progress",
            container=False, padding=False, min_height=0,
        )

    # Preload-only: Animate All + Split side-by-side in one row.
    # Live-align keeps the existing ts-row + action-btns-row layout above.
    with gr.Row(elem_id="preload-actions-row", visible=_is_preload) as c.preload_actions_row:
        c.preload_animate_all_btn = gr.Button(
            "Animate All", variant="primary", size="lg", interactive=False, visible=False,
            elem_id="preload-animate-all-btn",
            elem_classes=["animate-all-btn"],
        )
        c.preload_split_toggle_btn = gr.Button(
            "Split Segments", variant="primary", size="lg", visible=False,
            elem_id="preload-split-toggle-btn",
        )

    # Hidden Gradio button bridges — the visible Segments / Verses pills
    # are rendered as plain HTML inside the summary bar's foot row (see
    # ``_build_segment_summary``). These buttons stay in the DOM with
    # ``display: none`` so the existing click chains remain wired; client
    # JS bridges inline-pill clicks to these buttons via ``.click()``
    # forwarding.
    with gr.Row(elem_id="preload-display-rail", elem_classes=["hidden-bridge-row"]), \
            gr.Row(elem_id="preload-view-toggle", elem_classes=["preload-toggle-row"]):
            c.view_mode_segment_btn = gr.Button(
                "Segments", size="sm", min_width=0,
                elem_classes=["mode-active", "preload-seg-btn"],
            )
            c.view_mode_verse_btn = gr.Button(
                "Verses", size="sm", min_width=0,
                elem_classes=["preload-seg-btn"],
            )

    with gr.Column(visible=False) as c.split_panel:
        from config import (
            SPLIT_MAX_DURATION_DEFAULT,
            SPLIT_MAX_DURATION_MAX,
            SPLIT_MAX_DURATION_MIN,
            SPLIT_MAX_DURATION_STEP,
            SPLIT_MAX_VERSES_DEFAULT,
            SPLIT_MAX_VERSES_MAX,
            SPLIT_MAX_VERSES_MIN,
            SPLIT_MAX_WORDS_DEFAULT,
            SPLIT_MAX_WORDS_MAX,
            SPLIT_MAX_WORDS_MIN,
            SPLIT_MAX_WORDS_STEP,
        )
        gr.Markdown(
            "Subdivide long segments at word boundaries."
            "Sliders at max mean criterion disabled."
        )
        c.split_max_verses = gr.Slider(
            minimum=SPLIT_MAX_VERSES_MIN, maximum=SPLIT_MAX_VERSES_MAX, step=1,
            value=SPLIT_MAX_VERSES_DEFAULT,
            label=f"Max verses per segment: {SPLIT_MAX_VERSES_DEFAULT}",
            elem_id="split-max-verses",
        )
        c.split_max_words = gr.Slider(
            minimum=SPLIT_MAX_WORDS_MIN, maximum=SPLIT_MAX_WORDS_MAX,
            step=SPLIT_MAX_WORDS_STEP,
            value=SPLIT_MAX_WORDS_DEFAULT,
            label="Max words per segment: Off",
            elem_id="split-max-words",
        )
        c.split_max_duration = gr.Slider(
            minimum=SPLIT_MAX_DURATION_MIN, maximum=SPLIT_MAX_DURATION_MAX,
            step=SPLIT_MAX_DURATION_STEP,
            value=SPLIT_MAX_DURATION_DEFAULT,
            label="Max duration per segment (s): Off",
            elem_id="split-max-duration",
        )
        c.split_require_stop_sign = gr.Checkbox(
            value=False,
            label="Only split at stop signs",
            info="Segments without a waqf mark stay as-is, even if they exceed "
                 "word/duration limits. Verse splitting is unaffected.",
            elem_id="split-require-stop-sign",
        )
        c.split_btn = gr.Button("Split", variant="primary", size="lg", elem_id="split-btn")

    _placeholder = (
        ''
    )
    c.output_html = gr.HTML(
        value=f'<div style="text-align: center; color: #666; padding: 60px;">{_placeholder}</div>',
        elem_classes=["output-html"]
    )
    # Server-side state (gr.State avoids serializing the full JSON to the browser on every update)
    c.output_json = gr.State(None)