Spaces:
Running
Running
Update app.py
Browse filesOkay now we're cooking with gas! I think Gemini is finally understanding my column and table width requirements and my cell padding constraint (0.069 inches on all four sides)
109 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421432 unmodified lines14614714814915015115215315415515615715815916016116216316416516616716816917017117217317499 unmodified lines274275276277278279280109 unmodified linesreturn ""return str(text_string).replace("-", "‑")def calculate_dynamic_chunks(words_data, base_limit=7):"""Splits words into clean layout chunks of up to 7 slots."""chunks = []current_chunk = []word_index = 0while word_index < len(words_data):current_limit = 6 if len(chunks) == 0 else 7word = words_data[word_index]current_chunk.append(word)if len(current_chunk) == current_limit:chunks.append(current_chunk)current_chunk = []word_index += 1if current_chunk:chunks.append(current_chunk)return chunksdef build_html_tables(manuscript, reference, words_data):total_table_width_in = 7.0# Static overall structural boundaries matching your publishing layout template# Native margins forced to auto and align center for seamless Google Docs insertiontable_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; "2 unmodified lines)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;">']table_chunks = calculate_dynamic_chunks(words_data, base_limit=7)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)# Symmetrical filler keeps trailing short tables exactly 7 columns wideif is_last_table:while allocated_slots < 7:current_chunk.append({"hebrew": " ", "transliteration": " ", "translation": " ", "morphology": " "})allocated_slots += 1html_output.append(f'<table style="{table_style}" align="center">')# Rule: Every column is locked to exactly 1.0 inch wide to guarantee a 7.0 inch total widthhtml_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>')# Rule: Exact 0.069in cell padding on all 4 sides + word wrap strictly disabled (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}"99 unmodified linesyield 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)109 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921932 unmodified lines19619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324499 unmodified lines344345346347348349350109 unmodified linesreturn ""return str(text_string).replace("-", "‑")def get_minimum_column_width_in(word_dict, is_reference_block=False, ref_text="", ms_text=""):"""Measures character counts to calculate the physical minimum widthin inches needed to hold a column's text without any word-wrapping."""# System assumptions: 1 character in Arial 14.6px is approx 0.075 inches wide.# Hebrew characters at 24px are much wider, approx 0.145 inches per character.char_width_in = 0.075hebrew_char_width_in = 0.145# Base cell padding safety allowance: 0.069 inches on both sides = 0.138 inches totalpadding_buffer_in = 0.069 * 2if is_reference_block:max_chars = max(len(ref_text), len(ms_text))return (max_chars * char_width_in) + padding_buffer_inw_hebrew = len(word_dict.get("hebrew", "")) * hebrew_char_width_inw_translit = len(word_dict.get("transliteration", "")) * char_width_inw_trans = len(word_dict.get("translation", "")) * char_width_inw_morph = len(word_dict.get("morphology", "")) * char_width_inmax_content_width = max(w_hebrew, w_translit, w_trans, w_morph)# Give it a baseline minimum size if it's mostly blankreturn max(max_content_width, 0.65) + padding_buffer_indef calculate_recursive_table_chunks(words_data, reference, manuscript):"""ESSENTIAL PROCEDURE: Groups words dynamically. If a 7-slot row's minimum un-wrappedwidths exceed 7.0 inches total, the last word drops down to the next row group recursively."""total_allowed_width_in = 7.0final_row_chunks = []# Work with a shallow copy of the word array list so we can shift items dynamicallyword_pool = list(words_data)while len(word_pool) > 0:is_first_row = (len(final_row_chunks) == 0)# First row has 1 slot reserved for reference, leaving up to 6 word positions.# Other rows take up to 7 word positions.max_word_limit = 6 if is_first_row else 7# Pull out a trial row slicecurrent_row_words = word_pool[:max_word_limit]# Recursive check loop to pull words out until the row fits into 7 incheswhile len(current_row_words) > 1:minimum_widths = []if is_first_row:ref_min = get_minimum_column_width_in({}, is_reference_block=True, ref_text=reference, ms_text=manuscript)minimum_widths.append(ref_min)for word in current_row_words:w_min = get_minimum_column_width_in(word)minimum_widths.append(w_min)total_required_row_width = sum(minimum_widths)# Scenario A: The columns fit safely within 7 inches without wrapping text!if total_required_row_width <= total_allowed_width_in:break# Scenario B: Over 7 inches! Move the last word down to the next table row.current_row_words.pop()# Commit the finalized word slice to this table blockfinal_row_chunks.append(current_row_words)# Delete the processed slice off the front of our remaining word poolword_pool = word_pool[len(current_row_words):]return final_row_chunksdef build_html_tables(manuscript, reference, words_data):total_table_width_in = 7.0total_slots = 7table_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; "2 unmodified lines)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;">']# RUN RECURSIVE LAYOUT SPLITTING PROCEDUREtable_chunks = calculate_recursive_table_chunks(words_data, reference, manuscript)for idx, current_chunk in enumerate(table_chunks):is_first = (idx == 0)is_last_table = (idx == len(table_chunks) - 1)# Step 1: Establish baseline minimum requirements to verify absolute protection boundariesslot_minimums = []if is_first:ref_min = get_minimum_column_width_in({}, is_reference_block=True, ref_text=reference, ms_text=manuscript)slot_minimums.append(ref_min)for word in current_chunk:slot_minimums.append(get_minimum_column_width_in(word))# Symmetrical filler pads trailing tables up to exactly 7 columns wideif is_last_table:while (len(current_chunk) + (1 if is_first else 0)) < total_slots:current_chunk.append({"hebrew": " ", "transliteration": " ", "translation": " ", "morphology": " "})slot_minimums.append(0.75) # Standard padding size allocation score for blank boxes# Step 2 & 3: Run Proportional Balancing to scale the table footprint to exactly 7.0 inches widetotal_minimum_score = sum(slot_minimums)calculated_widths = []for min_w in slot_minimums:# Scale proportionally so the combined columns perfectly lock at 7 inchesallocated_width = (min_w / total_minimum_score) * total_table_width_incalculated_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)html_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: Exact 0.069in padding on all sides, text wrap disabled via nowrap, box size clampedbase_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}"99 unmodified linesyield 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("Executing Dynamic Recursive Word-Drop Pipeline")), "", gr.update(visible=False)try:final_table_html = build_html_tables(manuscript_name, reference_header, raw_json_data)
app.py+100-30