File size: 42,827 Bytes
bffb1c4
 
 
 
02a4427
 
 
bffb1c4
2b7ee03
bffb1c4
aca9ecc
bffb1c4
 
 
 
 
 
 
6e14b06
bffb1c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e14b06
 
bffb1c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e14b06
bffb1c4
6e14b06
 
 
 
 
bffb1c4
 
 
 
6e14b06
 
 
 
 
 
 
 
 
 
bffb1c4
 
 
 
 
 
 
02a4427
 
 
 
 
 
 
aca9ecc
 
 
 
56ea0f6
bffb1c4
 
 
 
 
 
 
 
 
56ea0f6
aca9ecc
bffb1c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02a4427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ab413e
02a4427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bffb1c4
 
 
 
 
f9bc2fd
bffb1c4
 
 
 
 
 
 
 
 
 
bdc9211
 
f9bc2fd
 
bdc9211
7f0b888
bdc9211
 
 
 
7f0b888
bdc9211
 
 
 
 
 
 
 
 
 
 
 
ffe2afc
bdc9211
 
 
 
7f0b888
bdc9211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b7ee03
bdc9211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bffb1c4
 
0a43262
bffb1c4
 
 
 
02a4427
 
9007e08
02a4427
 
 
bffb1c4
 
9007e08
ff51fe7
 
02a4427
 
 
bffb1c4
 
 
 
 
 
9007e08
bffb1c4
 
 
 
 
 
 
 
 
 
 
02a4427
 
 
 
 
 
 
 
 
 
 
bffb1c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02a4427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bffb1c4
 
 
bdc9211
 
bffb1c4
 
 
 
02a4427
 
bffb1c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02a4427
 
 
 
 
 
 
 
 
 
 
 
 
bffb1c4
 
 
 
 
 
 
 
 
02a4427
 
 
 
 
 
 
 
 
bffb1c4
 
 
 
 
02a4427
bffb1c4
 
 
02a4427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bffb1c4
02a4427
bffb1c4
 
 
 
 
 
 
02a4427
 
 
 
 
 
 
bffb1c4
 
 
 
 
 
 
 
 
 
 
 
 
aca9ecc
 
 
56ea0f6
bffb1c4
 
 
 
 
 
 
 
 
56a7544
1d8bca3
 
 
 
 
 
 
bffb1c4
 
56ea0f6
0fd8032
56ea0f6
 
bffb1c4
 
02a4427
 
bffb1c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff51fe7
bffb1c4
7dcf695
f9bc2fd
7f0b888
67aed57
0ab413e
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
import gradio as gr
from google import genai
from google.genai import types
import json
import re
from html import escape
from urllib.parse import quote


# --- BEI Premium Theme & Horizontal Interface Custom Engine ---
custom_css = """
/* Completely hide technical loading bars & indicators */
.subpanel.loading, .generating, div[class*="loading"], .progress-wrap {
    display: none !important;
    visibility: hidden !important;
    height: 0px !important;
    overflow: hidden !important;
}

/* Polished Minimalist Progress & Processing Window */
.progress-container {
    padding: 12px;
    text-align: center;
    border: 1px solid #d4af37;
    border-radius: 6px;
    background-color: #111827;
    margin-bottom: 12px;
}

/* White Canvas Table Wrapper for clear document viewing */
.white-canvas {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
}

/* Forcing BEI Charcoal/Onyx Background to Total UI Framework */
.gradio-container, html, body {
    background-color: #0b0f19 !important;
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif !important;
}

/* Antique Gold Typography Highlights */
.gradio-container h1, .gradio-container h2, .gradio-container h3 {
    color: #d4af37 !important;
    font-weight: 600 !important;
    margin: 0px !important;
}
.gradio-container p, .gradio-container span {
    color: #9ca3af !important;
}

/* Setup Accordion Boxes for Dark Mode Layout */
.label-wrap, .accordion-trigger {
    background-color: #111827 !important;
    border: 1px solid #1f2937 !important;
}

/* Input Fields Customized with Gold Accent Focus Rings */
input, textarea, select, .dropdown {
    border-radius: 6px !important;
    border: 1px solid #1f2937 !important;
    background-color: #111827 !important;
    color: #ffffff !important;
}
input:focus, textarea:focus, select:focus {
    border-color: #d4af37 !important;
    outline: none !important;
}

/* Primary Generate Action Button (BEI Emerald Teal Accent) */
button.primary-btn {
    background: linear-gradient(135deg, #059669 0%, #10b981 100%) !important;
    border: none !important;
    border-radius: 6px !important;
    color: #ffffff !important;
    font-weight: bold !important;
    cursor: pointer;
    height: 42px !important;
}

/* Secondary Actions / Clear Button (Dark Slate Gray) */
button.secondary-btn {
    background-color: #1f2937 !important;
    border: 1px solid #374151 !important;
    border-radius: 6px !important;
    color: #e5e7eb !important;
    cursor: pointer;
    height: 42px !important;
}

/* Google Docs Copy Button (BEI Signature Antique Gold Fill) */
button.gold-copy-btn {
    background: linear-gradient(135deg, #aa820a 0%, #d4af37 100%) !important;
    border: none !important;
    border-radius: 6px !important;
    color: #0b0f19 !important;
    font-weight: 800 !important;
    font-size: 14px !important;
    cursor: pointer;
    box-shadow: 0 4px 6px -1px rgba(212, 175, 55, 0.2);
    height: 42px !important;
}

/* Extended Document Theater Container Canvas Viewport Window */
.theater-viewport {
    border: 1px solid #1f2937 !important;
    border-radius: 8px !important;
    padding: 16px !important;
    background-color: #0d1321 !important;
    margin-top: 12px !important;
    min-height: 48vh !important;
}

/* Custom Gold Spinner Arrows for Number Inputs (Maximized Size) */
.gradio-container input[type="number"]::-webkit-inner-spin-button,
.gradio-container input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none !important;
    appearance: none !important;
    display: block !important;
    opacity: 1 !important;
    visibility: visible !important;
    width: 32px !important; 
    height: 100% !important; 
    min-height: 42px !important;
    background-color: #111827 !important;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23d4af37'%3E%3Cpath d='M12 3l-8 8h16zM12 21l-8-8h16z'/%3E%3C/svg%3E") !important;
    background-size: 24px !important;
    background-repeat: no-repeat !important;
    background-position: center !important;
    cursor: pointer !important;
    border-left: 1px solid #1f2937 !important;
}

/* Allow full text but force all labels to a uniform two-line height */
.gradio-container label span {
    white-space: normal !important; 
    display: flex !important;
    align-items: flex-end !important; 
    min-height: 42px !important; 
}

/* Forces all plain <span> text inside the generated table payload to black */
#table-payload span {
    color: #000000 !important;
    -webkit-text-fill-color: #000000 !important;
    opacity: 1 !important;
}
"""

