Spaces:
Running
Running
Update app.py
Browse filesI got this old code from an older chat
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387import osimport timeimport gradio as grimport docxfrom docx import Documentfrom docx.shared import Inches, Pt, RGBColorfrom docx.enum.text import WD_ALIGN_PARAGRAPHfrom docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICALfrom docx.oxml import parse_xml, OxmlElementfrom docx.oxml.ns import nsdecls, qn# Classic secure SDK version that maps your target model beautifullyimport google.generativeai as generative_ai# ---------------------------------------------------------------------------# 1. CORE AI LINGUISTIC PIPELINE (USER API KEY PASS)# ---------------------------------------------------------------------------def process_live_ai_request(word, api_key):"""Queries the stable Gemini 1.5 Flash model utilizing the user-provided API key.Enforces the full BEI Transliteration Schema Matrix and Morphology constraints."""clean_key = api_key.strip() if api_key else ""if not clean_key:return "Missing Key", "Missing Key", "Enter valid key above"try:# Configure the legacy library dynamically with the key from the UI text boxgenerative_ai.configure(api_key=clean_key)model = generative_ai.GenerativeModel('gemini-1.5-flash')prompt_instructions = f"""You are an expert academic philologist working for Benai Emunah International (BEI) on a critical interlinear text project for the Hebrew Book of Luke.Analyze this single isolated Hebrew word token: "{word}"Generate exactly THREE lines of text in your response. Do not include any markdown formatting, bullet points, introduction, or concluding text. Just output the three raw lines.Line 1: The English transliteration based strictly on the BEI Transliteration Schema rules below.Line 2: A smooth English contextual translation. If multiple options exist, separate them with a comma and a single space (e.g., "man, human, Adam"). Do not include trailing periods.Line 3: The descriptive grammatical morphology tag focusing ONLY on the absolute semantic root word (strip away prefixes like mi- or possessive suffixes). Never include a period.---CRITICAL BEI TRANSLITERATION SCHEMA RULES:1. Syllables MUST be explicitly separated using a middle dot character (Β·) (Alt+0183). Never vary from this standard. (Example: "gaΒ·dol", "beeΒ·mey", "haΒ·yaΜ±"). Do not output simple concatenated letters or standard apostrophes.2. Apply a specialized macron-below accent ( Μ± ) instantly directly after the target stressed vowel element block.VOWEL REALIZATIONS: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 | QAMATS_QATAN: o | FURTIVE_PATAH: aCOMPOUND MATRES LECTIONIS:HIRIQ_YOD: ee | TSERE_YOD: ey | SEGOL_YOD: ey | SHUREQ: oo | HOLAM_VAV: o | QAMATS_HE: a | SEGOL_HE: eh | TSERE_HE: eCONSONANTS BASE MATRIX:ALEF: | AYIN: | HE: h | VAV: v | ZAYIN: z | HET: kh | TET: t | YOD: y | LAMED: l | MEM/FINAL_MEM: m | NUN/FINAL_NUN: n | SAMEKH: s | QOF: q | RESH: r | SHIN: sh | SIN: s | TSADI/FINAL_TSADI: tsBEGADKEPAT PAIRS:BET: v / BET_DAGESH: b | GIMEL: g / GIMEL_DAGESH: g | DALET: d / DALET_DAGESH: d | KAF/FINAL_KAF: kh / KAF_DAGESH: k | PE/FINAL_PE: f / PE_DAGESH: p | TAV: t / TAV_DAGESH: tHARDCODED CLUSTERS & EXPLICIT WORDS:Χ©ΦΌΧ -> sh | Χ¦ΦΌ -> ts | ΧΦ°Χ¨ΧΧΦΌΧ©ΦΈΧΧΦ΄Φ·Χ -> yα΅Β·rooΒ·shaΒ·laΜ±Β·yeem | ΧΧΧ -> haΒ·maΒ·sheeΜ±Β·akh | Χ§Χ§Χ§ or ΧΦ΅Χ©ΧΧΦΌΧ’Φ· -> YeyΒ·shooΜ±Β·a | ΧΦ²ΧΦΉΧ ΦΈΧ -> aΒ·doΒ·naiΜ± | Χ©Φ΄ΧΧΧΦ· -> Β·sheeΜ±Β·akh | DIVINE_NAME (YHVH) -> Yα΅Β·hoΒ·vaΜ±h | DIVINE_NAME_ELOHIM -> YeΒ·hoΒ·veeΜ±h---CRITICAL BEI MORPHOLOGY RULES:- STRICT NO-PERIOD CONSTRAINT: Abbreviation tags must absolutely never contain a period (use 'v', never write 'v.').- Token Assembly Sequence: [Part of Speech] [Binyan (Verbs Only)] [Tense/Mood/Aspect (Verbs Only)] [Concordance Block].- Part of Speech Abbreviations: v, n, adv, adj, conj, part, prep, pron, name, ddo, #, intj, constr- Binyan: Pa'al, Nif'al, Pi'el, Pu'al, Hif'il, Huf'al, Hitpa'el- Tense/Mood/Aspect: perf, imp, ptcpl- Concordance Block: Combine Person (1, 2, 3), Gender (m, f, c), and Number (s, p) without spaces (e.g., "3ms", "mp", "cp").EXAMPLES:- ΧΦΌΦΈΧΧΦΉΧ -> Line 1: gaΒ·dol | Line 2: great, large | Line 3: adj ms- ΧΦΈΧΦΈΧ -> Line 1: haΒ·yaΜ± | Line 2: (there) was | Line 3: v Pa'al perf 3ms- ΧΦ΄ΧΦΌΦ΅ΧΧͺ -> Line 1: miΒ·beyΜ±t | Line 2: from the house of | Line 3: n ms constr"""response = model.generate_content(prompt_instructions)lines = [line.strip() for line in response.text.split('\n') if line.strip()]transliteration = lines[0] if len(lines) > 0 else "error"translation = lines[1] if len(lines) > 1 else "error"morphology = lines[2] if len(lines) > 2 else "error"return transliteration, translation, morphology.replace(".", "")except Exception as e:return "Connection Error", "Gemini Query Failed", str(e)# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)# ---------------------------------------------------------------------------def force_rtl_table(table):tblPr = table._tbl.tblPrbidiVisual = OxmlElement('w:bidiVisual')tblPr.append(bidiVisual)def build_docx_table(doc, word_packages, ms_name, heading_label, is_first=False):table = doc.add_table(rows=2, cols=7)table.alignment = WD_TABLE_ALIGNMENT.CENTERforce_rtl_table(table)col_widths = [1.0] * 7for i, pkg in enumerate(word_packages):if pkg:total_len = len(pkg[0]) + len(pkg[1]) + len(pkg[2])if total_len > 22:target = i + 1 if is_first else iif target < 7:col_widths[target] += 0.3borrow = 6 if target != 6 else 5col_widths[borrow] -= 0.3for col_idx in range(7):cell_top = table.cell(0, col_idx)cell_bottom = table.cell(1, col_idx)cell_top.width = Inches(col_widths[col_idx])tcPr_top = cell_top._tc.get_or_add_tcPr()borders_top = parse_xml(f'<w:tcBorders {nsdecls("w")}><w:top w:val="single" w:sz="4" w:color="B7B7B7"/><w:left w:val="single" w:sz="4" w:color="B7B7B7"/><w:bottom w:val="single" w:sz="4" w:color="B7B7B7"/><w:right w:val="single" w:sz="4" w:color="B7B7B7"/></w:tcBorders>')# Precise cell margin constraints set down to your 0.069 inches padding benchmark layoutpadding_top = parse_xml(f'<w:tcMar {nsdecls("w")}><w:top w:w="99" w:type="dxa"/><w:left w:w="99" w:type="dxa"/><w:bottom w:w="99" w:type="dxa"/><w:right w:w="99" w:type="dxa"/></w:tcMar>')tcPr_top.append(borders_top)tcPr_top.append(padding_top)cell_bottom.width = Inches(col_widths[col_idx])tcPr_bottom = cell_bottom._tc.get_or_add_tcPr()borders_bottom = parse_xml(f'<w:tcBorders {nsdecls("w")}><w:top w:val="single" w:sz="4" w:color="B7B7B7"/><w:left w:val="single" w:sz="4" w:color="B7B7B7"/><w:bottom w:val="single" w:sz="4" w:color="B7B7B7"/><w:right w:val="single" w:sz="4" w:color="B7B7B7"/></w:tcBorders>')padding_bottom = parse_xml(f'<w:tcMar {nsdecls("w")}><w:top w:w="99" w:type="dxa"/><w:left w:w="99" w:type="dxa"/><w:bottom w:w="99" w:type="dxa"/><w:right w:w="99" w:type="dxa"/></w:tcMar>')tcPr_bottom.append(borders_bottom)tcPr_bottom.append(padding_bottom)if is_first and col_idx == 0:cell_top.text = heading_labelcell_bottom.text = ms_namep1 = cell_top.paragraphs[0]p2 = cell_bottom.paragraphs[0]p1.alignment = WD_ALIGN_PARAGRAPH.CENTERp2.alignment = WD_ALIGN_PARAGRAPH.CENTERp1.runs[0].font.name = 'Times New Roman'p1.runs[0].font.size = Pt(14)p2.runs[0].font.name = 'Arial'p2.runs[0].font.size = Pt(11)cell_top.vertical_alignment = WD_ALIGN_VERTICAL.TOPcell_bottom.vertical_alignment = WD_ALIGN_VERTICAL.TOPcontinuepkg_idx = col_idx - 1 if is_first else col_idxif pkg_idx < len(word_packages) and word_packages[pkg_idx]:heb, tl, ts, mo = word_packages[pkg_idx]cell_top.text = hebp_top = cell_top.paragraphs[0]p_top.alignment = WD_ALIGN_PARAGRAPH.RIGHTcell_top.vertical_alignment = WD_ALIGN_VERTICAL.CENTERp_top.runs[0].font.name = 'Times New Roman'p_top.runs[0].font.size = Pt(18)cell_bottom.text = f"{tl}\n{ts}\n{mo}"p_bot = cell_bottom.paragraphs[0]p_bot.alignment = WD_ALIGN_PARAGRAPH.CENTERcell_bottom.vertical_alignment = WD_ALIGN_VERTICAL.TOPfor r in p_bot.runs:r.font.name = 'Arial'r.font.size = Pt(11)sp = doc.add_paragraph()sp.paragraph_format.space_before = Pt(0)sp.paragraph_format.space_after = Pt(4)run = sp.add_run()run.font.name = 'Times New Roman'run.font.size = Pt(4)# ---------------------------------------------------------------------------# 3. SCREEN CANVAS VIEW COMPILER# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label):html_elements = []html_elements.append('<div id="bei-target-tables" style="overflow-x:auto; background-color:white; padding:15px; border-radius:4px;">')t1_data = word_packages[:6]while len(t1_data) < 6:t1_data.append(None)html_elements.append('<table dir="rtl" style="width:7in; border-collapse:collapse; margin:0 auto 4pt auto; table-layout:fixed; border:1px solid #b7b7b7;">')html_elements.append('<tr style="height:40px;">')html_elements.append(f'<td style="width:1in; border:1px solid #b7b7b7; font-family:\'Times New Roman\'; font-size:14pt; text-align:center; vertical-align:top; color:#000000; font-weight:bold;">{heading_label}</td>')for pkg in t1_data:text = pkg[0] if pkg else ""html_elements.append(f'<td style="width:1in; border:1px solid #b7b7b7; font-family:\'Times New Roman\'; font-size:18pt; text-align:right; padding:0.069in; vertical-align:middle; color:#000000;">{text}</td>')html_elements.append('</tr><tr>')html_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; vertical-align:top; color:#000000;">{ms_name}</td>')for pkg in t1_data:if pkg:content = f'<div style="line-height:1.2; font-family:\'Arial\'; font-size:11pt;"><span style="color:#000000 !important; font-weight:normal !important;">{pkg[1]}</span><br><span style="color:#000000;">{pkg[2]}</span><br><span style="color:#000000;">{pkg[3]}</span></div>'else:content = ""html_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; padding:0.069in; vertical-align:top;">{content}</td>')html_elements.append('</tr></table>')rem = word_packages[6:]while len(rem) > 0:chunk = rem[:7]while len(chunk) < 7:chunk.append(None)html_elements.append('<table dir="rtl" style="width:7in; border-collapse:collapse; margin:0 auto 4pt auto; table-layout:fixed; border:1px solid #b7b7b7;"><tr>')for pkg in chunk:text = pkg[0] if pkg else ""html_elements.append(f'<td style="width:1in; border:1px solid #b7b7b7; font-family:\'Times New Roman\'; font-size:18pt; text-align:right; padding:0.069in; vertical-align:middle; color:#000000;">{text}</td>')html_elements.append('</tr><tr>')for pkg in chunk:if pkg:content = f'<div style="line-height:1.2; font-family:\'Arial\'; font-size:11pt;"><span style="color:#000000 !important; font-weight:normal !important;">{pkg[1]}</span><br><span style="color:#000000;">{pkg[2]}</span><br><span style="color:#000000;">{pkg[3]}</span></div>'else:content = ""html_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; padding:0.069in; vertical-align:top;">{content}</td>')html_elements.append('</tr></table>')rem = rem[7:]html_elements.append('</div>')return "".join(html_elements)# ---------------------------------------------------------------------------# 4. RUNTIME WORKFLOW CONTROLLER (PACED SEQUENCE ENGINE)# ---------------------------------------------------------------------------def process_pipeline(api_key, ms_name, book, ch, ver, raw_input):if not raw_input.strip():return "System Warning: Please paste Hebrew strings to build.", "", gr.update(visible=False)if not api_key or not api_key.strip():return "System Warning: Please enter your personal Gemini API Key above.", "", gr.update(visible=False)start_time = time.time()book_clean = book.replace(".", "").strip()heading_label = f"{book_clean[:3]}. {ch}:{ver}"tokens = raw_input.strip().split()word_packages = []for tok in tokens:time.sleep(0.4)tl, ts, mo = process_live_ai_request(tok, api_key)word_packages.append((tok, tl, ts, mo))html_canvas = build_html_canvas(word_packages, ms_name, heading_label)doc = Document()t1_data = word_packages[:6]while len(t1_data) < 6:t1_data.append(None)build_docx_table(doc, t1_data, ms_name, heading_label, is_first=True)rem = word_packages[6:]while len(rem) > 0:chunk = rem[:7]while len(chunk) < 7:chunk.append(None)build_docx_table(doc, chunk, ms_name, heading_label, is_first=False)rem = rem[7:]file_path = "BEI_Interlinear_Output.docx"doc.save(file_path)elapsed = time.time() - start_timestatus = f"Success! Processed {len(tokens)} words in {elapsed:.2f} seconds."return status, html_canvas, gr.update(value=file_path, visible=True)def clear_workspace():return "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)# ---------------------------------------------------------------------------# 5. GRADIO DESIGN THEME LAYOUT PARAMETERS# ---------------------------------------------------------------------------bei_css = """body, .gradio-container { background-color: #F4F3EF !important; }.bei-banner { background-color: #1B4D3E; padding: 22px; text-align: center; border-radius: 8px; border-bottom: 4px solid #D4AF37; }.bei-banner h1 { color: #F4F3EF !important; font-size: 28px; margin: 0; font-weight: bold; }.bei-banner p { color: #D4AF37 !important; margin: 4px 0 0 0; font-size: 14px; font-weight: 500; }.action-btn { background-color: #1B4D3E !important; color: white !important; font-weight: bold !important; border-radius: 4px !important; margin: 5px 0; }.clear-btn { background-color: #718096 !important; color: white !important; font-weight: bold !important; border-radius: 4px !important; margin: 5px 0; }.copy-btn { background-color: #D4AF37 !important; color: #1B4D3E !important; font-weight: bold !important; border-radius: 4px !important; margin: 5px 0; border: 1px solid #1B4D3E !important; }.api-guide-box { background-color: #E2E8F0 !important; border-left: 5px solid #1B4D3E !important; padding: 12px; border-radius: 4px; margin-bottom: 10px; }input[type="text"], input[type="password"], textarea {background-color: #FFFFFF !important;color: #2D3748 !important;border: 1px solid #CBD5E0 !important;}.hourglass-box { text-align: center; font-size: 24px; padding: 10px; color: #1B4D3E; }"""copy_tables_js = """function() {var container = document.getElementById('bei-target-tables');if (!container) {alert('No tables found to copy! Generate an interlinear layout canvas first.');return;}window.getSelection().removeAllRanges();var range = document.createRange();range.selectNode(container);window.getSelection().addRange(range);try {document.execCommand('copy');alert('Success! Tables copied to clipboard. You can now paste directly into Google Docs.');} catch (err) {alert('Clipboard copy encountered an error.');}window.getSelection().removeAllRanges();}"""with gr.Blocks(title="Shorashim Pro Workspace") as demo:with gr.Row(elem_classes="bei-banner"):gr.Markdown("<h1>π Shorashim Pro Workspace</h1><p>BEI Interlinear Table Generator</p>")with gr.Row():with gr.Column(scale=2):# RESTORED INTERFACE: Removed boldface text markers completely so the label displays cleanly in its native dark theme colorgr.HTML('''<div class="api-guide-box"><p style="color: #2D3748 !important; font-family: Arial, sans-serif !important; font-size: 11pt !important; margin: 0 !important; padding: 0 !important; line-height: 1.4 !important;">π Gemini API Key Guide: To generate your credentials key, log into<a href="https://aistudio.google.com/" target="_blank" style="color: #1B4D3E !important; font-weight: bold !important; text-decoration: underline !important;">Google AI Studio</a>,click the "Get API Key" button, copy the token code block, and paste it below.For a complete setup walkthrough, view our<a href="https://www.youtube.com/" target="_blank" style="color: #1B4D3E !important; font-weight: bold !important; text-decoration: underline !important;">YouTube Tutorial</a>.</p></div>''')api_key = gr.Textbox(label="π Gemini API Access Key", type="password", placeholder="Paste AI Studio Key Here...")with gr.Row():ms_name = gr.Textbox(label="π Manuscript Selection Name", value="Marseilles MS-24")book = gr.Textbox(label="Book", value="Luke")with gr.Row():ch = gr.Dropdown(label="Chapter", choices=[str(i) for i in range(1, 25)], value="1")ver = gr.Dropdown(label="Verse", choices=[str(i) for i in range(1, 81)], value="5")with gr.Column(scale=2):raw_input = gr.Textbox(label="Paste Your Hebrew Here", value="ΧΦΈΧΦΈΧ ΧΦΌΦ΄ΧΧΦ΅ΧΦΎΧΧΦΉΧ¨Φ°ΧΦΌΧΦΉΧ‘ ΧΦ·ΧΦΌΦΆΧΦΆΧΦ° ΧΦΌΦΉΧΦ΅Χ ΧΦΆΧΦΈΧ ΧΦΌΧ©ΧΦ°ΧΧΦΉ ΧΦ°ΧΦ·Χ¨Φ°ΧΦΈΧΧΦΌ ΧΦ΄ΧΦΌΦ΅ΧΧͺ ΧΦΈΧΦ΄ΧΦΈΧ ΧΦ°ΧΦ΄Χ©ΧΦ°ΧͺΦΌΧΦΉ ΧΦ΄ΧΦΌΦ΅ΧΧͺ ΧΦ·ΧΦ²Χ¨ΧΦΉΧ ΧΦΌΧ©ΧΦ°ΧΦΈΧΦΌ ΧΦ΅ΧΦ΄ΧΧΦ·ΧΦΌΦ΅Χͺ", lines=7)with gr.Row():gen_btn = gr.Button("π Generate Interlinear Canvas", elem_classes="action-btn")clear_btn = gr.Button("Clear Text", elem_classes="clear-btn")copy_btn = gr.Button("Copy Tables for Google Docs", elem_classes="copy-btn")with gr.Row():with gr.Column(scale=1, visible=False) as loading_area:gr.Markdown("<div class='hourglass-box'>β³ <b>Backend Operational Threads Active... Please Wait.</b></div>")with gr.Row():with gr.Column():status_field = gr.Textbox(label="System Status Pipeline Logs", interactive=False)doc_file = gr.File(label="π₯ Download Structured Document Asset (.docx)", visible=False)with gr.Row():canvas_area = gr.HTML(label="Interlinear Render Canvas Layer Output")# Connect UI Action Listenersgen_btn.click(fn=lambda: gr.update(visible=True),inputs=None,outputs=loading_area,queue=False).then(fn=process_pipeline,inputs=[api_key, ms_name, book, ch, ver, raw_input],outputs=[status_field, canvas_area, doc_file]).then(fn=lambda: gr.update(visible=False),inputs=None,outputs=loading_area,queue=False)clear_btn.click(fn=clear_workspace,inputs=None,outputs=[raw_input, status_field, canvas_area, doc_file])copy_btn.click(fn=None, js=copy_tables_js)# Launch with CSS applied inside launch method to fully comply with Gradio 6.0 standardsif __name__ == "__main__":demo.launch(css=bei_css)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341import gradio as grfrom google import genaifrom google.genai import typesimport timeimport json# --- Shorashim Pro Ultra-Compact Horizontal Layout 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;}/* White Canvas Table Wrapper for clear document viewing */.white-canvas {display: flex;justify-content: center;align-items: center;width: 100%;}/* Forcing Shorashim Pro Charcoal Background to Total UI */.gradio-container, html, body {background-color: #0b0f19 !important;font-family: 'Segoe UI', system-ui, -apple-system, sans-serif !important;}/* Premium Gold Header Typography */.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;}/* 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 (Shorashim Emerald Teal) */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 Accent) */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 (Shorashim Pro Signature Gold) */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;}/* Fixed Table Theater Container Viewport */.theater-viewport {border: 1px solid #1f2937 !important;border-radius: 8px !important;padding: 16px !important;background-color: #0d1321 !important;margin-top: 12px !important;min-height: 45vh !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("-", "‑")def calculate_clean_chunks(words_data):chunks = []current_chunk = []word_index = 0while word_index < len(words_data):current_limit = 6 if len(chunks) == 0 else 7word = words_data[word_index]current_chunk.append(word)if len(current_chunk) == current_limit:chunks.append(current_chunk)current_chunk = []word_index += 1if current_chunk:chunks.append(current_chunk)return chunksdef build_html_tables(manuscript, reference, words_data):column_width_in = 1.0total_slots = 7total_table_width_in = 7.0table_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; ""direction: rtl; border: 1pt solid #b7b7b7; background-color: #ffffff; ""line-height: 1.0 !important; height: auto; margin-left: auto !important; margin-right: auto !important;")base_cell = "border: 1pt solid #b7b7b7; 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: 24px !important; color: #000000 !important; text-align: right !important; vertical-align: middle; {base_cell}"english_cell_style = f"font-family: Arial, sans-serif !important; font-size: 14.6667px !important; color: #000000 !important; text-align: center !important; vertical-align: top; line-height: 1.0 !important; {base_cell}"heading_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18.6667px !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)html_output.append(f'<table style="{table_style}" align="center" cellpadding="5" 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>')for idx, current_chunk in enumerate(table_chunks):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": " ", "transliteration": " ", "translation": " ", "morphology": " "})allocated_slots += 1html_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", " ")}</td>')html_output.append(' </tr>')html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">')if is_first:formatted_manuscript = manuscript.replace(" ", "<br>") if " " in manuscript else manuscripthtml_output.append(f' <td style="{heading_cell_style}">{formatted_manuscript}</td>')is_first = Falsefor word in current_chunk:if word.get("hebrew") != " " 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}"> </td>')html_output.append(' </tr>')if not is_last_table:html_output.append(f'<tr style="height: 12pt !important;"><td colspan="{total_slots}" style="border-left: none; border-right: none; border-bottom: none; height: 12pt !important; background-color: #ffffff; padding: 0 !important; margin: 0 !important;"> </td></tr>')html_output.append('</table>')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)reference_header = f"{book} {chapter}:{verse}"try:client = genai.Client(api_key=api_key)system_instruction_text = ("You are a strict linguistic conversion engine. You process Hebrew text strings and return clean, ""valid JSON lists mapping each word to its transliteration, translation, and morphology properties.")prompt = f"""Analyze this Hebrew text string word-by-word from right to left: "{text_string}"Populate a JSON dictionary matching this schema format exactly:{{"hebrew": "The exact raw Hebrew word token","transliteration": "The structured syllabic transliteration using the provided rules","translation": "The direct lowercase contextual translation","morphology": "The clean root-only structural morphology string (e.g. 'v Pa'al perf 3ms' or 'n ms suff 2ms')"}}Return a flat JSON array. Maintain words joined by maqqef (ΦΎ) as a single element."""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))raw_json_data = json.loads(response.text.strip())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 Shorashim alignment!');}).catch(err => { alert('β Clipboard Copy Failed: ' + err); });}"""with gr.Blocks(title="Shorashim Pro Interlinear Workspace") as demo: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: 20px; font-weight: 700; color: #d4af37;'>π Shorashim Pro Workspace</h1>""<p style='margin: 0; font-size: 12px; color: #9ca3af;'>Convert raw Hebrew text strings into BEI style interlinear tables</p>""</div>")with gr.Accordion("π API Key Setup Instructions", open=False):gr.Markdown("1. Visit [Google AI Studio](https://aistudio.google.com/).\n""2. Click the **Get API Key** button on the left workspace menu.\n""3. Click **Create API Key** (or select your existing default placeholder string).\n""4. Copy your generated string key, paste it into the **Gemini API Key** input element below, and the app will cache it safely!")# --- MONOLITHIC COCKPIT INPUT ROW ---with gr.Row():api_key_input = gr.Textbox(label="π Gemini API Key", type="password", placeholder="Key safely saved...", scale=2)manuscript_input = gr.Textbox(label="π Manuscript", value="Marseilles MS-24", scale=2)book_input = gr.Textbox(label="π Book", value="Luke", scale=2)with gr.Column(scale=2):with gr.Row():chapter_input = gr.Dropdown(choices=[str(x) for x in range(1, 151)], label="Ch.", value="11", allow_custom_value=True)verse_input = gr.Dropdown(choices=[str(x) for x in range(1, 177)], label="Ver.", value="49", allow_custom_value=True)text_string_input = gr.Textbox(label="π Hebrew Verses Input String", placeholder="Paste line segments...", scale=4)# --- ZERO-SCROLL CONTROL BELT 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)# --- FULL WIDTH THEATER CANVAS 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)
app.py+305-351