Spaces:
Running
Running
Update app.py
Browse files11 unmodified lines1213141515161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128171819202122231322425262728293013831323334353614014114237383940144145414243444514714846474815049505152535455565758596061626364656667686970717273747576777879157808182831611621631641651661671681691701711721731741751761771781791808418285868788891871881899091929394959619119219397989910010119610210310410576 unmodified lines18218318427918518618718813 unmodified lines20220320429920520620712 unmodified lines2202212223182232242255 unmodified lines23123223333023423523623710 unmodified lines24824925034734825125225325425524 unmodified lines2802812823792832842852864 unmodified lines29129229329429539139229629729829930011 unmodified linesfrom docx.oxml.ns import nsdecls, qn
# ---------------------------------------------------------------------------# 1. BEI DEFINED SYSTEM MAPS & SCHEMAS# 1. CORE API ENGINE - DYNAMIC CONTEXTUAL TRANSLATION & TRANSLITERATION# ---------------------------------------------------------------------------CONSONANTS = { "א": "", "ע": "", "ה": "h", "ו": "v", "ז": "z", "ח": "kh", "ט": "t", "י": "y", "ל": "l", "ם": "m", "מ": "m", "ן": "n", "נ": "n", "ס": "s", "ק": "q", "ר": "r", "שׁ": "sh", "שׂ": "s", "ש": "sh", "צ": "ts", "ץ": "ts"}
BEGADKEPAT = { "ב": "v", "בּ": "b", "ג": "g", "גּ": "g", "ד": "d", "דּ": "d", "ך": "kh", "כ": "kh", "כּ": "k", "ף": "f", "פ": "f", "פּ": "p", "ת": "t", "תּ": "t"}
VOWELS = { "ְ": "e", "ֱ": "e", "ֲ": "a", "ֳ": "o", "ִ": "i", "ֶ": "e", "ַ": "a", "ָ": "o", "ֵ": "ey", "ֹ": "o", "ֻ": "oo"}
COMPOUNDS = { "וּ": "oo", "וֹ": "o", "ִי": "ee", "ֵי": "ey", "ֶי": "ey", "ָה": "a", "ֶה": "eh", "ֵה": "e"}
EXCEPTIONS = { "שּׁ": "sh", "צּ": "ts", "יְרוּשָׁלִַם": "yᵉ·roo·sha·la̱·yeem", "מממ": "ha·ma·shee̱·akh", "קקק": "Yey·shoo̱·a", "יֵשׁוּעַ": "Yey·shoo̱·a", "אֲדֹנָי": "a·do·nai̱", "שִׁיחַ": "·shee̱·akh"}
def force_bei_transliteration(word): if word in EXCEPTIONS: return EXCEPTIONS[word] clean_word = word.replace("׃", "").strip() if not clean_word: return "" if "גָּדוֹל" 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"
syllables = [] current_syllable = "" i = 0 while i < len(clean_word): char = clean_word[i] two_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 += 2 continue if char in VOWELS: current_syllable += VOWELS[char] syllables.append(current_syllable) current_syllable = "" i += 1 continue if char in BEGADKEPAT: current_syllable += BEGADKEPAT[char] elif char in CONSONANTS: current_syllable += CONSONANTS[char] i += 1 if current_syllable: syllables.append(current_syllable) real_syllables = [s for s in syllables if s.strip()] if not real_syllables: return "" if len(real_syllables) > 1: last_idx = len(real_syllables) - 1 for v_char in ['a', 'e', 'i', 'o', 'u', 'ey', 'ee', 'oo']: if real_syllables[last_idx].endswith(v_char): real_syllables[last_idx] += "̱" break else: for v_char in ['a', 'e', 'i', 'o', 'u', 'ey', 'ee', 'oo']: if real_syllables[0].endswith(v_char): real_syllables[0] += "̱" break
return "·".join(real_syllables)
# ---------------------------------------------------------------------------# 2. GEMINI REST API PIPELINE# ---------------------------------------------------------------------------def clean_morphology(text): return text.replace(".", "").strip()
def process_live_ai_request(word, api_key): """ Leverages Gemini 2.5 Flash via direct REST calls to dynamically analyze the Hebrew token, applying the exact BEI Transliteration Schema and Morphology rules. """ clean_key = api_key.strip() if api_key else "" if not clean_key: return "Missing Key", "Enter a valid key token above." 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 systemic prompt passing your precise organizational rules prompt = f""" Analyze this single isolated Hebrew word token taken from Luke: "{word}" 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, bullet points, or formatting. Just output the three raw lines. 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. 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. 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. 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). --- 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). 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). 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 CRITICAL CONSTRAINT: Absolutely never include any periods inside your response tokens. Example: use "v Pa'al perf 3ms" or "n mp constr". 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 & 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 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": 100 "maxOutputTokens": 150 } } sample_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) 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()] translation = lines[0] if len(lines) > 0 else "translation" morphology = lines[1] if len(lines) > 1 else "n ms" return translation, clean_morphology(morphology) 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 "translation", "n ms" except: return "translation", "n ms" return f"API Error ({response.status_code})", "Check Key Setup", "error" except Exception as e: return "Connection Timeout", "Network Error", "error"
# ---------------------------------------------------------------------------# 3. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)# ---------------------------------------------------------------------------def force_rtl_table(table): tblPr = table._tbl.tblPr76 unmodified lines run.font.size = Pt(4)
# ---------------------------------------------------------------------------# 4. SCREEN CANVAS VIEW COMPILER# 3. SCREEN CANVAS VIEW COMPILER (HTML DISPLAY ENGINE)# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label): html_elements = []13 unmodified lines 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: if pkg: # FIX: Explicit color styles injected on the transliteration line to overwrite the faint browser grey standard properties 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 = ""12 unmodified lines html_elements.append('</tr><tr>') for pkg in chunk: if pkg: # FIX: Explicit color styles applied identically across all cascading grid element paths 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 = ""5 unmodified lines return "".join(html_elements)
# ---------------------------------------------------------------------------# 5. RUNTIME SYSTEM EXECUTION ENGINE# 4. RUNTIME SYSTEM EXECUTION ENGINE# ---------------------------------------------------------------------------def process_pipeline(api_key, ms_name, book, ch, ver, raw_input): if not raw_input.strip():10 unmodified lines word_packages = [] for tok in tokens: tl = force_bei_transliteration(tok) ts, mo = process_live_ai_request(tok, api_key) # Request transliteration, translation, and morphology concurrently via systemic 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)24 unmodified lines return "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)
# ---------------------------------------------------------------------------# 6. GRADIO UI LAYOUT CONFIGURATIONS# 5. GRADIO UI DESIGN LAYOUT# ---------------------------------------------------------------------------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; }
/* FIX: Forced high-visibility dark charcoal text for the instructions box title and body lines */.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; }.api-guide-box p, .api-guide-box b, .api-guide-box a { color: #2D3748 !important; font-family: 'Arial', sans-serif !important; font-size: 11pt !important; margin: 0; }.api-guide-box a { color: #1B4D3E !important; font-weight: bold !important; text-decoration: underline !important; }
input[type="text"], input[type="password"], textarea { background-color: #FFFFFF !important;app.py+66-161