Spaces:
Running
Update app.py
Browse filesThe interface needs a few easy adjustments. These are numbered in the screenshot:
1 - The subheading should be the following text string: BEI Interlinear Table Generator
2 - Instead of 'Manuscript Hebrew Words Input String', the text should read 'Paste Your Hebrew Here'
3 - The 'Clear Text' box is missing, and I assume the command to clear the Hebrew text box is missing from the code as well. When the user clicks on this button, the text is cleared from the Hebrew input text field, and the tables that were previously generated disappear. The label on the button should read 'Clear Text'.
4 - The button to copy the tables so that they can be pasted into Google Docs is missing. When the user clicks this button, the tables are copied to the clipboard so that they can then be pasted straight into Google Docs - without reformatting or exporting from .docx to .gdoc format. The label on this button should be 'Copy Tables for Google Docs'
5 - Include a simple set of instructions for the user to find and paste their Gemini API key.
6 - The text above the book dropdown menu should be 'Book'.
7 - The text above the book dropdown menu should be 'Book'.
8 - The text above the book dropdown menu should be 'Book'.

9 unmodified lines1011121314151618 unmodified lines353637383940415 unmodified lines47484950515253545556575859606162636465666768697071724 unmodified lines77787980818283848 unmodified lines9394959697989942 unmodified lines1421431441451461471482 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891909 unmodified lines2002012022032042052062072082092102 unmodified lines2132142152162172182192202212222232242252262272282292302312322331 unmodified line2352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742756 unmodified lines28228328428528628728810 unmodified lines2993003013023039 unmodified linesfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. BEI DEFINED SYSTEM MAPS & SCHEMAS# ---------------------------------------------------------------------------TRANSLITERATION_MAP = {"ְ": "e", "ֱ": "e", "ֲ": "a", "ֳ": "o",18 unmodified lines}def clean_morphology(text):"""Enforces the strict no-period constraint rule across all grammar tokens."""return text.replace(".", "")def translit_word(word):5 unmodified linesreturn resdef call_mock_engine(word):"""Simulated breakdown isolating core semantic roots matching manuscript text."""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 property tree."""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 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)# Enforce exact 0.069 inches padding boundaries configurationcell_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>')42 unmodified linesr.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):"""Generates an explicit Right-To-Left styled HTML canvas container matching layout grid rules."""html = '<div style="overflow-x:auto; background-color:white; padding:15px; border-radius:4px;">'# Block 1 (Handles first 6 layout words + verse headings anchor)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;">'# Row 1: Hebrew Text Linehtml += '<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; font-weight:bold;">{heading_label}</td>'for pkg in t1_data:text = pkg[0] if pkg else ""html += 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 += '</tr>'# Row 2: Data Package Triple Stackshtml += '<tr>'html += 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:content = f'<div style="line-height:1.2;">{pkg[1]}<br>{pkg[2]}<br>{clean_morphology(pkg[3])}</div>' if pkg else ""html += 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 += '</tr></table>'# Trailing Blocks (Iterates over remaining strings across columns 1-7 sequentially)rem = word_packages[6:]while len(rem) > 0:chunk = rem[:7]while len(chunk) < 7:chunk.append(None)html += '<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 ""9 unmodified linesreturn html# ---------------------------------------------------------------------------# 4. RUNTIME SYSTEM EXECUTION BLOCK# ---------------------------------------------------------------------------def process_pipeline(api_key, ms_name, book, ch, ver, raw_input):if not raw_input.strip():return "System Warning: Please supply structural manuscript input lines.", "", gr.update(visible=False)start_time = time.time()time.sleep(1.2)2 unmodified linestokens = raw_input.strip().split()word_packages = [((tok,) + call_mock_engine(tok)) for tok in tokens]# 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: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:]1 unmodified linedoc.save(file_path)elapsed = time.time() - start_timestatus = f"Execution successful! Processed context parameters across {len(tokens)} words in {elapsed:.2f} seconds."return status, html_canvas, gr.update(value=file_path, visible=True)# ---------------------------------------------------------------------------# 5. GRADIO SPACE STYLING (BENAI EMUNAH FOREST ACCENTS)# ---------------------------------------------------------------------------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: 13px; }.action-btn { background-color: #1B4D3E !important; color: white !important; font-weight: bold !important; border-radius: 4px !important; }.hourglass-box { text-align: center; font-size: 24px; padding: 10px; color: #1B4D3E; }"""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>Benai Emunah International • Critical Manuscript Translation Interface</p>")with gr.Row():with gr.Column(scale=2):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="📘 Scripture Target Book", value="Luke")with gr.Row():ch = gr.Dropdown(label="Chapter Target", choices=[str(i) for i in range(1, 25)], value="1")ver = gr.Dropdown(label="Verse Target", choices=[str(i) for i in range(1, 81)], value="5")with gr.Column(scale=2):raw_input = gr.Textbox(label="📝 Manuscript Hebrew Words Input String", value="הָיָה בִּימֵי־הוֹרְדּוֹס הַמֶּלֶךְ כֹּהֵן אֶחָד", lines=5)with gr.Row():gen_btn = gr.Button("🚀 Generate Interlinear Canvas", elem_classes="action-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>")6 unmodified lineswith gr.Row():canvas_area = gr.HTML(label="Interlinear Render Canvas Layer Output")# Connect UI trigger actionsgen_btn.click(fn=lambda: gr.update(visible=True),inputs=None,10 unmodified linesqueue=False)if __name__ == "__main__":demo.launch()9 unmodified lines1011121314151618 unmodified lines3536373839405 unmodified lines4647484950515253545556575859606162634 unmodified lines6869707172738 unmodified lines82838485868742 unmodified lines1301311321331341352 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681699 unmodified lines1791801811821831841851861871881892 unmodified lines1921931941951961971981992002012022032042052062072081 unmodified line2102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922936 unmodified lines30030130230330430530610 unmodified lines3173183193203213223233243253263273283293303319 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>')42 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 WITH EXPLICIT ID FOR CLIPBOARD)# ---------------------------------------------------------------------------def build_html_canvas(word_packages, ms_name, heading_label):# Added wrapper ID 'bei-target-tables' so the system knows exactly what to capture for copy actionshtml = '<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; font-weight:bold;">{heading_label}</td>'for pkg in t1_data:text = pkg[0] if pkg else ""html += 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 += '</tr><tr>'html += 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:content = f'<div style="line-height:1.2;">{pkg[1]}<br>{pkg[2]}<br>{clean_morphology(pkg[3])}</div>' if pkg else ""html += 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 += '</tr></table>'rem = word_packages[6:]while len(rem) > 0:chunk = rem[:7]while len(chunk) < 7: chunk.append(None)html += '<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 ""9 unmodified linesreturn html# ---------------------------------------------------------------------------# 4. RUNTIME PIPELINE CONTROLLER# ---------------------------------------------------------------------------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)2 unmodified linestokens = 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:]1 unmodified linedoc.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():"""Wipes out the input fields and drops generated canvas tables instantly."""return "", "", "", gr.update(visible=False)# ---------------------------------------------------------------------------# 5. GRADIO UI DEFINITIONS WITH INTEGRATED CLIPBOARD JS INJECTIONS# ---------------------------------------------------------------------------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; }.api-guide { background-color: #E2E8F0; padding: 12px; border-radius: 6px; border-left: 4px solid #1B4D3E; font-size: 11.5pt; color: #2D3748; margin-bottom: 10px; }.hourglass-box { text-align: center; font-size: 24px; padding: 10px; color: #1B4D3E; }"""# JavaScript module function that copies formatted HTML tables directly onto your system clipboardcopy_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"):# Adjustments 1: Replaced subheading line text parametersgr.Markdown("<h1>📖 Shorashim Pro Workspace</h1><p>BEI Interlinear Table Generator</p>")with gr.Row():with gr.Column(scale=2):# Adjustment 5: Integrated simple guide instructions block for key acquisitiongr.HTML('''<div class="api-guide">🔑 <b>Gemini API Key Guide:</b> To generate your credentials key, log into <a href="https://aistudio.google.com/" target="_blank" style="color:#1B4D3E; font-weight:bold; text-decoration:underline;">Google AI Studio</a>, click the "Get API Key" button, copy the token code block, and paste it below.</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")# Adjustments 6, 7, 8: Unified text field inputs targeting the Book selection propertiesbook = gr.Textbox(label="Book", value="Luke")with gr.Row():ch = gr.Dropdown(label="Chapter Target", choices=[str(i) for i in range(1, 25)], value="1")ver = gr.Dropdown(label="Verse Target", choices=[str(i) for i in range(1, 81)], value="5")with gr.Column(scale=2):# Adjustment 2: Text parameters changed to '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")# Adjustment 3: Clean reset trigger button actionclear_btn = gr.Button("Clear Text", elem_classes="clear-btn")# Adjustment 4: Live Clipboard copy button component addedcopy_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>")6 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)# Clean reset action pipeline callback linkageclear_btn.click(fn=clear_workspace,inputs=None,outputs=[raw_input, status_field, canvas_area, doc_file])# Clipboard browser execution routing linkagecopy_btn.click(fn=None, js=copy_tables_js)if __name__ == "__main__":demo.launch()