TableGenerator / app.py
fizzickschick's picture
Update app.py
2b7ee03 verified
Raw History Blame Contribute Delete
42.8 kB
import gradio as gr
from google import genai
from google.genai import types
import json
import re
from html import escape
from urllib.parse import quote
# --- 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;
}
/* 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 (BEI Emerald Teal Accent) */
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 (Dark Slate Gray) */
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 (BEI Signature Antique Gold Fill) */
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;
box-shadow: 0 4px 6px -1px rgba(212, 175, 55, 0.2);
height: 42px !important;
}
/* Extended Document Theater Container Canvas Viewport Window */
.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 for Number Inputs (Maximized Size) */
.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;
opacity: 1 !important;
visibility: visible !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;
}
/* Allow full text but force all labels to a uniform two-line height */
.gradio-container label span {
white-space: normal !important;
display: flex !important;
align-items: flex-end !important;
min-height: 42px !important;
}
/* Forces all plain <span> text inside the generated table payload to black */
#table-payload span {
color: #000000 !important;
-webkit-text-fill-color: #000000 !important;
opacity: 1 !important;
}
"""
sticky_session_and_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);
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 }));
input.dispatchEvent(new Event('change', { 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);
}
});
});
document.addEventListener('change', (e) => {
document.querySelectorAll(inputSelectors).forEach((input, index) => {
if (input === e.target) {
localStorage.setItem('table_gen_v6_cache_' + index, input.value);
}
});
});
loadSavedValues();
setTimeout(loadSavedValues, 800);
}, 1200);
}
"""
MODEL_NAME = "gemini-3.1-flash-lite"
def clean_hyphens_for_docs(text_string):
if not text_string:
return ""
return str(text_string).replace("-", "&#8209;")
def parse_gemini_json_response(response_text):
response_text = response_text.strip()
# Remove markdown fences if Gemini accidentally returns them.
response_text = response_text.replace("```json", "").replace("```", "").strip()
# Keep only the JSON array if Gemini adds extra text before or after it.
first_bracket = response_text.find("[")
last_bracket = response_text.rfind("]")
if first_bracket != -1 and last_bracket != -1 and last_bracket > first_bracket:
response_text = response_text[first_bracket:last_bracket + 1]
# Remove illegal trailing commas before } or ].
response_text = re.sub(r",\s*([}\]])", r"\1", response_text)
return json.loads(response_text)
def space_hebrew_letters(root_word):
if not root_word:
return ""
root_word = str(root_word).strip()
if root_word.upper() == "NONE" or root_word == "&nbsp;":
return root_word
return ".".join(list(root_word))
def make_pealim_strongs_root_cell(
strongs_number,
hebrew_word,
word_first_ot_ref,
root_word,
root_strongs_number,
root_first_ot_ref
):
if not strongs_number:
return "&nbsp;"
strongs_number = str(strongs_number).strip()
hebrew_word = str(hebrew_word).strip()
word_first_ot_ref = str(word_first_ot_ref).strip() if word_first_ot_ref else ""
root_word = str(root_word).strip() if root_word else ""
root_strongs_number = str(root_strongs_number).strip() if root_strongs_number else ""
root_first_ot_ref = str(root_first_ot_ref).strip() if root_first_ot_ref else ""
if not root_word or root_word.upper() == "NONE" or root_word == "&nbsp;":
root_word = ""
if not root_strongs_number or root_strongs_number.upper() == "NONE" or root_strongs_number == "&nbsp;":
root_strongs_number = ""
# Top Strong's number searches Pealim for the actual Hebrew word in this column.
word_pealim_url = f"https://www.pealim.com/search/?q={quote(hebrew_word)}"
# Bottom root Strong's number searches Pealim for the Hebrew root word.
root_pealim_url = ""
if root_word:
root_pealim_url = f"https://www.pealim.com/search/?q={quote(root_word)}"
if (
strongs_number.upper() == "NONE"
or strongs_number == "&nbsp;"
or not hebrew_word
or hebrew_word == "&nbsp;"
):
word_strongs_display = escape(strongs_number)
else:
word_strongs_display = (
f'<a href="{word_pealim_url}" '
f'target="_blank" '
f'rel="noopener noreferrer" '
f'style="color: #0000EE !important; '
f'font-family: \'Times New Roman\', serif !important; '
f'font-size: 18px !important; '
f'text-decoration: underline !important;">'
f'{escape(strongs_number)}'
f'</a>'
)
word_first_ref_display = make_biblegateway_kjv_link(word_first_ot_ref)
if word_first_ref_display:
word_first_ref_display = f"<br>{word_first_ref_display}"
# separator_display = (
# f'<div style="'
# f'border-top: 1px solid #b7b7b7 !important; '
# f'height: 1px !important; '
# f'line-height: 1px !important; '
# f'margin: 3px 8px 2px 8px !important; '
# f'padding: 0 !important;">'
# f'</div>'
# )
if root_word:
spaced_root = space_hebrew_letters(root_word)
# Plain display only. The Hebrew root itself is NOT clickable.
root_display = (
f'<br>'
f'<div dir="rtl" '
f'style="font-family: \'Times New Roman\', serif !important; '
f'font-size: 18px !important; '
f'font-weight: normal !important; '
f'color: #000000 !important; '
f'-webkit-text-fill-color: #000000 !important; '
f'opacity: 1 !important; '
f'text-decoration: none !important; '
f'line-height: 1.0 !important; '
f'padding: 0 !important;">'
f'{escape(spaced_root)}'
f'</div>'
)
else:
root_display = ""
if root_strongs_number and root_pealim_url:
root_strongs_display = (
f'<br>'
f'<a href="{root_pealim_url}" '
f'target="_blank" '
f'rel="noopener noreferrer" '
f'style="color: #0000EE !important; '
f'font-family: \'Times New Roman\', serif !important; '
f'font-size: 18px !important; '
f'text-decoration: underline !important;">'
f'{escape(root_strongs_number)}'
f'</a>'
)
elif root_strongs_number:
root_strongs_display = f'<br>{escape(root_strongs_number)}'
else:
root_strongs_display = ""
root_first_ref_display = make_biblegateway_kjv_link(root_first_ot_ref)
if root_first_ref_display:
root_first_ref_display = f"<br>{root_first_ref_display}"
return (
word_strongs_display
+ word_first_ref_display
# + separator_display
+ root_display
+ root_strongs_display
+ root_first_ref_display
)
def abbreviate_bible_reference(reference_text):
if not reference_text:
return ""
reference_text = str(reference_text).strip()
book_abbreviations = {
"Genesis": "Gen",
"Exodus": "Exod",
"Leviticus": "Lev",
"Numbers": "Num",
"Deuteronomy": "Deut",
"Joshua": "Josh",
"Judges": "Judg",
"Ruth": "Ruth",
"1 Samuel": "1 Sam",
"2 Samuel": "2 Sam",
"1 Kings": "1 Kgs",
"2 Kings": "2 Kgs",
"1 Chronicles": "1 Chr",
"2 Chronicles": "2 Chr",
"Ezra": "Ezra",
"Nehemiah": "Neh",
"Esther": "Esth",
"Job": "Job",
"Psalms": "Ps",
"Psalm": "Ps",
"Proverbs": "Prov",
"Ecclesiastes": "Eccl",
"Song of Solomon": "Song",
"Song of Songs": "Song",
"Isaiah": "Isa",
"Jeremiah": "Jer",
"Lamentations": "Lam",
"Ezekiel": "Ezek",
"Daniel": "Dan",
"Hosea": "Hos",
"Joel": "Joel",
"Amos": "Amos",
"Obadiah": "Obad",
"Jonah": "Jonah",
"Micah": "Mic",
"Nahum": "Nah",
"Habakkuk": "Hab",
"Zephaniah": "Zeph",
"Haggai": "Hag",
"Zechariah": "Zech",
"Malachi": "Mal"
}
for full_book_name, abbreviated_book_name in book_abbreviations.items():
if reference_text.startswith(full_book_name + " "):
return reference_text.replace(full_book_name, abbreviated_book_name, 1)
return reference_text
def make_biblegateway_kjv_link(reference_text):
if not reference_text:
return ""
reference_text = str(reference_text).strip()
if (
not reference_text
or reference_text.upper() == "NONE"
or reference_text == "&nbsp;"
):
return ""
display_reference = abbreviate_bible_reference(reference_text)
biblegateway_url = (
f"https://www.biblegateway.com/passage/"
f"?search={quote(reference_text)}&version=KJV"
)
return (
f'<a href="{biblegateway_url}" '
f'target="_blank" '
f'rel="noopener noreferrer" '
f'style="color: #0000EE !important; '
f'font-family: \'Times New Roman\', serif !important; '
f'font-size: 12px !important; '
f'line-height: 1.0 !important; '
f'text-decoration: underline !important;">'
f'{escape(display_reference)}'
f'</a>'
)
def calculate_clean_chunks(words_data):
chunks = []
current_chunk = []
word_index = 0
while word_index < len(words_data):
current_limit = 4 if len(chunks) == 0 else 5
word = words_data[word_index]
current_chunk.append(word)
if len(current_chunk) == current_limit:
chunks.append(current_chunk)
current_chunk = []
word_index += 1
if current_chunk:
chunks.append(current_chunk)
return chunks
def build_html_tables(manuscript, reference, words_data):
column_width_in = 1.0
total_slots = 5
total_table_width_in = 5.0
# Table container locked to LTR flow with legacy centering for Docs - NO, WAIT! Gemini said this is why they're backwards. So I changed to RTL
table_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 !important; border-spacing: 0 !important; "
"direction: rtl; border: 1pt solid #b7b7b7 !important; background-color: #ffffff; "
"line-height: 1.0 !important; height: auto; "
"margin-top: 0 !important; margin-bottom: 0 !important; "
"margin-left: auto !important; margin-right: auto !important;"
)
base_cell = "border: 1pt solid #b7b7b7 !important; 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: 18px !important; color: #000000 !important; text-align: right !important; vertical-align: middle; padding-top: 0.069in !important; padding-bottom: 0.069in !important; padding-left: 0.069in !important; padding-right: 0.069in !important; {base_cell}"
english_cell_style = f"font-family: Arial, sans-serif !important; font-size: 11px !important; color: #000000 !important; text-align: center !important; vertical-align: top; line-height: 1.0 !important; {base_cell}"
strongs_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: center !important; vertical-align: middle; line-height: 1.15 !important; {base_cell}"
heading_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: center !important; vertical-align: middle; line-height: 1.0 !important; {base_cell}"
# Outer container explicitly forces LTR alignment so Docs will center it
html_output = ['<div id="table-payload" class="white-canvas" dir="rtl" align="center" style="background-color: #ffffff; padding: 15px; border-radius: 8px; display: block; width: 100%; box-sizing: border-box; text-align: center; direction: rtl;">']
table_chunks = calculate_clean_chunks(words_data)
for idx, current_chunk in enumerate(table_chunks):
# Open a new table for each chunk with align="center" and dir="ltr"
html_output.append(f'<table dir="rtl" align="center" style="{table_style}" cellpadding="0" 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": "&nbsp;",
"transliteration": "&nbsp;",
"translation": "&nbsp;",
"morphology": "&nbsp;",
"strongs": "&nbsp;",
"word_first_ot_ref": "&nbsp;",
"root": "&nbsp;",
"root_strongs": "&nbsp;",
"root_first_ot_ref": "&nbsp;"
})
allocated_slots += 1
# --- ROW 1: Hebrew Word Units (Right-Justified within their cells) ---
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 dir="rtl" style="{hebrew_cell_style}">{word.get("hebrew", "&nbsp;")}</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 manuscript
html_output.append(f' <td style="{heading_cell_style}">{formatted_manuscript}</td>')
is_first = False
for word in current_chunk:
if word.get("hebrew") != "&nbsp;" 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" dir="ltr" style="{english_cell_style}">{content}</td>')
else:
html_output.append(f' <td dir="ltr" style="{english_cell_style}">&nbsp;</td>')
html_output.append(' </tr>')
# --- ROW 3: Strong\'s Concordance Number Links ---
html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">')
if idx == 0:
html_output.append(f' <td style="{strongs_cell_style}">&nbsp;</td>')
for word in current_chunk:
hebrew_word = word.get("hebrew", "&nbsp;")
if hebrew_word != "&nbsp;" and hebrew_word != " ":
strongs_number = word.get("strongs", "NONE")
word_first_ot_ref = word.get("word_first_ot_ref", "NONE")
root_word = word.get("root", "NONE")
root_strongs_number = word.get("root_strongs", "NONE")
root_first_ot_ref = word.get("root_first_ot_ref", "NONE")
strongs_root_cell = make_pealim_strongs_root_cell(
strongs_number,
hebrew_word,
word_first_ot_ref,
root_word,
root_strongs_number,
root_first_ot_ref
)
html_output.append(f' <td dir="ltr" style="{strongs_cell_style}">{strongs_root_cell}</td>')
else:
html_output.append(f' <td dir="ltr" style="{strongs_cell_style}">&nbsp;</td>')
html_output.append(' </tr>')
# Close the table for this chunk and inject a small spacer
html_output.append(
"</table>"
"<div style=\"font-family: 'Times New Roman', serif !important; "
"font-size: 4pt !important; "
"line-height: 4pt !important; "
"height: 4pt !important; "
"margin: 0 !important; "
"padding: 0 !important; "
"background-color: #ffffff !important;\">&nbsp;</div>"
)
html_output.append('</div>')
return "".join(html_output)
"""
def build_html_tables(manuscript, reference, words_data):
column_width_in = 1.0
total_slots = 7
total_table_width_in = 7.0
table_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 !important; border-spacing: 0 !important; "
"direction: rtl; border: 1pt solid #b7b7b7 !important; background-color: #ffffff; "
"line-height: 1.0 !important; height: auto; "
"margin-top: 0 !important; margin-bottom: 0 !important; "
"margin-left: auto !important; margin-right: auto !important;"
)
base_cell = "border: 1pt solid #b7b7b7 !important; 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: 18px !important; color: #000000 !important; text-align: right !important; vertical-align: middle; padding-right: 0.069in !important;{base_cell}"
hebrew_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: right !important; vertical-align: middle; padding-top: 0.069in !important; padding-bottom: 0.069in !important; padding-left: 0.069in !important; padding-right: 0.069in !important; {base_cell}"
english_cell_style = f"font-family: Arial, sans-serif !important; font-size: 11px !important; color: #000000 !important; text-align: center !important; vertical-align: top; line-height: 1.0 !important; {base_cell}"
strongs_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !important; color: #000000 !important; text-align: center !important; vertical-align: middle; line-height: 1.15 !important; {base_cell}"
heading_cell_style = f"font-family: 'Times New Roman', serif !important; font-size: 18px !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):
# Open a new table for each chunk
html_output.append(f'<table style="{table_style}" padding: 0.069in;" align="center" cellpadding="0" 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": "&nbsp;",
"transliteration": "&nbsp;",
"translation": "&nbsp;",
"morphology": "&nbsp;",
"strongs": "&nbsp;",
"word_first_ot_ref": "&nbsp;",
"root": "&nbsp;",
"root_strongs": "&nbsp;",
"root_first_ot_ref": "&nbsp;"
})
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", "&nbsp;")}</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 manuscript
html_output.append(f' <td style="{heading_cell_style}">{formatted_manuscript}</td>')
is_first = False
for word in current_chunk:
if word.get("hebrew") != "&nbsp;" 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}">&nbsp;</td>')
html_output.append(' </tr>')
# --- ROW 3: Strong's Concordance Number Links ---
html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">')
if idx == 0:
html_output.append(f' <td style="{strongs_cell_style}"></td>')
# html_output.append(
# f' <td style="{strongs_cell_style}">'
# f'# Strong&rsquo;s<br>'
# f'1st Use<br>'
# f'<div style="border-top: 1px solid #b7b7b7; margin: 3px 8px 2px 8px;"></div>'
# f'Root Word<br>'
# f'# Root Strong&rsquo;s<br>'
# f'Root 1st Use'
# f'</td>'
# )
for word in current_chunk:
hebrew_word = word.get("hebrew", "&nbsp;")
if hebrew_word != "&nbsp;" and hebrew_word != " ":
strongs_number = word.get("strongs", "NONE")
word_first_ot_ref = word.get("word_first_ot_ref", "NONE")
root_word = word.get("root", "NONE")
root_strongs_number = word.get("root_strongs", "NONE")
root_first_ot_ref = word.get("root_first_ot_ref", "NONE")
strongs_root_cell = make_pealim_strongs_root_cell(
strongs_number,
hebrew_word,
word_first_ot_ref,
root_word,
root_strongs_number,
root_first_ot_ref
)
html_output.append(f' <td style="{strongs_cell_style}">{strongs_root_cell}</td>')
else:
html_output.append(f' <td style="{strongs_cell_style}">&nbsp;</td>')
html_output.append(' </tr>')
# Close the table for this chunk and inject only a small one line 4px spacer...DJM
html_output.append(
"</table>"
"<div style=\"font-family: 'Times New Roman', serif !important; "
"font-size: 4pt !important; "
"line-height: 4pt !important; "
"height: 4pt !important; "
"margin: 0 !important; "
"padding: 0 !important; "
"background-color: #ffffff !important;\">&nbsp;</div>"
)
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 "<p style='color:red; text-align:center;'>❌ Error: Please enter your Gemini API key.</p>", gr.update(visible=False)
chapter = max(1, int(chapter))
verse = max(1, int(verse))
reference_header = f"{book} {chapter}:{verse}"
try:
client = genai.Client(api_key=api_key)
system_instruction_text = (
"You are a strict linguistic conversion engine mapping raw Hebrew text into clean JSON lists. "
"You map words from right to left into transliteration, translation, and morphology components "
"matching your specific instructions. Return no conversation or markdown code block markers."
)
prompt = f"""
Analyze this Hebrew text string word-by-word from right to left: "{text_string}"
Populate a flat JSON array containing objects matching this schema format exactly:
{{
{{
{{
"hebrew": "The exact raw Hebrew word token from the input text",
"transliteration": "The syllabic transliteration strictly following the provided rules",
"translation": "The direct lowercase contextual translation",
"morphology": "The clean root-only structural morphology format string",
"strongs": "The best matching Hebrew Strong's Concordance number for the actual Hebrew word or lexical term used in this column, formatted like H7225, or NONE if no reliable Strong's number applies",
"word_first_ot_ref": "The first Old Testament reference where this actual Hebrew word or lexical term appears, formatted like Genesis 1:1, or NONE if uncertain",
"root": "The Hebrew root word behind the actual Hebrew word, written in Hebrew consonants only with no vowel points, no spaces, no hyphens, and no explanations",
"root_strongs": "The best matching Hebrew Strong's Concordance number for the Hebrew root word, formatted like H7218, or NONE if no reliable root Strong's number applies",
"root_first_ot_ref": "The first Old Testament reference where this Hebrew root word appears, formatted like Genesis 2:10, or NONE if uncertain"
}}
}}
}}
STRICT BEI TRANSLITERATION MAPPING TABLES:
- 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: "."
- HIRIQ_YOD: "ee", TSERE_YOD: "ey", SEGOL_YOD: "ey", SHUREQ: "oo", HOLAM_VAV: "o", QAMATS_HE: "a", SEGOL_HE: "eh", TSERE_HE: "e", MS_SUFX: "av"
- ALEF: "", BET: "v", BET_DAGESH: "b", GIMEL: "g", DALET: "d", HE: "h", VAV: "v", ZAYIN: "z", HET: "kh", TET: "t", YOD: "y", KAF: "kh", KAF_DAGESH: "k", FINAL_KAF: "kh", LAMED: "l", MEM: "m", FINAL_MEM: "m", NUN: "n", FINAL_NUN: "n", SAMEKH: "s", AYIN: "", PE: "f", PE_DAGESH: "p", FINAL_PE: "f", TSADI: "ts", FINAL_TSADI: "ts", QOF: "q", RESH: "r", SHIN: "sh", SIN: "s", TAV: "t"
- SPECIAL CLUSTERS: שּׁ = "sh", צּ = "ts", יְרוּשָׁלִַם = "yᵉ·roo·sha·la̱·yeem", יֵשׁוּעַ = "Yey·shoo̱·a"
- DIVINE_NAME: "Yᵉ·ho·va̱h", DIVINE_NAME_ELOHIM: "Ye·ho·vee̱h"
CRITICAL JSON OUTPUT RULES:
- Return ONLY one valid JSON array.
- Do not return markdown.
- Do not return explanations.
- Do not wrap the JSON in ```json fences.
- Do not put trailing commas after the final field in any object.
- Do not put trailing commas after the final object in the array.
- Every object must contain exactly these fields: hebrew, transliteration, translation, morphology, strongs, word_first_ot_ref, root, root_strongs, root_first_ot_ref.
CRITICAL SYLLABLE SEPARATOR RULE:
- You MUST use the middle dot symbol (·, ALT+0183) exclusively to separate syllables in the transliteration field (e.g., "ga·dol", "mi·bey̱t", "ha·me·le̱kh"). Never vary from this separator mark.
CRITICAL ROOT-ONLY MORPHOLOGY LOGIC:
- Report ONLY on the core 'root' properties of a word unit. Strip out all prefix or suffix clutter from the morphology description (e.g. for 'mi'beyt', evaluate only 'house' -> 'nms constr').
- Abbreviations: verb=v, noun=n, adverb=adv, adjective=adj, conjunction=conj, particle=part, preposition=prep, pronoun=pron, proper name=name, definite direct object=ddom, number=#, interjection=intj, construct=constr. Do not include periods.
- Binyan forms: Pa'al, Nif'al, Pi'el, Pu'al, Hif'il, Huf'al, Hitpa'el. Never use "Qal".
- Tense forms: perfect=perf, imperfect=imp, participle=ptcpl.
- Structure formatting: part_of_speech + space + binyan (if app) + space + tense (if app) + person/gender/number combo (no inner spacing, e.g., '3ms', '2mp'). Example: "v Pa'al perf 3ms" or "n mp constr".
CRITICAL STRONG'S CONCORDANCE LOGIC:
- Add a "strongs" field to every JSON object.
- The "strongs" field must identify the best matching Hebrew Strong's Concordance number for the actual Hebrew word/term in the column.
- Do NOT automatically use the root Strong's number for the "strongs" field.
- The "strongs" field should represent the lexical term being translated in that column, including derived nouns, names, particles, verbs, adjectives, or other Hebrew dictionary terms.
- Example: רֵאשִׁית should use strongs H7225 because the word/term means beginning.
- Example: the root behind רֵאשִׁית is ראש, and that root should use root_strongs H7218.
- Example: for a simple verb like אמר, the word Strong's number and root Strong's number may both be H559. That is acceptable only when they truly match.
- Format Hebrew Strong's numbers as H followed by digits, such as H7225.
- If no reliable Strong's number applies, return "NONE".
- Do not guess wildly. Prefer "NONE" when uncertain.
CRITICAL HEBREW ROOT WORD LOGIC:
- Add a "root" field to every JSON object.
- The "root" field must contain the Hebrew root behind the actual Hebrew word in that column.
- Return the root in Hebrew consonants only.
- Do not include vowel points, cantillation marks, spaces, hyphens, transliteration, English, labels, or explanatory notes.
- For verbs, prefer the shoresh/root, usually three Hebrew consonants when applicable.
- For derived nouns, identify the underlying Hebrew root, not merely the same noun repeated.
- Example: for רֵאשִׁית, return root ראש.
- Example: for ברא, return root ברא.
- If no reliable Hebrew root applies, return "NONE".
CRITICAL ROOT STRONG'S CONCORDANCE LOGIC:
- Add a "root_strongs" field to every JSON object.
- The "root_strongs" field must identify the best matching Hebrew Strong's Concordance number for the Hebrew root word in the "root" field.
- Do NOT simply copy the "strongs" field unless the word Strong's number and root Strong's number are truly the same.
- Example: רֵאשִׁית should use strongs H7225, root ראש, and root_strongs H7218.
- Example: ברא may use strongs H1254, root ברא, and root_strongs H1254 because the word and root are the same lexical item.
- Format Hebrew Strong's numbers as H followed by digits, such as H7218.
- If no reliable root Strong's number applies, return "NONE".
- Do not guess wildly. Prefer "NONE" when uncertain.
CRITICAL FIRST OLD TESTAMENT OCCURRENCE LOGIC:
- Add a "word_first_ot_ref" field to every JSON object.
- Add a "root_first_ot_ref" field to every JSON object.
- "word_first_ot_ref" must identify the first Old Testament / Hebrew Bible location where the actual Hebrew word or lexical term appears.
- "root_first_ot_ref" must identify the first Old Testament / Hebrew Bible location where the Hebrew root word appears.
- Use KJV book names and reference formatting, such as Genesis 1:1, Exodus 3:14, Deuteronomy 6:4.
- Do not include the verse text.
- Do not include Hebrew text in these reference fields.
- If you are uncertain, return "NONE".
- Do not simply copy "word_first_ot_ref" into "root_first_ot_ref" unless they are truly the same first occurrence.
"""
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
)
)
# response_text = response.text.strip()
# print("RAW GEMINI RESPONSE:")
# print(response_text)
# raw_json_data = json.loads(response_text)
raw_json_data = parse_gemini_json_response(response.text)
final_table_html = build_html_tables(manuscript_name, reference_header, raw_json_data)
return final_table_html, gr.update(visible=True)
except Exception as e:
return f"<p style='color:red; text-align:center;'>❌ Error: {str(e)}</p>", gr.update(visible=False)
copy_btn_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 BEI padding alignment!');
}).catch(err => { alert('❌ Clipboard Copy Failed: ' + err); });
}
"""
with gr.Blocks(title="Shorashim Pro Workspace") as demo:
# Header Panel [Marker 1]
gr.HTML(
"<div style='background: linear-gradient(135deg, #111827 0%, #0b0f19 100%); padding: 10px; border-radius: 6px; margin-bottom: 10px; text-align: center; border: 1px solid #d4af37;'>"
"<h1 style='margin: 0 0 2px 0; font-size: 30px; font-weight: 700; color: #d4af37;'>📖 Shorashim Pro Workspace</h1>"
"<p style='margin: 0; font-size: 14px; color: #9ca3af;'>Convert raw Hebrew text strings into BEI style interlinear tables</p>"
"</div>"
)
# API Verification Guideline Box
with gr.Accordion("🔑 API Key Setup Instructions", open=True):
gr.Markdown(
"1. Visit [Google AI Studio](https://aistudio.google.com/).\n\n"
"2. Click the **Get API Key** button on the left menu.\n\n"
"3. Click **Create API Key** (or use your default layout string).\n\n"
"4. Copy your string token and paste it into the input box below. "
"Click <a href='https://youtu.be/Uyn-P2nRvDA?si=LQi2U0tLsY-zE7a9' target='_blank' style='color: #d4af37; font-weight: bold; text-decoration: underline;'>here</a> to view a short how-to video."
)
# --- HORIZONTAL COCKPIT INPUT ROW ---
with gr.Row():
api_key_input = gr.Textbox(label="🔑 Gemini API Key", type="password", placeholder="Paste your Gemini API key here", scale=2)
manuscript_input = gr.Textbox(label="📜 Manuscript Reference", value="Marseilles MS-24", scale=2)
book_input = gr.Textbox(label="📚 Bible Book", value="Luke", scale=2)
# Chapter and Verse as Number inputs for spinner functionality
chapter_input = gr.Number(label="Chapter", value=11, minimum=1, step=1, precision=0, scale=1)
verse_input = gr.Number(label="Verse", value=49, minimum=1, step=1, precision=0, scale=1)
text_string_input = gr.Textbox(label="📝 Hebrew Verses Input String", placeholder="Paste line segments...", scale=4)
# --- CONTROL PLATFORM HUB ---
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)
# --- PREVIEW VIEWPORT ---
with gr.Column(elem_classes=["theater-viewport"]):
output_html = gr.HTML(label="Shorashim Frame Canvas")
demo.load(fn=None, inputs=None, outputs=None, js=sticky_session_and_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=[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_btn_js)
demo.queue().launch(server_name="0.0.0.0", server_port=7860, css=custom_css)