Spaces:
Running
Running
Update app.py
Browse files12345672 unmodified lines10111211121314151516171818 unmodified lines373839404041424345464445464849474849505152535455565758596061626364656667686970717273747576777879808152535455565758596061626364656667686970717273747576777879808182838485868788828384858687888990919293949590969798997 unmodified lines1071081091041101111124 unmodified lines11711811911511612012112218 unmodified lines14114214314114414514632 unmodified lines17918018118018218318412 unmodified lines19719819919920020120210 unmodified lines21321421521621621721823 unmodified lines2422432442462472452462472482492512502512521 unmodified line25425525625925726125825926026526126226826326426512 unmodified lines2782792802872812822832841 unmodified line286287288295289290291292import 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, qnfrom google import genaifrom google.genai import types
# ---------------------------------------------------------------------------# 1. BEI TRANSLITERATION SCHEMA CONFIGURATIONS# 1. BEI DEFINED SYSTEM MAPS & SCHEMAS# ---------------------------------------------------------------------------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. Speaks directly to the Gemini REST API endpoint using standard Python requests. This avoids any external library or version dependency errors entirely. """ if not api_key or len(api_key.strip()) < 10: return "transliteration", "Missing/Invalid API Key", "n ms" 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 model url = 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, constr 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". """ data = { "contents": [{"parts": [{"text": prompt}]}], "generationConfig": { "temperature": 0.1, "maxOutputTokens": 100 } } try: # Initialize the official GenAI Client with the user-provided key client = 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 injections return translation, clean_morphology(morphology) 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"Error contacting Gemini: {str(e)}", "n ms" 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): """Applies a strict right-to-left display orientation flag onto the table property tree.""" tblPr = table._tbl.tblPr bidiVisual = OxmlElement('w:bidiVisual') tblPr.append(bidiVisual)4 unmodified lines force_rtl_table(table) col_widths = [1.0] * 7 # 7.0-inch invariant structural width calculation logic loop for i, pkg in enumerate(word_packages): if pkg: total_len = len(pkg[0]) + len(pkg[1]) + len(pkg[2])18 unmodified lines 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>') # FIX: Changed broken 'd:type' attribute on the next line to exactly 'w:type' to completely eliminate runtime crashes 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 lines r.font.name = 'Arial' r.font.size = Pt(11)
# 4pt Times New Roman blank grid block spacing spacer sp = doc.add_paragraph() sp.paragraph_format.space_before = Pt(0) sp.paragraph_format.space_after = Pt(4)12 unmodified lines while len(t1_data) < 6: t1_data.append(None) # Table 1 Frame 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 lines 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; color:#000;">{content}</td>') html_elements.append('</tr></table>') # Sequential secondary block loops rem = word_packages[6:] while len(rem) > 0: chunk = rem[:7]23 unmodified lines if 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) 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() # Clean verse book title string mapping book_clean = book.replace(".", "").strip() heading_label = f"{book_clean[:3]}. {ch}:{ver}" 1 unmodified line word_packages = [] for tok in tokens: # Generate the strict BEI static transliteration pattern tl = translit_word(tok) # Fetch the live translation and root morphology context from Gemini ts, mo = process_live_ai_request(tok, api_key) word_packages.append((tok, tl, ts, mo)) # Render Output Layout HTML Canvas html_canvas = build_html_canvas(word_packages, ms_name, heading_label) # Build Document File Template Target doc = Document() t1_data = word_packages[:6] while len(t1_data) < 6: 12 unmodified lines doc.save(file_path) elapsed = time.time() - start_time status = f"Success! Processed {len(tokens)} words in {elapsed:.2f} seconds using Gemini 2.5 Flash." status = f"Success! Processed {len(tokens)} words in {elapsed:.2f} seconds." return status, html_canvas, gr.update(value=file_path, visible=True)
1 unmodified line return "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)
# ---------------------------------------------------------------------------# 5. GRADIO SPACE WORKSPACE AND LAYOUT DEFINITIONS# 5. GRADIO UI DEFINITIONS# ---------------------------------------------------------------------------bei_css = """body, .gradio-container { background-color: #F4F3EF !important; }app.py+56-62