Spaces:
Running
Running
Update app.py
Browse files8 unmodified lines9101112121314151617171819202122212223242526262728292930313233333435353637373839404139404142434445464546474849484950515251525354555455565758575859606160616263646566676869706566676869707172737475737475767778787980817 unmodified lines89909192929394969596979826 unmodified lines12512612712812913013162 unmodified lines1941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973981978 unmodified linesfrom docx.oxml import parse_xml, OxmlElementfrom docx.oxml.ns import nsdecls, qn
# Import the official Google GenAI package components# Use the official Google GenAI library that worked for you originallyfrom google import genaifrom google.genai import types
# ---------------------------------------------------------------------------# 1. CORE API LINGUISTIC PIPELINE (VIA STABLE SDK ROUTING)# 1. LIVE LINGUISTIC PIPELINE (RESTORED EXACTLY TO WORKING SDK PATH)# ---------------------------------------------------------------------------def process_live_ai_request(word, api_key): """ Queries the stable Gemini 1.5 Flash model utilizing the official SDK client library. This utilizes the correct structural mapping keywords to wipe away 404 errors. Queries the official Gemini 1.5 Flash model (3.1 Flash) using the standard SDK client method that successfully generated your tables last week. """ clean_key = api_key.strip() if api_key else "" if not clean_key: return "Missing Key", "Missing Key", "Enter valid key above" return "Missing Key", "Missing Key", "Enter valid key" try: # Initialize the official client wrapper securely # Initialize the standard SDK client wrapper client = genai.Client(api_key=clean_key) 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[cite: 2, 4]. 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}" [cite: 44, 71] Analyze this single isolated Hebrew word token: "{word}" Generate exactly THREE lines of text in your response[cite: 84]. Do not include any markdown formatting, bullet points, introduction, or concluding text. Just output the three raw lines. 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[cite: 85]. 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")[cite: 78, 80, 86]. Do not include trailing periods[cite: 77]. Line 3: The descriptive grammatical morphology tag focusing ONLY on the absolute semantic root word (strip away prefixes like mi- or possessive suffixes)[cite: 87, 102, 103]. Never include a period[cite: 77, 168]. 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)[cite: 14, 135]. Never vary from this standard[cite: 136]. (Example: "ga·dol", "bee·mey", "ha·ya̱"). Do not output simple concatenated letters or standard apostrophes[cite: 14, 136]. 2. Apply a specialized macron-below accent ( ̱ ) instantly directly after the target stressed vowel element block[cite: 145]. 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[cite: 39, 137]: VOCAL_SHEVA: ᵉ [cite: 39, 138] | HATAF_SEGOL: e [cite: 39, 138] | HATAF_PATAH: a [cite: 39, 138] | HATAF_QAMATS: o [cite: 39, 138] | HIRIQ: i [cite: 39, 139] | TSERE: ey [cite: 39, 140] | SEGOL: e [cite: 39, 139] | PATAH: a [cite: 39, 139] | QAMATS: a [cite: 39, 140] | HOLAM: o [cite: 39, 140] | QUBUTS: oo [cite: 39, 140] | QAMATS_QATAN: o [cite: 39, 139] | FURTIVE_PATAH: a [cite: 39, 143] 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: a COMPOUND MATRES LECTIONIS[cite: 39, 140]: HIRIQ_YOD: ee [cite: 39, 142] | TSERE_YOD: ey [cite: 39, 142] | SEGOL_YOD: ey [cite: 39, 142] | SHUREQ: oo [cite: 39, 140] | HOLAM_VAV: o [cite: 39, 141] | QAMATS_HE: a [cite: 39, 142] | SEGOL_HE: eh [cite: 39, 142] | TSERE_HE: e [cite: 39, 143] COMPOUND MATRES LECTIONIS: HIRIQ_YOD: ee | TSERE_YOD: ey | SEGOL_YOD: ey | SHUREQ: oo | HOLAM_VAV: o | QAMATS_HE: a | SEGOL_HE: eh | TSERE_HE: e CONSONANTS BASE MATRIX[cite: 39, 146]: ALEF: [cite: 39, 147] | AYIN: [cite: 39, 148] | HE: h [cite: 39, 147] | VAV: v [cite: 39, 147] | ZAYIN: z [cite: 39, 147] | HET: kh [cite: 39, 147] | TET: t [cite: 39, 148] | YOD: y [cite: 39, 148] | LAMED: l [cite: 39, 148] | MEM/FINAL_MEM: m [cite: 39, 148] | NUN/FINAL_NUN: n [cite: 39, 148] | SAMEKH: s [cite: 39, 148] | QOF: q [cite: 39, 149] | RESH: r [cite: 39, 149] | SHIN: sh [cite: 39, 149] | SIN: s [cite: 39, 149] | TSADI/FINAL_TSADI: ts [cite: 39] CONSONANTS 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: ts BEGADKEPAT PAIRS[cite: 39, 150]: BET: v / BET_DAGESH: b [cite: 39, 151] | GIMEL: g / GIMEL_DAGESH: g [cite: 39, 152] | DALET: d / DALET_DAGESH: d [cite: 39, 153] | KAF/FINAL_KAF: kh / KAF_DAGESH: k [cite: 39, 154] | PE/FINAL_PE: f / PE_DAGESH: p [cite: 39, 155] | TAV: t / TAV_DAGESH: t [cite: 39, 156] BEGADKEPAT 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: t HARDCODED CLUSTERS & EXPLICIT WORDS[cite: 39, 157]: שּׁ -> sh [cite: 39, 158] | צּ -> ts [cite: 39, 159] | יְרוושָׁלִַם -> yᵉ·roo·sha·la̱·yeem [cite: 39, 160] | מממ -> ha·ma·shee̱·akh [cite: 39, 161] | קקק or יֵשׁוּעַ -> Yey·shoo̱·a [cite: 39, 162] | אֲדֹנָי -> a·do·nai̱ [cite: 39, 163] | שִׁיחַ -> ·shee̱·akh [cite: 39, 164] | DIVINE_NAME (YHVH) -> Yᵉ·ho·va̱h [cite: 39, 165] | DIVINE_NAME_ELOHIM -> Ye·ho·vee̱h [cite: 39, 166] HARDCODED 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.')[cite: 77, 168]. - Token Assembly Sequence: [Part of Speech] [Binyan (Verbs Only)] [Tense/Mood/Aspect (Verbs Only)] [Concordance Block][cite: 172, 173]. - Part of Speech Abbreviations: v, n, adv, adj, conj, part, prep, pron, name, ddo, #, intj, constr[cite: 88, 174]. - Binyan: Pa'al, Nif'al, Pi'el, Pu'al, Hif'il, Huf'al, Hitpa'el[cite: 90, 175]. - Tense/Mood/Aspect: perf, imp, ptcpl[cite: 92, 176]. - Concordance Block: Combine Person (1, 2, 3), Gender (m, f, c), and Number (s, p) without spaces (e.g., "3ms", "mp", "cp")[cite: 94, 95, 96, 97, 177]. - 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 [cite: 14, 135] - הָיָה -> Line 1: ha·ya̱ | Line 2: (there) was | Line 3: v Pa'al perf 3ms [cite: 53, 98, 99, 179] - מִבֵּית -> Line 1: mi·bey̱t | Line 2: from the house of | Line 3: n ms constr [cite: 54, 100, 101, 180] - גָּדוֹל -> 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 """ # FIX: Instructing the library to look exactly for 'gemini-1.5-flash' # Call using the exact native string identifier that previously worked response = client.models.generate_content( model='gemini-1.5-flash', contents=prompt_instructions,7 unmodified lines 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", "SDK Request Failed", str(e) return "Connection Error", "SDK Call Failed", str(e)
# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)26 unmodified lines 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>') # TWEAK: Set hard clearance padding here to exactly 0.069 dxa equivalent boundaries padding_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)62 unmodified lines 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. PACED WORD-BY-WORD EXECUTION ROUTER# ---------------------------------------------------------------------------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: # Pacing step spacing out sequential web hits to completely avoid rate locks 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_time status = 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 UI LAYOUT CONFIGURATIONS# ---------------------------------------------------------------------------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; }.api-guide-box p, .api-guide-box span, .api-guide-box b, .api-guide-box strong, .api-guide-box a { color: #2D3748 !important; font-family: 'Arial', sans-serif !important; font-size: 11pt !important; margin: 0 !important;}.api-guide-box a { color: #1B4D3E !important; font-weight: bold !important; text-decoration: underline !important; }
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): gr.HTML(''' <div class="api-guide-box"> <p>🔑 <strong>Gemini API Key Guide:</strong> To generate your credentials key, log into <a href="https://aistudio.google.com/" target="_blank">Google AI Studio</a>, click the "Get API Key" button, copy the token code block, and paste it below.</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, 24)], 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 Listeners gen_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)
# FIX: CSS styling passed directly inside launch to keep Gradio 6.0 engine happyif __name__ == "__main__": demo.launch(css=bei_css) html_elements.append(f'<td style="width:1in; border:1px solid #b7b7b7; font-family:\'Times New Roman\'; font-size:18pt; text-app.py+37-238