sticky_session_and_layout_js = """
function() {
    const removeHeaderBlock = () => {
        const hfHeader = document.querySelector('header');
        const spaceHeader = document.querySelector('div[class*="space-header"]');
        if (hfHeader) hfHeader.remove();
        if (spaceHeader) spaceHeader.remove();
        document.querySelectorAll('div').forEach(div => {
            if (window.getComputedStyle(div).position === 'fixed' && div.innerHTML.includes('fizzickschick')) {
                div.remove();
            }
        });
    };
    removeHeaderBlock();
    setTimeout(removeHeaderBlock, 500);
    setTimeout(removeHeaderBlock, 1500);
    setTimeout(removeHeaderBlock, 3000);

    setTimeout(() => {
        const inputSelectors = '.gradio-container input, .gradio-container textarea, .gradio-container select';
        const loadSavedValues = () => {
            document.querySelectorAll(inputSelectors).forEach((input, index) => {
                const key = 'table_gen_v6_cache_' + index;
                const savedValue = localStorage.getItem(key);
                if (savedValue && input.value !== savedValue) {
                    input.value = savedValue;
                    input.dispatchEvent(new Event('input', { bubbles: true }));
                    input.dispatchEvent(new Event('change', { bubbles: true }));
                }
            });
        };

        document.addEventListener('input', (e) => {
            document.querySelectorAll(inputSelectors).forEach((input, index) => {
                if (input === e.target) {
                    localStorage.setItem('table_gen_v6_cache_' + index, input.value);
                }
            });
        });

        document.addEventListener('change', (e) => {
            document.querySelectorAll(inputSelectors).forEach((input, index) => {
                if (input === e.target) {
                    localStorage.setItem('table_gen_v6_cache_' + index, input.value);
                }
            });
        });

        loadSavedValues();
        setTimeout(loadSavedValues, 800);
    }, 1200);
}
"""
MODEL_NAME = "gemini-3.1-flash-lite"

def clean_hyphens_for_docs(text_string):
    if not text_string:
        return ""
    return str(text_string).replace("-", "&#8209;")

def parse_gemini_json_response(response_text):
    response_text = response_text.strip()

    # Remove markdown fences if Gemini accidentally returns them.
    response_text = response_text.replace("```json", "").replace("```", "").strip()

    # Keep only the JSON array if Gemini adds extra text before or after it.
    first_bracket = response_text.find("[")
    last_bracket = response_text.rfind("]")

    if first_bracket != -1 and last_bracket != -1 and last_bracket > first_bracket:
        response_text = response_text[first_bracket:last_bracket + 1]

    # Remove illegal trailing commas before } or ].
    response_text = re.sub(r",\s*([}\]])", r"\1", response_text)

    return json.loads(response_text)

def space_hebrew_letters(root_word):
    if not root_word:
        return ""

    root_word = str(root_word).strip()

    if root_word.upper() == "NONE" or root_word == "&nbsp;":
        return root_word

    return ".".join(list(root_word))

