Spaces:
Running
Running
Update app.py
Browse files11 unmodified lines121314151617181920212223242526272829303132333435363738392 unmodified lines424344454647488 unmodified lines575859606162636465666768694 unmodified lines74757677787980811 unmodified line8384858687888990919293949596979899100101102128 unmodified lines23123223323423523623710 unmodified lines24824925025125225325425517 unmodified lines2732742752762772782791 unmodified line2812822832842852862874 unmodified lines29229329429529629729829930030130230341 unmodified lines34534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940011 unmodified linesfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. CORE API LINGUISTIC PIPELINE (WORD-BY-WORD WITH FOOLPROOF URL ROUTING)# ---------------------------------------------------------------------------def process_live_ai_request(word, api_key):"""Queries the stable Gemini 1.5 Flash model web gateway for a single word token.Feeds your complete BEI Transliteration Schema Matrix and Morphology rulesdirectly into each call for pristine, context-aware translations."""clean_key = api_key.strip() if api_key else ""if not clean_key:return "Missing Key", "Missing Key", "Enter valid key above"# FIX: Updated to the correct, fully-qualified web path to eliminate the HTTP 404 errorurl = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={clean_key}"headers = {"Content-Type": "application/json"}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 single isolated Hebrew word token: "{word}"Generate exactly THREE lines of text in your response. Do not include any markdown, introductory remarks, bullet points, or formatting. 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.2 unmodified lines---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 (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: a8 unmodified linesBET: 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:שּׁ (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] [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").4 unmodified lines- מִבֵּית -> 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": 1501 unmodified line}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"API Error ({response.status_code})", "Connection Interrupted", "error"except Exception as e:return "Connection Timeout", "Network Error", "error"# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)128 unmodified linesreturn "".join(html_elements)# ---------------------------------------------------------------------------# 5. PACED WORD-BY-WORD EXECUTION ROUTER# ---------------------------------------------------------------------------def process_pipeline(api_key, ms_name, book, ch, ver, raw_input):if not raw_input.strip():10 unmodified linesword_packages = []for tok in tokens:# Pacing step spacing out sequential web hits to completely avoid rate lockstime.sleep(0.4)tl, ts, mo = process_live_ai_request(tok, api_key)word_packages.append((tok, tl, ts, mo))17 unmodified linesdoc.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)1 unmodified linereturn "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)# ---------------------------------------------------------------------------# 6. GRADIO UI LAYOUT CONFIGURATIONS# ---------------------------------------------------------------------------bei_css = """body, .gradio-container { background-color: #F4F3EF !important; }4 unmodified lines.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; }41 unmodified lines''')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 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)if __name__ == "__main__":demo.launch()11 unmodified lines1213141516171819202122232425262728293031323334353637382 unmodified lines414243444546478 unmodified lines565758596061626364656667684 unmodified lines73747576777879808182838485868788891 unmodified line919293949596979899100101102103104105106107108109110128 unmodified lines23924024124224324424510 unmodified lines25625725825926026126226317 unmodified lines2812822832842852862871 unmodified line2892902912922932942954 unmodified lines30030130230330430530630730830931031141 unmodified lines35335435535611 unmodified linesfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. FOOLPROOF GOOGLE REST API STRUCTURE (FIXES THE 404 DATA BINDING)# ---------------------------------------------------------------------------def process_live_ai_request(word, api_key):"""Queries the official Google web gateway using the exact structurally mandatorynested JSON data parameters to fully eliminate endpoint 404 mismatches."""clean_key = api_key.strip() if api_key else ""if not clean_key:return "Missing Key", "Missing Key", "Enter valid key above"# Standard stable endpoint mapping pathurl = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={clean_key}"headers = {"Content-Type": "application/json"}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.2 unmodified lines---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: a8 unmodified linesBET: 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").4 unmodified lines- מִבֵּית -> Line 1: mi·bey̱t | Line 2: from the house of | Line 3: n ms constr"""# Mandatory Google JSON structure layout schema mapping payloadpayload = {"contents": [{"parts": [{"text": prompt_instructions}]}],"generationConfig": {"temperature": 0.1,"maxOutputTokens": 1501 unmodified line}try:response = requests.post(url, headers=headers, json=payload, timeout=15)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 "translit_error"translation = lines[1] if len(lines) > 1 else "translation_error"morphology = lines[2] if len(lines) > 2 else "morphology_error"return transliteration, translation, morphology.replace(".", "")else:return f"Error ({response.status_code})", "API Request Rejected", "Check Connection"except Exception as e:return "Timeout Error", "Network Trace Blocked", str(e)# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)128 unmodified linesreturn "".join(html_elements)# ---------------------------------------------------------------------------# 4. PACED WORD-BY-WORD RECONSTRUCTION LAYER# ---------------------------------------------------------------------------def process_pipeline(api_key, ms_name, book, ch, ver, raw_input):if not raw_input.strip():10 unmodified linesword_packages = []for tok in tokens:# Crucial sequential thread pacing buffer (0.45s) completely avoids HTTP 429 lockstime.sleep(0.45)tl, ts, mo = process_live_ai_request(tok, api_key)word_packages.append((tok, tl, ts, mo))17 unmodified linesdoc.save(file_path)elapsed = time.time() - start_timestatus = f"Success! Processed {len(tokens)} words in {elapsed:.2f} seconds across Gemini 1.5 Flash."return status, html_canvas, gr.update(value=file_path, visible=True)1 unmodified linereturn "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)# ---------------------------------------------------------------------------# 5. GRADIO UI ACCENT SYSTEM & CSS OVERRIDES# ---------------------------------------------------------------------------bei_css = """body, .gradio-container { background-color: #F4F3EF !important; }4 unmodified lines.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; }/* FIXED SPECIFICITY: Targets explicit inner container divs to break font color inheritance overrides */.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 {color: #2D3748 !important;font-family: 'Arial', sans-serif !important;font-size: 11pt !important;}.api-guide-box a { color: #1B4D3E !important; font-weight: bold !important; text-decoration: underline !important; }41 unmodified lines''')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")
app.py+35-79