contiai / apps /api /app /services /appendix /renderer.py
aliabozahra315's picture
Deploy 64d7cd0
5895e58
Raw History Blame Contribute Delete
12.5 kB
"""The chapter appendix as an Arabic RTL Word document.
Ported from `ملتي_ايجنت_ملحقات_الفصول_(1).ipynb`, cells 17 and 19. Every
heading level, table, shading and bullet is carried over; the only change is
that the document is returned as bytes rather than written to a path.
"""
from __future__ import annotations
import io
from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Cm, Pt, RGBColor
ARABIC_FONT = "Arial"
def set_run_rtl_font(run, size=12, bold=False, color=None, italic=False):
run.font.name = ARABIC_FONT
run.font.size = Pt(size)
run.font.bold = bold
run.font.italic = italic
if color:
run.font.color.rgb = RGBColor.from_string(color)
rPr = run._r.get_or_add_rPr()
rFonts = rPr.find(qn('w:rFonts'))
if rFonts is None:
rFonts = OxmlElement('w:rFonts')
rPr.append(rFonts)
rFonts.set(qn('w:cs'), ARABIC_FONT)
rFonts.set(qn('w:ascii'), ARABIC_FONT)
rFonts.set(qn('w:hAnsi'), ARABIC_FONT)
rtl = rPr.find(qn('w:rtl'))
if rtl is None:
rtl = OxmlElement('w:rtl')
rPr.append(rtl)
rtl.set(qn('w:val'), '1')
szCs = rPr.find(qn('w:szCs'))
if szCs is None:
szCs = OxmlElement('w:szCs')
rPr.append(szCs)
szCs.set(qn('w:val'), str(int(size * 2)))
def set_paragraph_rtl(paragraph, align=WD_ALIGN_PARAGRAPH.RIGHT):
paragraph.alignment = align
pPr = paragraph._p.get_or_add_pPr()
bidi = pPr.find(qn('w:bidi'))
if bidi is None:
bidi = OxmlElement('w:bidi')
pPr.append(bidi)
bidi.set(qn('w:val'), '1')
def add_rtl_paragraph(doc, text="", size=12, bold=False, italic=False,
color=None, align=WD_ALIGN_PARAGRAPH.RIGHT,
space_after=6, style=None):
p = doc.add_paragraph(style=style)
set_paragraph_rtl(p, align=align)
p.paragraph_format.space_after = Pt(space_after)
if text:
run = p.add_run(text)
set_run_rtl_font(run, size=size, bold=bold, italic=italic, color=color)
return p
def add_rtl_heading(doc, text, level=1):
sizes = {1: 20, 2: 16, 3: 14}
colors = {1: "1F4E79", 2: "2E5C8A", 3: "31859C"}
p = doc.add_paragraph()
set_paragraph_rtl(p, align=WD_ALIGN_PARAGRAPH.RIGHT)
p.paragraph_format.space_before = Pt(18 if level == 1 else 10)
p.paragraph_format.space_after = Pt(10 if level == 1 else 6)
run = p.add_run(text)
set_run_rtl_font(run, size=sizes.get(level, 13), bold=True,
color=colors.get(level, "1F4E79"))
if level == 1:
pPr = p._p.get_or_add_pPr()
pBdr = OxmlElement('w:pBdr')
bottom = OxmlElement('w:bottom')
bottom.set(qn('w:val'), 'single')
bottom.set(qn('w:sz'), '6')
bottom.set(qn('w:space'), '4')
bottom.set(qn('w:color'), '1F4E79')
pBdr.append(bottom)
pPr.append(pBdr)
return p
def add_rtl_bullets(doc, items, size=11):
for item in items or []:
p = doc.add_paragraph(style='List Bullet')
set_paragraph_rtl(p, align=WD_ALIGN_PARAGRAPH.RIGHT)
run = p.add_run(item)
set_run_rtl_font(run, size=size)
def add_rtl_numbered(doc, items, size=11):
for item in items or []:
p = doc.add_paragraph(style='List Number')
set_paragraph_rtl(p, align=WD_ALIGN_PARAGRAPH.RIGHT)
run = p.add_run(item)
set_run_rtl_font(run, size=size)
def shade_cell(cell, color="1F4E79"):
tcPr = cell._tc.get_or_add_tcPr()
shd = OxmlElement('w:shd')
shd.set(qn('w:val'), 'clear')
shd.set(qn('w:color'), 'auto')
shd.set(qn('w:fill'), color)
tcPr.append(shd)
#: Where `w:bidiVisual` and `w:bidi` belong among their siblings. OOXML fixes
#: the order of these children, and an element out of place is dropped without
#: a word - which is how a table marked right-to-left rendered left-to-right,
#: putting the first column on the wrong side of the page.
_TBLPR_AFTER_BIDI = (
"tblStyleRowBandSize", "tblStyleColBandSize", "tblW", "jc", "tblCellSpacing",
"tblInd", "tblBorders", "shd", "tblLayout", "tblCellMar", "tblLook",
"tblCaption", "tblDescription",
)
_SECTPR_AFTER_BIDI = ("rtlGutter", "docGrid", "printerSettings", "sectPrChange")
def _insert_ordered(parent, tag, after):
"""Put the element where the schema expects it, not at the end."""
existing = parent.find(qn(tag))
if existing is not None:
return existing
element = OxmlElement(tag)
anchor = next(
(child for child in parent if child.tag.split("}")[-1] in after), None
)
if anchor is not None:
anchor.addprevious(element)
else:
parent.append(element)
return element
def add_rtl_two_col_table(doc, rows, header=None, col_widths_cm=(4, 12)):
n_rows = len(rows) + (1 if header else 0)
table = doc.add_table(rows=n_rows, cols=2)
table.alignment = WD_TABLE_ALIGNMENT.CENTER
_insert_ordered(table._tbl.tblPr, 'w:bidiVisual', _TBLPR_AFTER_BIDI)
start = 0
if header:
row = table.rows[0]
for i, text in enumerate(header):
cell = row.cells[i]
cell.width = Cm(col_widths_cm[i])
shade_cell(cell, "1F4E79")
p = cell.paragraphs[0]
set_paragraph_rtl(p, align=WD_ALIGN_PARAGRAPH.CENTER)
run = p.add_run(text)
set_run_rtl_font(run, size=11, bold=True, color="FFFFFF")
start = 1
for r, (label, value) in enumerate(rows):
row = table.rows[r + start]
for i, text in enumerate([label, value]):
cell = row.cells[i]
cell.width = Cm(col_widths_cm[i])
p = cell.paragraphs[0]
set_paragraph_rtl(p, align=WD_ALIGN_PARAGRAPH.RIGHT)
run = p.add_run(text)
set_run_rtl_font(run, size=11, bold=(i == 0))
return table
def render_tools_section(doc, tools_data):
add_rtl_heading(doc, "أولًا: أدوات تطبيقية", level=1)
for tool in (tools_data or {}).get("tools", []):
add_rtl_heading(doc, tool.get("name", ""), level=2)
if tool.get("purpose"):
add_rtl_paragraph(doc, f"الغرض: {tool['purpose']}")
if tool.get("steps"):
add_rtl_paragraph(doc, "خطوات الاستخدام:", bold=True)
add_rtl_numbered(doc, tool["steps"])
if tool.get("example"):
add_rtl_paragraph(doc, "مثال تطبيقي:", bold=True)
add_rtl_paragraph(doc, tool["example"])
if tool.get("common_mistakes"):
add_rtl_paragraph(doc, "أخطاء شائعة:", bold=True)
add_rtl_bullets(doc, tool["common_mistakes"])
if tool.get("success_indicators"):
add_rtl_paragraph(doc, "مؤشرات النجاح:", bold=True)
add_rtl_bullets(doc, tool["success_indicators"])
if tool.get("when_to_use"):
add_rtl_paragraph(doc, "متى تستخدم؟", bold=True)
add_rtl_bullets(doc, tool["when_to_use"])
if tool.get("reflection_question"):
add_rtl_paragraph(doc, f"سؤال تأمل قيادي: {tool['reflection_question']}",
italic=True, color="31859C")
def render_reflection_cards_section(doc, cards_data):
add_rtl_heading(doc, "ثانيًا: بطاقات تأمل", level=1)
for i, card in enumerate((cards_data or {}).get("cards", []), start=1):
add_rtl_heading(doc, f"بطاقة تأمل ({i}): {card.get('title','')}", level=2)
add_rtl_bullets(doc, card.get("questions", []))
if card.get("closing_message"):
add_rtl_paragraph(doc, f"رسالة تأمل: {card['closing_message']}",
italic=True, bold=True)
ORDINALS_AR = ["الأول", "الثاني", "الثالث", "الرابع", "الخامس", "السادس"]
def render_scenarios_section(doc, scenarios_data):
add_rtl_heading(doc, "ثالثًا: سيناريوهات مدرسية", level=1)
for i, sc in enumerate((scenarios_data or {}).get("scenarios", []), start=1):
ordinal = ORDINALS_AR[i - 1] if i <= len(ORDINALS_AR) else str(i)
add_rtl_heading(doc, f"السيناريو {ordinal}: {sc.get('title','')}", level=2)
add_rtl_paragraph(doc, sc.get("description", ""))
add_rtl_paragraph(doc, "ناقش:", bold=True)
add_rtl_bullets(doc, sc.get("discussion_questions", []))
def render_case_study_section(doc, case_data):
add_rtl_heading(doc, "رابعًا: دراسة حالة", level=1)
for cs in (case_data or {}).get("case_studies", []):
add_rtl_heading(doc, f"دراسة حالة: {cs.get('title','')}", level=2)
add_rtl_paragraph(doc, "وصف الحالة:", bold=True)
add_rtl_paragraph(doc, cs.get("description", ""))
add_rtl_paragraph(doc, "مهمة القائد:", bold=True)
add_rtl_bullets(doc, cs.get("leader_tasks", []))
def render_checklist_section(doc, checklist_data):
add_rtl_heading(doc, "خامسًا: قائمة تحقق", level=1)
checklist_data = checklist_data or {}
if checklist_data.get("title"):
add_rtl_paragraph(doc, checklist_data["title"], bold=True)
add_rtl_bullets(doc, checklist_data.get("items", []))
interp = checklist_data.get("interpretation", [])
if interp:
add_rtl_paragraph(doc, "تفسير النتيجة:", bold=True)
rows = [(it["range_label"], it["meaning"]) for it in interp]
add_rtl_two_col_table(doc, rows, header=["النطاق", "الدلالة"])
def render_indicators_section(doc, indicators_data):
add_rtl_heading(doc, "سادسًا: مؤشرات قياس", level=1)
indicators_data = indicators_data or {}
if indicators_data.get("title"):
add_rtl_paragraph(doc, indicators_data["title"], bold=True)
for cat in indicators_data.get("categories", []):
add_rtl_paragraph(doc, f"{cat.get('category_name','')}:", bold=True)
add_rtl_bullets(doc, cat.get("indicators", []))
interp = indicators_data.get("interpretation", [])
if interp:
add_rtl_paragraph(doc, "تفسير النتائج:", bold=True)
rows = [(it["range_label"], it["meaning"]) for it in interp]
add_rtl_two_col_table(doc, rows, header=["النطاق", "الدلالة"])
if indicators_data.get("when_to_use"):
add_rtl_paragraph(doc, f"متى تستخدم؟ {indicators_data['when_to_use']}", italic=True)
def set_document_defaults(doc):
section = doc.sections[0]
section.page_height = Cm(29.7)
section.page_width = Cm(21)
_insert_ordered(section._sectPr, 'w:bidi', _SECTPR_AFTER_BIDI).set(
qn('w:val'), '1')
normal = doc.styles['Normal']
normal.font.name = ARABIC_FONT
normal.font.size = Pt(11)
rpr = normal.element.get_or_add_rPr()
rFonts = rpr.find(qn('w:rFonts'))
if rFonts is None:
rFonts = OxmlElement('w:rFonts')
rpr.append(rFonts)
rFonts.set(qn('w:cs'), ARABIC_FONT)
def render_chapter_appendix(doc, chapter_json, is_first_chapter=False):
if not is_first_chapter:
doc.add_page_break()
add_rtl_paragraph(doc, f"ملحقات {chapter_json.get('chapter_title','')}",
size=22, bold=True, color="1F4E79",
align=WD_ALIGN_PARAGRAPH.CENTER, space_after=16)
render_tools_section(doc, chapter_json.get("tools", {}))
render_reflection_cards_section(doc, chapter_json.get("reflection_cards", {}))
render_scenarios_section(doc, chapter_json.get("scenarios", {}))
render_case_study_section(doc, chapter_json.get("case_study", {}))
render_checklist_section(doc, chapter_json.get("checklist", {}))
render_indicators_section(doc, chapter_json.get("indicators", {}))
def build_word_document(all_chapters_json: list) -> bytes:
"""The appendix as bytes.
The notebook saves to a path; here the step holds the document, so nothing
depends on a working directory surviving between steps.
"""
doc = Document()
set_document_defaults(doc)
for i, chapter_json in enumerate(all_chapters_json):
render_chapter_appendix(doc, chapter_json, is_first_chapter=(i == 0))
buffer = io.BytesIO()
from app.services.docx_rtl import fix_directions
fix_directions(doc) # right-to-left as Word reads it
doc.save(buffer)
return buffer.getvalue()