def make_pealim_strongs_root_cell(
    strongs_number,
    hebrew_word,
    word_first_ot_ref,
    root_word,
    root_strongs_number,
    root_first_ot_ref
):
    if not strongs_number:
        return "&nbsp;"

    strongs_number = str(strongs_number).strip()
    hebrew_word = str(hebrew_word).strip()
    word_first_ot_ref = str(word_first_ot_ref).strip() if word_first_ot_ref else ""
    root_word = str(root_word).strip() if root_word else ""
    root_strongs_number = str(root_strongs_number).strip() if root_strongs_number else ""
    root_first_ot_ref = str(root_first_ot_ref).strip() if root_first_ot_ref else ""

    if not root_word or root_word.upper() == "NONE" or root_word == "&nbsp;":
        root_word = ""

    if not root_strongs_number or root_strongs_number.upper() == "NONE" or root_strongs_number == "&nbsp;":
        root_strongs_number = ""

    # Top Strong's number searches Pealim for the actual Hebrew word in this column.
    word_pealim_url = f"https://www.pealim.com/search/?q={quote(hebrew_word)}"

    # Bottom root Strong's number searches Pealim for the Hebrew root word.
    root_pealim_url = ""
    if root_word:
        root_pealim_url = f"https://www.pealim.com/search/?q={quote(root_word)}"

    if (
        strongs_number.upper() == "NONE"
        or strongs_number == "&nbsp;"
        or not hebrew_word
        or hebrew_word == "&nbsp;"
    ):
        word_strongs_display = escape(strongs_number)
    else:
        word_strongs_display = (
            f'<a href="{word_pealim_url}" '
            f'target="_blank" '
            f'rel="noopener noreferrer" '
            f'style="color: #0000EE !important; '
            f'font-family: \'Times New Roman\', serif !important; '
            f'font-size: 18px !important; '
            f'text-decoration: underline !important;">'
            f'{escape(strongs_number)}'
            f'</a>'
        )

    word_first_ref_display = make_biblegateway_kjv_link(word_first_ot_ref)

    if word_first_ref_display:
        word_first_ref_display = f"<br>{word_first_ref_display}"

    # separator_display = (
    #     f'<div style="'
    #     f'border-top: 1px solid #b7b7b7 !important; '
    #     f'height: 1px !important; '
    #     f'line-height: 1px !important; '
    #     f'margin: 3px 8px 2px 8px !important; '
    #     f'padding: 0 !important;">'
    #     f'</div>'
    # )

    if root_word:
        spaced_root = space_hebrew_letters(root_word)

        # Plain display only. The Hebrew root itself is NOT clickable.
        root_display = (
            f'<br>'
            f'<div dir="rtl" '
            f'style="font-family: \'Times New Roman\', serif !important; '
            f'font-size: 18px !important; '
            f'font-weight: normal !important; '
            f'color: #000000 !important; '
            f'-webkit-text-fill-color: #000000 !important; '
            f'opacity: 1 !important; '
            f'text-decoration: none !important; '
            f'line-height: 1.0 !important; '
            f'padding: 0 !important;">'
            f'{escape(spaced_root)}'
            f'</div>'
        )
    else:
        root_display = ""

    if root_strongs_number and root_pealim_url:
        root_strongs_display = (
            f'<br>'
            f'<a href="{root_pealim_url}" '
            f'target="_blank" '
            f'rel="noopener noreferrer" '
            f'style="color: #0000EE !important; '
            f'font-family: \'Times New Roman\', serif !important; '
            f'font-size: 18px !important; '
            f'text-decoration: underline !important;">'
            f'{escape(root_strongs_number)}'
            f'</a>'
        )
    elif root_strongs_number:
        root_strongs_display = f'<br>{escape(root_strongs_number)}'
    else:
        root_strongs_display = ""

    root_first_ref_display = make_biblegateway_kjv_link(root_first_ot_ref)

    if root_first_ref_display:
        root_first_ref_display = f"<br>{root_first_ref_display}"

    return (
        word_strongs_display
        + word_first_ref_display
        # + separator_display
        + root_display
        + root_strongs_display
        + root_first_ref_display
    )

def abbreviate_bible_reference(reference_text):
    if not reference_text:
        return ""

    reference_text = str(reference_text).strip()

    book_abbreviations = {
        "Genesis": "Gen",
        "Exodus": "Exod",
        "Leviticus": "Lev",
        "Numbers": "Num",
        "Deuteronomy": "Deut",
        "Joshua": "Josh",
        "Judges": "Judg",
        "Ruth": "Ruth",
        "1 Samuel": "1 Sam",
        "2 Samuel": "2 Sam",
        "1 Kings": "1 Kgs",
        "2 Kings": "2 Kgs",
        "1 Chronicles": "1 Chr",
        "2 Chronicles": "2 Chr",
        "Ezra": "Ezra",
        "Nehemiah": "Neh",
        "Esther": "Esth",
        "Job": "Job",
        "Psalms": "Ps",
        "Psalm": "Ps",
        "Proverbs": "Prov",
        "Ecclesiastes": "Eccl",
        "Song of Solomon": "Song",
        "Song of Songs": "Song",
        "Isaiah": "Isa",
        "Jeremiah": "Jer",
        "Lamentations": "Lam",
        "Ezekiel": "Ezek",
        "Daniel": "Dan",
        "Hosea": "Hos",
        "Joel": "Joel",
        "Amos": "Amos",
        "Obadiah": "Obad",
        "Jonah": "Jonah",
        "Micah": "Mic",
        "Nahum": "Nah",
        "Habakkuk": "Hab",
        "Zephaniah": "Zeph",
        "Haggai": "Hag",
        "Zechariah": "Zech",
        "Malachi": "Mal"
    }

    for full_book_name, abbreviated_book_name in book_abbreviations.items():
        if reference_text.startswith(full_book_name + " "):
            return reference_text.replace(full_book_name, abbreviated_book_name, 1)

    return reference_text

def make_biblegateway_kjv_link(reference_text):
    if not reference_text:
        return ""

    reference_text = str(reference_text).strip()

    if (
        not reference_text
        or reference_text.upper() == "NONE"
        or reference_text == "&nbsp;"
    ):
        return ""

    display_reference = abbreviate_bible_reference(reference_text)

    biblegateway_url = (
        f"https://www.biblegateway.com/passage/"
        f"?search={quote(reference_text)}&version=KJV"
    )

    return (
        f'<a href="{biblegateway_url}" '
        f'target="_blank" '
        f'rel="noopener noreferrer" '
        f'style="color: #0000EE !important; '
        f'font-family: \'Times New Roman\', serif !important; '
        f'font-size: 12px !important; '
        f'line-height: 1.0 !important; '
        f'text-decoration: underline !important;">'
        f'{escape(display_reference)}'
        f'</a>'
    )

