Spaces:
Running
Running
Update app.py
Browse filesone more try before bed
110 unmodified lines11111211311411511611711811912012112212312412512612711 unmodified lines1391401411421431441451461471481491503 unmodified lines15415515615715815916016116216316416516616716816917017117217317417517617733 unmodified lines21121221321421521645 unmodified lines262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353110 unmodified linesreturn str(text_string).replace("-", "‑")def calculate_dynamic_chunks(words_data, base_limit=7):"""Splits words into groups of 7.The first group accommodates the reference block, leaving 6 slots for words.Subsequent groups take exactly 7 words."""chunks = []current_chunk = []word_index = 0while word_index < len(words_data):# First table row needs 1 slot for reference block + 6 slots for words = 7 total columnscurrent_limit = 6 if len(chunks) == 0 else 7word = words_data[word_index]11 unmodified linesreturn chunksdef build_html_tables(manuscript, reference, words_data):# ESSENTIAL RULE: Master constraint locked to exactly 7.0 inches widetable_style = ("width: 7.0in !important; min-width: 7.0in !important; max-width: 7.0in !important; ""table-layout: fixed !important; border-collapse: collapse; margin-bottom: 4pt; ""direction: rtl; border: 1pt solid #b7b7b7; background-color: #ffffff; ""line-height: 1.0 !important; height: auto; margin-left: auto; margin-right: auto;")html_output = ['<div id="table-payload" class="white-canvas" style="background-color: #ffffff; padding: 20px; border-radius: 8px; display: inline-block; width: 100%; box-sizing: border-box; text-align: center;">']3 unmodified linesis_first = (idx == 0)is_last_table = (idx == len(table_chunks) - 1)# Determine how many open slots remain to build a perfectly symmetrical 7-column matrixallocated_slots = len(current_chunk) + (1 if is_first else 0)# If the trailing table is shorter than 7 slots, fill the empty spaces with clean blank objectsif is_last_table:while allocated_slots < 7:current_chunk.append({"hebrew": " ", "transliteration": " ", "translation": " ", "morphology": " "})allocated_slots += 1html_output.append(f'<table style="{table_style}">')# ESSENTIAL RULE: Force every single column to be EXACTLY 1.0 inch wide to match your templatehtml_output.append(' <colgroup>')for _ in range(7):html_output.append(' <col style="width: 1.0in !important; min-width: 1.0in !important; max-width: 1.0in !important;">')html_output.append(' </colgroup>')# ESSENTIAL RULE: Exact 0.069in padding on all four sides + strict word wrap suppression (nowrap)base_cell = "border: 1pt solid #b7b7b7; padding: 0.069in !important; height: auto; overflow: hidden; white-space: nowrap !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; 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; vertical-align: top; line-height: 1.0 !important; {base_cell}"33 unmodified linesdef generate_table_code(api_key, manuscript_name, book, chapter, verse, text_string):if not api_key:yield gr.update(visible=True, value="<p style='color:red; text-align:center;'>❌ Error: Please enter your Gemini API key.</p>"), "", gr.update(visible=False)return45 unmodified lines- VOCAL_SHEVA: "ᵉ", HATAF_SEGOL: "e", HATAF_PATAH: "a", HATAF_QAMATS: "o", HIRIQ: "i", TSERE: "ey", SEGOL: "e", PATAH: "a", QAMATS: "a", HOLAM: "o", QUBUTS: "oo", MAQAF: "-", PASEQ: "׀", SOF_PASUQ: "."- SYLLABLE_SEPARATOR: "·", STRESS_MARKER: location: "after-vowel", mark: "̱"- DIVINE_NAME: "Yᵉ·ho·va̱h", DIVINE_NAME_ELOHIM: "Ye·ho·vee̱h"- Specific translations: Always map 'יֵשׁוּעַ' to transliteration 'yey·shoo̱·a' and translation 'Yeshua'."""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())except Exception as e:yield gr.update(visible=True, value=f"<p style='color:red; text-align:center;'>❌ API Error: {str(e)}</p>"), "", gr.update(visible=False)returnyield gr.update(visible=True, value=status_html("Assembling Fixed 7-Inch Symmetrical Grid Blueprint")), "", gr.update(visible=False)try:final_table_html = build_html_tables(manuscript_name, reference_header, raw_json_data)except Exception as e:yield gr.update(visible=True, value=f"<p style='color:red; text-align:center;'>❌ Layout Error: {str(e)}</p>"), "", gr.update(visible=False)returnyield gr.update(visible=False, value=""), final_table_html, gr.update(visible=True)copy_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 exact formatting!');}).catch(err => { alert('❌ Clipboard Copy Failed: ' + err); });}"""with gr.Blocks(css=custom_css, title="Hebrew Interlinear Table Generator") as demo:gr.HTML("<div style='background: linear-gradient(135deg, #111827 0%, #1f2937 100%); padding: 24px; border-radius: 12px; margin-bottom: 24px; color: white; text-align: center; border: 1px solid #374151; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.5);'>""<h1 style='margin: 0 0 8px 0; font-size: 28px; font-weight: 700; color: white;'>📖 Hebrew Interlinear Table Generator</h1>""<p style='margin: 0; font-size: 15px; opacity: 0.8; color: #9ca3af;'>Convert raw Hebrew text into structured, balanced 7-inch columns.</p>""</div>")with gr.Accordion("🔑 How to find and paste your Gemini API key", open=True):gr.Markdown("1. Go to [Google AI Studio](https://aistudio.google.com/).\n""2. Click **Get API Key** in the menu.\n""3. Copy the **Default API Key** shown on the screen.\n""4. Paste it into the **Gemini API Key** box below.\n\n""📺 **Need visual help?** Watch this [simple video tutorial](https://youtu.be/Uyn-P2nRvDA?si=_1NqPoJK-sHOVX-W).")with gr.Row():with gr.Column(scale=4):gr.Markdown("### 🛠️ Step 1: Configure Reference Settings")api_key_input = gr.Textbox(label="🔑 Gemini API Key", type="password", placeholder="Paste your default API key token here...")manuscript_input = gr.Textbox(label="📜 Manuscript Name", value="Marseilles MS-24")book_input = gr.Textbox(label="📚 Book Title", value="Luke")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)gr.Markdown("### 📝 Step 2: Paste Hebrew Text")text_string_input = gr.Textbox(label="Hebrew Verses Input String", placeholder="Paste your raw Hebrew string text right here...", lines=3)with gr.Row():submit_btn = gr.Button("🚀 Generate Table", variant="primary")clear_btn = gr.Button("🧹 Clear Text", variant="secondary")status_panel = gr.HTML(visible=False)gr.Markdown("### 📊 Step 3: Output View & Copy Options")copy_btn = gr.Button("📋 Copy for Google Docs", variant="secondary", visible=False)output_html = gr.HTML(label="Generated Output Table Grid Layout Canvas")demo.load(fn=None, inputs=None, outputs=None, js=force_clean_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=[status_panel, 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_js)if __name__ == "__main__":demo.queue().launch(server_name="0.0.0.0", server_port=7860)110 unmodified lines11111211311411511611711811912012111 unmodified lines1331341351361371381391401411421431441451461473 unmodified lines15115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020133 unmodified lines23523623723823924024145 unmodified lines287288289290110 unmodified linesreturn str(text_string).replace("-", "‑")def calculate_dynamic_chunks(words_data, base_limit=7):chunks = []current_chunk = []word_index = 0while word_index < len(words_data):current_limit = 6 if len(chunks) == 0 else 7word = words_data[word_index]11 unmodified linesreturn chunksdef build_html_tables(manuscript, reference, words_data):total_table_width_in = 7.0total_slots = 7# Embedded align="center" ensures Google Docs centers the table geometry upon pastingtable_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; ""margin-bottom: 4pt; direction: rtl; border: 1pt solid #b7b7b7; background-color: #ffffff; ""line-height: 1.0 !important; height: auto; margin-left: auto !important; margin-right: auto !important;")html_output = ['<div id="table-payload" class="white-canvas" style="background-color: #ffffff; padding: 20px; border-radius: 8px; display: inline-block; width: 100%; box-sizing: border-box; text-align: center;">']3 unmodified linesis_first = (idx == 0)is_last_table = (idx == len(table_chunks) - 1)# Build character scoring arrays to execute proper dynamic logic adjustmentsslot_weights = []if is_first:ref_len = max(len(reference), len(manuscript))slot_weights.append(ref_len)for word in current_chunk:# Score scaling factor maps visual space accuratelyw_hebrew = len(word.get("hebrew", "")) * 1.6w_translit = len(word.get("transliteration", ""))w_trans = len(word.get("translation", ""))w_morph = len(word.get("morphology", ""))max_text_footprint = max(w_hebrew, w_translit, w_trans, w_morph)slot_weights.append(max_text_footprint if max_text_footprint > 0 else 6)if is_last_table:while (len(current_chunk) + (1 if is_first else 0)) < total_slots:current_chunk.append({"hebrew": " ", "transliteration": " ", "translation": " ", "morphology": " "})slot_weights.append(6)# --- RUN 3-STEP BALANCING MATRIX LOGIC ---total_weight_score = sum(slot_weights)calculated_widths = []for w in slot_weights:allocated_width = (w / total_weight_score) * total_table_width_in# Guard constraint protects narrow columns from causing text wrap glitchesif allocated_width < 0.75:allocated_width = 0.75calculated_widths.append(round(allocated_width, 3))remainder_adjustment = round(total_table_width_in - sum(calculated_widths), 3)if remainder_adjustment != 0 and len(calculated_widths) > 0:calculated_widths[-1] = round(calculated_widths[-1] + remainder_adjustment, 3)# The align="center" attribute is included here for native Google Docs pasting supporthtml_output.append(f'<table style="{table_style}" align="center">')html_output.append(' <colgroup>')for c_width in calculated_widths:html_output.append(f' <col style="width: {c_width}in !important; min-width: {c_width}in !important; max-width: {c_width}in !important;">')html_output.append(' </colgroup>')# LOCKED REQUIREMENT: Symmetrical 0.069in cell padding across all four boundaries + suppressed text wrapbase_cell = "border: 1pt solid #b7b7b7; padding: 0.069in !important; height: auto; overflow: hidden; white-space: nowrap !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; 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; vertical-align: top; line-height: 1.0 !important; {base_cell}"33 unmodified linesdef generate_table_code(api_key, manuscript_name, book, chapter, verse, text_string):if not api_key:gr.Warning("API Key missing.")yield gr.update(visible=True, value="<p style='color:red; text-align:center;'>❌ Error: Please enter your Gemini API key.</p>"), "", gr.update(visible=False)return45 unmodified lines- VOCAL_SHEVA: "ᵉ", HATAF_SEGOL: "e", HATAF_PATAH: "a", HATAF_QAMATS: "o", HIRIQ: "i", TSERE: "ey", SEGOL: "e", PATAH: "a", QAMATS: "a", HOLAM: "o", QUBUTS: "oo", MAQAF: "-", PASEQ: "׀", SOF_PASUQ: "."- SYLLABLE_SEPARATOR: "·", STRESS_MARKER: location: "after-vowel", mark: "̱"- DIVINE_NAME: "Yᵉ·ho·va̱h", DIVINE_NAME_ELOHIM: "Ye·ho·vee̱h"- Specific translations: Always map 'יֵשׁוּעַ' to transliteration 'yey
app.py+47-110