"""The HTML export - cell [20].
Ported from `case_study_pipeline.ipynb`. The notebook was one namespace, so
each module re-imports the ones before it; every prompt and every standard is
the notebook's text, compared character by character by the fidelity test.
"""
from __future__ import annotations
import asyncio # noqa: F401
import datetime # noqa: F401
import html # noqa: F401
import json # noqa: F401
import pathlib # noqa: F401
import re # noqa: F401
from typing import Any, Callable, Literal, Optional # noqa: F401
from pydantic import ( # noqa: F401
BaseModel,
ConfigDict,
Field,
ValidationError,
model_validator,
)
from app.agents.case_study.helpers import * # noqa: F403
from app.agents.case_study.profiles import * # noqa: F403
from app.agents.case_study.standards import * # noqa: F403
# The notebook was one namespace; the exporters read it too.
from app.agents.case_study.llms import RUN_CONFIG # noqa: F401
# `_answer_lines` is defined in the Word exporter's cell and used by both.
from app.services.case_study.docx_case import _answer_lines
def _e(s) -> str:
return html.escape(str(s or ""))
_HTML_CSS = """
:root{--ink:#1d2433;--muted:#667085;--line:#d0d7e2;--brand:#1f4e79;--soft:#eef4fb;--ok:#e2efda;--warn:#fff2cc;--act:#c55a11;--bg:#f6f8fb;--card:#fff}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.8 "Noto Naskh Arabic","Traditional Arabic",Tahoma,Arial,sans-serif}
main{max-width:1180px;margin:0 auto;padding:24px 16px 64px}h1{font-size:26px;margin:0 0 4px;color:var(--brand)}
.sub{color:var(--muted);margin:0 0 24px}h2{font-size:19px;color:var(--brand);margin:32px 0 12px;border-bottom:2px solid var(--brand);padding-bottom:4px}
table{width:100%;border-collapse:collapse;background:var(--card);table-layout:fixed}td,th{border:1px solid var(--line);padding:8px 10px;vertical-align:top;text-align:start;word-wrap:break-word}
th{background:var(--brand);color:#fff}.lab{background:var(--soft);font-weight:700;width:24%}.num{width:8%;text-align:center;font-weight:700;font-size:20px}
.kind{display:block;font-size:11px;color:var(--muted);font-weight:400}.vo{width:40%}.ln{margin:0 0 4px}.idx{color:#98a2b3;font-size:11px;margin-inline-end:4px}
td p{margin:0 0 6px}.dlg b{color:#7030a0}.bul::before{content:"▪ ";color:var(--brand)}.strong{font-weight:700}.center{text-align:center}
.inter-title{color:var(--act);font-weight:700;margin-bottom:6px}.itab td{font-size:14px}.ok{background:var(--ok);font-weight:700}.fb{background:var(--warn);font-weight:700}
.btn{display:inline-block;border:1px solid var(--brand);border-radius:6px;padding:0 10px;color:var(--brand);font-weight:700}
.k{color:var(--brand);font-weight:700}.freeze{color:#bf8f00;font-weight:700;margin-top:6px}ul{margin:4px 0;padding-inline-start:20px}
.beat{margin:0 0 4px;font-size:14px}.note{color:var(--muted);font-style:italic}details{margin-top:24px;background:var(--card);border:1px solid var(--line);padding:10px 14px;border-radius:8px}
@media (max-width:760px){table,tbody,tr,td,th{display:block;width:100%!important}thead{display:none}td{border-top:none}.num{text-align:start}}
"""
def _answers_html(it: dict, fam: str) -> str:
return "".join(f"
{_e(a)}
" for a in _answer_lines(it, fam))
def _interaction_html(sc: dict) -> str:
it, fam = sc["interaction"], sc["interaction_family"]
rows = [f"{_e(it['header'])} {_e(it['situation_sentence'] + ' ' + it['question'])} |
"]
if fam == "choice" and len(it["items"]) == 2:
rows.append("" + "".join(f"| {'أب'[i]}. {_e(x['text'])} | " for i, x in enumerate(it["items"])) + "
")
else:
mark = {"multi_select": "🔘", "reveal": "▣", "poll": "○"}.get(fam, "▫")
cats = f"الفئات: {_e(' | '.join(it['categories']))}
" if fam == "categorize" else ""
rows.append("| " + cats + "".join(f" {mark} {_e(x['text'])} " for x in it["items"]) + " |
")
rows.append(f"| {_e(it['instruction'])}" + (f" {_e(it['hint_sentence'])} " if it.get("hint_sentence") else "") + " |
")
if it.get("hint"):
rows.append("💡 تلميح (Hint):" + "".join(f"- {_e(h)}
" for h in it["hint"]) + " |
")
rows.append(f"| ✅ الإجابة الصحيحة |
| {_answers_html(it, fam)} |
")
if it.get("check_button"):
rows.append(f"| {_e(it['check_button_label'])} |
")
rows.append("| التغذية الراجعة |
")
fc, fi = it["feedback_correct"], it.get("feedback_incorrect")
if fi:
rows.append(f"| ✅ {_e(fc['opener'])} {_e(fc['text'])} | "
f"❌{' (بعد استنفاد المحاولات)' if it.get('feedback_retry') else ''} {_e(fi['opener'])} {_e(fi['text'])}"
+ "".join(f"({_e(x['id'])}) {_e(x['feedback'])} " for x in it["items"] if x.get("feedback") and not x.get("is_correct"))
+ " |
")
else:
rows.append(f"| ✅ تعليق ختامي {_e(fc['opener'])} {_e(fc['text'])} |
")
if it.get("feedback_retry"):
r = it["feedback_retry"]
rows.append(f"| ❌ المحاولة الأولى الخاطئة (مع إتاحة المحاولة الثانية) {_e(r['opener'])} {_e(r['text'])} |
")
mech = "آلية التفاعل التقني:
" + "".join(f"- {_e(m)}
" for m in it["mechanism"]) + "
"
return (f"⏸ شاشة تفاعل: {_e(it['type_ar'])}
المحاولات المتاحة: {it['attempts']}
"
f"{mech}")
def _vo_html(sc: dict) -> str:
out = []
for i, ln in enumerate(sc["lines"]):
cls = {"bullet": "ln bul", "closing_sentence": "ln strong", "thanks": "ln strong center", "dialogue": "ln dlg"}.get(ln["role"], "ln")
sp = f"{_e(ln['speaker'])}: " if ln["role"] == "dialogue" else ""
out.append(f"[{i + 1}]{sp}{_e(ln['text'])}
")
return "".join(out)
def _desc_html(sc: dict) -> str:
v = sc["visual"]
if not v:
return ""
out = ["وصف المشهد:
التتابع البصري (beat لكل سطر):
"]
for b in v["beats"]:
parts = [b["visual_idea"], f"اللقطة: {b['shot']}", f"الحركة: {b['action']}"]
if b.get("on_screen_text"):
parts.append(f"على الشاشة: «{b['on_screen_text']}»" + (f" ({b['text_position']})" if b.get("text_position") else ""))
parts += [f"{lab}: {b[k]}" for k, lab in (("effect", "التأثير"), ("sfx", "الصوت"), ("transition", "الانتقال")) if b.get(k)]
out.append(f"[{b['line_index'] + 1}]{_e(' — '.join(parts))}
")
out.append(f"الوصف التنفيذي: {_e(v['narrative'])}
")
d = v["description"]
for k, lab in (("background", "الخلفية والبيئة"), ("characters", "الشخصيات وتعبيرات الوجه"), ("actions", "الحركات والأفعال"),
("shots", "اللقطات والزوايا"), ("visual_effects", "المؤثرات البصرية"), ("sound_effects", "المؤثرات الصوتية"),
("graphics_notes", "ملحوظات لفريق الجرافيك")):
out.append(f"{lab}: {_e(d[k])}
")
iv = v.get("interaction_visual")
if iv:
out.append(f"مشهد التفاعل
إطار السؤال: {_e(iv['question_frame'])}
")
out.append("بطاقات العناصر/الخيارات:
" + "".join(f"- ({_e(o['item_id'])}) {_e(o['visual'])}
" for o in iv["option_cards"]) + "
")
for key, lab in (("instruction_frame", "إطار الجملة التوجيهية"), ("hint_visual", "التلميح 💡"), ("check_button_visual", "زر التحقق"),
("feedback_correct_visual", "✅ مشهد التغذية الإيجابية"), ("feedback_incorrect_visual", "❌ مشهد التغذية السلبية")):
if iv.get(key):
out.append(f"{lab}: {_e(iv[key])}
")
if iv.get("mechanism_visual"):
out.append("" + "".join(f"- {_e(m)}
" for m in iv["mechanism_visual"]) + "
")
if v.get("reference_suggestions"):
out.append("" + "".join(f"- مرجع بصري مقترح: {_e(r)}
" for r in v["reference_suggestions"]) + "
")
if v.get("freeze_at_end"):
out.append(f"⏸ تتجمّد الشاشة عند هذه اللحظة: {_e(v.get('freeze_description'))}
")
return "".join(out)
def export_html(content: dict, path: Optional[str] = None) -> pathlib.Path:
path = pathlib.Path(path or out_path("case_study_script.html"))
m, cv = content["meta"], content["covers"]
cc, es = cv["case_cover"], cv["end_screen"]
lst = lambda xs: "" + "".join(f"- {_e(x)}
" for x in xs) + "
"
t1 = "".join(f"| {lab} | {val} |
" for lab, val in (
("نوع العنصر", _e(m["type_label"])),
("اسم العنصر (المحور الرئيس)", _e(m["title"])), ("المحاور الفرعية", lst(m["axes"])), ("الأهداف التعليمية", lst(m["objectives"]))))
icons = "".join(f"الأيقونة {i} (من المشهد {ic['scene_number']}): {_e(ic['description'])}" for i, ic in enumerate(cc["icons"], 1))
rows = [f"""| الغلاف | غلاف دراسة الحالة: {_e(cc['title'])}
والـ Header: {_e(cc['header'])} مع زر: {' '.join(f'{_e(b)}' for b in cc['buttons'])} |
غلاف دراسة الحالة — التصميم: {_e(cc['character_design'])}
جميع الأيقونات مستخرجة من مشاهد حقيقية داخل دراسة الحالة نفسها لضمان التكامل البصري. |
"""]
for sc in content["scenes"]:
vo = _interaction_html(sc) if sc["interaction"] else _vo_html(sc)
rows.append(f"| {sc['scene_number']}{_e(sc['kind_ar'])} | "
f"{vo} | {_desc_html(sc)} |
")
thanks = "".join(f"{_e(t)}
" for t in es["thanks_lines"])
end_btns = ("مع زر: " + " ".join(f"{_e(b)}" for b in es["buttons"]) + "
") if es.get("buttons") else ""
rows.append(f"| الختام | {thanks}{end_btns} | "
f"شاشة الختام: {_e(es['design'])} عند الضغط: {_e(es.get('return_to'))} |
")
qa_items = content.get("qa", {}).get("qa_log", [])
qa_html = "".join(f"{_e(q['step'])} ({_e(q['kind'])}): {_e('؛ '.join(q['messages']))}" for q in qa_items) or "لا ملاحظات"
doc = f"""
{_e(m['title'])}
إسكربت {_e(m['type_label'])}: {_e(m['title'])}
{_e(m['profile_label'])} — {m['actual_words']} كلمة مسموعة (المستهدف {m['target_words']})
الجدول الأول: المعلومات التوصيفية
الجدول الثاني: النص المسموع (VO) ووصف المشاهد
| رقم المشهد | النص المسموع (VO) | وصف المشاهد لفريق الجرافيك |
{''.join(rows)}
ملحوظات مهمة لفريق الجرافيك والإنتاج
{lst(content['production_notes'])}
تقرير الجودة (ملاحظات مقبولة / ضبط الطول)
"""
log(f"✓ HTML: {path}")
return doc