def calculate_clean_chunks(words_data):
    chunks = []
    current_chunk = []
    word_index = 0
    while word_index < len(words_data):
        current_limit = 4 if len(chunks) == 0 else 5
        word = words_data[word_index]
        current_chunk.append(word)
        if len(current_chunk) == current_limit:
            chunks.append(current_chunk)
            current_chunk = []
        word_index += 1
    if current_chunk:
        chunks.append(current_chunk)
    return chunks

def build_html_tables(manuscript, reference, words_data):
    column_width_in = 1.0
    total_slots = 5
    total_table_width_in = 5.0
    
    # Table container locked to LTR flow with legacy centering for Docs - NO, WAIT! Gemini said this is why they're backwards. So I changed to RTL
    table_style = (
        f"width: {total_table_width_in}in !important; min-width: {total_table_width_in}in !important; "
        f"max-width: {total_table_width_in}in !important; table-layout: fixed !important; "
        "border-collapse: collapse !important; border-spacing: 0 !important; "
        "direction: rtl; border: 1pt solid #b7b7b7 !important; background-color: #ffffff; "
        "line-height: 1.0 !important; height: auto; "
        "margin-top: 0 !important; margin-bottom: 0 !important; "
        "margin-left: auto !important; margin-right: auto !important;"
    )
    
    base_cell = "border: 1pt solid #b7b7b7 !important; padding: 0.069in !important; height: auto; overflow: hidden; white-space: normal !important; word-wrap: break-word !important; box-sizing: border-box !important;"
    hebrew_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: right !important; vertical-align: middle; padding-top: 0.069in !important; padding-bottom: 0.069in !important; padding-left: 0.069in !important; padding-right: 0.069in !important; {base_cell}"
    english_cell_style = f"font-family: Arial, sans-serif !important; font-size: 11px !important; color: #000000 !important; text-align: center !important; vertical-align: top; line-height: 1.0 !important; {base_cell}"
    strongs_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: center !important; vertical-align: middle; line-height: 1.15 !important; {base_cell}"
    heading_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: center !important; vertical-align: middle; line-height: 1.0 !important; {base_cell}"
    
    # Outer container explicitly forces LTR alignment so Docs will center it
    html_output = ['<div id="table-payload" class="white-canvas" dir="rtl" align="center" style="background-color: #ffffff; padding: 15px; border-radius: 8px; display: block; width: 100%; box-sizing: border-box; text-align: center; direction: rtl;">']
    table_chunks = calculate_clean_chunks(words_data)
    
    for idx, current_chunk in enumerate(table_chunks):
        # Open a new table for each chunk with align="center" and dir="ltr"
        html_output.append(f'<table dir="rtl" align="center" style="{table_style}" cellpadding="0" cellspacing="0">')
        html_output.append('  <colgroup>')
        for _ in range(total_slots):
            html_output.append(f'    <col style="width: {column_width_in}in !important; min-width: {column_width_in}in !important; max-width: {column_width_in}in !important;">')
        html_output.append('  </colgroup>')
        
        is_first = (idx == 0)
        is_last_table = (idx == len(table_chunks) - 1)
        allocated_slots = len(current_chunk) + (1 if is_first else 0)
        
        if is_last_table:
            while allocated_slots < total_slots:
                current_chunk.append({
                    "hebrew": "&nbsp;", 
                    "transliteration": "&nbsp;", 
                    "translation": "&nbsp;", 
                    "morphology": "&nbsp;",
                    "strongs": "&nbsp;",
                    "word_first_ot_ref": "&nbsp;",
                    "root": "&nbsp;",
                    "root_strongs": "&nbsp;",
                    "root_first_ot_ref": "&nbsp;"
                })
                allocated_slots += 1
        
        # --- ROW 1: Hebrew Word Units (Right-Justified within their cells) ---
        html_output.append('  <tr style="height: auto; line-height: 1.0 !important;">')
        if is_first:
            html_output.append(f'    <td style="{heading_cell_style}">{reference}</td>')
        for word in current_chunk:
            html_output.append(f'    <td dir="rtl" style="{hebrew_cell_style}">{word.get("hebrew", "&nbsp;")}</td>')
        html_output.append('  </tr>')
        
        # --- ROW 2: Centered English Multi-Line Stacks ---
        html_output.append('  <tr style="height: auto; line-height: 1.0 !important;">')
        if is_first:
            formatted_manuscript = manuscript.replace(" ", "<br>") if " " in manuscript else manuscript
            html_output.append(f'    <td style="{heading_cell_style}">{formatted_manuscript}</td>')
            is_first = False 
        
        for word in current_chunk:
            if word.get("hebrew") != "&nbsp;" and word.get("hebrew") != " ":
                t_lit = clean_hyphens_for_docs(word.get("transliteration", ""))
                t_lat = clean_hyphens_for_docs(word.get("translation", ""))
                morph = clean_hyphens_for_docs(word.get("morphology", ""))
                
                content = f'{t_lit}<br>{t_lat}<br>{morph}'
                html_output.append(f'    <td class="english-cell" dir="ltr" style="{english_cell_style}">{content}</td>')
            else:
                html_output.append(f'    <td dir="ltr" style="{english_cell_style}">&nbsp;</td>')
        html_output.append('  </tr>')

        # --- ROW 3: Strong\'s Concordance Number Links ---
        html_output.append('  <tr style="height: auto; line-height: 1.0 !important;">')

        if idx == 0:
            html_output.append(f'    <td style="{strongs_cell_style}">&nbsp;</td>')

        for word in current_chunk:
            hebrew_word = word.get("hebrew", "&nbsp;")

            if hebrew_word != "&nbsp;" and hebrew_word != " ":
                strongs_number = word.get("strongs", "NONE")
                word_first_ot_ref = word.get("word_first_ot_ref", "NONE")
                root_word = word.get("root", "NONE")
                root_strongs_number = word.get("root_strongs", "NONE")
                root_first_ot_ref = word.get("root_first_ot_ref", "NONE")

                strongs_root_cell = make_pealim_strongs_root_cell(
                    strongs_number,
                    hebrew_word,
                    word_first_ot_ref,
                    root_word,
                    root_strongs_number,
                    root_first_ot_ref
                )

                html_output.append(f'    <td dir="ltr" style="{strongs_cell_style}">{strongs_root_cell}</td>')
            else:
                html_output.append(f'    <td dir="ltr" style="{strongs_cell_style}">&nbsp;</td>')

        html_output.append('  </tr>')

        # Close the table for this chunk and inject a small spacer
        html_output.append(
            "</table>"
            "<div style=\"font-family: 'Times New Roman', serif !important; "
            "font-size: 4pt !important; "
            "line-height: 4pt !important; "
            "height: 4pt !important; "
            "margin: 0 !important; "
            "padding: 0 !important; "
            "background-color: #ffffff !important;\">&nbsp;</div>"
        )
    html_output.append('</div>')
    return "".join(html_output)


