Spaces:
Running
Running
Update app.py
Browse files7 unmodified lines891011121314151618 unmodified lines35363738394041423 unmodified lines4647484950515253545556575859606162636465666768697071725 unmodified lines787980818283848 unmodified lines939495969798994 unmodified lines10410510610710810911023 unmodified lines1341351361371381391401 unmodified line1421431441451461471482 unmodified lines15115215315415515615715815916012 unmodified lines17317417517617717817912 unmodified lines1921931941951961971989 unmodified lines20820921021121221321421521621721821922022122222312 unmodified lines2362372382392402412422432442452462477 unmodified lines25525625725825926026124 unmodified lines2862872882892902912922932942952962976 unmodified lines3043053063073083093103113123133143153163173183193203213228 unmodified lines33133233333433533633710 unmodified lines3483493503513523533547 unmodified linesfrom docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICALfrom docx.oxml import parse_xml, OxmlElementfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. BEI DEFINED SYSTEM MAPS & SCHEMAS [cite: 39, 50]# ---------------------------------------------------------------------------TRANSLITERATION_MAP = {"职": "e", "直": "e", "植": "a", "殖": "o",18 unmodified lines}def clean_morphology(text):"""Enforces strict no-period constraint rule across all grammar tokens[cite: 77, 168]."""return text.replace(".", "")def translit_word(word):if word in EXCEPTIONS:3 unmodified linesreturn "ga路dol"return resdef call_mock_engine(word):"""Simulated breakdown isolating core semantic roots matching manuscript text[cite: 102, 170]."""if "讛指讬指讛" in word:return "ha路ya瘫", "(there) was", "v Pa'al past 3ms"if "讘旨执讬诪值讬志" in word:return "bee路mey", "in the days of", "nmp constr"if "讛讜止专职讚旨讜止住" in word:return "hor路do瘫s", "Herod", "name"if "讛址诪旨侄诇侄讱职" in word:return "ha路me路le瘫kh", "the king", "nms"if "讻旨止讛值谉" in word:return "ko路hey瘫n", "priest", "nms"if "讗侄讞指讚" in word:return "e路kha瘫d", "a certain, one", "# m"return translit_word(word), "translation", "n ms"# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)# ---------------------------------------------------------------------------def force_rtl_table(table):"""Applies a strict right-to-left display orientation flag onto the table[cite: 65, 131]."""tblPr = table._tbl.tblPrbidiVisual = OxmlElement('w:bidiVisual')tblPr.append(bidiVisual)5 unmodified linescol_widths = [1.0] * 7# 7.0-inch invariant width calculation loop [cite: 34, 129]for i, pkg in enumerate(word_packages):if pkg:total_len = len(pkg[0]) + len(pkg[1]) + len(pkg[2])8 unmodified linescell_top = table.cell(0, col_idx)cell_bottom = table.cell(1, col_idx)# Enforce cell margins [cite: 42, 118] and structural widths [cite: 30, 124]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>')4 unmodified linescell_bottom.width = Inches(col_widths[col_idx])tcPr_bottom = cell_bottom._tc.get_or_add_tcPr()borders_bottom = 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_bottom = parse_xml(f'<w:tcMar {nsdecls("w")}><w:top w:w="99" w:type="dxa"/><w:left w:w="99" d:type="dxa"/><w:bottom w:w="99" w:type="dxa"/><w:right w:w="99" w:type="dxa"/></w:tcMar>')tcPr_bottom.append(borders_bottom)tcPr_bottom.append(padding_bottom)23 unmodified linesp_top.runs[0].font.name = 'Times New Roman'p_top.runs[0].font.size = Pt(18)cell_bottom.text = f"{tl}\n{ts}\n{clean_morphology(mo)}"p_bot = cell_bottom.paragraphs[0]p_bot.alignment = WD_ALIGN_PARAGRAPH.CENTERcell_bottom.vertical_alignment = WD_ALIGN_VERTICAL.TOP1 unmodified liner.font.name = 'Arial'r.font.size = Pt(11)# 4pt spacer line block space [cite: 37, 119]sp = doc.add_paragraph()sp.paragraph_format.space_before = Pt(0)sp.paragraph_format.space_after = Pt(4)2 unmodified linesrun.font.size = Pt(4)# ---------------------------------------------------------------------------# 3. SCREEN CANVAS VIEW COMPILER (FIXED HTML BLOCKS WITHOUT LINE BREAKS)# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label):"""Generates an explicit Right-To-Left styled HTML canvas container using triple quotes[cite: 65]."""html_elements = []html_elements.append('<div id="bei-target-tables" style="overflow-x:auto; background-color:white; padding:15px; border-radius:4px;">')12 unmodified lineshtml_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; vertical-align:top; color:#000;">{ms_name}</td>')for pkg in t1_data:if pkg:content = f'<div style="line-height:1.2;">{pkg[1]}<br>{pkg[2]}<br>{clean_morphology(pkg[3])}</div>'else:content = ""html_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; padding:0.069in; vertical-align:top; color:#000;">{content}</td>')12 unmodified lineshtml_elements.append('</tr><tr>')for pkg in chunk:if pkg:content = f'<div style="line-height:1.2;">{pkg[1]}<br>{pkg[2]}<br>{clean_morphology(pkg[3])}</div>'else:content = ""html_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; padding:0.069in; vertical-align:top; color:#000;">{content}</td>')9 unmodified linesdef process_pipeline(api_key, ms_name, book, ch, ver, raw_input):if not raw_input.strip():return "System Warning: Please paste Hebrew strings to build.", "", gr.update(visible=False)start_time = time.time()time.sleep(1.2)heading_label = f"{book[:3]}. {ch}:{ver}"tokens = raw_input.strip().split()word_packages = [((tok,) + call_mock_engine(tok)) for tok in tokens]html_canvas = build_html_canvas(word_packages, ms_name, heading_label)doc = Document()t1_data = word_packages[:6]while len(t1_data) < 6:12 unmodified linesdoc.save(file_path)elapsed = time.time() - start_timestatus = f"Success! Processed {len(tokens)} words in {elapsed:.2f} seconds."return status, html_canvas, gr.update(value=file_path, visible=True)def clear_workspace():return "", "", "", gr.update(visible=False)# ---------------------------------------------------------------------------# 5. GRADIO SPACE WORKSPACE AND LAYOUT DEFINITIONS7 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: Clear high-contrast text styling for the API help element block container */.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; }24 unmodified lineswith gr.Blocks(css=bei_css, title="Shorashim Pro Workspace") as demo:with gr.Row(elem_classes="bei-banner"):# Fix 1: Subheading updated exactly to "BEI Interlinear Table Generator"gr.Markdown("<h1>馃摉 Shorashim Pro Workspace</h1><p>BEI Interlinear Table Generator</p>")with gr.Row():with gr.Column(scale=2):# Fix 5: Forced clean dark text rule across the HTML guide container to resolve illegibility bugsgr.HTML('''<div class="api-guide-box"><p>馃攽 <b>Gemini API Key Guide:</b> To generate your credentials key, log into6 unmodified linesms_name = gr.Textbox(label="馃搵 Manuscript Selection Name", value="Marseilles MS-24")book = gr.Textbox(label="Book", value="Luke")with gr.Row():# Fix 6, 7, 8: Cleaned dropdown title text down to exactly "Chapter" and "Verse"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):# Fix 2: Changed input string label box to read "Paste Your Hebrew Here"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")# Fix 3: Implemented the missing "Clear Text" clear button and command pipeline mappingclear_btn = gr.Button("Clear Text", elem_classes="clear-btn")# Fix 4: Incorporated the Google Docs direct browser copy tool elementcopy_btn = gr.Button("Copy Tables for Google Docs", elem_classes="copy-btn")with gr.Row():8 unmodified lineswith gr.Row():canvas_area = gr.HTML(label="Interlinear Render Canvas Layer Output")# Connect UI Action Listeners [cite: 62]gen_btn.click(fn=lambda: gr.update(visible=True),inputs=None,10 unmodified linesqueue=False)# Link up layout wipe operations to completely drop output tables on triggerclear_btn.click(fn=clear_workspace,inputs=None,7 unmodified lines8910111213141516171818 unmodified lines3738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192933 unmodified lines9798991001011021031041051061075 unmodified lines1131141151161171181198 unmodified lines1281291301311321334 unmodified lines13813914014114214314414523 unmodified lines1691701711721731741751 unmodified line1771781791801811821832 unmodified lines18618718818919019119219319412 unmodified lines20720820921021121221312 unmodified lines2262272282292302312329 unmodified lines24224324424524624724824925025125225325425525625725825926026126226326426526626726826927027112 unmodified lines2842852862872882892902912922932942957 unmodified lines30330430530630730824 unmodified lines3333343353363373383393403413426 unmodified lines3493503513523533543553563573583593603613623638 unmodified lines37237337437537637737810 unmodified lines3893903913923933947 unmodified linesfrom docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICALfrom docx.oxml import parse_xml, OxmlElementfrom docx.oxml.ns import nsdecls, qnfrom google import genaifrom google.genai import types# ---------------------------------------------------------------------------# 1. BEI TRANSLITERATION SCHEMA CONFIGURATIONS# ---------------------------------------------------------------------------TRANSLITERATION_MAP = {"职": "e", "直": "e", "植": "a", "殖": "o",18 unmodified lines}def clean_morphology(text):"""Enforces strict no-period constraint rule across all grammar tokens."""return text.replace(".", "").strip()def process_live_ai_request(word, api_key):"""Calls the official Gemini Live Engine using the user's provided API key box.Instructs the LLM to provide the correct contextual translation and root morphology."""if not api_key or len(api_key.strip()) < 10:return "transliteration", "Missing/Invalid API Key", "n ms"try:# Initialize the official GenAI Client with the user-provided keyclient = genai.Client(api_key=api_key.strip())prompt = f"""You are an expert academic text processor assisting Benai Emunah International (BEI) with a critical text translation of the Hebrew manuscript of the Book of Luke.Analyze this single isolated Hebrew word token: "{word}"Provide exactly two lines of output:Line 1: The smooth contextual English translation (if multiple options exist, separate with a comma and a single space like: "man, human, Adam"). Do not include periods.Line 2: The descriptive grammatical morphology token analyzing the absolute semantic ROOT word only. Strip away all structural preposition prefixes (like mi-) or attached pronominal suffixes.Format the morphology token using exactly these space-separated parameters (omit where not applicable):1. Part of Speech: 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).2. Binyan (Verbs Only): Pa'al, Nif'al, Pi'el, Pu'al, Hif'il, Huf'al, Hitpa'el.3. Tense/Mood/Aspect (Verbs Only): perf, imp, ptcpl.4. Concordance String (Unbroken block): Combined Person (1, 2, 3), Gender (m, f, c), and Number (s, p). Example: "3ms" or "mp".CRITICAL: Never include any periods inside your response tokens. Example: use "v Pa'al perf 3ms" or "n mp constr"."""response = client.models.generate_content(model='gemini-2.5-flash',contents=prompt,config=types.GenerateContentConfig(temperature=0.1,max_output_tokens=100))lines = [line.strip() for line in response.text.split('\n') if line.strip()]translation = lines[0] if len(lines) > 0 else "translation"morphology = lines[1] if len(lines) > 1 else "n ms"# Fallback security check to scrub out sneaky punctuation injectionsreturn translation, clean_morphology(morphology)except Exception as e:return f"Error contacting Gemini: {str(e)}", "n ms"def translit_word(word):if word in EXCEPTIONS:3 unmodified linesreturn "ga路dol"return res# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)# ---------------------------------------------------------------------------def force_rtl_table(table):"""Applies a strict right-to-left display orientation flag onto the table property tree."""tblPr = table._tbl.tblPrbidiVisual = OxmlElement('w:bidiVisual')tblPr.append(bidiVisual)5 unmodified linescol_widths = [1.0] * 7# 7.0-inch invariant structural width calculation logic loopfor i, pkg in enumerate(word_packages):if pkg:total_len = len(pkg[0]) + len(pkg[1]) + len(pkg[2])8 unmodified linescell_top = table.cell(0, col_idx)cell_bottom = table.cell(1, col_idx)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>')4 unmodified linescell_bottom.width = Inches(col_widths[col_idx])tcPr_bottom = cell_bottom._tc.get_or_add_tcPr()borders_bottom = 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>')# FIX: Changed broken 'd:type' attribute on the next line to exactly 'w:type' to completely eliminate runtime crashespadding_bottom = 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_bottom.append(borders_bottom)tcPr_bottom.append(padding_bottom)23 unmodified linesp_top.runs[0].font.name = 'Times New Roman'p_top.runs[0].font.size = Pt(18)cell_bottom.text = f"{tl}\n{ts}\n{mo}"p_bot = cell_bottom.paragraphs[0]p_bot.alignment = WD_ALIGN_PARAGRAPH.CENTERcell_bottom.vertical_alignment = WD_ALIGN_VERTICAL.TOP1 unmodified liner.font.name = 'Arial'r.font.size = Pt(11)# 4pt Times New Roman blank grid block spacing spacersp = doc.add_paragraph()sp.paragraph_format.space_before = Pt(0)sp.paragraph_format.space_after = Pt(4)2 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 = []html_elements.append('<div id="bei-target-tables" style="overflow-x:auto; background-color:white; padding:15px; border-radius:4px;">')12 unmodified lineshtml_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; vertical-align:top; color:#000;">{ms_name}</td>')for pkg in t1_data:if pkg:content = f'<div style="line-height:1.2;">{pkg[1]}<br>{pkg[2]}<br>{pkg[3]}</div>'else:content = ""html_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; padding:0.069in; vertical-align:top; color:#000;">{content}</td>')12 unmodified lineshtml_elements.append('</tr><tr>')for pkg in chunk:if pkg:content = f'<div style="line-height:1.2;">{pkg[1]}<br>{pkg[2]}<br>{pkg[3]}</div>'else:content = ""html_elements.append(f'<td style="border:1px solid #b7b7b7; font-family:\'Arial\'; font-size:11pt; text-align:center; padding:0.069in; vertical-align:top; color:#000;">{content}</td>')9 unmodified linesdef process_pipeline(api_key, ms_name, book, ch, ver, raw_input):if not raw_input.strip():return "System Warning: Please paste Hebrew strings to build.", "", gr.update(visible=False)if not api_key.strip():return "System Warning: Please enter your personal Gemini API Key above to generate translations.", "", gr.update(visible=False)start_time = time.time()# Clean verse book title string mappingbook_clean = book.replace(".", "").strip()heading_label = f"{book_clean[:3]}. {ch}:{ver}"tokens = raw_input.strip().split()word_packages = []for tok in tokens:# Generate the strict BEI static transliteration patterntl = translit_word(tok)# Fetch the live translation and root morphology context from Geminits, mo = process_live_ai_request(tok, api_key)word_packages.append((tok, tl, ts, mo))# Render Output Layout HTML Canvashtml_canvas = build_html_canvas(word_packages, ms_name, heading_label)# Build Document File Template Targetdoc = Document()t1_data = word_packages[:6]while len(t1_data) < 6:12 unmodified linesdoc.save(file_path)elapsed = time.time() - start_timestatus = f"Success! Processed {len(tokens)} words in {elapsed:.2f} seconds using Gemini 2.5 Flash."return status, html_canvas, gr.update(value=file_path, visible=True)def clear_workspace():return "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)# ---------------------------------------------------------------------------# 5. GRADIO SPACE WORKSPACE AND LAYOUT DEFINITIONS7 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; }24 unmodified lineswith 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 into6 unmodified linesms_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="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")clear_btn = gr.Button("Clear Text", elem_classes="clear-btn")copy_btn = gr.Button("Copy Tables for Google Docs", elem_classes="copy-btn")with gr.Row():8 unmodified lineswith gr.Row():canvas_area = gr.HTML(label="Interlinear Render Canvas Layer Output")# Connect UI Action Listenersgen_btn.click(fn=lambda: gr.update(visible=True),inputs=None,10 unmodified linesqueue=False)clear_btn.click(fn=clear_workspace,inputs=None,
app.py+84-44