Spaces:
Running
Running
Update app.py
Browse files9 unmodified lines1011121314151618 unmodified lines3536373839405 unmodified lines4647484950515253545556575859606162634 unmodified lines6869707172738 unmodified lines8283848586874 unmodified lines9293949596979831 unmodified lines1301311321331341352 unmodified lines1381391401411421431441451461471481491501519 unmodified linesfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. BEI TRANSLITERATION SCHEMAS & DICTIONARIES# ---------------------------------------------------------------------------TRANSLITERATION_MAP = {"ְ": "e", "ֱ": "e", "ֲ": "a", "ֳ": "o",18 unmodified lines}def clean_morphology(text):return text.replace(".", "")def translit_word(word):5 unmodified linesreturn resdef call_mock_engine(word):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):tblPr = table._tbl.tblPrbidiVisual = OxmlElement('w:bidiVisual')tblPr.append(bidiVisual)4 unmodified linesforce_rtl_table(table)col_widths = [1.0] * 7for 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>')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)31 unmodified linesr.font.name = 'Arial'r.font.size = Pt(11)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 (HTML DISPLAY ENGINE)# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label):html = '<div id="bei-target-tables" style="overflow-x:auto; background-color:white; padding:15px; border-radius:4px;">'t1_data = word_packages[:6]while len(t1_data) < 6: t1_data.append(None)html += '<table dir="rtl" style="width:7in; border-collapse:collapse; margin:0 auto 4pt auto; table-layout:fixed; border:1px solid #b7b7b7;">'html += '<tr style="height:40px;">'html += f'<td style="width:1in; border:1px solid #b7b7b7; font-family:\'Times New Roman\'; font-size:14pt; text-align:center; vertical-align:top; color:#000;9 unmodified lines1011121314151618 unmodified lines353637383940415 unmodified lines47484950515253545556575859606162636465666768697071724 unmodified lines77787980818283848 unmodified lines939495969798994 unmodified lines10410510610710810911031 unmodified lines1421431441451461471482 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603619 unmodified linesfrom 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):5 unmodified linesreturn 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)4 unmodified linesforce_rtl_table(table)col_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)31 unmodified linesr.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;">')t1_data = word_packages[:6]while len(t1_data) < 6:t1_data.append(None)# Table 1 Framehtml_elements.append('<table dir="rtl" style="width:7in; border-collapse:collapse; margin:0 auto 4pt auto; table-layout:fixed; border:1px solid #b7b7b7;">')html_elements.append('<tr style="height:40px;">')html_elements.append(f'<td style="width:1in; border:1px solid #b7b7b7; font-family:\'Times New Roman\'; font-size:14pt; text-align:center; vertical-align:top; color:#000; font-weight:bold;">{heading_label}</td>')for pkg in t1_data:text = pkg[0] if pkg else ""html_elements.append(f'<td style="width:1in; border:1px solid #b7b7b7; font-family:\'Times New Roman\'; font-size:18pt; text-align:right; padding:0.069in; vertical-align:middle; color:#000;">{text}</td>')html_elements.append('</tr><tr>')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>'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>')html_elements.append('</tr></table>')# Sequential secondary block loopsrem = word_packages[6:]while len(rem) > 0:chunk = rem[:7]while len(chunk) < 7:chunk.append(None)html_elements.append('<table dir="rtl" style="width:7in; border-collapse:collapse; margin:0 auto 4pt auto; table-layout:fixed; border:1px solid #b7b7b7;"><tr>')for pkg in chunk:text = pkg[0] if pkg else ""html_elements.append(f'<td style="width:1in; border:1px solid #b7b7b7; font-family:\'Times New Roman\'; font-size:18pt; text-align:right; padding:0.069in; vertical-align:middle; color:#000;">{text}</td>')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>'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>')html_elements.append('</tr></table>')rem = rem[7:]html_elements.append('</div>')return "".join(html_elements)# ---------------------------------------------------------------------------# 4. RUNTIME SYSTEM EXECUTION ENGINE# ---------------------------------------------------------------------------def 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:t1_data.append(None)build_docx_table(doc, t1_data, ms_name, heading_label, is_first=True)rem = word_packages[6:]while len(rem) > 0:chunk = rem[:7]while len(chunk) < 7:chunk.append(None)build_docx_table(doc, chunk, ms_name, heading_label, is_first=False)rem = rem[7:]file_path = "BEI_Interlinear_Output.docx"doc.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 DEFINITIONS# ---------------------------------------------------------------------------bei_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; }.bei-banner h1 { color: #F4F3EF !important; font-size: 28px; margin: 0; font-weight: bold; }.bei-banner p { color: #D4AF37 !important; margin: 4px 0 0 0; font-size: 14px; font-weight: 500; }.action-btn { background-color: #1B4D3E !important; color: white !important; font-weight: bold !important; border-radius: 4px !important; margin: 5px 0; }.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; }.hourglass-box { text-align: center; font-size: 24px; padding: 10px; color: #1B4D3E; }"""copy_tables_js = """function() {var container = document.getElementById('bei-target-tables');if (!container) {alert('No tables found to copy! Generate an interlinear layout canvas first.');return;}window.getSelection().removeAllRanges();var range = document.createRange();range.selectNode(container);window.getSelection().addRange(range);try {document.execCommand('copy');alert('Success! Tables copied to clipboard. You can now paste directly into Google Docs.');} catch (err) {alert('Clipboard copy encountered an error.');}window.getSelection().removeAllRanges();}"""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 bugsgr.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="AI key token platform credentials...")with gr.Row():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")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():with gr.Column(scale=1, visible=False) as loading_area:gr.Markdown("<div class='hourglass-box'>⏳ <b>Backend Operational Threads Active... Please Wait.</b></div>")with gr.Row():with gr.Column():status_field = gr.Textbox(label="System Status Pipeline Logs", interactive=False)doc_file = gr.File(label="📥 Download Structured Document Asset (.docx)", visible=False)with 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,outputs=loading_area,queue=False).then(fn=process_pipeline,inputs=[api_key, ms_name, book, ch, ver, raw_input],outputs=[status_field, canvas_area, doc_file]).then(fn=lambda: gr.update(visible=False),inputs=None,outputs=loading_area,queue=False)# Link up layout wipe operations to completely drop output tables on triggerclear_btn.click(fn=clear_workspace,inputs=None,outputs=[raw_input, status_field, canvas_area, doc_file])copy_btn.click(fn=None, js=copy_tables_js)if __name__ == "__main__":demo.launch()
app.py+224-14