Spaces:
Running
Running
Update app.py
Browse filesStarted over. Instructions generated by Colab
123125678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626396979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128641301311321331341351361371381391401411421431441451461471486566676869707172737475150151152153154155156157761591601611621631641651661671681691701711721731741751761771787778798081828384858687180181182183184185888990919293949596979899100101102103104105106107108187188189190109110111112192193113114115116117118119120195196197198199121122123124125126127128129130131201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246132133134135136137138139140141142248249250251252253254255256257258259260261262263264265143144145146267268269270271272273274275276277278279280281282283284285286287288289147148149291292293294295296297150151152153154299300301302303304305155156157158159160161162163164165166167168169170171172173174307308309310311175176177313314315316317318319320321322323324325326327328329330331332333334335336337338339340341178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216import gradio as grfrom google import genaifrom google.genai import typesimport osimport timeimport json
# --- Shorashim Pro Ultra-Compact Horizontal Layout Engine ---custom_css = """/* Completely hide technical loading bars & indicators */.subpanel.loading, .generating, div[class*="loading"], .progress-wrap { display: none !important; visibility: hidden !important; height: 0px !important; overflow: hidden !important;}
/* White Canvas Table Wrapper for clear document viewing */.white-canvas { display: flex; justify-content: center; align-items: center; width: 100%;}
/* Forcing Shorashim Pro Charcoal Background to Total UI */.gradio-container, html, body { background-color: #0b0f19 !important; font-family: 'Segoe UI', system-ui, -apple-system, sans-serif !important;}
/* Premium Gold Header Typography */.gradio-container h1, .gradio-container h2, .gradio-container h3 { color: #d4af37 !important; font-weight: 600 !important; margin: 0px !important;}.gradio-container p, .gradio-container span { color: #9ca3af !important;}
/* Input Fields Customized with Gold Accent Focus Rings */input, textarea, select, .dropdown { border-radius: 6px !important; border: 1px solid #1f2937 !important; background-color: #111827 !important; color: #ffffff !important;}input:focus, textarea:focus, select:focus { border-color: #d4af37 !important; outline: none !important;}
/* Primary Generate Action Button (Shorashim Emerald Teal) */button.primary-btn { background: linear-gradient(135deg, #059669 0%, #10b981 100%) !important; border: none !important; border-radius: 6px !important; color: #ffffff !important; font-weight: bold !important; cursor: pointer; height: 42px !important;}
/* Secondary Actions / Clear Button (Dark Slate Accent) */button.secondary-btn { background-color: #1f2937 !important; border: 1px solid #374151 !important; border-radius: 6px !important; color: #e5e7eb !important; cursor: pointer; height: 42px !important;}
/* Google Docs Copy Button (Shorashim Pro Signature Gold) */button.gold-copy-btn { background: linear-gradient(135deg, #aa820a 0%, #d4af37 100%) !important; border: none !important; border-radius: 6px !important; color: #0b0f19 !important; font-weight: 800 !important; font-size: 14px !important; cursor: pointer; box-shadow: 0 4px 6px -1px rgba(212, 175, 55, 0.2); height: 42px !important;}
/* Fixed Table Theater Container Viewport */.theater-viewport { border: 1px solid #1f2937 !important; border-radius: 8px !important; padding: 16px !important; background-color: #0d1321 !important; margin-top: 12px !important; min-height: 45vh !important;import gradio as grimport docxfrom docx import Documentfrom 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"}"""
sticky_session_and_layout_js = """function() { const removeHeaderBlock = () => { const hfHeader = document.querySelector('header'); const spaceHeader = document.querySelector('div[class*="space-header"]'); if (hfHeader) hfHeader.remove(); if (spaceHeader) spaceHeader.remove(); document.querySelectorAll('div').forEach(div => { if (window.getComputedStyle(div).position === 'fixed' && div.innerHTML.includes('fizzickschick')) { div.remove(); } }); }; removeHeaderBlock(); setTimeout(removeHeaderBlock, 500); setTimeout(removeHeaderBlock, 1500); setTimeout(removeHeaderBlock, 3000);
setTimeout(() => { const inputSelectors = '.gradio-container input, .gradio-container textarea, .gradio-container select'; const loadSavedValues = () => { document.querySelectorAll(inputSelectors).forEach((input, index) => { const key = 'table_gen_v6_cache_' + index; const savedValue = localStorage.getItem(key); if (savedValue && input.value !== savedValue) { input.value = savedValue; input.dispatchEvent(new Event('input', { bubbles: true })); input.dispatchEvent(new Event('change', { bubbles: true })); } }); };
document.addEventListener('input', (e) => { document.querySelectorAll(inputSelectors).forEach((input, index) => { if (input === e.target) { localStorage.setItem('table_gen_v6_cache_' + index, input.value); } }); });
document.addEventListener('change', (e) => { document.querySelectorAll(inputSelectors).forEach((input, index) => { if (input === e.target) { localStorage.setItem('table_gen_v6_cache_' + index, input.value); } }); });
loadSavedValues(); setTimeout(loadSavedValues, 800); }, 1200);# Explicit Words & Clusters Hardcoded MappingsEXCEPTIONS = { "Χ©ΦΌΧ": "sh", "Χ¦ΦΌ": "ts", "ΧΦ°Χ¨ΧΦΌΧ©ΦΈΧΧΦ΄Φ·Χ": "yα΅Β·rooΒ·shaΒ·laΜ±Β·yeem", "ΧΧΧ": "haΒ·maΒ·sheeΜ±Β·akh", "Χ§Χ§Χ§": "YeyΒ·shooΜ±Β·a", "ΧΦ΅Χ©ΧΧΦΌΧ’Φ·": "YeyΒ·shooΜ±Β·a", "ΧΦ²ΧΦΉΧ ΦΈΧ": "aΒ·doΒ·naiΜ±", "Χ©Φ΄ΧΧΧΦ·": "Β·sheeΜ±Β·akh"}"""
MODEL_NAME = "gemini-3.1-flash-lite"
def clean_hyphens_for_docs(text_string): if not text_string: return "" return str(text_string).replace("-", "‑")
def calculate_clean_chunks(words_data): chunks = [] current_chunk = [] word_index = 0 while word_index < len(words_data): current_limit = 6 if len(chunks) == 0 else 7 word = words_data[word_index] current_chunk.append(word) if len(current_chunk) == current_limit: chunks.append(current_chunk) current_chunk = [] word_index += 1 if current_chunk: chunks.append(current_chunk) return chunks
def build_html_tables(manuscript, reference, words_data): column_width_in = 1.0 total_slots = 7 total_table_width_in = 7.0# ---------------------------------------------------------------------------# 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] table_style = ( f"width: {total_table_width_in}in !important; min-width: {total_table_width_in}in !important; " f"max-width: {total_table_width_in}in !important; table-layout: fixed !important; border-collapse: collapse; " "direction: rtl; border: 1pt solid #b7b7b7; background-color: #ffffff; " "line-height: 1.0 !important; height: auto; margin-left: auto !important; margin-right: auto !important;" ) # Process characters sequentially result = "" for char in hebrew_word: result += TRANSLITERATION_MAP.get(char, char) # Standard cleanup checks to guarantee explicit syllable layout # and prevent arbitrary standard apostrophe injections if "ga" in result and "dol" in result: return "gaΒ·dol" return result
def get_mock_ai_data(word, api_key): """ Fallback mock processor engine simulating data responses. In real usage, swap this function context block for your external Gemini live endpoint iteration schema. """ # Clean prefixes/suffixes to isolate root context cleaned = word.replace("ΧΦ΄ΦΌ", "").replace("ΧΦ°", "") base_cell = "border: 1pt solid #b7b7b7; padding: 0.069in !important; height: auto; overflow: hidden; white-space: normal !important; word-wrap: break-word !important; box-sizing: border-box !important;" hebrew_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 24px !important; color: #000000 !important; text-align: right !important; vertical-align: middle; {base_cell}" english_cell_style = f"font-family: Arial, sans-serif !important; font-size: 14.6667px !important; color: #000000 !important; text-align: center !important; vertical-align: top; line-height: 1.0 !important; {base_cell}" heading_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18.6667px !important; color: #000000 !important; text-align: center !important; vertical-align: middle; line-height: 1.0 !important; {base_cell}" transliteration = translit_word(word) translation = "translation, definition" morphology = "v Pa'al perf 3ms" # Explicitly period-free html_output = ['<div id="table-payload" class="white-canvas" style="background-color: #ffffff; padding: 15px; border-radius: 8px; display: inline-block; width: 100%; box-sizing: border-box; text-align: center;">'] table_chunks = calculate_clean_chunks(words_data) return 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() html_output.append(f'<table style="{table_style}" align="center" cellpadding="5" cellspacing="0">') html_output.append(' <colgroup>') for _ in range(total_slots): html_output.append(f' <col style="width: {column_width_in}in !important; min-width: {column_width_in}in !important; max-width: {column_width_in}in !important;">') html_output.append(' </colgroup>') # Thin grey solid border configuration borders = 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) for idx, current_chunk in enumerate(table_chunks): is_first = (idx == 0) is_last_table = (idx == len(table_chunks) - 1) allocated_slots = len(current_chunk) + (1 if is_first else 0) if is_last_table: while allocated_slots < total_slots: current_chunk.append({"hebrew": " ", "transliteration": " ", "translation": " ", "morphology": " "}) allocated_slots += 1 html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">') if is_first: html_output.append(f' <td style="{heading_cell_style}">{reference}</td>') for word in current_chunk: html_output.append(f' <td style="{hebrew_cell_style}">{word.get("hebrew", " ")}</td>') html_output.append(' </tr>') html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">') if is_first: formatted_manuscript = manuscript.replace(" ", "<br>") if " " in manuscript else manuscript html_output.append(f' <td style="{heading_cell_style}">{formatted_manuscript}</td>') is_first = False for word in current_chunk: if word.get("hebrew") != " " and word.get("hebrew") != " ": t_lit = clean_hyphens_for_docs(word.get("transliteration", "")) t_lat = clean_hyphens_for_docs(word.get("translation", "")) morph = clean_hyphens_for_docs(word.get("morphology", "")) content = f'{t_lit}<br>{t_lat}<br>{morph}' html_output.append(f' <td class="english-cell" style="{english_cell_style}">{content}</td>') else: html_output.append(f' <td style="{english_cell_style}"> </td>') html_output.append(' </tr>') if not is_last_table: html_output.append(f'<tr style="height: 12pt !important;"><td colspan="{total_slots}" style="border-left: none; border-right: none; border-bottom: none; height: 12pt !important; background-color: #ffffff; padding: 0 !important; margin: 0 !important;"> </td></tr>')
html_output.append('</table>') html_output.append('</div>') return "".join(html_output)
def generate_table_code(api_key, manuscript_name, book, chapter, verse, text_string): if not api_key: return "<p style='color:red; text-align:center;'>β Error: Please enter your Gemini API key.</p>", gr.update(visible=False)
reference_header = f"{book} {chapter}:{verse}" # Explicit inner cell padding clearance margins = 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) try: client = genai.Client(api_key=api_key) system_instruction_text = ( "You are a strict linguistic conversion engine. You process Hebrew text strings and return clean, " "valid JSON lists mapping each word to its transliteration, translation, and morphology properties." )
prompt = f""" Analyze this Hebrew text string word-by-word from right to left: "{text_string}" Populate a JSON dictionary matching this schema format exactly: {{ "hebrew": "The exact raw Hebrew word token", "transliteration": "The structured syllabic transliteration using the provided rules", "translation": "The direct lowercase contextual translation", "morphology": "The clean root-only structural morphology string (e.g. 'v Pa'al perf 3ms' or 'n ms suff 2ms')" }} Return a flat JSON array. Maintain words joined by maqqef (ΦΎ) as a single element. """ if bg_hex: shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{bg_hex}"/>') tcPr.append(shading) response = client.models.generate_content( model=MODEL_NAME, contents=prompt, config=types.GenerateContentConfig( system_instruction=system_instruction_text, response_mime_type="application/json", candidate_count=1 ) ) raw_json_data = json.loads(response.text.strip()) final_table_html = build_html_tables(manuscript_name, reference_header, raw_json_data) return final_table_html, gr.update(visible=True) except Exception as e: return f"<p style='color:red; text-align:center;'>β Error: {str(e)}</p>", gr.update(visible=False)
copy_btn_js = """function() { const payload = document.getElementById('table-payload').innerHTML; const blob = new Blob([payload], { type: 'text/html' }); const data = [new ClipboardItem({ 'text/html': blob })]; navigator.clipboard.write(data).then(() => { alert('π Tables successfully copied to clipboard with Shorashim alignment!'); }).catch(err => { alert('β Clipboard Copy Failed: ' + err); });}""" if width_in: cell.width = Inches(width_in)
with gr.Blocks(title="Shorashim Pro Interlinear Workspace") as demo: gr.HTML( "<div style='background: linear-gradient(135deg, #111827 0%, #0b0f19 100%); padding: 10px; border-radius: 6px; margin-bottom: 10px; text-align: center; border: 1px solid #d4af37;'>" "<h1 style='margin: 0 0 2px 0; font-size: 20px; font-weight: 700; color: #d4af37;'>π Shorashim Pro Workspace</h1>" "<p style='margin: 0; font-size: 12px; color: #9ca3af;'>Convert raw Hebrew text strings into BEI style interlinear tables</p>" "</div>" )def generate_table_block(doc, words_data, ms_name, heading_text, is_first=False): # Standard baseline: 7 columns wide, 2 rows deep table = doc.add_table(rows=2, cols=7) table.alignment = WD_TABLE_ALIGNMENT.CENTER with gr.Accordion("π API Key Setup Instructions", open=False): gr.Markdown( "1. Visit [Google AI Studio](https://aistudio.google.com/).\n" "2. Click the **Get API Key** button on the left workspace menu.\n" "3. Click **Create API Key** (or select your existing default placeholder string).\n" "4. Copy your generated string key, paste it into the **Gemini API Key** input element below, and the app will cache it safely!" ) # Base configuration widths: Seeded initial layout constraint map col_widths = [1.0] * 7 # Dynamic word wrap balancing calculation loop for 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 risk target_col = idx + 1 if is_first else idx if target_col < 7: col_widths[target_col] += 0.3 # Borrow from neighbors to balance overall sum back down to 7.0 borrow_col = 6 if target_col != 6 else 5 col_widths[borrow_col] -= 0.3
# Row 1 and Row 2 processing arrays for col_idx in range(7): cell_r1 = table.cell(0, col_idx) cell_r2 = table.cell(1, col_idx) # --- MONOLITHIC COCKPIT INPUT ROW --- with gr.Row(): api_key_input = gr.Textbox(label="π Gemini API Key", type="password", placeholder="Key safely saved...", scale=2) manuscript_input = gr.Textbox(label="π Manuscript", value="Marseilles MS-24", scale=2) book_input = gr.Textbox(label="π Book", value="Luke", scale=2) set_cell_properties(cell_r1, width_in=col_widths[col_idx]) set_cell_properties(cell_r2, width_in=col_widths[col_idx]) with gr.Column(scale=2): with gr.Row(): chapter_input = gr.Dropdown(choices=[str(x) for x in range(1, 151)], label="Ch.", value="11", allow_custom_value=True) verse_input = gr.Dropdown(choices=[str(x) for x in range(1, 177)], label="Ver.", value="49", allow_custom_value=True) text_string_input = gr.Textbox(label="π Hebrew Verses Input String", placeholder="Paste line segments...", scale=4)
# --- ZERO-SCROLL CONTROL BELT HUB --- with gr.Row(): submit_btn = gr.Button("π Generate Canvas", elem_classes=["primary-btn"], scale=3) clear_btn = gr.Button("π§Ή Clear Input", elem_classes=["secondary-btn"], scale=2) copy_btn = gr.Button("π Copy for Google Docs", elem_classes=["gold-copy-btn"], visible=False, scale=5)
# --- FULL WIDTH THEATER CANVAS VIEWPORT --- with gr.Column(elem_classes=["theater-viewport"]): output_html = gr.HTML(label="Shorashim Frame Canvas")
demo.load(fn=None, inputs=None, outputs=None, js=sticky_session_and_layout_js)
submit_btn.click( fn=generate_table_code, inputs=[api_key_input, manuscript_input, book_input, chapter_input, verse_input, text_string_input], outputs=[output_html, copy_btn], show_progress="hidden" ) clear_btn.click(fn=None, inputs=[], outputs=[text_string_input], js="() => ''") copy_btn.click(fn=None, js=copy_btn_js)
demo.queue().launch(server_name="0.0.0.0", server_port=7860, css=custom_css) # Table 1 Anchor Configuration (Right side in actual space alignment layout block) if is_first and col_idx == 0: cell_r1.text = heading_text cell_r2.text = ms_name # Format top row heading p1 = cell_r1.paragraphs[0] p1.alignment = WD_ALIGN_PARAGRAPH.CENTER r1 = p1.runs[0] r1.font.name = 'Times New Roman' r1.font.size = Pt(14) r1.font.bold = True # Format bottom row source name p2 = cell_r2.paragraphs[0] p2.alignment = WD_ALIGN_PARAGRAPH.CENTER r2 = p2.runs[0] r2.font.name = 'Arial' r2.font.size = Pt(11) cell_r1.vertical_alignment = WD_ALIGN_VERTICAL.TOP cell_r2.vertical_alignment = WD_ALIGN_VERTICAL.TOP continue
# Map word iteration calculations data_idx = col_idx - 1 if is_first else col_idx if 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 = heb p_heb = cell_r1.paragraphs[0] p_heb.alignment = WD_ALIGN_PARAGRAPH.RIGHT cell_r1.vertical_alignment = WD_ALIGN_VERTICAL.CENTER r_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{tsapp.py+200-325