Spaces:
Running
Running
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667def build_html_tables(manuscript, reference, words_data):column_width_in = 1.0total_slots = 7total_table_width_in = 7.0table_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;")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}"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)for idx, current_chunk in enumerate(table_chunks):# Start Table for this chunkhtml_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>')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# Row 1: Hebrewhtml_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>')# Row 2: Englishhtml_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}">{formatted_manuscript}</td>')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>')# End Table + Spacerhtml_output.append('</table><br><br>')html_output.append('</div>')return "".join(html_output)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import gradio as grfrom google import genaifrom google.genai import typesimport json# --- CSS and JS definitions ---custom_css = """.subpanel.loading, .generating, div[class*="loading"], .progress-wrap { display: none !important; visibility: hidden !important; height: 0px !important; }.gradio-container, html, body { background-color: #0b0f19 !important; font-family: 'Segoe UI', system-ui, sans-serif !important; max-width: 98% !important; }.gradio-container h1 { color: #d4af37 !important; }input, textarea { border-radius: 6px !important; border: 1px solid #1f2937 !important; background-color: #111827 !important; color: #ffffff !important; }.theater-viewport { border: 1px solid #1f2937 !important; border-radius: 8px !important; padding: 16px !important; background-color: #0d1321 !important; min-height: 48vh !important; }"""sticky_session_and_layout_js = """function() {const removeHeaderBlock = () => { const hfHeader = document.querySelector('header'); if (hfHeader) hfHeader.remove(); };removeHeaderBlock();}"""MODEL_NAME = "gemini-3.1-flash-lite"def clean_hyphens_for_docs(text):return str(text).replace("-", "‑") if text else ""def calculate_clean_chunks(words_data):chunks = []current_chunk = []for i, word in enumerate(words_data):current_limit = 6 if len(chunks) == 0 else 7current_chunk.append(word)if len(current_chunk) == current_limit:chunks.append(current_chunk)current_chunk = []if current_chunk: chunks.append(current_chunk)return chunksdef build_html_tables(manuscript, reference, words_data):table_style = "width: 7.0in !important; border-collapse: collapse; direction: rtl; border: 1pt solid #b7b7b7; background-color: #ffffff; line-height: 1.0 !important;"base_cell = "border: 1pt solid #b7b7b7; padding: 0.069in !important;"html_output = ['<div id="table-payload" class="white-canvas" style="background-color: #ffffff; padding: 15px; width: 100%; box-sizing: border-box; text-align: center;">']table_chunks = calculate_clean_chunks(words_data)for idx, current_chunk in enumerate(table_chunks):html_output.append(f'<table style="{table_style}" align="center" cellpadding="5" cellspacing="0">')is_first = (idx == 0)# Hebrew Rowhtml_output.append('<tr>')if is_first: html_output.append(f'<td style="{base_cell}">{reference}</td>')for word in current_chunk:html_output.append(f'<td style="{base_cell}">{word.get("hebrew", " ")}</td>')html_output.append('</tr>')# English Rowhtml_output.append('<tr>')if is_first:f_man = manuscript.replace(" ", "<br>")html_output.append(f'<td style="{base_cell}">{f_man}</td>')for word in current_chunk:content = f'{clean_hyphens_for_docs(word.get("transliteration", ""))}<br>{clean_hyphens_for_docs(word.get("translation", ""))}<br>{clean_hyphens_for_docs(word.get("morphology", ""))}'html_output.append(f'<td style="{base_cell}">{content}</td>')html_output.append('</tr></table><br><br>')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 "❌ Error: API Key missing.", gr.update(visible=False)try:client = genai.Client(api_key=api_key)prompt = f'Analyze "{text_string}" into JSON.'response = client.models.generate_content(model=MODEL_NAME, contents=prompt, config=types.GenerateContentConfig(response_mime_type="application/json"))return build_html_tables(manuscript_name, f"{book} {chapter}:{verse}", json.loads(response.text.strip())), gr.update(visible=True)except Exception as e: return f"❌ Error: {str(e)}", gr.update(visible=False)with gr.Blocks() as demo:with gr.Row():api_key_input = gr.Textbox(label="API Key", type="password")manuscript_input = gr.Textbox(label="Manuscript")book_input = gr.Textbox(label="Book")chapter_input = gr.Number(label="Ch")verse_input = gr.Number(label="Ver")text_string_input = gr.Textbox(label="Hebrew String")submit_btn = gr.Button("Generate Canvas")output_html = gr.HTML(elem_classes=["theater-viewport"])submit_btn.click(generate_table_code, [api_key_input, manuscript_input, book_input, chapter_input, verse_input, text_string_input], [output_html])demo.launch(server_name="0.0.0.0", server_port=7860, css=custom_css)
app.py+78-53