"""
def build_html_tables(manuscript, reference, words_data):
    column_width_in = 1.0
    total_slots = 7
    total_table_width_in = 7.0
    
    table_style = (
        f"width: {total_table_width_in}in !important; min-width: {total_table_width_in}in !important; "
        f"max-width: {total_table_width_in}in !important; table-layout: fixed !important; "
        "border-collapse: collapse !important; border-spacing: 0 !important; "
        "direction: rtl; border: 1pt solid #b7b7b7 !important; background-color: #ffffff; "
        "line-height: 1.0 !important; height: auto; "
        "margin-top: 0 !important; margin-bottom: 0 !important; "
        "margin-left: auto !important; margin-right: auto !important;"
    )
    
    base_cell = "border: 1pt solid #b7b7b7 !important; padding: 0.069in !important; height: auto; overflow: hidden; white-space: normal !important; word-wrap: break-word !important; box-sizing: border-box !important;"
    # hebrew_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: right !important; vertical-align: middle; padding-right: 0.069in !important;{base_cell}"
    hebrew_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: right !important; vertical-align: middle; padding-top: 0.069in !important; padding-bottom: 0.069in !important; padding-left: 0.069in !important; padding-right: 0.069in !important; {base_cell}"
    english_cell_style = f"font-family: Arial, sans-serif !important; font-size: 11px !important; color: #000000 !important; text-align: center !important; vertical-align: top; line-height: 1.0 !important; {base_cell}"
    strongs_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: center !important; vertical-align: middle; line-height: 1.15 !important; {base_cell}"
    heading_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: center !important; vertical-align: middle; line-height: 1.0 !important; {base_cell}"
    
    html_output = ['<div id="table-payload" class="white-canvas" style="background-color: #ffffff; padding: 15px; border-radius: 8px; display: inline-block; width: 100%; box-sizing: border-box; text-align: center;">']
    table_chunks = calculate_clean_chunks(words_data)
    
    for idx, current_chunk in enumerate(table_chunks):
        # Open a new table for each chunk
        html_output.append(f'<table style="{table_style}" padding: 0.069in;" align="center" cellpadding="0" cellspacing="0">')
        html_output.append('  <colgroup>')
        for _ in range(total_slots):
            html_output.append(f'    <col style="width: {column_width_in}in !important; min-width: {column_width_in}in !important; max-width: {column_width_in}in !important;">')
        html_output.append('  </colgroup>')
        
        is_first = (idx == 0)
        is_last_table = (idx == len(table_chunks) - 1)
        allocated_slots = len(current_chunk) + (1 if is_first else 0)
        
        if is_last_table:
            while allocated_slots < total_slots:
                current_chunk.append({
                    "hebrew": "&nbsp;", 
                    "transliteration": "&nbsp;", 
                    "translation": "&nbsp;", 
                    "morphology": "&nbsp;",
                    "strongs": "&nbsp;",
                    "word_first_ot_ref": "&nbsp;",
                    "root": "&nbsp;",
                    "root_strongs": "&nbsp;",
                    "root_first_ot_ref": "&nbsp;"
                })
                allocated_slots += 1
        
        # --- ROW 1: Right-Justified Hebrew Word Units ---
        html_output.append('  <tr style="height: auto; line-height: 1.0 !important;">')
        if is_first:
            html_output.append(f'    <td style="{heading_cell_style}">{reference}</td>')
        for word in current_chunk:
            html_output.append(f'    <td style="{hebrew_cell_style}">{word.get("hebrew", "&nbsp;")}</td>')
        html_output.append('  </tr>')
        
        # --- ROW 2: Centered English Multi-Line Stacks ---
        html_output.append('  <tr style="height: auto; line-height: 1.0 !important;">')
        if is_first:
            formatted_manuscript = manuscript.replace(" ", "<br>") if " " in manuscript else manuscript
            html_output.append(f'    <td style="{heading_cell_style}">{formatted_manuscript}</td>')
            is_first = False 
        
        for word in current_chunk:
            if word.get("hebrew") != "&nbsp;" and word.get("hebrew") != " ":
                t_lit = clean_hyphens_for_docs(word.get("transliteration", ""))
                t_lat = clean_hyphens_for_docs(word.get("translation", ""))
                morph = clean_hyphens_for_docs(word.get("morphology", ""))
                
                content = f'{t_lit}<br>{t_lat}<br>{morph}'
                html_output.append(f'    <td class="english-cell" style="{english_cell_style}">{content}</td>')
            else:
                html_output.append(f'    <td style="{english_cell_style}">&nbsp;</td>')
        html_output.append('  </tr>')

        # --- ROW 3: Strong's Concordance Number Links ---
        html_output.append('  <tr style="height: auto; line-height: 1.0 !important;">')

        if idx == 0:
            html_output.append(f'    <td style="{strongs_cell_style}"></td>')
            # html_output.append(
            #     f'    <td style="{strongs_cell_style}">'
            #     f'# Strong&rsquo;s<br>'
            #     f'1st Use<br>'
            #     f'<div style="border-top: 1px solid #b7b7b7; margin: 3px 8px 2px 8px;"></div>'
            #     f'Root Word<br>'
            #     f'# Root Strong&rsquo;s<br>'
            #     f'Root 1st Use'
            #     f'</td>'
            # )

        for word in current_chunk:
            hebrew_word = word.get("hebrew", "&nbsp;")

            if hebrew_word != "&nbsp;" and hebrew_word != " ":
                strongs_number = word.get("strongs", "NONE")
                word_first_ot_ref = word.get("word_first_ot_ref", "NONE")
                root_word = word.get("root", "NONE")
                root_strongs_number = word.get("root_strongs", "NONE")
                root_first_ot_ref = word.get("root_first_ot_ref", "NONE")

                strongs_root_cell = make_pealim_strongs_root_cell(
                    strongs_number,
                    hebrew_word,
                    word_first_ot_ref,
                    root_word,
                    root_strongs_number,
                    root_first_ot_ref
                )

                html_output.append(f'    <td style="{strongs_cell_style}">{strongs_root_cell}</td>')
            else:
                html_output.append(f'    <td style="{strongs_cell_style}">&nbsp;</td>')

        html_output.append('  </tr>')

        # Close the table for this chunk and inject only a small one line 4px spacer...DJM
        html_output.append(
        "</table>"
        "<div style=\"font-family: 'Times New Roman', serif !important; "
        "font-size: 4pt !important; "
        "line-height: 4pt !important; "
        "height: 4pt !important; "
        "margin: 0 !important; "
        "padding: 0 !important; "
        "background-color: #ffffff !important;\">&nbsp;</div>"
    )
    html_output.append('</div>')
    return "".join(html_output)

"""

