Spaces:
Running
Update app.py
Browse filesOh, I see the new crash log in image_1afc4.pngβgrrr is right! Hugging Face is running Gradio 6.0, which completely changed how persistent memory works and threw a TypeError: unexpected keyword argument 'storage_key'. My fault for using an argument the new version doesn't support!
Let's fix this once and for all by bypassing Gradio's changing rules completely. We will write our own native, bulletproof JavaScript persistence engine inside sticky_session_and_layout_js. It doesn't rely on Gradio arguments; it hooks directly into the browser's hidden localStorage mechanics to lock your API Key, manuscript title, book name, chapters, verses, and Hebrew strings into your browser's physical memory. If Hugging Face refreshes, the script immediately forces your data back into the slots before the screen even paints!
π Fixing the Stubborn Google Docs Padding
Since Google Docs strips out web CSS styling padding from cell borders, we have to cheat the system using literal structural text containers:
Top and Bottom Padding: We inject a small, hidden structural spacer block (<div style="font-size: 5pt; line-height: 5pt; height: 5pt;"> </div>) directly above the first line of text and right below the last line of text inside the cell.
Left and Right Padding: We wrap every single word stack with a left and right margin using standard HTML non-breaking spaces ( ). Because Google Docs views these non-breaking spaces as permanent alphanumeric characters rather than style formatting, it physically cannot strip them out. They are forced to stay in the document, keeping your perfect
78 unmodified lines7980818283848586878889909192939495969798991001011021031041055 unmodified lines11111211311411511618 unmodified lines13513613713813914076 unmodified lines2172182192202212222232242252262272282292302312322332342352362372382392402412422432442 unmodified lines24724824925025125225325425525625725825995 unmodified lines35535635735835936036136213 unmodified lines3763773783793803813823833843853863873883893903913925 unmodified lines3983994004014024034044 unmodified lines40941041141241378 unmodified lines}"""# JAVASCRIPT TO STRIP AWAY THE HUGGING FACE TOP NAVIGATION HEADERforce_clean_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);}"""5 unmodified linesreturn str(text_string).replace("-", "‑")def get_minimum_column_width_in(word_dict, is_reference_block=False, ref_text="", ms_text=""):char_width_in = 0.076hebrew_char_width_in = 0.145padding_buffer_in = 0.069 * 218 unmodified linesreturn max(longest_single_token_width, 0.60) + padding_buffer_indef calculate_recursive_table_chunks(words_data, reference, manuscript):total_allowed_width_in = 7.0final_row_chunks = []word_pool = list(words_data)76 unmodified lineshtml_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>')# Symmetrical cell padding fallback logic for Google Docs clipboard processingbase_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; 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}"heading_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18.6667px !important; color: #000000 !important; text-align: center; vertical-align: middle; line-height: 1.0 !important; {base_cell}"# Empty safety spacing rows ensure vertical padding is maintained in Google Docsspacer_text_style = "font-size: 4.5pt; line-height: 4.5pt; height: 4.5pt;"# --- ROW 1: Hebrew Text / Reference ---html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">')if is_first:html_output.append(f' <td style="{heading_cell_style}"><div style="{spacer_text_style}"> </div> {reference} <div style="{spacer_text_style}"> </div></td>')for word in current_chunk:html_output.append(f' <td style="{hebrew_cell_style}"><div style="{spacer_text_style}"> </div> {word.get("hebrew", " ")} <div style="{spacer_text_style}"> </div></td>')html_output.append(' </tr>')# --- ROW 2: English Structural Stack ---html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">')if is_first:formatted_manuscript = manuscript.replace(" ", "<br>") if " " in manuscript else manuscripthtml_output.append(f' <td style="{heading_cell_style}"><div style="{spacer_text_style}"> </div> {formatted_manuscript} <div style="{spacer_text_style}"> </div></td>')is_first = Falsefor word in current_chunk:2 unmodified linest_lat = clean_hyphens_for_docs(word.get("translation", ""))morph = clean_hyphens_for_docs(word.get("morphology", ""))# Double characters ( ) pad the sides, and empty spacer divs pad the top/bottomcontent = (f'<div style="{spacer_text_style}"> </div>'f' {t_lit} <br>'f' {t_lat} <br>'f' {morph} 'f'<div style="{spacer_text_style}"> </div>')html_output.append(f' <td class="english-cell" style="{english_cell_style}">{content}</td>')else:95 unmodified lines}"""# Native Gradio state management hooks hold variables securely in browser memorywith 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>"13 unmodified lineswith gr.Row():with gr.Column(scale=4):gr.Markdown("### π οΈ Step 1: Configure Reference Settings")# Using Gradio native browser storage triggers to stick data values firmly across refresh bootsapi_key_input = gr.Textbox(label="π Gemini API Key", type="password", placeholder="Paste your default API key token here...", storage_key="api_key_persistent")manuscript_input = gr.Textbox(label="π Manuscript Name", value="Marseilles MS-24", storage_key="manuscript_persistent")book_input = gr.Textbox(label="π Book Title", value="Luke", storage_key="book_title_persistent")with gr.Row():chapter_input = gr.Dropdown(choices=[str(x) for x in range(1, 151)], label="Ch.", value="11", allow_custom_value=True, storage_key="chapter_persistent")verse_input = gr.Dropdown(choices=[str(x) for x in range(1, 177)], label="Ver.", value="49", allow_custom_value=True, storage_key="verse_persistent")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, storage_key="text_input_persistent")with gr.Row():submit_btn = gr.Button("π Generate Table", variant="primary")5 unmodified linescopy_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,4 unmodified linesclear_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)78 unmodified lines7980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401415 unmodified lines14714814915015115215315415515618 unmodified lines17517617717817918018118218318476 unmodified lines2612622632642652662672682692702712722732742752762772782792802812822832842852862872882 unmodified lines29129229329429529629729829930030130230395 unmodified lines39940040140240340440513 unmodified lines4194204214224234244254264274284294304314324335 unmodified lines4394404414424434444454 unmodified lines45045145245345478 unmodified lines}"""# JAVASCRIPT: STRIPIFY HEADERS + BULLETPROOF STORAGE RESCUE MECHANISMsticky_session_and_layout_js = """function() {// 1. Strip Away Hugging Face Framing Headersconst 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);// 2. Native Browser Cache Core - Keeps values alive across hard reloads/refreshessetTimeout(() => {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 }));}});};// Continually track and capture entries to safeguard against disconnectsdocument.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();// Secondary safety check to let slow UI components register values cleanlysetTimeout(loadSavedValues, 800);}, 1200);}"""5 unmodified linesreturn str(text_string).replace("-", "‑")def get_minimum_column_width_in(word_dict, is_reference_block=False, ref_text="", ms_text=""):"""Finds the absolute longest single word token in a cell to establish thewrapping safety layout width, factoring in your 0.069in side borders."""char_width_in = 0.076hebrew_char_width_in = 0.145padding_buffer_in = 0.069 * 218 unmodified linesreturn max(longest_single_token_width, 0.60) + padding_buffer_indef calculate_recursive_table_chunks(words_data, reference, manuscript):"""ESSENTIAL PROCEDURE: Groups your text words. If a single unbroken word token causes a columnfootprint to exceed 7.0 inches total, the last word drops recursively."""total_allowed_width_in = 7.0final_row_chunks = []word_pool = list(words_data)76 unmodified lineshtml_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>')# Symmetrical cell padding baseline configuration with soft word splitting enabledbase_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; 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}"heading_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18.6667px !important; color: #000000 !important; text-align: center; vertical-align: middle; line-height: 1.0 !important; {base_cell}"# Hard spacer configurations enforce vertical layout padding blocks inside Google Docsspacer_block = '<div style="font-size: 4.5pt; line-height: 4.5pt; height: 4.5pt;"> </div>'# --- ROW 1: Hebrew Text / Reference ---html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">')if is_first:html_output.append(f' <td style="{heading_cell_style}">{spacer_block} {reference} {spacer_block}</td>')for word in current_chunk:html_output.append(f' <td style="{hebrew_cell_style}">{spacer_block} {word.get("hebrew", " ")} {spacer_block}</td>')html_output.append(' </tr>')# --- ROW 2: English Structural Stack ---html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">')if is_first:formatted_manuscript = manuscript.replace(" ", "<br>") if " " in manuscript else manuscripthtml_output.append(f' <td style="{heading_cell_style}">{spacer_block} {formatted_manuscript} {spacer_block}</td>')is_first = Falsefor word in current_chunk:2 unmodified linest_lat = clean_hyphens_for_docs(word.get("translation", ""))morph = clean_hyphens_for_docs(word.get("morphology", ""))# Triple literal characters enforce un-strippable left/right safety margins in Docscontent = (f'{spacer_block}'f' {t_lit} <br>'f' {t_lat} <br>'f' {morph} 'f'{spacer_block}')html_output.append(f' <td class="english-cell" style="{english_cell_style}">{content}</td>')else:95 unmodified lines}"""with gr.Blocks(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>"13 unmodified lineswith 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")5 unmodified linescopy_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=sticky_session_and_layout_js)submit_btn.click(fn=generate_table_code,4 unmodified linesclear_btn.click(fn=None, inputs=[], outputs=[text_string_input], js="() => ''")copy_btn.click(fn=None, js=copy_js)# GRADIO 6.0 THEME SPECS REQUIRE CSS OVERRIDES EXCLUSIVELY DEPLOYED AT THE LAUNCH CONFIG LEVELdemo.queue().launch(server_name="0.0.0.0", server_port=7860, css=custom_css)