Spaces:
Running
Running
Update app.py
Browse files12343453 unmodified lines910111213141515161718191920202122232425262627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828327858687888990919293949596972829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586998788899026 unmodified lines11711811912012112212347 unmodified lines17117217318517417517617742 unmodified lines22022122223422322422522610 unmodified lines23723823925124024124224325 unmodified lines2692702712832722732742752762774 unmodified lines28228328429529628528628724 unmodified lines3123133143273153163173183193203213223233243353363373253263273283293303311 unmodified line33333433534534633633733834833934034134238 unmodified lines381382383384385394386import osimport timeimport requestsimport jsonimport gradio as grimport docxfrom docx import Document3 unmodified linesfrom docx.oxml import parse_xml, OxmlElementfrom docx.oxml.ns import nsdecls, qn
# Use the classic legacy package to guarantee perfect model connectivityimport google.generativeai as generative_ai
# ---------------------------------------------------------------------------# 1. CORE API ENGINE - DYNAMIC CONTEXTUAL TRANSLATION & TRANSLITERATION# 1. CORE API LINGUISTIC PIPELINE (VERIFIED LEGACY WORKSPACE ROUTING)# ---------------------------------------------------------------------------def process_live_ai_request(word, api_key): """ Leverages Gemini 2.5 Flash to dynamically analyze the Hebrew token, applying the exact BEI Transliteration Schema Matrix and Morphology rules. Queries the stable Gemini 1.5 Flash model directly using the classic generativeai SDK configuration setup to completely bypass 404 mismatches. """ 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 instruction set containing your structural schema matrices prompt = 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, or formatting. Just output the three lines. Line 1: The English transliteration based strictly on the BEI Transliteration Schema. 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̱"). 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: a 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 & EXCEPTIONS: שּׁ (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"Error (Status {response.status_code})", "Check API Connection", "error" # Bind your personal API key directly to the classic workspace configuration generative_ai.configure(api_key=clean_key) model = generative_ai.GenerativeModel('gemini-1.5-flash') prompt_instructions = 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 single isolated Hebrew word token: "{word}" Generate exactly THREE lines of text in your response. Do not include any markdown formatting, bullet points, introduction, or concluding text. 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. 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 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: שּׁ -> sh | צּ -> 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] [Binyan (Verbs Only)] [Tense/Mood/Aspect (Verbs Only)] [Concordance Block]. - Part of Speech Abbreviations: 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 """ response = model.generate_content(prompt_instructions) lines = [line.strip() for line in response.text.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(".", "") except Exception as e: return "Connection Error", "Network Timeout", "error" return "Connection Error", "Legacy API Call Failed", str(e)
# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)26 unmodified lines cell_top.width = Inches(col_widths[col_idx]) tcPr_top = cell_top._tc.get_or_add_tcPr() borders_top = 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>') # Cell cushion margin padding assigned exactly to your 0.069 inches benchmark padding_top = 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_top.append(borders_top) tcPr_top.append(padding_top)47 unmodified lines run.font.size = Pt(4)
# ---------------------------------------------------------------------------# 3. SCREEN CANVAS VIEW COMPILER (HTML GRID ENGINE)# 3. SCREEN CANVAS VIEW COMPILER# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label): html_elements = []42 unmodified lines return "".join(html_elements)
# ---------------------------------------------------------------------------# 4. RUNTIME SYSTEM EXECUTION MODULE# 4. RUNTIME WORKFLOW CONTROLLER (PACED SEQUENCE 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: # Fetch the contextual transliteration, translation, and morphology simultaneously from the model instructions time.sleep(0.4) tl, ts, mo = process_live_ai_request(tok, api_key) word_packages.append((tok, tl, ts, mo)) 25 unmodified lines return "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)
# ---------------------------------------------------------------------------# 5. GRADIO UI DESIGN LAYOUT# 5. GRADIO UI DESIGN PALETTE CONFIGURATIONS# ---------------------------------------------------------------------------# Re-bound background to your exact #F4F3EF ivory hue parametersbei_css = """body, .gradio-container { background-color: #F4F3EF !important; }.bei-banner { background-color: #1B4D3E; padding: 22px; text-align: center; border-radius: 8px; border-bottom: 4px solid #D4AF37; }4 unmodified lines.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;24 unmodified lines}"""
with gr.Blocks(css=bei_css, title="Shorashim Pro Workspace") as demo:with gr.Blocks(title="Shorashim Pro Workspace") as demo: with gr.Row(elem_classes="bei-banner"): gr.Markdown("<h1>📖 Shorashim Pro Workspace</h1><p>BEI Interlinear Table Generator</p>") with gr.Row(): with gr.Column(scale=2): # FIX: Injected inline styling directly into standard text tags to force high contrast gray over Gradio's standard layouts gr.HTML(''' <div class="api-guide-box"> <p style="color: #2D3748 !important; font-family: Arial, sans-serif !important; font-size: 11pt !important; margin: 0 !important;"> <p>🔑 <b>Gemini API Key Guide:</b> To generate your credentials key, log into <a href="https://aistudio.google.com/" target="_blank">Google AI Studio</a>, click the "Get API Key" button, copy the token code block, and paste it below.</p> 🔑 <strong style="color: #2D3748 !important;">Gemini API Key Guide:</strong> To generate your credentials key, log into <a href="https://aistudio.google.com/" target="_blank" style="color: #1B4D3E !important; font-weight: bold !important; text-decoration: underline !important;">Google AI Studio</a>, click the "Get API Key" button, copy the token code block, and paste it below. </p> </div> ''') api_key = gr.Textbox(label="🔑 Gemini API Access Key", type="password", placeholder="Paste AI Studio Key Here...")1 unmodified line ms_name = gr.Textbox(label="📋 Manuscript Selection Name", value="Marseilles MS-24") book = gr.Textbox(label="Book", value="Luke") with gr.Row(): ch = gr.Dropdown(label="Chapter", choices=[str(i) for i in range(1, 25)], value="1") ver = gr.Dropdown(label="Verse", choices=[str(i) for i in range(1, 81)], value=None) ch = gr.Dropdown(label="Chapter", choices=[str(i) for i in range(1, 24)], value="1") ver = gr.Dropdown(label="Verse", choices=[str(i) for i in range(1, 81)], value="5") with gr.Column(scale=2): raw_input = gr.Textbox(label="Paste Your Hebrew Here", placeholder="Paste raw manuscript phrase content here...", lines=7) raw_input = gr.Textbox(label="Paste Your Hebrew Here", value="הָיָה בִּימֵי־הוֹרְדּוֹס הַמֶּלֶךְ כֹּהֵן אֶחָד וּשְׁמוֹ זְכַרְיָהוּ מִבֵּית אָבִיָה וְאִשְׁתּוֹ מִבֵּית אַהֲרוֹן וּשְׁמָהּ אֵלִיזַבֵּת", lines=7) with gr.Row(): gen_btn = gr.Button("🚀 Generate Interlinear Canvas", elem_classes="action-btn")38 unmodified lines
copy_btn.click(fn=None, js=copy_tables_js)
# Launch with CSS applied inside launch method to fully comply with Gradio 6.0 standardsif __name__ == "__main__": demo.launch() demo.launch(css=bei_css)app.py+83-91