Spaces:
Running
Running
Upload 2 files
Browse filesClaude maded these for me, based on the code that Gemini produced
Files changed (2)
- app.py+391-163
- requirements.txt+2-1
1234567891011121 unmodified line141516171819204 unmodified lines252627282930311 unmodified line3334353637383940414243444546474849505152535455562 unmodified lines596061626364655 unmodified lines717273747576771 unmodified line798081828384851 unmodified line87888990919293949596974 unmodified lines1021031041051061071086 unmodified lines1151161171181191201211 unmodified line1231241251261271281294 unmodified lines134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390import gradio as grfrom google import genaifrom google.genai import typesimport timeimport json# --- Advanced Premium Dark/Black Theme Engine ---custom_css = """/* Completely hide technical loading bars & indicators */.subpanel.loading, .generating, div[class*="loading"], .progress-wrap {display: none !important;visibility: hidden !important;1 unmodified lineoverflow: hidden !important;}/* Polished Minimalist Progress Window */.progress-container {padding: 20px;text-align: center;4 unmodified linesmargin-bottom: 20px;}/* White Canvas Table Wrapper for clear document viewing */.white-canvas {display: flex;justify-content: center;1 unmodified linewidth: 100%;}/* Forcing Total UI Background to Black */.gradio-container, html, body {background-color: #000000 !important;font-family: 'Segoe UI', system-ui, -apple-system, sans-serif !important;}/* Text elements color correction for readability against black background */.gradio-container h1, .gradio-container h2, .gradio-container h3, .gradio-container p, .gradio-container span {color: #f8fafc !important;}/* Style Accordion Boxes for Dark Mode */.label-wrap, .accordion-trigger {background-color: #111827 !important;border: 1px solid #1f2937 !important;}/* Form Input Field Polishing */input, textarea, select {border-radius: 8px !important;border: 1px solid #374151 !important;2 unmodified linesbox-shadow: inset 0 1px 2px 0 rgba(0, 0, 0, 0.5) !important;}/* Primary Action Button Customization */button.primary {background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%) !important;border: none !important;5 unmodified linestransform: translateY(-1px) !important;}/* Secondary Actions Customization */button.secondary {background-color: #1f2937 !important;border: 1px solid #374151 !important;1 unmodified line}"""# JAVASCRIPT: STRIPIFY HEADERS + BULLETPROOF STORAGE RESCUE MECHANISMsticky_session_and_layout_js = """function() {const removeHeaderBlock = () => {1 unmodified lineconst 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);4 unmodified linesconst 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;6 unmodified linesdocument.addEventListener('input', (e) => {document.querySelectorAll(inputSelectors).forEach((input, index) => {if (input === e.target) {localStorage.setItem('table_gen_v6_cache_' + index, input.value);}});});1 unmodified linedocument.addEventListener('change', (e) => {document.querySelectorAll(inputSelectors).forEach((input, index) => {if (input === e.target) {localStorage.setItem('table_gen_v6_cache_' + index, input.value);}});});4 unmodified lines}"""MODEL_NAME = "gemini-3.1-flash-lite"def clean_hyphens_for_docs(text_string):if not text_string:return ""return str(text_string).replace("-", "‑")def calculate_clean_chunks(words_data):"""Slices words cleanly into rows of 7 slots max."""chunks = []current_chunk = []word_index = 0while word_index < len(words_data):# First table row needs 1 slot for reference block + 6 slots for words = 7 total columnscurrent_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):# Enforce strict 1-inch width to match your layout metricscolumn_width_in = 1.0total_slots = 7total_table_width_in = 7.0# MASTER RULE FIXED: Added cellpadding="5" attribute natively for flawless Google Docs supporttable_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;")# Cell style properties with explicit layout dimensionsbase_cell = "border: 1pt solid #b7b7b7; height: auto; overflow: hidden; white-space: normal !important; word-wrap: break-word !important; box-sizing: border-box !important;"# JUSTIFICATION RULES FIXED: Separated right-alignment from center-alignment styles cleanlyhebrew_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: 20px; border-radius: 8px; display: inline-block; width: 100%; box-sizing: border-box; text-align: center;">']table_chunks = calculate_clean_chunks(words_data)# MASTER FRAME FIXED: Open the structural table block OUTSIDE of the line looping sequencehtml_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>')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 terminal blocks cleanly structuredif is_last_table:while allocated_slots < total_slots:current_chunk.append({"hebrew": " ", "transliteration": " ", "translation": " ", "morphology": " "})allocated_slots += 1# --- ROW 1: Hebrew Text / Reference Block ---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: English Structural Stack / Manuscript Block ---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>')is_first = Falsefor 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:# SYMMETRY FIXED: Render clean empty box frames for trailing positions instead of dropped bordershtml_output.append(f' <td style="{english_cell_style}"> </td>')html_output.append(' </tr>')# Add a thin structural spacer row between text segments to simulate a clean breakif not is_last_table:html_output.append(f'<tr style="height: 12pt !important;"><td colspan="{total_slots}" style="border-left: none; border-right: none; border-bottom: none; height: 12pt !important; background-color: #ffffff;"> </td></tr>')# MASTER FRAME FIXED: Close the table block safely at the very end of processinghtml_output.append('</table>')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:yield gr.update(visible=True, value="<p style='color:red; text-align:center;'>β Error: Please enter your Gemini API key.</p>"), "", gr.update(visible=False)returnstart_time = time.time()gif_url = "https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExM3VwY3Ntc3R0bW91bTh3cHZpY290YmFwNm15M2p6bXF5M3V4eiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9cw/fScIuK8p8YvV5Gg0S8/giphy.gif"reference_header = f"{book} {chapter}:{verse}"def status_html(step_text):elapsed = round(time.time() - start_time, 1)return f"""<div class="progress-container"><img src="{gif_url}" width="40" height="40" style="margin: 0 auto 10px auto; display: block;" /><p style="color: #2563eb; font-weight: bold; font-family: Arial; margin: 0 0 5px 0;">β³ Processing: {step_text}...</p><p style="color: #64748b; font-family: sans-serif; font-size: 13px; margin: 0;">Elapsed Time: {elapsed}s</p></div>"""try:client = genai.Client(api_key=api_key)system_instruction_text = ("You are a strict linguistic conversion engine. You process Hebrew text strings and return clean, ""valid JSON lists mapping each word to its transliteration, translation, and morphology properties. ""Do NOT return any markdown formatting or dialogue.")prompt = f"""Analyze this Hebrew text string word-by-word from right to left:"{text_string}"For each distinct word unit, populate a JSON dictionary matching this schema format exactly:{{"hebrew": "The exact raw Hebrew word token","transliteration": "The structured syllabic transliteration using the provided rules","translation": "The direct lowercase contextual translation (use parenthetical tracking like '(was)' for verbless elements, no 'King Jamesisms')","morphology": "The clean root-only structural morphology string (e.g. 'v Pa'al perf 3ms' or 'n ms suff 2ms')"}}Return your final answer as a flat, standard JSON array containing these word dictionaries.CRITICAL MAQQEF COMPOUND RULE:- Words joined together by a maqqef hyphen (ΦΎ) (for example, 'ΧΦ°ΧΦΆΧͺΦΎΧΦ·ΧΦ°ΦΌΧ©Φ»ΧΧΦΈΦΌΧΦ΄ΧΧ' or 'ΧΦ°ΦΌΧΦΈΧΦΎΧͺΦΌΧΦΉΧ’Φ²ΧΧΦΉΧͺΦ·ΧΦ΄ΧΦ°') MUST remain together as a SINGLE entry in a single column. Do not split them into separate array elements. Combine their translation and morphology properties linearly (e.g., translation: "and-the messengers" or morphology: "conj + ddom + art + n mp").CRITICAL LINGUISTIC SCHEMA RULES:1. When parsing the definite direct object marker 'ΧΦΆΧͺ' or 'ΧΦΆΧͺΦΎ', always set its translation parameter exactly to a single hyphen "-" and its morphology parameter exactly to "ddom".2. For any other standard grammatical particle occurrences, always abbreviate the word 'particle' down to "part".3. Never use the terminology "Qal". For the Pa'al binyan stem, always specify it exactly as "Pa'al" (e.g., 'v Pa'al imperf 3ms').CRITICAL TRANSLITERATION MAPPINGS:- 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: "."- SYLLABLE_SEPARATOR: "Β·", STRESS_MARKER: location: "after-vowel", mark: "Μ±"- DIVINE_NAME: "Yα΅Β·hoΒ·vaΜ±h", DIVINE_NAME_ELOHIM: "YeΒ·hoΒ·veeΜ±h"- Specific translations: Always map 'ΧΦ΅Χ©ΧΧΦΌΧ’Φ·' to transliteration 'yeyΒ·shooΜ±Β·a' and translation 'Yeshua'."""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))raw_json_data = json.loads(response.text.strip())except Exception as e:yield 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 Monolithic Grid Frame Layout")), "", gr.update(visible=False)try:final_table_html = build_html_tables(manuscript_name, reference_header, raw_json_data)except Exception as e:yield gr.update(visible=True, value=f"<p style='color:red; text-align:center;'>β Layout Error: {str(e)}</p>"), "", gr.update(visible=False)returnyield gr.update(visible=False, value=""), final_table_html, gr.update(visible=True)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 formatting!');}).catch(err => { alert('β Clipboard Copy Failed: ' + err); });}"""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>""<p style='margin: 0; font-size: 15px; opacity: 0.8; color: #9ca3af;'>Convert raw Hebrew text into structured, balanced columns.</p>""</div>")with gr.Accordion("π How to find and paste your Gemini API key", open=True):gr.Markdown("1. Go to [Google AI Studio](https://aistudio.google.com/).\n""2. Click **Get API Key** in the menu.\n""3. Copy the **Default API Key** shown on the screen.\n""4. Paste it into the **Gemini API Key** box below.\n\n""πΊ **Need visual help?** Watch this [simple video tutorial](https://youtu.be/Uyn-P2nRvDA?si=_1NqPoJK-sHOVX-W).")with 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")clear_btn = gr.Button("π§Ή Clear Text", variant="secondary")status_panel = gr.HTML(visible=False)gr.Markdown("### π Step 3: Output View & Copy Options")copy_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,inputs=[api_key_input, manuscript_input, book_input, chapter_input, verse_input, text_string_input],outputs=[status_panel, 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)123456789101 unmodified line1213141516174 unmodified lines2223242526271 unmodified line2930313233343536373839404142434445464748492 unmodified lines5253545556575 unmodified lines6364656667681 unmodified line707172737475761 unmodified line7879808182834 unmodified lines888990919293946 unmodified lines1011021031041051061071 unmodified line1091101111121131141154 unmodified lines120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618import gradio as grimport anthropicimport timeimport json# --- Custom CSS (dark theme, preserved from original) ---custom_css = """.subpanel.loading, .generating, div[class*="loading"], .progress-wrap {display: none !important;visibility: hidden !important;1 unmodified lineoverflow: hidden !important;}.progress-container {padding: 20px;text-align: center;4 unmodified linesmargin-bottom: 20px;}.white-canvas {display: flex;justify-content: center;1 unmodified linewidth: 100%;}.gradio-container, html, body {background-color: #000000 !important;font-family: 'Segoe UI', system-ui, -apple-system, sans-serif !important;}.gradio-container h1, .gradio-container h2, .gradio-container h3,.gradio-container p, .gradio-container span {color: #f8fafc !important;}.label-wrap, .accordion-trigger {background-color: #111827 !important;border: 1px solid #1f2937 !important;}input, textarea, select {border-radius: 8px !important;border: 1px solid #374151 !important;2 unmodified linesbox-shadow: inset 0 1px 2px 0 rgba(0, 0, 0, 0.5) !important;}button.primary {background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%) !important;border: none !important;5 unmodified linestransform: translateY(-1px) !important;}button.secondary {background-color: #1f2937 !important;border: 1px solid #374151 !important;1 unmodified line}"""# --- Session persistence + header removal JS ---sticky_session_and_layout_js = """function() {const removeHeaderBlock = () => {1 unmodified lineconst spaceHeader = document.querySelector('div[class*="space-header"]');if (hfHeader) hfHeader.remove();if (spaceHeader) spaceHeader.remove();};removeHeaderBlock();setTimeout(removeHeaderBlock, 500);4 unmodified linesconst inputSelectors = '.gradio-container input, .gradio-container textarea, .gradio-container select';const loadSavedValues = () => {document.querySelectorAll(inputSelectors).forEach((input, index) => {const key = 'table_gen_claude_cache_' + index;const savedValue = localStorage.getItem(key);if (savedValue && input.value !== savedValue) {input.value = savedValue;6 unmodified linesdocument.addEventListener('input', (e) => {document.querySelectorAll(inputSelectors).forEach((input, index) => {if (input === e.target) {localStorage.setItem('table_gen_claude_cache_' + index, input.value);}});});1 unmodified linedocument.addEventListener('change', (e) => {document.querySelectorAll(inputSelectors).forEach((input, index) => {if (input === e.target) {localStorage.setItem('table_gen_claude_cache_' + index, input.value);}});});4 unmodified lines}"""# --- Utility: replace hyphens with non-breaking hyphens for Google Docs ---def clean_hyphens_for_docs(text_string):if not text_string:return ""return str(text_string).replace("-", "‑")# --- Slice word list into table-sized chunks ---def calculate_clean_chunks(words_data):chunks = []current_chunk = []word_index = 0while word_index < len(words_data):# First table: 6 word slots (column 1 = verse reference block)# Subsequent tables: 7 word slotscurrent_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 chunks# --- Build the full HTML table output ---def 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; height: auto; overflow: hidden; ""white-space: normal !important; word-wrap: break-word !important; ""box-sizing: border-box !important; padding: 5pt;")hebrew_cell_style = (f"font-family: 'Times New Roman', serif !important; font-size: 18pt !important; "f"color: #000000 !important; text-align: right !important; vertical-align: middle; {base_cell}")english_cell_style = (f"font-family: Arial, sans-serif !important; font-size: 11pt !important; "f"color: #000000 !important; text-align: center !important; vertical-align: top; "f"line-height: 1.0 !important; {base_cell}")heading_cell_style = (f"font-family: 'Times New Roman', serif !important; font-size: 14pt !important; "f"color: #000000 !important; text-align: center !important; vertical-align: top; "f"line-height: 1.0 !important; {base_cell}")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_clean_chunks(words_data)html_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; 'f'min-width: {column_width_in}in !important; 'f'max-width: {column_width_in}in !important;">')html_output.append(' </colgroup>')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)# Pad final table with empty cells to fill 7 columnsif is_last_table:while allocated_slots < total_slots:current_chunk.append({"hebrew": " ","transliteration": " ","translation": " ","morphology": " "})allocated_slots += 1# --- ROW 1: Hebrew text row ---html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">')if is_first:html_output.append(f' <td rowspan="2" 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: English content row ---html_output.append(' <tr style="height: auto; line-height: 1.0 !important;">')if is_first:# Manuscript name goes in row 2 of col 1, but col 1 is rowspan=2 above,# so we handle manuscript as part of the rowspan cell contentpass # already handled via rowspan above β see note belowfor word in current_chunk:hebrew_val = word.get("hebrew", "")if hebrew_val not in (" ", " ", ""):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 style="{english_cell_style}">{content}</td>')else:html_output.append(f' <td style="{english_cell_style}"> </td>')html_output.append(' </tr>')# Spacer row between tables (4pt Times New Roman equivalent)if not is_last_table:html_output.append(f'<tr style="height: 4pt !important;">'f'<td colspan="{total_slots}" style="border: none; height: 4pt !important; 'f'font-family: \'Times New Roman\', serif; font-size: 4pt; 'f'background-color: #ffffff;"> </td></tr>')html_output.append('</table>')html_output.append('</div>')# Fix: inject manuscript name into the rowspan cell of first table# We do this by post-processing the reference cell to include both ref and manuscriptfull_ref_cell_content = (f'<span style="font-family: \'Times New Roman\', serif; font-size: 14pt; 'f'color: #000000; display: block; text-align: center;">{reference}</span>'f'<span style="font-family: \'Times New Roman\', serif; font-size: 11pt; 'f'color: #000000; display: block; text-align: center; margin-top: 4pt;">{manuscript}</span>')result = "".join(html_output)result = result.replace(f'>{reference}</td>', f'>{full_ref_cell_content}</td>', 1)return result# --- Full Claude system prompt with all rules ---SYSTEM_PROMPT = """You are a strict Hebrew linguistic engine. You process Biblical Hebrew text strings and returnclean, valid JSON arrays. Each element maps one Hebrew word (or maqqef compound) to its transliteration,translation, and morphology. Return ONLY the raw JSON array β no markdown, no explanation, no code fences.=== TRANSLITERATION RULES ===Use these mappings exactly: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"DAGESH: "" (silent)DAGESH_CHAZAQ: falseMAQAF: "-"PASEQ: "Χ"SOF_PASUQ: "."QAMATS_QATAN: "o"FURTIVE_PATAH: "a"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"Consonants:ALEF: "" | BET: "v" | BET_DAGESH: "b" | GIMEL: "g" | DALET: "d" | HE: "h"VAV: "v" | ZAYIN: "z" | HET: "kh" | TET: "t" | YOD: "y" | FINAL_KAF: "kh"KAF: "kh" | KAF_DAGESH: "k" | LAMED: "l" | FINAL_MEM: "m" | MEM: "m"FINAL_NUN: "n" | NUN: "n" | SAMEKH: "s" | AYIN: "" | FINAL_PE: "f"PE: "f" | PE_DAGESH: "p" | FINAL_TSADI: "ts" | TSADI: "ts" | QOF: "q"RESH: "r" | SHIN: "sh" | SIN: "s" | TAV: "t" | TAV_DAGESH: ""Syllable separator: Β· (middle dot)Stress marker: Μ± placed AFTER the stressed vowel (e.g., haΒ·yaΜ±)Special words:ΧΦ°Χ¨ΧΦΌΧ©ΦΈΧΧΦ΄Φ·Χ β yα΅Β·rooΒ·shaΒ·laΜ±Β·yeemΧΦ²ΧΦΉΧ ΦΈΧ β aΒ·doΒ·naiΜ±ΧΦ΅Χ©ΧΧΦΌΧ’Φ· β yeyΒ·shooΜ±Β·a (ALWAYS, no exceptions)Divine Name (ΧΧΧΧ) β Yα΅Β·hoΒ·vaΜ±hDivine Name + Elohim context β YeΒ·hoΒ·veeΜ±hΧΦ·ΧΦΈΦΌΧ©Φ΄ΧΧΧΦ· β haΒ·maΒ·sheeΜ±Β·akhSyllable clusters:Χ©ΦΌΧ β "sh"Χ¦ΦΌ β "ts"Φ·Χ or ΦΈΧ β "ai"=== TRANSLATION RULES ===- Do NOT capitalize any word unless it is a proper name (e.g., Yeshua, Jericho, Aaron, Zechariah).- ΧΦ΅Χ©ΧΧΦΌΧ’Φ· always translates as "Yeshua" β never "Jesus."- Avoid all "King Jamesisms." Base translations strictly on Biblical Hebrew word meanings.- When encountering a verbless clause, supply the implied copula in parentheses: (was), (is), (are), etc.- When a word has multiple valid translations, separate them with a comma and space: e.g., "man, human, Adam"- The definite direct object marker ΧΦΆΧͺ or ΧΦΆΧͺΦΎ: translation = "-", morphology = "ddo"=== MORPHOLOGY RULES ===Primary parts of speech abbreviations (NO periods):verb = vnoun = nadverb = advadjective = adjconjunction = conjparticle = partpreposition = preppronoun = pronproper name = namedefinite direct object = ddonumber = #interjection = intjconstruct = constrBinyan (stem) β use ONLY these spellings:Pa'al, Nif'al, Pi'el, Pu'al, Hif'il, Huf'al, Hitpa'elNEVER use "Qal" β always use "Pa'al"Tense/mood/aspect:perfect = perfimperfect = impparticiple = ptcplPerson-gender-number (concatenated, no spaces between):person: 3, 2, 1gender: m, f, cnumber: s, pExamples:Pa'al perfect 3rd masculine singular verb β v Pa'al perf 3msmasculine plural noun in construct β n mp constrfeminine singular noun β n fsIMPORTANT: When a word has a prefix or suffix (e.g., ΧΦ΄ΧΦ΅ΦΌΧΧͺ = mi + beit),report morphology of the ROOT word only. Do NOT include prefix/suffix morphology.This keeps the output clean and readable.=== MAQQEF RULE ===Words joined by a maqqef (ΦΎ) must be kept as ONE single entry in the JSON array.Do NOT split them. Combine their transliteration, translation, and morphology linearly.Example: ΧΦ°ΦΌΧΦΈΧΦΎΧͺΦΌΧΦΉΧ’Φ²ΧΧΦΉΧͺΦ·ΧΦ΄ΧΦ° stays as one entry.=== OUTPUT FORMAT ===Return a flat JSON array. Each element must have exactly these four keys:"hebrew" β the exact Hebrew word token (or maqqef compound)"transliteration"β syllabic transliteration per the rules above"translation" β lowercase contextual translation (proper names capitalized)"morphology" β root-only morphology stringExample output structure:[{"hebrew": "ΧΦΈΧΦΈΧ","transliteration": "haΒ·yaΜ±","translation": "(there) was","morphology": "v Pa'al perf 3ms"},...]"""# --- Main generation function ---def generate_table_code(api_key, manuscript_name, book, chapter, verse, text_string):if not api_key:yield (gr.update(visible=True, value="<p style='color:red;text-align:center;'>β Please enter your Claude API key.</p>"),"",gr.update(visible=False))returnif not text_string or not text_string.strip():yield (gr.update(visible=True, value="<p style='color:red;text-align:center;'>β Please enter a Hebrew text string.</p>"),"",gr.update(visible=False))returnstart_time = time.time()reference_header = f"{book} {chapter}:{verse}"def status_html(step_text):elapsed = round(time.time() - start_time, 1)return (f"<div class='progress-container'>"f"<p style='color:#2563eb;font-weight:bold;font-family:Arial;margin:0 0 5px 0;'>β³ {step_text}...</p>"f"<p style='color:#64748b;font-family:sans-serif;font-size:13px;margin:0;'>Elapsed: {elapsed}s</p>"f"</div>")yield gr.update(visible=True, value=status_html("Connecting to Claude API")), "", gr.update(visible=False)try:client = anthropic.Anthropic(api_key=api_key)user_prompt = (f'Process this Hebrew text string word-by-word from right to left:\n\n"{text_string}"\n\n'f'Return a JSON array. Each element represents one word (or maqqef compound). 'f'Each element must have keys: "hebrew", "transliteration", "translation", "morphology". 'f'Return ONLY the raw JSON array β no markdown, no explanation, no code fences.')yield gr.update(visible=True, value=status_html("Analyzing Hebrew text with Claude")), "", gr.update(visible=False)message = client.messages.create(model="claude-sonnet-4-20250514",max_tokens=4096,system=SYSTEM_PROMPT,messages=[{"role": "user", "content": user_prompt}])raw_text = message.content[0].text.strip()# Strip markdown fences if Claude included them despite instructionsif raw_text.startswith("```"):raw_text = raw_text.split("\n", 1)[-1]if raw_text.endswith("```"):raw_text = raw_text.rsplit("```", 1)[0]raw_text = raw_text.strip()raw_json_data = json.loads(raw_text)except anthropic.AuthenticationError:yield (gr.update(visible=True, value="<p style='color:red;text-align:center;'>β Invalid API key. Please check your Claude API key and try again.</p>"),"",gr.update(visible=False))returnexcept anthropic.RateLimitError:yield (gr.update(visible=True, value="<p style='color:red;text-align:center;'>β Rate limit reached. Please wait a moment and try again.</p>"),"",gr.update(visible=False))returnexcept json.JSONDecodeError as e:yield (gr.update(visible=True, value=f"<p style='color:red;text-align:center;'>β JSON parse error: {str(e)}<br>Raw response: {raw_text[:300]}</p>"),"",gr.update(visible=False))returnexcept Exception as e:yield (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("Building interlinear tables")), "", gr.update(visible=False)try:final_table_html = build_html_tables(manuscript_name, reference_header, raw_json_data)except Exception as e:yield (gr.update(visible=True, value=f"<p style='color:red;text-align:center;'>β Table build error: {str(e)}</p>"),"",gr.update(visible=False))returnyield gr.update(visible=False, value=""), final_table_html, gr.update(visible=True)# --- Copy-to-clipboard JS (copies as rich HTML for Google Docs) ---copy_btn_js = """function() {const payload = document.getElementById('table-payload');if (!payload) { alert('No table found to copy.'); return; }const htmlContent = payload.outerHTML;const blob = new Blob([htmlContent], { type: 'text/html' });const data = [new ClipboardItem({ 'text/html': blob })];navigator.clipboard.write(data).then(() => {alert('β Table copied to clipboard! Now paste into Google Docs with Ctrl+V (or Cmd+V on Mac).');}).catch(err => {alert('β Clipboard copy failed: ' + err + '\\n\\nTry selecting the table manually and copying.');});}"""# --- Gradio UI ---with gr.Blocks(title="Hebrew Interlinear Table Generator", css=custom_css) 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);'>""<!-- LOGO PLACEHOLDER: replace the line below with your logo <img> tag -->""<div style='width:80px;height:80px;background:#374151;border-radius:8px;""margin:0 auto 16px auto;display:flex;align-items:center;justify-content:center;""font-size:32px;'>π</div>""<h1 style='margin: 0 0 8px 0; font-size: 28px; font-weight: 700; color: white;'>""Hebrew Interlinear Table Generator</h1>""<p style='margin: 0; font-size: 15px; opacity: 0.8; color: #9ca3af;'>""Convert raw Hebrew text into structured interlinear tables.</p>""</div>")with gr.Accordion("π How to get your Claude API key", open=False):gr.Markdown("1. Go to [console.anthropic.com](https://console.anthropic.com/).\n""2. Sign in or create a free account.\n""3. Click **API Keys** in the left sidebar.\n""4. Click **Create Key**, give it a name, and copy it.\n""5. Paste it into the **Claude API Key** box below.\n\n""β οΈ Your key is never stored β it is only used for the current session.")with gr.Row():with gr.Column(scale=4):gr.Markdown("### π οΈ Step 1: Configure Reference Settings")api_key_input = gr.Textbox(label="π Claude API Key",type="password",placeholder="sk-ant-...")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="1",allow_custom_value=True)verse_input = gr.Dropdown(choices=[str(x) for x in range(1, 177)],label="Ver.",value="5",allow_custom_value=True)gr.Markdown("### π Step 2: Paste Hebrew Text")text_string_input = gr.Textbox(label="Hebrew Text String",placeholder="Paste your raw Hebrew text here...",lines=3)with gr.Row():submit_btn = gr.Button("π Generate Tables", variant="primary")clear_btn = gr.Button("π§Ή Clear Text", variant="secondary")status_panel = gr.HTML(visible=False)gr.Markdown("### π Step 3: Copy Output to Google Docs")copy_btn = gr.Button("π Copy Tables for Google Docs", variant="secondary", visible=False)output_html = gr.HTML(label="Generated Interlinear Tables")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=[status_panel, 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)
1google-genai12anthropic>=0.40.0gradio>=4.0.0
app.py+391-163
requirements.txt+2-1