import os
import time
import gradio as gr
import docx
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.oxml import parse_xml, OxmlElement
from docx.oxml.ns import nsdecls, qn
# Classic reliable legacy library that natively connects your interface to Gemini 1.5 Flash
import google.generativeai as generative_ai
# ---------------------------------------------------------------------------
# 1. CORE LINGUISTIC PIPELINE (GEMINI TRANSLITERATION & TRANSLATION ENGINE)
# ---------------------------------------------------------------------------
def process_live_ai_request(word, api_key):
"""
Queries the stable Gemini 1.5 Flash model using the user's custom API key.
Enforces the full BEI Transliteration Schema Matrix and Morphology constraints.
"""
clean_key = api_key.strip() if api_key else ""
if not clean_key:
return "Missing Key", "Missing Key", "Enter valid key above"
try:
# Configure the legacy library with the user-provided key
generative_ai.configure(api_key=clean_key)
model = generative_ai.GenerativeModel('gemini-1.5-flash')
prompt_instructions = f"""
You are an expert academic philologist working for Benai Emunah International (BEI) on a critical interlinear text project for the Hebrew Book of Luke.
Analyze this single isolated Hebrew word token: "{word}"
Generate exactly THREE lines of text in your response. Do not include any markdown formatting, bullet points, introduction, or concluding text. Just output the three raw lines.
Line 1: The English transliteration based strictly on the BEI Transliteration Schema rules below.
Line 2: A smooth English contextual translation. If multiple options exist, separate them with a comma and a single space (e.g., "man, human, Adam"). Do not include trailing periods.
Line 3: The descriptive grammatical morphology tag focusing ONLY on the absolute semantic root word (strip away prefixes like mi- or possessive suffixes). Never include a period.
---
CRITICAL BEI TRANSLITERATION SCHEMA RULES:
1. Syllables MUST be explicitly separated using a middle dot character (·) (Alt+0183). Never vary from this standard. (Example: "ga·dol", "bee·mey", "ha·ya̱"). Do not output simple concatenated letters or standard apostrophes.
2. Apply a specialized macron-below accent ( ̱ ) instantly directly after the target stressed vowel element block.
VOWEL REALIZATIONS:
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 | QAMATS_QATAN: o | FURTIVE_PATAH: a
COMPOUND MATRES LECTIONIS:
HIRIQ_YOD: ee | TSERE_YOD: ey | SEGOL_YOD: ey | SHUREQ: oo | HOLAM_VAV: o | QAMATS_HE: a | SEGOL_HE: eh | TSERE_HE: e
CONSONANTS BASE MATRIX:
ALEF: | AYIN: | HE: h | VAV: v | ZAYIN: z | HET: kh | TET: t | YOD: y | LAMED: l | MEM/FINAL_MEM: m | NUN/FINAL_NUN: n | SAMEKH: s | QOF: q | RESH: r | SHIN: sh | SIN: s | TSADI/FINAL_TSADI: ts
BEGADKEPAT PAIRS:
BET: v / BET_DAGESH: b | GIMEL: g / GIMEL_DAGESH: g | DALET: d / DALET_DAGESH: d | KAF/FINAL_KAF: kh / KAF_DAGESH: k | PE/FINAL_PE: f / PE_DAGESH: p | TAV: t / TAV_DAGESH: t
HARDCODED CLUSTERS & EXPLICIT WORDS:
שּׁ -> sh | צּ -> ts | יְרוּשָׁלִַם -> yᵉ·roo·sha·la̱·yeem | מממ -> ha·ma·shee̱·akh | קקק or יֵשׁוּעַ -> Yey·shoo̱·a | אֲדֹנָי -> a·do·nai̱ | שִׁיחַ -> ·shee̱·akh | DIVINE_NAME (YHVH) -> Yᵉ·ho·va̱h | DIVINE_NAME_ELOHIM -> Ye·ho·vee̱h
---
CRITICAL BEI MORPHOLOGY RULES:
- STRICT NO-PERIOD CONSTRAINT: Abbreviation tags must absolutely never contain a period (use 'v', never write 'v.').
- Token Assembly Sequence: [Part of Speech] [Binyan (Verbs Only)] [Tense/Mood/Aspect (Verbs Only)] [Concordance Block].
- Part of Speech Abbreviations: v, n, adv, adj, conj, part, prep, pron, name, ddo, #, intj, constr
- Binyan: Pa'al, Nif'al, Pi'el, Pu'al, Hif'il, Huf'al, Hitpa'el
- Tense/Mood/Aspect: perf, imp, ptcpl
- Concordance Block: Combine Person (1, 2, 3), Gender (m, f, c), and Number (s, p) without spaces (e.g., "3ms", "mp", "cp").
EXAMPLES:
- גָּדוֹל -> Line 1: ga·dol | Line 2: great, large | Line 3: adj ms
- הָיָה -> Line 1: ha·ya̱ | Line 2: (there) was | Line 3: v Pa'al perf 3ms
- מִבֵּית -> Line 1: mi·bey̱t | Line 2: from the house of | Line 3: n ms constr
"""
response = model.generate_content(prompt_instructions)
lines = [line.strip() for line in response.text.split('\n') if line.strip()]
transliteration = lines[0] if len(lines) > 0 else "error"
translation = lines[1] if len(lines) > 1 else "error"
morphology = lines[2] if len(lines) > 2 else "error"
return transliteration, translation, morphology.replace(".", "")
except Exception as e:
return "Connection Error", "Gemini Query Failed", str(e)
# ---------------------------------------------------------------------------
# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)
# ---------------------------------------------------------------------------
def force_rtl_table(table):
tblPr = table._tbl.tblPr
bidiVisual = OxmlElement('w:bidiVisual')
tblPr.append(bidiVisual)
def build_docx_table(doc, word_packages, ms_name, heading_label, is_first=False):
table = doc.add_table(rows=2, cols=7)
table.alignment = WD_TABLE_ALIGNMENT.CENTER
force_rtl_table(table)
col_widths = [1.0] * 7
for i, pkg in enumerate(word_packages):
if pkg:
total_len = len(pkg[0]) + len(pkg[1]) + len(pkg[2])
if total_len > 22:
target = i + 1 if is_first else i
if target < 7:
col_widths[target] += 0.3
borrow = 6 if target != 6 else 5
col_widths[borrow] -= 0.3
for col_idx in range(7):
cell_top = table.cell(0, col_idx)
cell_bottom = table.cell(1, col_idx)
cell_top.width = Inches(col_widths[col_idx])
tcPr_top = cell_top._tc.get_or_add_tcPr()
borders_top = parse_xml(f'')
# Cell margin padding locked precisely to your true 0.069 inches benchmark spacing
padding_top = parse_xml(f'')
tcPr_top.append(borders_top)
tcPr_top.append(padding_top)
cell_bottom.width = Inches(col_widths[col_idx])
tcPr_bottom = cell_bottom._tc.get_or_add_tcPr()
borders_bottom = parse_xml(f'')
padding_bottom = parse_xml(f'')
tcPr_bottom.append(borders_bottom)
tcPr_bottom.append(padding_bottom)
if is_first and col_idx == 0:
cell_top.text = heading_label
cell_bottom.text = ms_name
p1 = cell_top.paragraphs[0]
p2 = cell_bottom.paragraphs[0]
p1.alignment = WD_ALIGN_PARAGRAPH.CENTER
p2.alignment = WD_ALIGN_PARAGRAPH.CENTER
p1.runs[0].font.name = 'Times New Roman'
p1.runs[0].font.size = Pt(14)
p2.runs[0].font.name = 'Arial'
p2.runs[0].font.size = Pt(11)
cell_top.vertical_alignment = WD_ALIGN_VERTICAL.TOP
cell_bottom.vertical_alignment = WD_ALIGN_VERTICAL.TOP
continue
pkg_idx = col_idx - 1 if is_first else col_idx
if pkg_idx < len(word_packages) and word_packages[pkg_idx]:
heb, tl, ts, mo = word_packages[pkg_idx]
cell_top.text = heb
p_top = cell_top.paragraphs[0]
p_top.alignment = WD_ALIGN_PARAGRAPH.RIGHT
cell_top.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
p_top.runs[0].font.name = 'Times New Roman'
p_top.runs[0].font.size = Pt(18)
cell_bottom.text = f"{tl}\n{ts}\n{mo}"
p_bot = cell_bottom.paragraphs[0]
p_bot.alignment = WD_ALIGN_PARAGRAPH.CENTER
cell_bottom.vertical_alignment = WD_ALIGN_VERTICAL.TOP
for r in p_bot.runs:
r.font.name = 'Arial'
r.font.size = Pt(11)
sp = doc.add_paragraph()
sp.paragraph_format.space_before = Pt(0)
sp.paragraph_format.space_after = Pt(4)
run = sp.add_run()
run.font.name = 'Times New Roman'
run.font.size = Pt(4)
# ---------------------------------------------------------------------------
# 3. SCREEN CANVAS VIEW COMPILER
# ---------------------------------------------------------------------------
def build_html_canvas(word_packages, ms_name, heading_label):
html_elements = []
html_elements.append('
')
t1_data = word_packages[:6]
while len(t1_data) < 6:
t1_data.append(None)
html_elements.append('
')
html_elements.append('')
html_elements.append(f'| {heading_label} | ')
for pkg in t1_data:
text = pkg[0] if pkg else ""
html_elements.append(f'{text} | ')
html_elements.append('
')
html_elements.append(f'| {ms_name} | ')
for pkg in t1_data:
if pkg:
content = f'{pkg[1]}
{pkg[2]}
{pkg[3]}
'
else:
content = ""
html_elements.append(f'{content} | ')
html_elements.append('
')
rem = word_packages[6:]
while len(rem) > 0:
chunk = rem[:7]
while len(chunk) < 7:
chunk.append(None)
html_elements.append('
')
for pkg in chunk:
text = pkg[0] if pkg else ""
html_elements.append(f'| {text} | ')
html_elements.append('
')
for pkg in chunk:
if pkg:
content = f'{pkg[1]}
{pkg[2]}
{pkg[3]}
'
else:
content = ""
html_elements.append(f'{content} | ')
html_elements.append('
')
rem = rem[7:]
html_elements.append('
')
return "".join(html_elements)
# ---------------------------------------------------------------------------
# 4. RUNTIME WORKFLOW CONTROLLER (PACED INDIVIDUAL TOKEN ENGINE)
# ---------------------------------------------------------------------------
def process_pipeline(api_key, ms_name, book, ch, ver, raw_input):
if not raw_input.strip():
return "System Warning: Please paste Hebrew strings to build.", "", gr.update(visible=False)
if not api_key or not api_key.strip():
return "System Warning: Please enter your personal Gemini API Key above.", "", gr.update(visible=False)
start_time = time.time()
book_clean = book.replace(".", "").strip()
heading_label = f"{book_clean[:3]}. {ch}:{ver}"
tokens = raw_input.strip().split()
word_packages = []
for tok in tokens:
# Pacing constraint (0.4s) naturally prevents network rate blocks
time.sleep(0.4)
tl, ts, mo = process_live_ai_request(tok, api_key)
word_packages.append((tok, tl, ts, mo))
html_canvas = build_html_canvas(word_packages, ms_name, heading_label)
doc = Document()
t1_data = word_packages[:6]
while len(t1_data) < 6:
t1_data.append(None)
build_docx_table(doc, t1_data, ms_name, heading_label, is_first=True)
rem = word_packages[6:]
while len(rem) > 0:
chunk = rem[:7]
while len(chunk) < 7:
chunk.append(None)
build_docx_table(doc, chunk, ms_name, heading_label, is_first=False)
rem = rem[7:]
file_path = "BEI_Interlinear_Output.docx"
doc.save(file_path)
elapsed = time.time() - start_time
status = f"Success! Processed {len(tokens)} words in {elapsed:.2f} seconds across Gemini 1.5 Flash."
return status, html_canvas, gr.update(value=file_path, visible=True)
def clear_workspace():
return "", "Success: Canvas workspace cleared cleanly.", "", gr.update(visible=False)
# ---------------------------------------------------------------------------
# 5. GRADIO INTERFACE LAYOUT (WITH CORRECT CONTRAST PALETTES)
# ---------------------------------------------------------------------------
bei_css = """
body, .gradio-container { background-color: #F4F3EF !important; }
.bei-banner { background-color: #1B4D3E; padding: 22px; text-align: center; border-radius: 8px; border-bottom: 4px solid #D4AF37; }
.bei-banner h1 { color: #F4F3EF !important; font-size: 28px; margin: 0; font-weight: bold; }
.bei-banner p { color: #D4AF37 !important; margin: 4px 0 0 0; font-size: 14px; font-weight: 500; }
.action-btn { background-color: #1B4D3E !important; color: white !important; font-weight: bold !important; border-radius: 4px !important; margin: 5px 0; }
.clear-btn { background-color: #718096 !important; color: white !important; font-weight: bold !important; border-radius: 4px !important; margin: 5px 0; }
.copy-btn { background-color: #D4AF37 !important; color: #1B4D3E !important; font-weight: bold !important; border-radius: 4px !important; margin: 5px 0; border: 1px solid #1B4D3E !important; }
.api-guide-box { background-color: #E2E8F0 !important; border-left: 5px solid #1B4D3E !important; padding: 12px; border-radius: 4px; margin-bottom: 10px; }
input[type="text"], input[type="password"], textarea {
background-color: #FFFFFF !important;
color: #2D3748 !important;
border: 1px solid #CBD5E0 !important;
}
.hourglass-box { text-align: center; font-size: 24px; padding: 10px; color: #1B4D3E; }
"""
copy_tables_js = """
function() {
var container = document.getElementById('bei-target-tables');
if (!container) {
alert('No tables found to copy! Generate an interlinear layout canvas first.');
return;
}
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(container);
window.getSelection().addRange(range);
try {
document.execCommand('copy');
alert('Success! Tables copied to clipboard. You can now paste directly into Google Docs.');
} catch (err) {
alert('Clipboard copy encountered an error.');
}
window.getSelection().removeAllRanges();
}
"""
with gr.Blocks(title="Shorashim Pro Workspace") as demo:
with gr.Row(elem_classes="bei-banner"):
gr.Markdown("📖 Shorashim Pro Workspace
BEI Interlinear Table Generator
")
with gr.Row():
with gr.Column(scale=2):
# FIXED VISIBILITY: Removed the bold text tags to ensure the title inherits clear dark charcoal text natively
gr.HTML('''
🔑 Gemini API Key Guide: To generate your credentials key, log into
Google AI Studio,
click the "Get API Key" button, copy the token code block, and paste it below.
For a complete setup walkthrough, view our
YouTube Tutorial.
''')
api_key = gr.Textbox(label="🔑 Gemini API Access Key", type="password", placeholder="Paste AI Studio Key Here...")
with gr.Row():
ms_name = gr.Textbox(label="📋 Manuscript Selection Name", value="Marseilles MS-24")
book = gr.Textbox(label="Book", value="Luke")
with gr.Row():
ch = gr.Dropdown(label="Chapter", choices=[str(i) for i in range(1, 25)], value="1")
ver = gr.Dropdown(label="Verse", choices=[str(i) for i in range(1, 81)], value="5")
with gr.Column(scale=2):
raw_input = gr.Textbox(label="Paste Your Hebrew Here", value="הָיָה בִּימֵי־הוֹרְדּוֹס הַמֶּלֶךְ כֹּהֵן אֶחָד וּשְׁמוֹ זְכַרְיָהוּ מִבֵּית אָבִיָה וְאִשְׁתּוֹ מִבֵּית אַהֲרוֹן וּשְׁמָהּ אֵלִיזַבֵּת", lines=7)
with gr.Row():
gen_btn = gr.Button("🚀 Generate Interlinear Canvas", elem_classes="action-btn")
clear_btn = gr.Button("Clear Text", elem_classes="clear-btn")
copy_btn = gr.Button("Copy Tables for Google Docs", elem_classes="copy-btn")
with gr.Row():
with gr.Column(scale=1, visible=False) as loading_area:
gr.Markdown("⏳ Backend Operational Threads Active... Please Wait.
")
with gr.Row():
with gr.Column():
status_field = gr.Textbox(label="System Status Pipeline Logs", interactive=False)
doc_file = gr.File(label="📥 Download Structured Document Asset (.docx)", visible=False)
with gr.Row():
canvas_area = gr.HTML(label="Interlinear Render Canvas Layer Output")
# Connect UI Action Listeners
gen_btn.click(
fn=lambda: gr.update(visible=True),
inputs=None,
outputs=loading_area,
queue=False
).then(
fn=process_pipeline,
inputs=[api_key, ms_name, book, ch, ver, raw_input],
outputs=[status_field, canvas_area, doc_file]
).then(
fn=lambda: gr.update(visible=False),
inputs=None,
outputs=loading_area,
queue=False
)
clear_btn.click(
fn=clear_workspace,
inputs=None,
outputs=[raw_input, status_field, canvas_area, doc_file]
)
copy_btn.click(fn=None, js=copy_tables_js)
# Launch with CSS applied inside launch method to fully comply with Gradio 6.0 standards
if __name__ == "__main__":
demo.launch(css=bei_css)