Spaces:
Running
Running
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032044 unmodified lines209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262import gradio as grfrom google import genaifrom google.genai import typesimport timeimport json# --- BEI Premium Theme & Horizontal Interface Custom 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;}/* Polished Minimalist Progress & Processing Window */.progress-container {padding: 12px;text-align: center;border: 1px solid #d4af37;border-radius: 6px;background-color: #111827;margin-bottom: 12px;}/* White Canvas Table Wrapper for clear document viewing */.white-canvas {display: flex;justify-content: center;align-items: center;width: 100%;}/* Forcing BEI Charcoal/Onyx Background to Total UI Framework */.gradio-container, html, body {background-color: #0b0f19 !important;font-family: 'Segoe UI', system-ui, -apple-system, sans-serif !important;max-width: 98% !important;}/* Antique Gold Typography Highlights */.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;}/* Setup Accordion Boxes for Dark Mode Layout */.label-wrap, .accordion-trigger {background-color: #111827 !important;border: 1px solid #1f2937 !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 */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 */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 */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;height: 42px !important;}.theater-viewport {border: 1px solid #1f2937 !important;border-radius: 8px !important;padding: 16px !important;background-color: #0d1321 !important;margin-top: 12px !important;min-height: 48vh !important;}/* Custom Gold Spinner Arrows */.gradio-container input[type="number"]::-webkit-inner-spin-button,.gradio-container input[type="number"]::-webkit-outer-spin-button {-webkit-appearance: none !important;appearance: none !important;display: block !important;width: 32px !important;height: 100% !important;min-height: 42px !important;background-color: #111827 !important;background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23d4af37'%3E%3Cpath d='M12 3l-8 8h16zM12 21l-8-8h16z'/%3E%3C/svg%3E") !important;background-size: 24px !important;background-repeat: no-repeat !important;background-position: center !important;cursor: pointer !important;border-left: 1px solid #1f2937 !important;}.gradio-container label span {white-space: normal !important;display: flex !important;align-items: flex-end !important;min-height: 42px !important;}"""sticky_session_and_layout_js = """function() {const removeHeaderBlock = () => {const hfHeader = document.querySelector('header');if (hfHeader) hfHeader.remove();};removeHeaderBlock();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 }));}});};document.addEventListener('input', (e) => {document.querySelectorAll(inputSelectors).forEach((input, index) => {if (input === e.target) localStorage.setItem('table_gen_v6_cache_' + index, input.value);});});loadSavedValues();}, 1200);}"""MODEL_NAME = "gemini-3.1-flash-lite"def clean_hyphens_for_docs(text_string):return str(text_string).replace("-", "‑") if text_string else ""def calculate_clean_chunks(words_data):chunks = []current_chunk = []word_index = 0while word_index < len(words_data):current_limit = 6 if len(chunks) == 0 else 7current_chunk.append(words_data[word_index])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):column_width_in, total_slots = 1.0, 7table_style = f"width: 7.0in !important; min-width: 7.0in !important; max-width: 7.0in !important; table-layout: fixed !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; height: auto; overflow: hidden; white-space: normal !important;"hebrew_cell = f"font-family: 'Times New Roman', serif !important; font-size: 24px !important; color: #000000 !important; text-align: right !important; {base_cell}"english_cell = f"font-family: Arial, sans-serif !important; font-size: 14.6667px !important; color: #000000 !important; text-align: center !important; {base_cell}"heading_cell = f"font-family: 'Times New Roman', serif !important; font-size: 18.6667px !important; color: #000000 !important; text-align: center !important; {base_cell}"html_output = ['<div id="table-payload" class="white-canvas">']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"><colgroup>')for _ in range(total_slots):html_output.append(f'<col style="width: {column_width_in}in !important;">')html_output.append('</colgroup>')is_first = (idx == 0)is_last_table = (idx == len(table_chunks) - 1)4 unmodified linescurrent_chunk.append({"hebrew": " ", "transliteration": " ", "translation": " ", "morphology": " "})allocated_slots += 1html_output.append('<tr>')if is_first: html_output.append(f'<td style="{heading_cell}">{reference}</td>')for word in current_chunk:html_output.append(f'<td style="{hebrew_cell}">{word.get("hebrew", " ")}</td>')html_output.append('</tr><tr>')if is_first:f_man = manuscript.replace(" ", "<br>") if " " in manuscript else manuscripthtml_output.append(f'<td style="{heading_cell}">{f_man}</td>')for word in current_chunk:if word.get("hebrew") != " ":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="{english_cell}">{content}</td>')else: html_output.append(f'<td style="{english_cell}"> </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: Please enter API key.", gr.update(visible=False)reference_header = f"{book} {chapter}:{verse}"try:client = genai.Client(api_key=api_key)prompt = f'Analyze "{text_string}" into JSON with hebrew, transliteration, translation, morphology fields.'response = client.models.generate_content(model=MODEL_NAME, contents=prompt, config=types.GenerateContentConfig(response_mime_type="application/json"))return build_html_tables(manuscript_name, reference_header, json.loads(response.text.strip())), gr.update(visible=True)except Exception as e: return f"β Error: {str(e)}", gr.update(visible=False)copy_btn_js = "() => { const p = document.getElementById('table-payload').innerHTML; navigator.clipboard.write([new ClipboardItem({'text/html': new Blob([p], {type: 'text/html'})})]); alert('π Copied!'); }"with gr.Blocks(title="Shorashim Pro Workspace") as demo:gr.HTML("<div style='text-align: center; border: 1px solid #d4af37; padding: 10px; border-radius: 6px;'><h1>π Shorashim Pro Workspace</h1></div>")with gr.Row():api_key_input = gr.Textbox(label="π Gemini API Key", type="password", scale=2)manuscript_input = gr.Textbox(label="π Manuscript Reference", scale=2)book_input = gr.Textbox(label="π Bible Book", scale=2)chapter_input = gr.Number(label="Chapter", precision=0, scale=1)verse_input = gr.Number(label="Verse", precision=0, scale=1)text_string_input = gr.Textbox(label="π Hebrew Verses Input String", scale=4)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)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, copy_btn])copy_btn.click(fn=None, js=copy_btn_js)demo.load(js=sticky_session_and_layout_js)demo.queue().launch(server_name="0.0.0.0", server_port=7860, css=custom_css)1234567891011121314151617181920212223242526272829304 unmodified lines353637383940414243444546474849505152535455565758596061626364656667def 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):# Build individual table for each 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)4 unmodified linescurrent_chunk.append({"hebrew": " ", "transliteration": " ", "translation": " ", "morphology": " "})allocated_slots += 1# --- ROW 1: Right-Justified Hebrew Word Units ---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>')# --- ROW 2: Centered English Multi-Line Stacks ---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}">{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>')# Close the table and add the spacerhtml_output.append('</table><br><br>')html_output.append('</div>')return "".join(html_output)
app.py+45-240