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 lines101112131314151618 unmodified lines353637383839405 unmodified lines46474850515253545556575859606162495051525354555657585960696162634 unmodified lines68697080817172738 unmodified lines8283849685868742 unmodified lines1301311321451331341352 unmodified lines1381391401541411421431571581441451461601471621631481491501661511521531541551721731741751561571581591601611621821631641651861871661671681699 unmodified lines1791801812031821831841852071861871881892 unmodified lines1921931942161951962191971982222231992002012022032042292302052062072081 unmodified line2102112122382132142152162172182192202212432222232242252262272492502282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592562602612622632642652662672682692702712722732742632752762772782792682802812822832842852862872882892902702712722912922936 unmodified lines30030130228530330430530610 unmodified lines3173183193203213223233243253263273283293303319 unmodified linesfrom docx.oxml.ns import nsdecls, qn
# ---------------------------------------------------------------------------# 1. BEI DEFINED SYSTEM MAPS & SCHEMAS# 1. BEI TRANSLITERATION SCHEMAS & DICTIONARIES# ---------------------------------------------------------------------------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 lines return res
def 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" 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.tblPr bidiVisual = OxmlElement('w:bidiVisual') tblPr.append(bidiVisual)4 unmodified lines force_rtl_table(table) col_widths = [1.0] * 7 # 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 exact 0.069 inches padding boundaries configuration 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 lines r.font.name = 'Arial' r.font.size = Pt(11)
# 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 (HTML DISPLAY ENGINE)# 3. SCREEN CANVAS VIEW COMPILER (HTML DISPLAY WITH EXPLICIT ID FOR CLIPBOARD)# ---------------------------------------------------------------------------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;">' # Added wrapper ID 'bei-target-tables' so the system knows exactly what to capture for copy actions html = '<div id="bei-target-tables" 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) 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 Line 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>' # Row 2: Data Package Triple Stacks html += '<tr>' 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>' # 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) 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 lines return html
# ---------------------------------------------------------------------------# 4. RUNTIME SYSTEM EXECUTION BLOCK# 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 supply structural manuscript input lines.", "", gr.update(visible=False) return "System Warning: Please paste Hebrew strings to build.", "", gr.update(visible=False) start_time = time.time() time.sleep(1.2)2 unmodified lines tokens = raw_input.strip().split() word_packages = [((tok,) + call_mock_engine(tok)) for tok in tokens] # 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: t1_data.append(None) 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) while len(chunk) < 7: chunk.append(None) build_docx_table(doc, chunk, ms_name, heading_label, is_first=False) rem = rem[7:] 1 unmodified line doc.save(file_path) elapsed = time.time() - start_time status = f"Execution successful! Processed context parameters across {len(tokens)} words in {elapsed:.2f} seconds." status = 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 SPACE STYLING (BENAI EMUNAH FOREST ACCENTS)# 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: 13px; }.action-btn { background-color: #1B4D3E !important; color: white !important; font-weight: bold !important; border-radius: 4px !important; }.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"): gr.Markdown("<h1>๐ Shorashim Pro Workspace</h1><p>Benai Emunah International โข Critical Manuscript Translation Interface</p>") # Adjustments 1: Replaced subheading line text parameters gr.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 acquisition gr.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 properties book = gr.Textbox(label="๐ Scripture Target Book", value="Luke") book = 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): raw_input = gr.Textbox(label="๐ Manuscript Hebrew Words Input String", value="ืึธืึธื ืึผึดืืึตืึพืืึนืจึฐืึผืึนืก ืึทืึผึถืึถืึฐ ืึผึนืึตื ืึถืึธื", lines=5) # 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 action clear_btn = gr.Button("Clear Text", elem_classes="clear-btn") # Adjustment 4: Live Clipboard copy button component added copy_btn = gr.Button("Copy Tables for Google Docs", elem_classes="copy-btn") 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 lines with gr.Row(): canvas_area = gr.HTML(label="Interlinear Render Canvas Layer Output")
# Connect UI trigger actions # Connect UI Action Listeners gen_btn.click( fn=lambda: gr.update(visible=True), inputs=None,10 unmodified lines queue=False )
# Clean reset action pipeline callback linkage clear_btn.click( fn=clear_workspace, inputs=None, outputs=[raw_input, status_field, canvas_area, doc_file] )
# Clipboard browser execution routing linkage copy_btn.click(fn=None, js=copy_tables_js)
if __name__ == "__main__": demo.launch()