Spaces:
Running
Running
Update app.py
Browse files12345673 unmodified lines1112131213141416151617182021192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858586878889909192939495969798879910010110226 unmodified lines12913013112013213313447 unmodified lines18218318417418518618718842 unmodified lines23123223322323423523623710 unmodified lines24824925024025125225325425 unmodified lines2802812822722832842852865 unmodified lines29229329429529629729829924 unmodified lines3243253263143273283293303313323203333343233243253263353363373273383393401 unmodified line34234334433533634534634733834834935035138 unmodified lines390391392383393385394import 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
# Standard classic library that natively maps your stable model choice seamlesslyimport google.generativeai as generative_ai
# ---------------------------------------------------------------------------# 1. CORE API LINGUISTIC PIPELINE (STABLE LEGACY WORKSPACE ROUTING)# 1. CORE API ENGINE - DYNAMIC CONTEXTUAL TRANSLATION & TRANSLITERATION# ---------------------------------------------------------------------------def process_live_ai_request(word, api_key): """ Queries the stable Gemini 1.5 Flash model directly using the classic generativeai SDK configuration setup to completely bypass 404 mismatches. Leverages Gemini 2.5 Flash to dynamically analyze the Hebrew token, applying the exact BEI Transliteration Schema Matrix 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 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: # Bind your personal API key directly to the classic legacy 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(".", "") 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" except Exception as e: return "Connection Error", "Legacy API Call Failed", str(e) return "Connection Error", "Network Timeout", "error"
# ---------------------------------------------------------------------------# 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 margin cell padding locked tightly to your clean 0.069 inches benchmark config 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# 3. SCREEN CANVAS VIEW COMPILER (HTML GRID ENGINE)# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label): html_elements = []42 unmodified lines return "".join(html_elements)
# ---------------------------------------------------------------------------# 4. RUNTIME WORKFLOW CONTROLLER (PACED SEQUENCE ENGINE)# 4. RUNTIME SYSTEM EXECUTION MODULE# ---------------------------------------------------------------------------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: time.sleep(0.4) # Fetch the contextual transliteration, translation, and morphology simultaneously from the model instructions 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 DESIGN THEME LAYOUT PARAMETERS# 5. GRADIO UI DESIGN LAYOUT# ---------------------------------------------------------------------------bei_css = """body, .gradio-container { background-color: #F4F3EF !important; }5 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(title="Shorashim Pro Workspace") as demo:with gr.Blocks(css=bei_css, 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 color attributes directly into the HTML tag properties to enforce clear gray 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; padding: 0 !important; line-height: 1.4 !important;"> 🔑 <strong style="color: #2D3748 !important; font-weight: bold !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>🔑 <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> </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, 24)], value="1") ver = gr.Dropdown(label="Verse", choices=[str(i) for i in range(1, 81)], value="5") 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) with gr.Column(scale=2): raw_input = gr.Textbox(label="Paste Your Hebrew Here", value="הָיָה בִּימֵי־הוֹרְדּוֹס הַמֶּלֶךְ כֹּהֵן אֶחָד וּשְׁמוֹ זְכַרְיָהוּ מִבֵּית אָבִיָה וְאִשְׁתּוֹ מִבֵּית אַהֲרוֹן וּשְׁמָהּ אֵלִיזַבֵּת", lines=7) raw_input = gr.Textbox(label="Paste Your Hebrew Here", placeholder="Paste raw manuscript phrase content here...", 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(css=bei_css) demo.launch()app.py+91-82