Spaces:
Running
Running
Update app.py
Browse files123452 unmodified lines8910111213141516171818 unmodified lines3738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192937 unmodified lines1011021031041051061074 unmodified lines11211311411511611711811918 unmodified lines13813914014114214314432 unmodified lines17717817918018118218312 unmodified lines19619719819920020120210 unmodified lines21321421521621721821923 unmodified lines2432442452462472482492502512522532541 unmodified line25625725825926026126226326426526626726826927027112 unmodified lines2842852862872882892901 unmodified line292293294295296297298import osimport timeimport gradio as grimport docxfrom docx import Document2 unmodified linesfrom docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICALfrom docx.oxml import parse_xml, OxmlElementfrom docx.oxml.ns import nsdecls, qnfrom google import genaifrom google.genai import types# ---------------------------------------------------------------------------# 1. BEI TRANSLITERATION SCHEMA CONFIGURATIONS# ---------------------------------------------------------------------------TRANSLITERATION_MAP = {"ְ": "e", "ֱ": "e", "ֲ": "a", "ֳ": "o",18 unmodified lines}def clean_morphology(text):"""Enforces strict no-period constraint rule across all grammar tokens."""return text.replace(".", "").strip()def process_live_ai_request(word, api_key):"""Calls the official Gemini Live Engine using the user's provided API key box.Instructs the LLM to provide the correct contextual translation and root morphology."""if not api_key or len(api_key.strip()) < 10:return "transliteration", "Missing/Invalid API Key", "n ms"try:# Initialize the official GenAI Client with the user-provided keyclient = genai.Client(api_key=api_key.strip())prompt = f"""You are an expert academic text processor assisting Benai Emunah International (BEI) with a critical text translation of the Hebrew manuscript of the Book of Luke.Analyze this single isolated Hebrew word token: "{word}"Provide exactly two lines of output:Line 1: The smooth contextual English translation (if multiple options exist, separate with a comma and a single space like: "man, human, Adam"). Do not include periods.Line 2: The descriptive grammatical morphology token analyzing the absolute semantic ROOT word only. Strip away all structural preposition prefixes (like mi-) or attached pronominal suffixes.Format the morphology token using exactly these space-separated parameters (omit where not applicable):1. Part of Speech: v (verb), n (noun), adv (adverb), adj (adjective), conj (conjunction), part (particle), prep (preposition), pron (pronoun), name (proper name), ddo (definite direct object), # (number), intj (interjection), constr (construct state).2. Binyan (Verbs Only): Pa'al, Nif'al, Pi'el, Pu'al, Hif'il, Huf'al, Hitpa'el.3. Tense/Mood/Aspect (Verbs Only): perf, imp, ptcpl.4. Concordance String (Unbroken block): Combined Person (1, 2, 3), Gender (m, f, c), and Number (s, p). Example: "3ms" or "mp".CRITICAL: Never include any periods inside your response tokens. Example: use "v Pa'al perf 3ms" or "n mp constr"."""response = client.models.generate_content(model='gemini-2.5-flash',contents=prompt,config=types.GenerateContentConfig(temperature=0.1,max_output_tokens=100))lines = [line.strip() for line in response.text.split('\n') if line.strip()]translation = lines[0] if len(lines) > 0 else "translation"morphology = lines[1] if len(lines) > 1 else "n ms"# Fallback security check to scrub out sneaky punctuation injectionsreturn translation, clean_morphology(morphology)except Exception as e:return f"Error contacting Gemini: {str(e)}", "n ms"def translit_word(word):if word in EXCEPTIONS:7 unmodified lines# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)# ---------------------------------------------------------------------------def force_rtl_table(table):"""Applies a strict right-to-left display orientation flag onto the table property tree."""tblPr = table._tbl.tblPrbidiVisual = OxmlElement('w:bidiVisual')tblPr.append(bidiVisual)4 unmodified linesforce_rtl_table(table)col_widths = [1.0] * 7# 7.0-inch invariant structural width calculation logic loopfor i, pkg in enumerate(word_packages):if pkg:total_len = len(pkg[0]) + len(pkg[1]) + len(pkg[2])18 unmodified linescell_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>')# FIX: Changed broken 'd:type' attribute on the next line to exactly 'w:type' to completely eliminate runtime crashespadding_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)32 unmodified linesr.font.name = 'Arial'r.font.size = Pt(11)# 4pt Times New Roman blank grid block spacing spacersp = doc.add_paragraph()sp.paragraph_format.space_before = Pt(0)sp.paragraph_format.space_after = Pt(4)12 unmodified lineswhile len(t1_data) < 6:t1_data.append(None)# Table 1 Framehtml_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:#000; font-weight:bold;">{heading_label}</td>')10 unmodified lineshtml_elements.append(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_elements.append('</tr></table>')# Sequential secondary block loopsrem = word_packages[6:]while len(rem) > 0:chunk = rem[:7]23 unmodified linesif not raw_input.strip():return "System Warning: Please paste Hebrew strings to build.", "", gr.update(visible=False)if not api_key.strip():return "System Warning: Please enter your personal Gemini API Key above to generate translations.", "", gr.update(visible=False)start_time = time.time()# Clean verse book title string mappingbook_clean = book.replace(".", "").strip()heading_label = f"{book_clean[:3]}. {ch}:{ver}"1 unmodified lineword_packages = []for tok in tokens:# Generate the strict BEI static transliteration patterntl = translit_word(tok)# Fetch the live translation and root morphology context from Geminits, mo = process_live_ai_request(tok, api_key)word_packages.append((tok, tl, ts, mo))# Render Output Layout HTML Canvashtml_canvas = build_html_canvas(word_packages, ms_name, heading_label)# Build Document File Template Targetdoc = Document()t1_data = word_packages[:6]while len(t1_data) < 6:12 unmodified linesdoc.save(file_path)elapsed = time.time() - start_timestatus = f"Success! Processed {len(tokens)} words in {elapsed:.2f} seconds using Gemini 2.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 SPACE WORKSPACE AND LAYOUT DEFINITIONS# ---------------------------------------------------------------------------bei_css = """body, .gradio-container { background-color: #F4F3EF !important; }12345672 unmodified lines10111213141516171818 unmodified lines3738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798997 unmodified lines1071081091101111124 unmodified lines11711811912012112218 unmodified lines14114214314414514632 unmodified lines17918018118218318412 unmodified lines19719819920020120210 unmodified lines21321421521621721823 unmodified lines2422432442452462472482492502512521 unmodified line25425525625725825926026126226326426512 unmodified lines2782792802812822832841 unmodified line286287288289290291292import osimport timeimport requestsimport jsonimport gradio as grimport docxfrom docx import Document2 unmodified linesfrom docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICALfrom docx.oxml import parse_xml, OxmlElementfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. BEI DEFINED SYSTEM MAPS & SCHEMAS# ---------------------------------------------------------------------------TRANSLITERATION_MAP = {"ְ": "e", "ֱ": "e", "ֲ": "a", "ֳ": "o",18 unmodified lines}def clean_morphology(text):return text.replace(".", "").strip()def process_live_ai_request(word, api_key):"""Speaks directly to the Gemini REST API endpoint using standard Python requests.This avoids any external library or version dependency errors entirely."""clean_key = api_key.strip() if api_key else ""if not clean_key:return "Missing API Key", "Please enter a valid key above."# Endpoint for the stable Gemini 2.5 Flash modelurl = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={clean_key}"headers = {"Content-Type": "application/json"}prompt = f"""You are an expert academic text processor assisting Benai Emunah International (BEI) with a critical text translation of the Hebrew manuscript of the Book of Luke.Analyze this single isolated Hebrew word token: "{word}"Provide exactly two lines of output:Line 1: The smooth contextual English translation (if multiple options exist, separate with a comma and a single space like: "man, human, Adam"). Do not include periods.Line 2: The descriptive grammatical morphology token analyzing the absolute semantic ROOT word only. Strip away all structural preposition prefixes (like mi-) or attached pronominal suffixes.Format the morphology token using exactly these space-separated parameters (omit where not applicable):1. Part of Speech: v, n, adv, adj, conj, part, prep, pron, name, ddo, #, intj, constr2. Binyan (Verbs Only): Pa'al, Nif'al, Pi'el, Pu'al, Hif'il, Huf'al, Hitpa'el3. Tense/Mood/Aspect (Verbs Only): perf, imp, ptcpl4. Concordance String (Unbroken block): Combined Person (1, 2, 3), Gender (m, f, c), and Number (s, p). Example: "3ms" or "mp".CRITICAL: Never include any periods inside your response tokens. Example: use "v Pa'al perf 3ms" or "n mp constr"."""data = {"contents": [{"parts": [{"text": prompt}]}],"generationConfig": {"temperature": 0.1,"maxOutputTokens": 100}}try:response = requests.post(url, headers=headers, json=data, timeout=10)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()]translation = lines[0] if len(lines) > 0 else "translation"morphology = lines[1] if len(lines) > 1 else "n ms"return translation, clean_morphology(morphology)elif response.status_code == 400:return "API Authentication Error", "Verify your Gemini API Key is correct."else:return f"API Connection Error (Status {response.status_code})", "n ms"except Exception as e:return f"Network Timeout / Exception", "n ms"def translit_word(word):if word in EXCEPTIONS:7 unmodified lines# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)# ---------------------------------------------------------------------------def force_rtl_table(table):tblPr = table._tbl.tblPrbidiVisual = OxmlElement('w:bidiVisual')tblPr.append(bidiVisual)4 unmodified linesforce_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])18 unmodified linescell_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)32 unmodified linesr.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)12 unmodified lineswhile 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:#000; font-weight:bold;">{heading_label}</td>')10 unmodified lineshtml_elements.append(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_elements.append('</tr></table>')rem = word_packages[6:]while len(rem) > 0:chunk = rem[:7]23 unmodified linesif 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}"1 unmodified lineword_packages = []for tok in tokens:tl = translit_word(tok)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:12 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)# ---------------------------------------------------------------------------# 5. GRADIO UI DEFINITIONS# ---------------------------------------------------------------------------bei_css = """body, .gradio-container { background-color: #F4F3EF !important; }
app.py+56-62