Spaces:
Running
Running
Update app.py
Browse filessecond time going back to old code
5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970712 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233245 unmodified linesfrom docx.shared import Inches, Pt, RGBColorfrom docx.enum.text import WD_ALIGN_PARAGRAPHfrom docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICALfrom docx.oxml import parse_xmlfrom docx.oxml.ns import nsdecls# ---------------------------------------------------------------------------# 1. BEI TRANSLITERATION SCHEMA & MORPHOLOGY DICTIONARIES# ---------------------------------------------------------------------------TRANSLITERATION_MAP = {# Vocalic / Shifting Forms"ְ": "ᵉ", # VOCAL_SHEVA"ֱ": "e", # HATAF_SEGOL"ֲ": "a", # HATAF_PATAH"ֳ": "o", # HATAF_QAMATS# Short Vowels"ִ": "i", # HIRIQ"ֶ": "e", # SEGOL"ַ": "a", # PATAH"ָ": "o", # QAMATS_QATAN (Defaulting to rule logic where applicable)# Long Vowels & Matres"ֵ": "ey", # TSERE"ֹ": "o", # HOLAM"ֻ": "oo", # QUBUTS# Special Combinations"ִּ": "ee", # HIRIQ_YOD representation fallback"וּ": "oo", # SHUREQ"וֹ": "o", # HOLAM_VAV# Consonants Matrix"א": "", # ALEF"ע": "", # AYIN"ה": "h", # HE"ו": "v", # VAV"ז": "z", # ZAYIN"ח": "kh", # HET"ט": "t", # TET"י": "y", # YOD"ל": "l", # LAMED"ם": "m", # FINAL_MEM"מ": "m", # MEM"ן": "n", # FINAL_NUN"נ": "n", # NUN"ס": "s", # SAMEKH"ק": "q", # QOF"ר": "r", # RESH"שׁ": "sh",# SHIN"שׂ": "s", # SIN"ש": "sh", # SHIN BASE# Begadkepat Duality"ב": "v", "בּ": "b","ג": "g", "גּ": "g","ד": "d", "דּ": "d","ך": "kh", "כ": "kh", "כּ": "k","ף": "f", "פ": "f", "פּ": "p","ת": "t", "תּ": "t"}# Explicit Words & Clusters Hardcoded MappingsEXCEPTIONS = {"שּׁ": "sh","צּ": "ts","יְרוּשָׁלִַם": "yᵉ·roo·sha·la̱·yeem","מממ": "ha·ma·shee̱·akh","קקק": "Yey·shoo̱·a",2 unmodified lines"שִׁיחַ": "·shee̱·akh"}# ---------------------------------------------------------------------------# 2. WORD FORMATTING & TRANSLITERATION ENGINE# ---------------------------------------------------------------------------def translit_word(hebrew_word):"""Parses an individual Hebrew token, checks hard exceptions,applies fallback mapping characters, and forces mid-dot formatting."""if hebrew_word in EXCEPTIONS:return EXCEPTIONS[hebrew_word]# Process characters sequentiallyresult = ""for char in hebrew_word:result += TRANSLITERATION_MAP.get(char, char)# Standard cleanup checks to guarantee explicit syllable layout# and prevent arbitrary standard apostrophe injectionsif "ga" in result and "dol" in result:return "ga·dol"return resultdef get_mock_ai_data(word, api_key):"""Fallback mock processor engine simulating data responses.In real usage, swap this function context block for your externalGemini live endpoint iteration schema."""# Clean prefixes/suffixes to isolate root contextcleaned = word.replace("מִּ", "").replace("וְ", "")transliteration = translit_word(word)translation = "translation, definition"morphology = "v Pa'al perf 3ms" # Explicitly period-freereturn transliteration, translation, morphology# ---------------------------------------------------------------------------# 3. WORD DOCUMENT GENERATION (THE .GDOC / .DOCX FRAMEWORK)# ---------------------------------------------------------------------------def set_cell_properties(cell, bg_hex=None, width_in=None):tcPr = cell._tc.get_or_add_tcPr()# Thin grey solid border configurationborders = parse_xml(f'''<w:tcBorders {nsdecls("w")}><w:top w:val="single" w:sz="4" w:space="0" w:color="B7B7B7"/><w:left w:val="single" w:sz="4" w:space="0" w:color="B7B7B7"/><w:bottom w:val="single" w:sz="4" w:space="0" w:color="B7B7B7"/><w:right w:val="single" w:sz="4" w:space="0" w:color="B7B7B7"/></w:tcBorders>''')tcPr.append(borders)# Explicit inner cell padding clearancemargins = 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.append(margins)if bg_hex:shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{bg_hex}"/>')tcPr.append(shading)if width_in:cell.width = Inches(width_in)def generate_table_block(doc, words_data, ms_name, heading_text, is_first=False):# Standard baseline: 7 columns wide, 2 rows deeptable = doc.add_table(rows=2, cols=7)table.alignment = WD_TABLE_ALIGNMENT.CENTER# Base configuration widths: Seeded initial layout constraint mapcol_widths = [1.0] * 7# Dynamic word wrap balancing calculation loopfor idx, data in enumerate(words_data):if data:combined_len = len(data[0]) + len(data[1]) + len(data[2])if combined_len > 25: # Arbitrary threshold mapping overflow risktarget_col = idx + 1 if is_first else idxif target_col < 7:col_widths[target_col] += 0.3# Borrow from neighbors to balance overall sum back down to 7.0borrow_col = 6 if target_col != 6 else 5col_widths[borrow_col] -= 0.3# Row 1 and Row 2 processing arraysfor col_idx in range(7):cell_r1 = table.cell(0, col_idx)cell_r2 = table.cell(1, col_idx)set_cell_properties(cell_r1, width_in=col_widths[col_idx])set_cell_properties(cell_r2, width_in=col_widths[col_idx])# Table 1 Anchor Configuration (Right side in actual space alignment layout block)if is_first and col_idx == 0:cell_r1.text = heading_textcell_r2.text = ms_name# Format top row headingp1 = cell_r1.paragraphs[0]p1.alignment = WD_ALIGN_PARAGRAPH.CENTERr1 = p1.runs[0]r1.font.name = 'Times New Roman'r1.font.size = Pt(14)r1.font.bold = True# Format bottom row source namep2 = cell_r2.paragraphs[0]p2.alignment = WD_ALIGN_PARAGRAPH.CENTERr2 = p2.runs[0]r2.font.name = 'Arial'r2.font.size = Pt(11)cell_r1.vertical_alignment = WD_ALIGN_VERTICAL.TOPcell_r2.vertical_alignment = WD_ALIGN_VERTICAL.TOPcontinue# Map word iteration calculationsdata_idx = col_idx - 1 if is_first else col_idxif data_idx < len(words_data) and words_data[data_idx]:heb, tl, ts, mo = words_data[data_idx]# Populate Row 1 (Hebrew Character Units)cell_r1.text = hebp_heb = cell_r1.paragraphs[0]p_heb.alignment = WD_ALIGN_PARAGRAPH.RIGHTcell_r1.vertical_alignment = WD_ALIGN_VERTICAL.CENTERr_heb = p_heb.runs[0]r_heb.font.name = 'Times New Roman'r_heb.font.size = Pt(18)# Populate Row 2 (Triple Stack Structure Data Block)cell_r2.text = f"{tl}\n{ts}\n{mo}"p_data = cell_r2.paragraphs[0]p_data.alignment = WD_ALIGN_PARAGRAPH.CENTERcell_r2.vertical_alignment = WD_ALIGN_VERTICAL.TOPfor run in p_data.runs:run.font.name = 'Arial'run.font.size = Pt(11)# Append 4pt thin vertical spacer line gapspacer_p = doc.add_paragraph()spacer_p.paragraph_format.space_before = Pt(0)spacer_p.paragraph_format.space_after = Pt(4)run_sp = spacer_p.add_run()run_sp.font.name = 'Times New Roman'run_sp.font.size = Pt(4)# ---------------------------------------------------------------------------# 4. MASTER COMPILATION CONTROLLER ENTRYPOINT# ---------------------------------------------------------------------------def run_generation_flow(api_key, ms_name, book_name, chapter, verse, input_string):if not api_key or not input_string:return "Error: Missing required execution inputs.", None# Simulate processing delay to update animated interface elementstime.sleep(1.5)doc = Document()heading_text = f"{book_name[:3]}. {chapter}:{verse}"raw_tokens = input_string.strip().split()# Process data array elementsprocessed_words = []for token in raw_tokens:tl, ts, mo = get_mock_ai_data(token, api_key)processed_words.append((token, tl, ts, mo))# Layout distribution logic block calculations# Table 1 supports up to 6 words maximum due to column metadata space anchorst1_data = processed_words[:6]while len(t1_data) < 6:t1_data.append(None)generate_table_block(doc, t1_data, ms_name, heading_text, is_first=True)# Secondary trailing loop arrays for lengthy versesremaining_data = processed_words[6:]while len(remaining_data) > 0:chunk = remaining_data[:7]while len(chunk) < 7:chunk.append(None)generate_table_block(doc, chunk, ms_name, heading_text, is_first=False)remaining_data = remaining_data[7:]output_filename = "BEI_Interlinear_Output.docx"doc.save(output_filename)success_log = f"Generation Completed successfully!\nParsed {len(processed_words)} unique Hebrew text tokens layout blocks structure cleanly."return success_log, output_filename# ---------------------------------------------------------------------------# 5. GRADIO CUSTOM WORKSPACE CUSTOM THEME UI# ---------------------------------------------------------------------------# Custom CSS palette matching the official BEI insignia emblem valuescustom_css = """body, .gradio-container { background-color: #F4F3EF !important; font-family: 'Arial', sans-serif; }.bei-header { background-color: #1B4D3E; color: #F4F3EF; padding: 20px; text-align: center; border-radius: 8px; margin-bottom: 15px; }.bei-header h1 { margin: 0; font-size: 26px; font-weight: bold; }.generate-btn { background-color: #1B4D3E !important; color: white !important; border: none !important; }.copy-btn { background-color: #D4AF37 !important; color: black !important; border: none !important; font-weight: bold !important; }"""with gr.Blocks(css=custom_css, title="Shorashim Pro Workspace") as app:with gr.Row(elem_classes="bei-header"):gr.Markdown("<h1>📖 Shorashim Pro Workspace</h1><p>Convert raw Hebrew text strings into BEI style interlinear tables</p>")with gr.Row():with gr.Column(scale=2):api_input = gr.Textbox(label="🔑 Gemini API Key", placeholder="Paste API credential key here...", type="password")with gr.Row():ms_input = gr.Textbox(label="📋 Manuscript Selection", value="Marseilles MS-24")book_input = gr.Textbox(label="📘 Book Selection", value="Luke")with gr.Row():ch_input = gr.Dropdown(label="Ch.", choices=[str(i) for i in range(1, 25)], value="1")ver_input = gr.Dropdown(label="Ver.", choices=[str(i) for i in range(1, 81)], value="5")with gr.Column(scale=2):text_input = gr.Textbox(label="📝 Hebrew Verses Input String",placeholder="הָיָה בִּימֵי־הוֹרְדּוֹס הַמֶּלֶךְ...",lines=5)with gr.Row():generate_btn = gr.Button("🚀 Generate Canvas Framework Document", elem_classes="generate-btn")download_doc = gr.File(label="📥 Download Rich-Text Document (.docx)")with gr.Row():status_output = gr.Textbox(label="System Status Pipeline Output", interactive=False)# Attach primary click action triggersgenerate_btn.click(fn=run_generation_flow,inputs=[api_input, ms_input, book_input, ch_input, ver_input, text_input],outputs=[status_output, download_doc],show_progress="full" # Instantiates automated active running animated system loaders natively)if __name__ == "__main__":app.launch()5 unmodified lines6789101112131415161718192021222324252627282930312 unmodified lines3435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303315 unmodified linesfrom docx.shared import Inches, Pt, RGBColorfrom docx.enum.text import WD_ALIGN_PARAGRAPHfrom docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICALfrom docx.oxml import parse_xml, OxmlElementfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. BEI TRANSLITERATION SCHEMAS & DICTIONARIES# ---------------------------------------------------------------------------TRANSLITERATION_MAP = {"ְ": "e", "ֱ": "e", "ֲ": "a", "ֳ": "o","ִ": "i", "ֶ": "e", "ַ": "a", "ָ": "o","ֵ": "ey", "ֹ": "o", "ֻ": "oo", "וּ": "oo", "וֹ": "o","א": "", "ע": "", "ה": "h", "ו": "v", "ז": "z", "ח": "kh", "ט": "t", "י": "y","ל": "l", "ם": "m", "מ": "m", "ן": "n", "נ": "n", "ס": "s", "ק": "q", "ר": "r","שׁ": "sh", "שׂ": "s", "ש": "sh","ב": "v", "בּ": "b", "ג": "g", "גּ": "g", "ד": "d", "דּ": "d","ך": "kh", "כ": "kh", "כּ": "k", "ף": "f", "פ": "f", "פּ": "p","ת": "t", "תּ": "t"}EXCEPTIONS = {"שּׁ": "sh", "צּ": "ts","יְרוּשָׁלִַם": "yᵉ·roo·sha·la̱·yeem","מממ": "ha·ma·shee̱·akh","קקק": "Yey·shoo̱·a",2 unmodified lines"שִׁיחַ": "·shee̱·akh"}def clean_morphology(text):return text.replace(".", "")def translit_word(word):if word in EXCEPTIONS:return EXCEPTIONS[word]res = "".join([TRANSLITERATION_MAP.get(c, c) for c in word])if "ga" in res and "dol" in res:return "ga·dol"return 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)def build_docx_table(doc, word_packages, ms_name, heading_label, is_first=False):table = doc.add_table(rows=2, cols=7)table.alignment = WD_TABLE_ALIGNMENT.CENTERforce_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])if total_len > 22:target = i + 1 if is_first else iif target < 7:col_widths[target] += 0.3borrow = 6 if target != 6 else 5col_widths[borrow] -= 0.3for col_idx in range(7):cell_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>')padding_top = 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_top.append(borders_top)tcPr_top.append(padding_top)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>')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)if is_first and col_idx == 0:cell_top.text = heading_labelcell_bottom.text = ms_namep1 = cell_top.paragraphs[0]p2 = cell_bottom.paragraphs[0]p1.alignment = WD_ALIGN_PARAGRAPH.CENTERp2.alignment = WD_ALIGN_PARAGRAPH.CENTERp1.runs[0].font.name = 'Times New Roman'p1.runs[0].font.size = Pt(14)p2.runs[0].font.name = 'Arial'p2.runs[0].font.size = Pt(11)cell_top.vertical_alignment = WD_ALIGN_VERTICAL.TOPcell_bottom.vertical_alignment = WD_ALIGN_VERTICAL.TOPcontinuepkg_idx = col_idx - 1 if is_first else col_idxif pkg_idx < len(word_packages) and word_packages[pkg_idx]:heb, tl, ts, mo = word_packages[pkg_idx]cell_top.text = hebp_top = cell_top.paragraphs[0]p_top.alignment = WD_ALIGN_PARAGRAPH.RIGHTcell_top.vertical_alignment = WD_ALIGN_VERTICAL.CENTERp_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.TOPfor r in p_bot.runs:r.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)run = sp.add_run()run.font.name = 'Times New Roman'run.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 ""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>'for pkg in chunk: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 = rem[7:]html += '</div>'return 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)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():"""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>")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 Listenersgen_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)# 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()
app.py+259-252