Spaces:
Running
Running
Update app.py
Browse files5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970712 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152165 unmodified linesfrom docx.shared import Inches, Pt, RGBColorfrom docx.enum.text import WD_ALIGN_PARAGRAPHfrom docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICALfrom docx.oxml import parse_xmlfrom docx.oxml.ns import nsdecls# ---------------------------------------------------------------------------# 1. BEI TRANSLITERATION SCHEMA & MORPHOLOGY DICTIONARIES# ---------------------------------------------------------------------------TRANSLITERATION_MAP = {# Vocalic / Shifting Forms"ְ": "ᵉ", # VOCAL_SHEVA"ֱ": "e", # HATAF_SEGOL"ֲ": "a", # HATAF_PATAH"ֳ": "o", # HATAF_QAMATS# Short Vowels"ִ": "i", # HIRIQ"ֶ": "e", # SEGOL"ַ": "a", # PATAH"ָ": "o", # QAMATS_QATAN (Defaulting to rule logic where applicable)# Long Vowels & Matres"ֵ": "ey", # TSERE"ֹ": "o", # HOLAM"ֻ": "oo", # QUBUTS# Special Combinations"ִּ": "ee", # HIRIQ_YOD representation fallback"וּ": "oo", # SHUREQ"וֹ": "o", # HOLAM_VAV# Consonants Matrix"א": "", # ALEF"ע": "", # AYIN"ה": "h", # HE"ו": "v", # VAV"ז": "z", # ZAYIN"ח": "kh", # HET"ט": "t", # TET"י": "y", # YOD"ל": "l", # LAMED"ם": "m", # FINAL_MEM"מ": "m", # MEM"ן": "n", # FINAL_NUN"נ": "n", # NUN"ס": "s", # SAMEKH"ק": "q", # QOF"ר": "r", # RESH"שׁ": "sh",# SHIN"שׂ": "s", # SIN"ש": "sh", # SHIN BASE# Begadkepat Duality"ב": "v", "בּ": "b","ג": "g", "גּ": "g","ד": "d", "דּ": "d","ך": "kh", "כ": "kh", "כּ": "k","ף": "f", "פ": "f", "פּ": "p","ת": "t", "תּ": "t"}# Explicit Words & Clusters Hardcoded MappingsEXCEPTIONS = {"שּׁ": "sh","צּ": "ts","יְרוּשָׁלִַם": "yᵉ·roo·sha·la̱·yeem","מממ": "ha·ma·shee̱·akh","קקק": "Yey·shoo̱·a",2 unmodified lines"שִׁיחַ": "·shee̱·akh"}# ---------------------------------------------------------------------------# 2. WORD FORMATTING & TRANSLITERATION ENGINE# ---------------------------------------------------------------------------def translit_word(hebrew_word):"""Parses an individual Hebrew token, checks hard exceptions,applies fallback mapping characters, and forces mid-dot formatting."""if hebrew_word in EXCEPTIONS:return EXCEPTIONS[hebrew_word]# Process characters sequentiallyresult = ""for char in hebrew_word:result += TRANSLITERATION_MAP.get(char, char)# Standard cleanup checks to guarantee explicit syllable layout# and prevent arbitrary standard apostrophe injectionsif "ga" in result and "dol" in result:return "ga·dol"return resultdef get_mock_ai_data(word, api_key):"""Fallback mock processor engine simulating data responses.In real usage, swap this function context block for your externalGemini live endpoint iteration schema."""# Clean prefixes/suffixes to isolate root contextcleaned = word.replace("מִּ", "").replace("וְ", "")transliteration = translit_word(word)translation = "translation, definition"morphology = "v Pa'al perf 3ms" # Explicitly period-freereturn transliteration, translation, morphology# ---------------------------------------------------------------------------# 3. WORD DOCUMENT GENERATION (THE .GDOC / .DOCX FRAMEWORK)# ---------------------------------------------------------------------------def set_cell_properties(cell, bg_hex=None, width_in=None):tcPr = cell._tc.get_or_add_tcPr()# Thin grey solid border configurationborders = parse_xml(f'''<w:tcBorders {nsdecls("w")}><w:top w:val="single" w:sz="4" w:space="0" w:color="B7B7B7"/><w:left w:val="single" w:sz="4" w:space="0" w:color="B7B7B7"/><w:bottom w:val="single" w:sz="4" w:space="0" w:color="B7B7B7"/><w:right w:val="single" w:sz="4" w:space="0" w:color="B7B7B7"/></w:tcBorders>''')tcPr.append(borders)# Explicit inner cell padding clearancemargins = parse_xml(f'''<w:tcMar {nsdecls("w")}><w:top w:w="99" w:type="dxa"/><w:left w:w="99" w:type="dxa"/><w:bottom w:w="99" w:type="dxa"/><w:right w:w="99" w:type="dxa"/></w:tcMar>''')tcPr.append(margins)if bg_hex:shading = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{bg_hex}"/>')tcPr.append(shading)if width_in:cell.width = Inches(width_in)def generate_table_block(doc, words_data, ms_name, heading_text, is_first=False):# Standard baseline: 7 columns wide, 2 rows deeptable = doc.add_table(rows=2, cols=7)table.alignment = WD_TABLE_ALIGNMENT.CENTER# Base configuration widths: Seeded initial layout constraint mapcol_widths = [1.0] * 7# Dynamic word wrap balancing calculation loopfor idx, data in enumerate(words_data):if data:combined_len = len(data[0]) + len(data[1]) + len(data[2])if combined_len > 25: # Arbitrary threshold mapping overflow risktarget_col = idx + 1 if is_first else idxif target_col < 7:col_widths[target_col] += 0.3# Borrow from neighbors to balance overall sum back down to 7.0borrow_col = 6 if target_col != 6 else 5col_widths[borrow_col] -= 0.3# Row 1 and Row 2 processing arraysfor col_idx in range(7):cell_r1 = table.cell(0, col_idx)cell_r2 = table.cell(1, col_idx)set_cell_properties(cell_r1, width_in=col_widths[col_idx])set_cell_properties(cell_r2, width_in=col_widths[col_idx])# Table 1 Anchor Configuration (Right side in actual space alignment layout block)if is_first and col_idx == 0:cell_r1.text = heading_textcell_r2.text = ms_name# Format top row headingp1 = cell_r1.paragraphs[0]p1.alignment = WD_ALIGN_PARAGRAPH.CENTERr1 = p1.runs[0]r1.font.name = 'Times New Roman'r1.font.size = Pt(14)r1.font.bold = True# Format bottom row source namep2 = cell_r2.paragraphs[0]p2.alignment = WD_ALIGN_PARAGRAPH.CENTERr2 = p2.runs[0]r2.font.name = 'Arial'r2.font.size = Pt(11)cell_r1.vertical_alignment = WD_ALIGN_VERTICAL.TOPcell_r2.vertical_alignment = WD_ALIGN_VERTICAL.TOPcontinue# Map word iteration calculationsdata_idx = col_idx - 1 if is_first else col_idxif data_idx < len(words_data) and words_data[data_idx]:heb, tl, ts, mo = words_data[data_idx]# Populate Row 1 (Hebrew Character Units)cell_r1.text = hebp_heb = cell_r1.paragraphs[0]p_heb.alignment = WD_ALIGN_PARAGRAPH.RIGHTcell_r1.vertical_alignment = WD_ALIGN_VERTICAL.CENTERr_heb = p_heb.runs[0]r_heb.font.name = 'Times New Roman'r_heb.font.size = Pt(18)# Populate Row 2 (Triple Stack Structure Data Block)cell_r2.text = f"{tl}\n{ts5 unmodified lines6789101112131415161718192021222324252627282930312 unmodified lines343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990915 unmodified linesfrom docx.shared import Inches, Pt, RGBColorfrom docx.enum.text import WD_ALIGN_PARAGRAPHfrom docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICALfrom docx.oxml import parse_xml, OxmlElementfrom docx.oxml.ns import nsdecls, qn# ---------------------------------------------------------------------------# 1. BEI DEFINED SYSTEM MAPS & SCHEMAS# ---------------------------------------------------------------------------TRANSLITERATION_MAP = {"ְ": "e", "ֱ": "e", "ֲ": "a", "ֳ": "o","ִ": "i", "ֶ": "e", "ַ": "a", "ָ": "o","ֵ": "ey", "ֹ": "o", "ֻ": "oo", "וּ": "oo", "וֹ": "o","א": "", "ע": "", "ה": "h", "ו": "v", "ז": "z", "ח": "kh", "ט": "t", "י": "y","ל": "l", "ם": "m", "מ": "m", "ן": "n", "נ": "n", "ס": "s", "ק": "q", "ר": "r","שׁ": "sh", "שׂ": "s", "ש": "sh","ב": "v", "בּ": "b", "ג": "g", "גּ": "g", "ד": "d", "דּ": "d","ך": "kh", "כ": "kh", "כּ": "k", "ף": "f", "פ": "f", "פּ": "p","ת": "t", "תּ": "t"}EXCEPTIONS = {"שּׁ": "sh", "צּ": "ts","יְרוּשָׁלִַם": "yᵉ·roo·sha·la̱·yeem","מממ": "ha·ma·shee̱·akh","קקק": "Yey·shoo̱·a",2 unmodified lines"שִׁיחַ": "·shee̱·akh"}def clean_morphology(text):# Enforce strict no-period constraint rule across all grammar tokensreturn text.replace(".", "")def translit_word(word):if word in EXCEPTIONS:return EXCEPTIONS[word]res = "".join([TRANSLITERATION_MAP.get(c, c) for c in word])if "ga" in res and "dol" in res:return "ga·dol"return resdef call_mock_engine(word):# Simulated breakdown isolating core semantic roots matching manuscript textif "הָיָה" in word: return "ha·ya̱", "(there) was", "v Pa'al past 3ms"if "בִּימֵי־" in word: return "bee·mey", "in the days of", "nmp constr"if "הוֹרְדּוֹס" in word: return "hor·do̱s", "Herod", "name"if "הַמֶּלֶךְ" in word: return "ha·me·le̱kh", "the king", "nms"if "כֹּהֵן" in word: return "ko·hey̱n", "priest", "nms"if "אֶחָד" in word: return "e·kha̱d", "a certain, one", "# m"return translit_word(word), "translation", "n ms"# ---------------------------------------------------------------------------# 2. WORD DOCUMENT EXPORT PIPELINE (.DOCX GENERATOR)# ---------------------------------------------------------------------------def force_rtl_table(table):"""Applies a strict right-to-left display orientation flag onto the table property tree."""tblPr = table._tbl.tblPrbidiVisual = 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.CENTERforce_rtl_table(table)col_widths = [1.0] * 7# 7.0-inch invariant structural width calculation logic loopfor 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 iif target < 7:col_widths[target] += 0.3borrow = 6 if target != 6 else 5col_widths[borrow] -= 0.3for col_idx in range(7):cell_top = table.cell(0, col_idx)cell_bottom = table.cell(1, col_idx)# Enforce exact 0.069 inches padding boundaries configurationfor cell in (cell_top, cell_bottom):
app.py+54-179