def generate_table_code(api_key, manuscript_name, book, chapter, verse, text_string):
    if not api_key:
        return "<p style='color:red; text-align:center;'>❌ Error: Please enter your Gemini API key.</p>", gr.update(visible=False)

    chapter = max(1, int(chapter))
    verse = max(1, int(verse))
    reference_header = f"{book} {chapter}:{verse}"
    
    try:
        client = genai.Client(api_key=api_key)
        system_instruction_text = (
            "You are a strict linguistic conversion engine mapping raw Hebrew text into clean JSON lists. "
            "You map words from right to left into transliteration, translation, and morphology components "
            "matching your specific instructions. Return no conversation or markdown code block markers."
        )

        prompt = f"""
        Analyze this Hebrew text string word-by-word from right to left: "{text_string}"
        
        Populate a flat JSON array containing objects matching this schema format exactly:
        {{
            {{
                {{
                    "hebrew": "The exact raw Hebrew word token from the input text",
                    "transliteration": "The syllabic transliteration strictly following the provided rules",
                    "translation": "The direct lowercase contextual translation",
                    "morphology": "The clean root-only structural morphology format string",
                    "strongs": "The best matching Hebrew Strong's Concordance number for the actual Hebrew word or lexical term used in this column, formatted like H7225, or NONE if no reliable Strong's number applies",
                    "word_first_ot_ref": "The first Old Testament reference where this actual Hebrew word or lexical term appears, formatted like Genesis 1:1, or NONE if uncertain",
                    "root": "The Hebrew root word behind the actual Hebrew word, written in Hebrew consonants only with no vowel points, no spaces, no hyphens, and no explanations",
                    "root_strongs": "The best matching Hebrew Strong's Concordance number for the Hebrew root word, formatted like H7218, or NONE if no reliable root Strong's number applies",
                    "root_first_ot_ref": "The first Old Testament reference where this Hebrew root word appears, formatted like Genesis 2:10, or NONE if uncertain"
                }}
            }}
        }}
        
        STRICT BEI TRANSLITERATION MAPPING TABLES:
        - VOCAL_SHEVA: "ᵉ", HATAF_SEGOL: "e", HATAF_PATAH: "a", HATAF_QAMATS: "o", HIRIQ: "i", TSERE: "ey", SEGOL: "e", PATAH: "a", QAMATS: "a", HOLAM: "o", QUBUTS: "oo", MAQAF: "-", PASEQ: "׀", SOF_PASUQ: "."
        - HIRIQ_YOD: "ee", TSERE_YOD: "ey", SEGOL_YOD: "ey", SHUREQ: "oo", HOLAM_VAV: "o", QAMATS_HE: "a", SEGOL_HE: "eh", TSERE_HE: "e", MS_SUFX: "av"
        - ALEF: "", BET: "v", BET_DAGESH: "b", GIMEL: "g", DALET: "d", HE: "h", VAV: "v", ZAYIN: "z", HET: "kh", TET: "t", YOD: "y", KAF: "kh", KAF_DAGESH: "k", FINAL_KAF: "kh", LAMED: "l", MEM: "m", FINAL_MEM: "m", NUN: "n", FINAL_NUN: "n", SAMEKH: "s", AYIN: "", PE: "f", PE_DAGESH: "p", FINAL_PE: "f", TSADI: "ts", FINAL_TSADI: "ts", QOF: "q", RESH: "r", SHIN: "sh", SIN: "s", TAV: "t"
        - SPECIAL CLUSTERS: שּׁ = "sh", צּ = "ts", יְרוּשָׁלִַם = "yᵉ·roo·sha·la̱·yeem", יֵשׁוּעַ = "Yey·shoo̱·a"
        - DIVINE_NAME: "Yᵉ·ho·va̱h", DIVINE_NAME_ELOHIM: "Ye·ho·vee̱h"
        
        CRITICAL JSON OUTPUT RULES:
        - Return ONLY one valid JSON array.
        - Do not return markdown.
        - Do not return explanations.
        - Do not wrap the JSON in ```json fences.
        - Do not put trailing commas after the final field in any object.
        - Do not put trailing commas after the final object in the array.
        - Every object must contain exactly these fields: hebrew, transliteration, translation, morphology, strongs, word_first_ot_ref, root, root_strongs, root_first_ot_ref.

        CRITICAL SYLLABLE SEPARATOR RULE:
        - You MUST use the middle dot symbol (·, ALT+0183) exclusively to separate syllables in the transliteration field (e.g., "ga·dol", "mi·bey̱t", "ha·me·le̱kh"). Never vary from this separator mark.
        
        CRITICAL ROOT-ONLY MORPHOLOGY LOGIC:
        - Report ONLY on the core 'root' properties of a word unit. Strip out all prefix or suffix clutter from the morphology description (e.g. for 'mi'beyt', evaluate only 'house' -> 'nms constr').
        - Abbreviations: verb=v, noun=n, adverb=adv, adjective=adj, conjunction=conj, particle=part, preposition=prep, pronoun=pron, proper name=name, definite direct object=ddom, number=#, interjection=intj, construct=constr. Do not include periods.
        - Binyan forms: Pa'al, Nif'al, Pi'el, Pu'al, Hif'il, Huf'al, Hitpa'el. Never use "Qal".
        - Tense forms: perfect=perf, imperfect=imp, participle=ptcpl.
        - Structure formatting: part_of_speech + space + binyan (if app) + space + tense (if app) + person/gender/number combo (no inner spacing, e.g., '3ms', '2mp'). Example: "v Pa'al perf 3ms" or "n mp constr".

        CRITICAL STRONG'S CONCORDANCE LOGIC:
        - Add a "strongs" field to every JSON object.
        - The "strongs" field must identify the best matching Hebrew Strong's Concordance number for the actual Hebrew word/term in the column.
        - Do NOT automatically use the root Strong's number for the "strongs" field.
        - The "strongs" field should represent the lexical term being translated in that column, including derived nouns, names, particles, verbs, adjectives, or other Hebrew dictionary terms.
        - Example: רֵאשִׁית should use strongs H7225 because the word/term means beginning.
        - Example: the root behind רֵאשִׁית is ראש, and that root should use root_strongs H7218.
        - Example: for a simple verb like אמר, the word Strong's number and root Strong's number may both be H559. That is acceptable only when they truly match.
        - Format Hebrew Strong's numbers as H followed by digits, such as H7225.
        - If no reliable Strong's number applies, return "NONE".
        - Do not guess wildly. Prefer "NONE" when uncertain.

        CRITICAL HEBREW ROOT WORD LOGIC:
        - Add a "root" field to every JSON object.
        - The "root" field must contain the Hebrew root behind the actual Hebrew word in that column.
        - Return the root in Hebrew consonants only.
        - Do not include vowel points, cantillation marks, spaces, hyphens, transliteration, English, labels, or explanatory notes.
        - For verbs, prefer the shoresh/root, usually three Hebrew consonants when applicable.
        - For derived nouns, identify the underlying Hebrew root, not merely the same noun repeated.
        - Example: for רֵאשִׁית, return root ראש.
        - Example: for ברא, return root ברא.
        - If no reliable Hebrew root applies, return "NONE".

       CRITICAL ROOT STRONG'S CONCORDANCE LOGIC:
        - Add a "root_strongs" field to every JSON object.
        - The "root_strongs" field must identify the best matching Hebrew Strong's Concordance number for the Hebrew root word in the "root" field.
        - Do NOT simply copy the "strongs" field unless the word Strong's number and root Strong's number are truly the same.
        - Example: רֵאשִׁית should use strongs H7225, root ראש, and root_strongs H7218.
        - Example: ברא may use strongs H1254, root ברא, and root_strongs H1254 because the word and root are the same lexical item.
        - Format Hebrew Strong's numbers as H followed by digits, such as H7218.
        - If no reliable root Strong's number applies, return "NONE".
        - Do not guess wildly. Prefer "NONE" when uncertain.

        CRITICAL FIRST OLD TESTAMENT OCCURRENCE LOGIC:
        - Add a "word_first_ot_ref" field to every JSON object.
        - Add a "root_first_ot_ref" field to every JSON object.
        - "word_first_ot_ref" must identify the first Old Testament / Hebrew Bible location where the actual Hebrew word or lexical term appears.
        - "root_first_ot_ref" must identify the first Old Testament / Hebrew Bible location where the Hebrew root word appears.
        - Use KJV book names and reference formatting, such as Genesis 1:1, Exodus 3:14, Deuteronomy 6:4.
        - Do not include the verse text.
        - Do not include Hebrew text in these reference fields.
        - If you are uncertain, return "NONE".
        - Do not simply copy "word_first_ot_ref" into "root_first_ot_ref" unless they are truly the same first occurrence.
        """

        response = client.models.generate_content(
            model=MODEL_NAME, contents=prompt,
            config=types.GenerateContentConfig(
                system_instruction=system_instruction_text,
                response_mime_type="application/json", candidate_count=1
            )
        )
        # response_text = response.text.strip()
        # print("RAW GEMINI RESPONSE:")
        # print(response_text)

        # raw_json_data = json.loads(response_text)
        raw_json_data = parse_gemini_json_response(response.text)

        final_table_html = build_html_tables(manuscript_name, reference_header, raw_json_data)
        return final_table_html, gr.update(visible=True)
    except Exception as e:
        return f"<p style='color:red; text-align:center;'>❌ Error: {str(e)}</p>", gr.update(visible=False)

