Spaces:
Running
Running
Update app.py
Browse files3rd time reverting to old code
12345674 unmodified lines1213141315161516171819202122232425262728293031323334353637383940414243444546474849505152535455171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110263 unmodified lines1661671681251691701711729 unmodified lines1821831841411851861871441451881891901911481921931941501511521951961971981991551561572002012022031591601612042052062072082092102112122131661672142152162172181701712192202211731741752222232242252262272282291781792302312322331822342352362372382392402412422431892442452461912471932482492502512522532542552562572581992592602612622632642652052662672682692706 unmodified lines2772782792182192802812822222832842852863 unmodified lines29029129223229329429529629729829930030130230330430523630630730817 unmodified lines32632732826032933033133226533326726833433533633733833927134034134227434334427727834534634728028134834935035128535235328835435535625 unmodified lines382383384320385386387388389390327391392393import osimport timeimport requestsimport jsonimport gradio as grimport docxfrom docx import Document4 unmodified linesfrom docx.oxml.ns import nsdecls, qn
# ---------------------------------------------------------------------------# 1. BEI TRANSLITERATION SCHEMAS & DICTIONARIES# 1. CORE API ENGINE - DYNAMIC CONTEXTUAL TRANSLATION & TRANSLITERATION# ---------------------------------------------------------------------------TRANSLITERATION_MAP = { "ְ": "e", "ֱ": "e", "ֲ": "a", "ֳ": "o", "ִ": "i", "ֶ": "e", "ַ": "a", "ָ": "o", "ֵ": "ey", "ֹ": "o", "ֻ": "oo", "וּ": "oo", "וֹ": "o", "א": "", "ע": "", "ה": "h", "ו": "v", "ז": "z", "ח": "kh", "ט": "t", "י": "y", "ל": "l", "ם": "m", "מ": "m", "ן": "n", "נ": "n", "ס": "s", "ק": "q", "ר": "r", "שׁ": "sh", "שׂ": "s", "ש": "sh", "ב": "v", "בּ": "b", "ג": "g", "גּ": "g", "ד": "d", "דּ": "d", "ך": "kh", "כ": "kh", "כּ": "k", "ף": "f", "פ": "f", "פּ": "p", "ת": "t", "תּ": "t"}
EXCEPTIONS = { "שּׁ": "sh", "צּ": "ts", "יְרוּשָׁלִַם": "yᵉ·roo·sha·la̱·yeem", "מממ": "ha·ma·shee̱·akh", "קקק": "Yey·shoo̱·a", "יֵשׁוּעַ": "Yey·shoo̱·a", "אֲדֹנָי": "a·do·nai̱", "שִׁיחַ": "·shee̱·akh"}
def clean_morphology(text): return text.replace(".", "")
def translit_word(word): if word in EXCEPTIONS: return EXCEPTIONS[word] res = "".join([TRANSLITERATION_MAP.get(c, c) for c in word]) if "ga" in res and "dol" in res: return "ga·dol" return res
def call_mock_engine(word): if "הָיָה" in word: return "ha·ya̱", "(there) was", "v Pa'al past 3ms" if "בִּימֵי־" in word: return "bee·mey", "in the days of", "nmp constr" if "הוֹרְדּוֹס" in word: return "hor·do̱s", "Herod", "name" if "הַמֶּלֶךְ" in word: return "ha·me·le̱kh", "the king", "nms" if "כֹּהֵן" in word: return "ko·hey̱n", "priest", "nms" if "אֶחָד" in word: return "e·kha̱d", "a certain, one", "# m" return translit_word(word), "translation", "n ms"def process_live_ai_request(word, api_key): """ Leverages Gemini 2.5 Flash to dynamically analyze the Hebrew token, applying the exact BEI Transliteration Schema Matrix and Morphology rules. """ clean_key = api_key.strip() if api_key else "" if not clean_key: return "Missing Key", "Missing Key", "Enter valid key above" url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={clean_key}" headers = {"Content-Type": "application/json"} # Complete instruction set containing your structural schema matrices prompt = 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 isolated Hebrew word token: "{word}" Generate exactly THREE lines of text in your response. Do not include any markdown, introductory remarks, or formatting. Just output the three lines. Line 1: The English transliteration based strictly on the BEI Transliteration Schema. 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̱"). 2. Apply a specialized macron-below accent ( ̱ ) instantly directly after the target stressed vowel element block (typically the final syllable). 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: 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: 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: 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 & EXCEPTIONS: שּׁ (Shin Cluster) -> sh | צּ (Tsadi Cluster) -> 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 Abbreviation] [Binyan (Verbs Only)] [Tense/Mood/Aspect (Verbs Only)] [Concordance Block]. - Part of Speech: 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 """ data = { "contents": [{"parts": [{"text": prompt}]}], "generationConfig": { "temperature": 0.1, "maxOutputTokens": 150 } } try: response = requests.post(url, headers=headers, json=data, timeout=12) if response.status_code == 200: res_json = response.json() text_out = res_json['candidates'][0]['content']['parts'][0]['text'] lines = [line.strip() for line in text_out.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(".", "") else: return f"Error (Status {response.status_code})", "Check API Connection", "error" except Exception as e: return "Connection Error", "Network Timeout", "error"
# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)63 unmodified lines p_top.runs[0].font.name = 'Times New Roman' p_top.runs[0].font.size = Pt(18) cell_bottom.text = f"{tl}\n{ts}\n{clean_morphology(mo)}" cell_bottom.text = f"{tl}\n{ts}\n{mo}" p_bot = cell_bottom.paragraphs[0] p_bot.alignment = WD_ALIGN_PARAGRAPH.CENTER cell_bottom.vertical_alignment = WD_ALIGN_VERTICAL.TOP9 unmodified lines run.font.size = Pt(4)
# ---------------------------------------------------------------------------# 3. SCREEN CANVAS VIEW COMPILER (HTML DISPLAY WITH EXPLICIT ID FOR CLIPBOARD)# 3. SCREEN CANVAS VIEW COMPILER (HTML GRID ENGINE)# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label): # Added wrapper ID 'bei-target-tables' so the system knows exactly what to capture for copy actions html = '<div id="bei-target-tables" style="overflow-x:auto; background-color:white; padding:15px; border-radius:4px;">' 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) while len(t1_data) < 6: t1_data.append(None) html += '<table dir="rtl" style="width:7in; border-collapse:collapse; margin:0 auto 4pt auto; table-layout:fixed; border:1px solid #b7b7b7;">' html += '<tr style="height:40px;">' html += f'<td style="width:1in; border:1px solid #b7b7b7; font-family:\'Times New Roman\'; font-size:14pt; text-align:center; vertical-align:top; color:#000; font-weight:bold;">{heading_label}</td>' 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 += 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:#000;">{text}</td>' html += '</tr><tr>' html += f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; vertical-align:top; color:#000;">{ms_name}</td>' 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: content = f'<div style="line-height:1.2;">{pkg[1]}<br>{pkg[2]}<br>{clean_morphology(pkg[3])}</div>' if pkg else "" html += f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; padding:0.069in; vertical-align:top; color:#000;">{content}</td>' html += '</tr></table>' 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 += '<table dir="rtl" style="width:7in; border-collapse:collapse; margin:0 auto 4pt auto; table-layout:fixed; border:1px solid #b7b7b7;"><tr>' 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 += 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:#000;">{text}</td>' html += '</tr><tr>' 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: content = f'<div style="line-height:1.2;">{pkg[1]}<br>{pkg[2]}<br>{clean_morphology(pkg[3])}</div>' if pkg else "" html += f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; padding:0.069in; vertical-align:top; color:#000;">{content}</td>' html += '</tr></table>' 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 += '</div>' return html html_elements.append('</div>') return "".join(html_elements)
# ---------------------------------------------------------------------------# 4. RUNTIME PIPELINE CONTROLLER# 4. RUNTIME SYSTEM EXECUTION MODULE# ---------------------------------------------------------------------------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() time.sleep(1.2) book_clean = book.replace(".", "").strip() heading_label = f"{book_clean[:3]}. {ch}:{ver}" heading_label = f"{book[:3]}. {ch}:{ver}" tokens = raw_input.strip().split() word_packages = [((tok,) + call_mock_engine(tok)) for tok in tokens] word_packages = [] for tok in tokens: # Fetch the contextual transliteration, translation, and morphology simultaneously from the model instructions 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) 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) while len(chunk) < 7: chunk.append(None) build_docx_table(doc, chunk, ms_name, heading_label, is_first=False) rem = rem[7:] 6 unmodified lines return status, html_canvas, gr.update(value=file_path, visible=True)
def clear_workspace(): """Wipes out the input fields and drops generated canvas tables instantly.""" return "", "", "", gr.update(visible=False) return "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)
# ---------------------------------------------------------------------------# 5. GRADIO UI DEFINITIONS WITH INTEGRATED CLIPBOARD JS INJECTIONS# 5. GRADIO UI DESIGN LAYOUT# ---------------------------------------------------------------------------bei_css = """body, .gradio-container { background-color: #F4F3EF !important; }3 unmodified lines.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 { background-color: #E2E8F0; padding: 12px; border-radius: 6px; border-left: 4px solid #1B4D3E; font-size: 11.5pt; color: #2D3748; margin-bottom: 10px; }
.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 a { color: #1B4D3E !important; font-family: 'Arial', sans-serif !important; font-size: 11pt !important; margin: 0; }.api-guide-box a { 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; }"""
# JavaScript module function that copies formatted HTML tables directly onto your system clipboardcopy_tables_js = """function() { var container = document.getElementById('bei-target-tables');17 unmodified lines
with gr.Blocks(css=bei_css, title="Shorashim Pro Workspace") as demo: with gr.Row(elem_classes="bei-banner"): # Adjustments 1: Replaced subheading line text parameters gr.Markdown("<h1>📖 Shorashim Pro Workspace</h1><p>BEI Interlinear Table Generator</p>") with gr.Row(): with gr.Column(scale=2): # Adjustment 5: Integrated simple guide instructions block for key acquisition gr.HTML(''' <div class="api-guide"> 🔑 <b>Gemini API Key Guide:</b> To generate your credentials key, log into <a href="https://aistudio.google.com/" target="_blank" style="color:#1B4D3E; font-weight:bold; text-decoration:underline;">Google AI Studio</a>, click the "Get API Key" button, copy the token code block, and paste it below. <div class="api-guide-box"> <p>🔑 <b>Gemini API Key Guide:</b> 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="AI key token platform credentials...") 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") # Adjustments 6, 7, 8: Unified text field inputs targeting the Book selection properties book = gr.Textbox(label="Book", value="Luke") with gr.Row(): ch = gr.Dropdown(label="Chapter Target", choices=[str(i) for i in range(1, 25)], value="1") ver = gr.Dropdown(label="Verse Target", choices=[str(i) for i in range(1, 81)], value="5") 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=None) with gr.Column(scale=2): # Adjustment 2: Text parameters changed to 'Paste Your Hebrew Here' raw_input = gr.Textbox(label="Paste Your Hebrew Here", value="הָיָה בִּימֵי־הוֹרְדּוֹס הַמֶּלֶךְ כֹּהֵן אֶחָד", lines=7) raw_input = gr.Textbox(label="Paste Your Hebrew Here", placeholder="Paste raw manuscript phrase content here...", lines=7) with gr.Row(): gen_btn = gr.Button("🚀 Generate Interlinear Canvas", elem_classes="action-btn") # Adjustment 3: Clean reset trigger button action clear_btn = gr.Button("Clear Text", elem_classes="clear-btn") # Adjustment 4: Live Clipboard copy button component added copy_btn = gr.Button("Copy Tables for Google Docs", elem_classes="copy-btn") with gr.Row():25 unmodified lines queue=False )
# Clean reset action pipeline callback linkage clear_btn.click( fn=clear_workspace, inputs=None, outputs=[raw_input, status_field, canvas_area, doc_file] )
# Clipboard browser execution routing linkage copy_btn.click(fn=None, js=copy_tables_js)
if __name__ == "__main__":app.py+153-90