Spaces:
Running
Running
Update app.py
Browse files123453 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899026 unmodified lines11711811912012112212347 unmodified lines17117217317417517617742 unmodified lines22022122222322422522610 unmodified lines23723823924024124224325 unmodified lines2692702712722732742755 unmodified lines28128228328428528624 unmodified lines3113123133143153163173183193203213223233243253263273283293301 unmodified line33233333433533633733833934034138 unmodified lines380381382383384385import osimport timeimport 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)# ---------------------------------------------------------------------------def process_live_ai_request(word, api_key):"""Queries the stable Gemini 1.5 Flash model directly using the classicgenerativeai 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"try:# Bind your personal API key directly to the classic legacy workspace configurationgenerative_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: 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:שּׁ -> 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", "Legacy API Call Failed", str(e)# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)26 unmodified linescell_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 configpadding_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 linesrun.font.size = Pt(4)# ---------------------------------------------------------------------------# 3. SCREEN CANVAS VIEW COMPILER# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label):html_elements = []42 unmodified linesreturn "".join(html_elements)# ---------------------------------------------------------------------------# 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 linesword_packages = []for tok in tokens:time.sleep(0.4)tl, ts, mo = process_live_ai_request(tok, api_key)word_packages.append((tok, tl, ts, mo))25 unmodified linesreturn "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)# ---------------------------------------------------------------------------# 5. GRADIO DESIGN THEME LAYOUT PARAMETERS# ---------------------------------------------------------------------------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; }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.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 graygr.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></div>''')api_key = gr.Textbox(label="🔑 Gemini API Access Key", type="password", placeholder="Paste AI Studio Key Here...")1 unmodified linems_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")with gr.Column(scale=2):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 linescopy_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)12345673 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110226 unmodified lines12913013113213313447 unmodified lines18218318418518618718842 unmodified lines23123223323423523623710 unmodified lines24824925025125225325425 unmodified lines2802812822832842852865 unmodified lines29229329429529629729829924 unmodified lines3243253263273283293303313323333343353363373383393401 unmodified line34234334434534634734834935035138 unmodified lines390391392393394import 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# ---------------------------------------------------------------------------# 1. CORE API ENGINE - DYNAMIC CONTEXTUAL TRANSLATION & TRANSLITERATION# ---------------------------------------------------------------------------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."""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 matricesprompt = 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: 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 & 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"except Exception as e:return "Connection Error", "Network Timeout", "error"# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)26 unmodified linescell_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>')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 linesrun.font.size = Pt(4)# ---------------------------------------------------------------------------# 3. SCREEN CANVAS VIEW COMPILER (HTML GRID ENGINE)# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label):html_elements = []42 unmodified linesreturn "".join(html_elements)# ---------------------------------------------------------------------------# 4. RUNTIME SYSTEM EXECUTION MODULE# ---------------------------------------------------------------------------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:# Fetch the contextual transliteration, translation, and morphology simultaneously from the model instructionstl, ts, mo = process_live_ai_request(tok, api_key)word_packages.append((tok, tl, ts, mo))25 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; }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(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):gr.HTML('''<div class="api-guide-box"><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></div>''')api_key = gr.Textbox(label="🔑 Gemini API Access Key", type="password", placeholder="Paste AI Studio Key Here...")1 unmodified linems_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)with gr.Column(scale=2):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 linescopy_btn.click(fn=None, js=copy_tables_js)if __name__ == "__main__":demo.launch()
app.py+91-82