Spaces:
Running
Running
Update app.py
Browse files11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819976 unmodified lines27627727827928028128213 unmodified lines29629729829930030130212 unmodified lines3153163173183193203215 unmodified lines32732832933033133233310 unmodified lines34434534634734834935035124 unmodified lines3763773783793803813824 unmodified lines38738838939039139239339439511 unmodified linesfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. BEI DEFINED SYSTEM MAPS & SCHEMAS# ---------------------------------------------------------------------------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 = 0while 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 += 2continueif char in VOWELS:current_syllable += VOWELS[char]syllables.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)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) - 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] += "̱"breakreturn "·".join(real_syllables)# ---------------------------------------------------------------------------# 2. GEMINI REST API PIPELINE# ---------------------------------------------------------------------------def clean_morphology(text):return text.replace(".", "").strip()def process_live_ai_request(word, api_key):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 = {"contents": [{"parts": [{"text": prompt}]}],"generationConfig": {"temperature": 0.1,"maxOutputTokens": 100}}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)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)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# ---------------------------------------------------------------------------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:#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 propertiescontent = 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 lineshtml_elements.append('</tr><tr>')for pkg in chunk:if pkg:# FIX: Explicit color styles applied identically across all cascading grid element pathscontent = 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 linesreturn "".join(html_elements)# ---------------------------------------------------------------------------# 5. RUNTIME SYSTEM EXECUTION ENGINE# ---------------------------------------------------------------------------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:tl = force_bei_transliteration(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)24 unmodified linesreturn "", "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 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; }input[type="text"], input[type="password"], textarea {background-color: #FFFFFF !important;11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410576 unmodified lines18218318418518618718813 unmodified lines20220320420520620712 unmodified lines2202212222232242255 unmodified lines23123223323423523623710 unmodified lines24824925025125225325425524 unmodified lines2802812822832842852864 unmodified lines29129229329429529629729829930011 unmodified linesfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. CORE API ENGINE - DYNAMIC CONTEXTUAL TRANSLATION & TRANSLITERATION# ---------------------------------------------------------------------------def process_live_ai_request(word, api_key):"""Leverages Gemini 2.5 Flash via direct REST calls to dynamically analyzethe 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", "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 rulesprompt = 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 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.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.---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: aCOMPOUND MATRES LECTIONIS:HIRIQ_YOD: ee | TSERE_YOD: ey | SEGOL_YOD: ey | SHUREQ: oo | HOLAM_VAV: o | QAMATS_HE: a | SEGOL_HE: eh | TSERE_HE: eCONSONANTS 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: tsBEGADKEPAT 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: 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 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": 150}}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})", "Check Key Setup", "error"except Exception as e:return "Connection Timeout", "Network Error", "error"# ---------------------------------------------------------------------------# 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:#000000;">{ms_name}</td>')for pkg in t1_data:if pkg: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 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;"><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 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():10 unmodified linesword_packages = []for tok in tokens:# Request transliteration, translation, and morphology concurrently via systemic instructionstl, 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 linesreturn "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)# ---------------------------------------------------------------------------# 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 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