Spaces:
Running
Running
Create app.py
Browse filesThe column width logic still needs work. However, Gemini suggested I use Hugging Face to host my site so it's always available. In other words, I will no longer be using Google Colab. Hugging face interacts directly with Gradio and will handle my code, providing a Table Generator (BEI style) that is accesssible to multiple users 24/7
The only thing I would like to change is upgrading to the Pro version so that I can control access - right now it is set to Public.
Each user needs to enter their own API key.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291import gradio as grfrom google import genaifrom google.genai import typesimport timeimport json
# --- Custom CSS to polish layout and hide default loading indicators ---custom_css = """.subpanel.loading, .generating, div[class*="loading"], .progress-wrap { display: none !important; visibility: hidden !important; height: 0px !important; overflow: hidden !important;}
.progress-container { padding: 15px; text-align: center; border: 1px solid #b7b7b7; border-radius: 8px; background-color: #1e1e1e; margin-bottom: 15px;}
.white-canvas { display: flex; justify-content: center; align-items: center; width: 100%;}"""
MODEL_NAME = "gemini-3.1-flash-lite"
def clean_hyphens_for_docs(text_string): """ Swaps standard hyphens with HTML non-breaking hyphens. This freezes compounds so Google Docs cannot split them across lines. """ if not text_string: return "" return str(text_string).replace("-", "‑")
def calculate_dynamic_chunks(words_data, base_limit=7): """ Dynamic Fixed-Grid Hybrid Engine. Inspects the text footprint of each word cell. If a row's combined horizontal text footprint grows too heavy, it dynamically scales down column capacity to prevent clipboard overflow. """ chunks = [] current_chunk = [] word_index = 0 while word_index < len(words_data): current_limit = (base_limit - 1) if len(chunks) == 0 else base_limit word = words_data[word_index] current_chunk.append(word) total_row_footprint = 0 for w in current_chunk: lit_len = len(w.get("transliteration", "")) lat_len = len(w.get("translation", "")) morph_len = len(w.get("morphology", "")) total_row_footprint += max(lit_len, lat_len, morph_len) if total_row_footprint > 68 and len(current_chunk) > 1: current_chunk.pop() chunks.append(current_chunk) current_chunk = [] continue 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): """ Native Python engine to assemble right-to-left interlinear grids. Applies non-breaking hyphen locks to stabilize clipboard styling. """ table_style = ( "width: 7in !important; border-collapse: collapse; margin-bottom: 4pt; " "direction: rtl; border: 1pt solid #b7b7b7; background-color: #ffffff; " "line-height: 1.0 !important; height: auto;" ) hebrew_cell_style = ( "font-family: 'Times New Roman', serif !important; font-size: 24px !important; color: #000000 !important; " "text-align: right; vertical-align: middle; border: 1pt solid #b7b7b7; " "padding: 5pt; height: auto; white-space: nowrap;" ) english_cell_style = ( "font-family: Arial, sans-serif !important; font-size: 14.6667px !important; color: #000000 !important; " "border: 1pt solid #b7b7b7; padding: 5pt; text-align: center; " "vertical-align: top; height: auto; line-height: 1.0 !important;" ) heading_cell_style = ( "font-family: 'Times New Roman', serif !important; font-size: 18.6667px !important; color: #000000 !important; " "text-align: center; vertical-align: middle; border: 1pt solid #b7b7b7; " "padding: 5pt; height: auto; white-space: nowrap; line-height: 1.0 !important;" ) 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;">'] table_chunks = calculate_dynamic_chunks(words_data, base_limit=7) for idx, current_chunk in enumerate(table_chunks): html_output.append(f'<table style="{table_style}">') is_first = (idx == 0) target_total_cols = 7 actual_slots_used = len(current_chunk) + (1 if is_first else 0) is_last_table = (idx == len(table_chunks) - 1) if is_last_table: while actual_slots_used < target_total_cols: current_chunk.append({"hebrew": " ", "transliteration": "", "translation": "", "morphology": ""}) actual_slots_used += 1 # --- ROW 1: Hebrew Text / Reference --- 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 --- 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") != " ": 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>') html_output.append('</table>') html_output.append('<div style="font-family: \'Times New Roman\'; font-size: 4pt; height: 4pt; line-height: 4pt;"> </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: 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) return
start_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: #ff6600; font-weight: bold; font-family: Arial; margin: 0 0 5px 0;">⏳ Current Step: {step_text}...</p> <p style="color: #ffffff; font-family: monospace; font-size: 14px; 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) return
yield gr.update(visible=True, value=status_html("Assembling inline CSS blocks and optimizing column bounds")), "", 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) return
yield gr.update(visible=False, value=""), final_table_html, gr.update(visible=True)
copy_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(css=custom_css) as demo: gr.Markdown("# Hebrew Interlinear Table Generator") # SHORT, CLEAN USER KEY INSTRUCTIONS ON-SCREEN with gr.Accordion("🔑 How to get your free Gemini API Key", open=False): gr.Markdown( "1. Go to [aistudio.google.com](https://aistudio.google.com/).\n" "2. Log in with any standard Google or Gmail account.\n" "3. Click the blue **'Get API key'** button in the top left.\n" "4. Click **'Create API key'**, choose a project, and copy your key token string." ) with gr.Row(): with gr.Column(scale=4): gr.Markdown("### 🛠️ Table Parameters") api_key_input = gr.Textbox(label="Gemini API Key", type="password", placeholder="Paste your personal Gemini API key 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="Chapter", value="11", allow_custom_value=True) verse_input = gr.Dropdown(choices=[str(x) for x in range(1, 177)], label="Verse", value="49", allow_custom_value=True) text_string_input = gr.Textbox(label="Hebrew Text String", placeholder="Paste your Hebrew text string 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) copy_btn = gr.Button("📋 Copy for Google Docs", variant="secondary", visible=False) output_html = gr.HTML(label="Generated Table")
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_js)
if __name__ == "__main__": demo.queue().launch(server_name="0.0.0.0", server_port=7860)app.pyAdded+291