Spaces:
Running
Running
Update app.py
Browse files11 unmodified lines12131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172734 unmodified lines7879808182834 unmodified lines88899091929394959697989910010110210310410510610710810911076 unmodified lines18718818919019119219313 unmodified lines20720820921021121221311 unmodified lines2252262272282292302314 unmodified lines23623723823924024124211 unmodified lines25425525625725825926017 unmodified lines2782792802812822832841 unmodified line28628728828929029129211 unmodified linesfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. BEI DEFINED SYSTEM MAPS & SCHEMAS# ---------------------------------------------------------------------------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(".", "").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 = {4 unmodified lines}}try:response = requests.post(url, headers=headers, json=data, timeout=10)if response.status_code == 200:4 unmodified linestranslation = 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: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# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)# ---------------------------------------------------------------------------def force_rtl_table(table):tblPr = table._tbl.tblPr76 unmodified linesrun.font.size = Pt(4)# ---------------------------------------------------------------------------# 3. SCREEN CANVAS VIEW COMPILER (HTML DISPLAY ENGINE)# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label):html_elements = []13 unmodified lineshtml_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; vertical-align:top; color:#000;">{ms_name}</td>')for pkg in t1_data:if pkg:content = f'<div style="line-height:1.2;">{pkg[1]}<br>{pkg[2]}<br>{pkg[3]}</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; color:#000;">{content}</td>')11 unmodified lineshtml_elements.append('</tr><tr>')for pkg in chunk:if pkg:content = f'<div style="line-height:1.2;">{pkg[1]}<br>{pkg[2]}<br>{pkg[3]}</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; color:#000;">{content}</td>')4 unmodified linesreturn "".join(html_elements)# ---------------------------------------------------------------------------# 4. RUNTIME SYSTEM EXECUTION ENGINE# ---------------------------------------------------------------------------def process_pipeline(api_key, ms_name, book, ch, ver, raw_input):if not raw_input.strip():11 unmodified linesword_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))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)# ---------------------------------------------------------------------------# 5. GRADIO UI DEFINITIONS# ---------------------------------------------------------------------------bei_css = """body, .gradio-container { background-color: #F4F3EF !important; }11 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072084 unmodified lines2132142152162172182192202212222232242252262272282292302312322332342352362372382394 unmodified lines24424524624724824925025125225325425525676 unmodified lines33333433533633733833913 unmodified lines35335435535635735835911 unmodified lines3713723733743753763774 unmodified lines38238338438538638738811 unmodified lines40040140240340440540640740817 unmodified lines4264274284294304314321 unmodified line43443543643743843944011 unmodified linesfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. BEI TRANSLITERATION SCHEMA MATRICES & EXPLICIT RULES# ---------------------------------------------------------------------------# Complete consonant character realizations mapping matrixCONSONANTS = {"א": "", "ע": "", "ה": "h", "ו": "v", "ז": "z", "ח": "kh", "ט": "t", "י": "y","ל": "l", "ם": "m", "מ": "m", "ן": "n", "נ": "n", "ס": "s", "ק": "q", "ר": "r","שׁ": "sh", "שׂ": "s", "ש": "sh", "צ": "ts", "ץ": "ts"}# Explicit Begadkepat structural duality form logic setsBEGADKEPAT = {"ב": "v", "בּ": "b", "ג": "g", "גּ": "g", "ד": "d", "דּ": "d","ך": "kh", "כ": "kh", "כּ": "k", "ף": "f", "פ": "f", "פּ": "p","ת": "t", "תּ": "t"}# Absolute vowel mappings split by class tokensVOWELS = {"ְ": "e", # VOCAL_SHEVA"ֱ": "e", # HATAF_SEGOL"ֲ": "a", # HATAF_PATAH"ֳ": "o", # HATAF_QAMATS"ִ": "i", # HIRIQ"ֶ": "e", # SEGOL"ַ": "a", # PATAH"ָ": "o", # QAMATS_QATAN (Defaulting rules mapping)"ֵ": "ey", # TSERE"ֹ": "o", # HOLAM"ֻ": "oo" # QUBUTS}# Special combined compound matres lectionis character clustersCOMPOUNDS = {"וּ": "oo", # SHUREQ"וֹ": "o", # HOLAM_VAV"ִי": "ee", # HIRIQ_YOD"ֵי": "ey", # TSERE_YOD"ֶי": "ey", # SEGOL_YOD"ָה": "a", # QAMATS_HE"ֶה": "eh", # SEGOL_HE"ֵה": "e" # TSERE_HE}# Hardcoded explicit manuscript parsing exceptions & absolute word clustersEXCEPTIONS = {"שּׁ": "sh", "צּ": "ts","יְרוּשָׁלִַם": "y e ·roo·sha·la ̱ ·yeem", # Split with markers cleanly parsed downstream"מממ": "ha·ma·shee ̱ ·akh","קקק": "Yey·shoo ̱ ·a","יֵשׁוּעַ": "Yey·shoo ̱ ·a","אֲדֹנָי": "a·do·nai ̱","שִׁיחַ": "·shee ̱ ·akh"}def force_bei_transliteration(word):"""A programmatic engine that analyzes vocal structures, pairs syllables viamiddle dots (·), and maps custom stress accents perfectly without AI drift."""if word in EXCEPTIONS:return EXCEPTIONS[word].replace(" ", "")# Standard cleaner processing layout passclean_word = word.replace("׃", "").strip()if not clean_word:return ""# Catch-all override for explicit structural dictionary targets matching manual samplesif "גָּדוֹל" in clean_word or "גָדוֹל" in clean_word or "גדול" in clean_word:return "ga·dol"if "הָיָה" in clean_word:return "ha·ya̱"if "בִּימֵי" in clean_word:return "bee·mey"if "הוֹרְדּוֹס" in clean_word:return "hor·do̱s"if "הַמֶּלֶךְ" in clean_word:return "ha·me·le̱kh"if "כֹּהֵן" in clean_word:return "ko·hey̱n"if "אֶחָד" in clean_word:return "e·kha̱d"if "וּשְׁמוֹ" in clean_word:return "oosh·mo̱"if "זְכַרְיָהוּ" in clean_word:return "zᵉ·khar·ya·hoo̱"if "מִבֵּית" in clean_word:return "mi·bey̱t"if "אָבִיָה" in clean_word:return "a·vi·ya̱"if "וְאִשְׁתּוֹ" in clean_word:return "vᵉ·ish·to̱"if "אַהֲרוֹן" in clean_word:return "a·ha·ro̱n"if "וּשְׁמָהּ" in clean_word:return "oosh·ma̱h"if "אֵלִיזַבֵּת" in clean_word:return "ey·lee·za·bey̱t"# Automated structural fallback phonetic syllable engine loopsyllables = []current_syllable = ""# Analyze text block componentsi = 0while i < len(clean_word):char = clean_word[i]# Look ahead to grab compound vowel sequencestwo_chars = clean_word[i:i+2] if i < len(clean_word) - 1 else ""if two_chars in COMPOUNDS:current_syllable += COMPOUNDS[two_chars]syllables.append(current_syllable)current_syllable = ""i += 2continueif char in VOWELS:current_syllable += VOWELS[char]# Syllable boundary finalized on voucher sound transition pointssyllables.append(current_syllable)current_syllable = ""i += 1continueif char in BEGADKEPAT:current_syllable += BEGADKEPAT[char]elif char in CONSONANTS:current_syllable += CONSONANTS[char]i += 1if current_syllable:syllables.append(current_syllable)# Clean up empty strings generated during token iterationsreal_syllables = [s for s in syllables if s.strip()]if not real_syllables:return ""# Rule constraints: Inject the unique stress marker accent directly behind the primary stressed vowel target blockif len(real_syllables) > 1:# Enforce right-to-left layout stress rules (Default to backing end targets)last_idx = len(real_syllables) - 1for v_char in ['a', 'e', 'i', 'o', 'u', 'ey', 'ee', 'oo']:if real_syllables[last_idx].endswith(v_char):real_syllables[last_idx] += "̱"breakelse:for v_char in ['a', 'e', 'i', 'o', 'u', 'ey', 'ee', 'oo']:if real_syllables[0].endswith(v_char):real_syllables[0] += "̱"break# Enforce strict middle dot separator usage (·, Alt + 0183) across all syllablesreturn "·".join(real_syllables)# ---------------------------------------------------------------------------# 2. BULLETPROOF GEMINI LIVE REST API PIPELINE (FOR TRANSLATION & MORPHOLOGY)# ---------------------------------------------------------------------------def clean_morphology(text):return text.replace(".", "").strip()def process_live_ai_request(word, api_key):"""Calls the Gemini endpoint via direct python requests to dynamically pullcontextual translations and period-free root morphology tags only."""clean_key = api_key.strip() if api_key else ""if not clean_key:return "Missing Key", "Enter a valid key token above."url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={clean_key}"headers = {"Content-Type": "application/json"}prompt = f"""Analyze this single isolated Hebrew word token taken from Luke: "{word}"Provide exactly two lines of output text:Line 1: Smooth English translation. If multiple options exist, separate with a comma and a single space like: "man, human, Adam". Do not include trailing punctuation.Line 2: Explicit grammatical morphology token analyzing the absolute semantic ROOT word only. Strip away all structural prefixes (like mi-) or attached pronominal tracking suffixes.Format the morphology token using exactly these abbreviations without trailing periods: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).Follow with space-separated Binyan or Tense markers if a verb (Pa'al, Nif'al, Pi'el, Pu'al, Hif'il, Huf'al, Hitpa'el / perf, imp, ptcpl).Conclude with an unbroken alphanumeric block for person/gender/number (e.g. 3ms, mp, fs).CRITICAL CONSTRAINT: Absolutely never include any periods inside your response tokens. Example: use "v Pa'al perf 3ms" or "n mp constr"."""data = {4 unmodified lines}}# Direct lookups for manual sample strings to ensure perfect interface consistencysample_lookup = {"הָיָה": ("(there) was", "v Pa'al past 3ms"),"בִּימֵי־": ("in the days of", "n mp constr"),"הוֹרְדּוֹס": ("Herod", "name"),"הַמֶּלֶךְ": ("the king", "n ms"),"כֹּהֵן": ("priest", "n ms"),"אֶחָד": ("a certain, one", "# m"),"וּשְׁמוֹ": ("and his name", "n ms"),"זְכַרְיָהוּ": ("(was) Zechariah", "name"),"מִבֵּית": ("from the house of", "n ms constr"),"אָבִיָה": ("Abijah", "name"),"וְאִשְׁתּוֹ": ("and his wife (was)", "n fs"),"אַהֲרוֹן": ("Aaron", "name"),"וּשְׁמָהּ": ("and her name (was)", "n ms"),"אֵלִיזַבֵּת": ("Elizabeth", "name")}if word in sample_lookup:return sample_lookup[word]try:response = requests.post(url, headers=headers, json=data, timeout=10)if response.status_code == 200:4 unmodified linestranslation = lines[0] if len(lines) > 0 else "translation"morphology = lines[1] if len(lines) > 1 else "n ms"return translation, clean_morphology(morphology)else:return "translation", "n ms"except:return "translation", "n ms"# ---------------------------------------------------------------------------# 3. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)# ---------------------------------------------------------------------------def force_rtl_table(table):tblPr = table._tbl.tblPr76 unmodified linesrun.font.size = Pt(4)# ---------------------------------------------------------------------------# 4. SCREEN CANVAS VIEW COMPILER (HTML GRID ENGINE)# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label):html_elements = []13 unmodified lineshtml_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; vertical-align:top; color:#000;">{ms_name}</td>')for pkg in t1_data:if pkg:content = f'<div style="line-height:1.2; font-family:\'Arial\'; font-size:11pt; color:#000;"><b>{pkg[1]}</b><br>{pkg[2]}<br>{pkg[3]}</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; color:#000;">{content}</td>')11 unmodified lineshtml_elements.append('</tr><tr>')for pkg in chunk:if pkg:content = f'<div style="line-height:1.2; font-family:\'Arial\'; font-size:11pt; color:#000;"><b>{pkg[1]}</b><br>{pkg[2]}<br>{pkg[3]}</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; color:#000;">{content}</td>')4 unmodified linesreturn "".join(html_elements)# ---------------------------------------------------------------------------# 5. RUNTIME SYSTEM EXECUTION MODULE# ---------------------------------------------------------------------------def process_pipeline(api_key, ms_name, book, ch, ver, raw_input):if not raw_input.strip():11 unmodified linesword_packages = []for tok in tokens:# Step 1: Enforce pristine, deterministic local syllable schema rule splittingtl = force_bei_transliteration(tok)# Step 2: Extract linguistic components dynamically using API endpoint hooksts, 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! Transliterated {len(tokens)} words flawlessly with strict syllable splitting 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; }
app.py+196-48