Spaces:
Running
Running
Update app.py
Browse files7 unmodified lines891011121314131516171818 unmodified lines37383938394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192933 unmodified lines97989949505152535455565758596061626364100101102103691041051061075 unmodified lines113114115811161171181198 unmodified lines128129130961311321334 unmodified lines13813914014110714214314414523 unmodified lines1691701711371721731741751 unmodified line1771781791451801811821832 unmodified lines18618718815418919019115719219319412 unmodified lines20720820917621021121221312 unmodified lines2262272281952292302312329 unmodified lines24224324424524624724824921325025125221525325425521725625725825926026126226326426526626726826927027112 unmodified lines2842852862392872882892902912442922932942957 unmodified lines30330430525830630730824 unmodified lines3333343352893363373383392943403413426 unmodified lines3493503513073083523533543113553563573583163593603193613623638 unmodified lines37237337433437537637737810 unmodified lines3893903913513923933947 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 DEFINED SYSTEM MAPS & SCHEMAS [cite: 39, 50]# 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[cite: 77, 168].""" return text.replace(".", "") """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 key client = 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 injections return 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 lines return "ga路dol" return res
def 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].""" """Applies a strict right-to-left display orientation flag onto the table property tree.""" tblPr = table._tbl.tblPr bidiVisual = OxmlElement('w:bidiVisual') tblPr.append(bidiVisual)5 unmodified lines col_widths = [1.0] * 7 # 7.0-inch invariant width calculation loop [cite: 34, 129] # 7.0-inch invariant structural width calculation logic loop for i, pkg in enumerate(word_packages): if pkg: total_len = len(pkg[0]) + len(pkg[1]) + len(pkg[2])8 unmodified lines cell_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 lines cell_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 crashes 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>') padding_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 lines p_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)}" cell_bottom.text = f"{tl}\n{ts}\n{mo}" p_bot = cell_bottom.paragraphs[0] p_bot.alignment = WD_ALIGN_PARAGRAPH.CENTER cell_bottom.vertical_alignment = WD_ALIGN_VERTICAL.TOP1 unmodified line r.font.name = 'Arial' r.font.size = Pt(11)
# 4pt spacer line block space [cite: 37, 119] # 4pt Times New Roman blank grid block spacing spacer sp = doc.add_paragraph() sp.paragraph_format.space_before = Pt(0) sp.paragraph_format.space_after = Pt(4)2 unmodified lines run.font.size = Pt(4)
# ---------------------------------------------------------------------------# 3. SCREEN CANVAS VIEW COMPILER (FIXED HTML BLOCKS WITHOUT LINE BREAKS)# 3. SCREEN CANVAS VIEW COMPILER (HTML DISPLAY ENGINE)# ---------------------------------------------------------------------------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 lines html_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>' 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 lines html_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>' 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() time.sleep(1.2) # Clean verse book title string mapping book_clean = book.replace(".", "").strip() heading_label = f"{book[:3]}. {ch}:{ver}" heading_label = f"{book_clean[:3]}. {ch}:{ver}" tokens = raw_input.strip().split() word_packages = [((tok,) + call_mock_engine(tok)) for tok in tokens] word_packages = [] for tok in tokens: # Generate the strict BEI static transliteration pattern tl = translit_word(tok) # Fetch the live translation and root morphology context from Gemini ts, mo = process_live_ai_request(tok, api_key) word_packages.append((tok, tl, ts, mo)) # Render Output Layout HTML Canvas html_canvas = build_html_canvas(word_packages, ms_name, heading_label) # Build Document File Template Target doc = Document() t1_data = word_packages[:6] while len(t1_data) < 6: 12 unmodified lines doc.save(file_path) elapsed = time.time() - start_time status = f"Success! Processed {len(tokens)} words in {elapsed:.2f} seconds." status = 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 "", "", "", gr.update(visible=False) 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; }
/* 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 lines
with 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 bugs gr.HTML(''' <div class="api-guide-box"> <p>馃攽 <b>Gemini API Key Guide:</b> To generate your credentials key, log into 6 unmodified lines ms_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") 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): # 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 mapping clear_btn = gr.Button("Clear Text", elem_classes="clear-btn") # Fix 4: Incorporated the Google Docs direct browser copy tool element copy_btn = gr.Button("Copy Tables for Google Docs", elem_classes="copy-btn") with gr.Row():8 unmodified lines with gr.Row(): canvas_area = gr.HTML(label="Interlinear Render Canvas Layer Output")
# Connect UI Action Listeners [cite: 62] # Connect UI Action Listeners gen_btn.click( fn=lambda: gr.update(visible=True), inputs=None,10 unmodified lines queue=False )
# Link up layout wipe operations to completely drop output tables on trigger clear_btn.click( fn=clear_workspace, inputs=None,app.py+84-44