copy_btn_js = """
function() {
    const payload = document.getElementById('table-payload').innerHTML;
    const blob = new Blob([payload], { type: 'text/html' });
    const data = [new ClipboardItem({ 'text/html': blob })];
    navigator.clipboard.write(data).then(() => {
        alert('📋 Tables successfully copied to clipboard with exact BEI padding alignment!');
    }).catch(err => { alert('❌ Clipboard Copy Failed: ' + err); });
}
"""

with gr.Blocks(title="Shorashim Pro Workspace") as demo:
    # Header Panel [Marker 1]
    gr.HTML(
        "<div style='background: linear-gradient(135deg, #111827 0%, #0b0f19 100%); padding: 10px; border-radius: 6px; margin-bottom: 10px; text-align: center; border: 1px solid #d4af37;'>"
        "<h1 style='margin: 0 0 2px 0; font-size: 30px; font-weight: 700; color: #d4af37;'>📖 Shorashim Pro Workspace</h1>"
        "<p style='margin: 0; font-size: 14px; color: #9ca3af;'>Convert raw Hebrew text strings into BEI style interlinear tables</p>"
        "</div>"
    )
    
    # API Verification Guideline Box 
    with gr.Accordion("🔑 API Key Setup Instructions", open=True):
        gr.Markdown(
            "1. Visit [Google AI Studio](https://aistudio.google.com/).\n\n"
            "2. Click the **Get API Key** button on the left menu.\n\n"
            "3. Click **Create API Key** (or use your default layout string).\n\n"
            "4. Copy your string token and paste it into the input box below. "
            "Click <a href='https://youtu.be/Uyn-P2nRvDA?si=LQi2U0tLsY-zE7a9' target='_blank' style='color: #d4af37; font-weight: bold; text-decoration: underline;'>here</a> to view a short how-to video."
        )
        
    # --- HORIZONTAL COCKPIT INPUT ROW ---
    with gr.Row():
        api_key_input = gr.Textbox(label="🔑 Gemini API Key", type="password", placeholder="Paste your Gemini API key here", scale=2)
        manuscript_input = gr.Textbox(label="📜 Manuscript Reference", value="Marseilles MS-24", scale=2)
        book_input = gr.Textbox(label="📚 Bible Book", value="Luke", scale=2)
        
        # Chapter and Verse as Number inputs for spinner functionality
        chapter_input = gr.Number(label="Chapter", value=11, minimum=1, step=1, precision=0, scale=1)
        verse_input = gr.Number(label="Verse", value=49, minimum=1, step=1, precision=0, scale=1)
        
        text_string_input = gr.Textbox(label="📝 Hebrew Verses Input String", placeholder="Paste line segments...", scale=4)

    # --- CONTROL PLATFORM HUB ---
    with gr.Row():
        submit_btn = gr.Button("🚀 Generate Canvas", elem_classes=["primary-btn"], scale=3)
        clear_btn = gr.Button("🧹 Clear Input", elem_classes=["secondary-btn"], scale=2)
        copy_btn = gr.Button("📋 Copy for Google Docs", elem_classes=["gold-copy-btn"], visible=False, scale=5)

    # --- PREVIEW VIEWPORT ---
    with gr.Column(elem_classes=["theater-viewport"]):
        output_html = gr.HTML(label="Shorashim Frame Canvas")

    demo.load(fn=None, inputs=None, outputs=None, js=sticky_session_and_layout_js)

    submit_btn.click(
        fn=generate_table_code, 
        inputs=[api_key_input, manuscript_input, book_input, chapter_input, verse_input, text_string_input], 
        outputs=[output_html, copy_btn],
        show_progress="hidden"
    )
    clear_btn.click(fn=None, inputs=[], outputs=[text_string_input], js="() => ''")
    copy_btn.click(fn=None, js=copy_btn_js)
    

demo.queue().launch(server_name="0.0.0.0", server_port=7860, css=custom_css)