contiai / apps /api /tests /test_bag_deck.py
aliabozahra315's picture
Deploy be8b84f
968115e
Raw History Blame Contribute Delete
16.9 kB
"""The bag's presentation file, against the standard it was written from.
Most of that standard is arithmetic and naming rather than judgement - the
cover's three lines, when a day heading is written at all, what a session's
topic page lists, what an activity slide may and may not carry - so most of it
is code, and code is what these test.
The prose compression is not tested here. It is a model's judgement, and the
things worth pinning about it are structural: that the writer is asked for one
session at a time, that activity instructions are copied rather than
rewritten, and that nothing outside the bag's own covers ever reaches it.
"""
from __future__ import annotations
import inspect
from app.agents.arabic_bag.context import ArabicBagContext, _ctx
from app.agents.arabic_bag.deck_layouts import DECK_SLIDE_TYPES, DECK_STANDARD_AR
from app.agents.arabic_bag.deck_planner import (
SLIDES_PER_DAY_MAX,
SLIDES_PER_DAY_MIN,
check_plan,
slide_budget_note,
)
from app.agents.arabic_bag.deck_render import (
build_pages,
day_session_lines,
generate_deck_word,
)
from app.agents.arabic_bag.deck_writer import (
RENDERED_TYPES,
cover_text,
over_ceiling,
slide_words,
)
# ───────────────────────────── ترتيب الصفحات ورؤوسها
def _blueprint(days: int, sessions: int) -> dict:
return {
"bag_name": "القيادة الفعّالة",
"days": [
{
"day_number": d,
"sessions": [
{
"session_number": s,
"session_title": f"جلسة {s}",
"topics": [{"topic": "مفهوم القيادة", "covers": []},
{"topic": "أنماط القيادة", "covers": []}],
}
for s in range(1, sessions + 1)
],
}
for d in range(1, days + 1)
],
}
def test_one_day_writes_no_day_line():
"""«إذا كان البرنامج يومًا واحدًا: لا تُكتب عبارة اليوم الأول ولا عنوانه»."""
lines = day_session_lines(1, 1, "مهارات التواصل", "التواصل المهني",
total_days=1, sessions_in_day=2)
assert not any("اليوم" in ln for ln in lines)
def test_one_session_writes_the_title_alone():
"""«إذا كان يتكون من جلسة واحدة: لا تُكتب الجلسة الأولى، يُكتفى بعنوانها»."""
lines = day_session_lines(1, 1, "", "التواصل وبناء العلاقات المهنية",
total_days=1, sessions_in_day=1)
assert lines == ["التواصل وبناء العلاقات المهنية"]
def test_several_days_and_sessions_get_both_lines():
lines = day_session_lines(2, 3, "", "اتخاذ القرار",
total_days=3, sessions_in_day=3)
assert lines[0] == "اليوم الثاني"
assert lines[1] == "الجلسة الثالثة: اتخاذ القرار"
def test_the_ordinals_are_words_not_digits():
"""The bag's own review asked for this everywhere; the deck is no
exception."""
lines = day_session_lines(1, 2, "", "س", total_days=2, sessions_in_day=2)
assert "اليوم الأول" in lines[0]
assert "1" not in lines[0] and "2" not in lines[1]
def test_the_first_three_pages_are_fixed_and_in_order():
"""الغلاف، ثم المقدمة، ثم الهدف العام."""
pages = build_pages(_blueprint(1, 1), "مقدمة", "تمكين المشاركين", [], [])
assert [p["kind"] for p in pages[:3]] == ["cover", "intro", "general_objective"]
def test_the_topics_page_lists_topics_and_not_their_covers():
"""«أسماء المحاور الرئيسة فقط. لا تُدرج المحاور الفرعية»."""
blueprint = _blueprint(1, 1)
blueprint["days"][0]["sessions"][0]["topics"][0]["covers"] = [
{"cover": "تعريف القيادة"}, {"cover": "أهمية القيادة"},
]
pages = build_pages(blueprint, "م", "ه", [], [])
topics = next(p for p in pages if p["kind"] == "session_topics")
assert topics["items"] == ["مفهوم القيادة", "أنماط القيادة"]
assert "تعريف القيادة" not in topics["items"]
def test_slides_follow_their_own_session():
slides = [
{"day": 1, "session": 2, "slide_type": "concept", "title": "ب"},
{"day": 1, "session": 1, "slide_type": "concept", "title": "أ"},
]
pages = build_pages(_blueprint(1, 2), "م", "ه", slides, [])
order = [p.get("title") for p in pages if p.get("slide_type")]
assert order == ["أ", "ب"]
def test_a_slide_on_a_day_the_blueprint_does_not_name_is_still_written():
"""Dropping it silently is how a file comes back short and nobody knows."""
stray = {"day": 9, "session": 1, "slide_type": "summary", "title": "شاردة"}
pages = build_pages(_blueprint(1, 1), "م", "ه", [stray], [])
assert any(p.get("title") == "شاردة" for p in pages)
# ───────────────────────────── النشاط
def test_an_activity_slide_is_never_sent_to_the_model():
"""«يُكتفى بعرض تعليمات المتدرب» - and those are already written on the
card. Asking a model to write them would paraphrase approved words."""
assert "activity" in RENDERED_TYPES
def test_the_activity_slide_carries_only_the_trainee_instructions(tmp_path):
"""No objective, no duration, no tools, no trainer steps - the standard
forbids all four by name."""
from docx import Document
card = {
"day": 1, "session": 1, "title": "تحليل موقف قيادي",
"objectives": ["تمييز الأنماط القيادية"],
"duration_minutes": 25, "activity_type": "دراسة حالة",
"grouping": "جماعي",
"steps": ["يوزّع المدرب الحالة", "يناقش المدرب النتائج"],
"trainee_instructions": "اقرأ الموقف وحدد النمط القيادي الأنسب.",
}
slide = {"day": 1, "session": 1, "slide_type": "activity",
"title": "تحليل موقف قيادي", "source_activity": "تحليل موقف قيادي"}
out = tmp_path / "deck.docx"
token = _ctx.set(ArabicBagContext(blueprint=_blueprint(1, 1)))
try:
generate_deck_word(str(out), blueprint=_blueprint(1, 1),
intro_paragraph="م", general_objective="ه",
slides=[slide], activities=[card])
finally:
_ctx.reset(token)
text = "\n".join(p.text for p in Document(str(out)).paragraphs)
assert "اقرأ الموقف" in text
assert "عزيزي المتدرب:" in text
assert "يوزّع المدرب" not in text
assert "تمييز الأنماط" not in text
assert "25" not in text
assert "دراسة حالة" not in text
def test_the_trainee_line_is_feminised_by_the_renderer_not_by_hand(tmp_path):
"""The `add_*` helpers already voice what they are given. Voicing it here
as well turns «المدرب» into «المدربة» into «المدربةة», which is the fault
the language module's single pass exists to prevent."""
from docx import Document
card = {"title": "ن", "trainee_instructions": "ناقش الموقف مع زميلتك."}
slide = {"day": 1, "session": 1, "slide_type": "activity",
"title": "ن", "source_activity": "ن"}
out = tmp_path / "she.docx"
token = _ctx.set(ArabicBagContext(blueprint=_blueprint(1, 1),
audience_gender="مؤنث"))
try:
generate_deck_word(str(out), blueprint=_blueprint(1, 1),
intro_paragraph="م", general_objective="ه",
slides=[slide], activities=[card])
finally:
_ctx.reset(token)
text = "\n".join(p.text for p in Document(str(out)).paragraphs)
assert "عزيزتي المتدربة:" in text
assert "المتدربةة" not in text
assert "عزيزي المشارك" not in text
# ───────────────────────────── الخطة
def test_material_must_be_followed_by_its_activity():
"""A case study with no activity after it is a slide nobody can act on."""
slides = [{"slide_type": "activity_material", "title": "موقف",
"source_activity": "ن", "session": 1}]
assert any("لا تليها" in e for e in check_plan(slides, []))
def test_every_activity_gets_a_slide():
slides = [{"slide_type": "concept", "title": "أ", "source_cover": "م",
"session": 1}] * 12
errs = check_plan(slides, [{"title": "نشاط الافتتاح"}])
assert any("نشاط الافتتاح" in e for e in errs)
def test_a_day_below_the_floor_is_refused():
thin = [{"slide_type": "concept", "title": "أ", "source_cover": "م",
"session": 1}] * 4
assert any("أقل من" in e for e in check_plan(thin, []))
def test_going_over_thirty_is_noted_and_not_refused():
"""«مش صارم صارم — لو اليوم محاوره كتير وتضطر تعمل الفواصل يبقى عادي لو
عدّه». So a big day is reported, never rejected."""
many = [{"slide_type": "concept", "title": f"ش{i}", "source_cover": "م",
"session": 1} for i in range(34)]
assert check_plan(many, []) == []
note = slide_budget_note([{**s, "day": 1} for s in many])
assert note["over_max"] == [1]
assert note["total"] == 34
def test_the_band_is_the_one_the_author_gave():
assert (SLIDES_PER_DAY_MIN, SLIDES_PER_DAY_MAX) == (25, 30)
def test_the_two_bag_types_join_the_nine():
assert len(DECK_SLIDE_TYPES) == 11
assert "activity" in DECK_SLIDE_TYPES
assert "activity_material" in DECK_SLIDE_TYPES
# ───────────────────────────── الكاتب
def test_a_long_slide_is_reported_and_not_rejected():
fat = {"slide_type": "key_message", "title": "ع",
"body": " ".join(["كلمة"] * 40)}
over = over_ceiling([fat])
assert over and over[0]["ceiling"] == 22
assert over[0]["words"] > 22
def test_the_word_count_includes_everything_printed():
"""The ceilings are set on the whole slide, not on its body alone."""
slide = {"slide_type": "comparison", "title": "أ ب",
"columns": ["ج", "د"], "rows": [["هـ", "و"]]}
assert slide_words(slide) == 6
def test_the_writer_reads_every_block_the_renderer_can_draw():
"""A block type the flattener does not know becomes a heading and nothing
else, and the slide built from it comes out empty."""
source = inspect.getsource(cover_text)
for kind in ("paragraph", "titled_points", "bullet_list", "grouped_list",
"table", "contrast_pair", "key_insight", "practice_scenario",
"shift_in_practice", "checklist"):
assert kind in source, kind
def test_the_material_flattens_into_something_readable():
cover = {
"cover": "أنماط القيادة",
"blocks": [
{"block_type": "titled_points", "heading": "الأنماط",
"point_items": [{"title": "الديمقراطية", "explanation": "يشارك الفريق."}]},
{"block_type": "table", "headers": ["النمط", "متى"],
"rows": [["الحرة", "فريق ناضج"]]},
],
}
text = cover_text(cover)
assert "أنماط القيادة" in text
assert "الديمقراطية: يشارك الفريق." in text
assert "النمط | متى" in text
# ───────────────────────────── المسار
def test_the_deck_is_two_optional_steps_before_the_export():
from app.pipelines.registry import get
keys = [s.key for s in get("arabic_training_bag").steps]
assert keys.index("bag_ar.deck_plan") < keys.index("bag_ar.deck")
assert keys.index("bag_ar.deck") < keys.index("bag_ar.export")
by_key = {s.key: s for s in get("arabic_training_bag").steps}
assert by_key["bag_ar.deck_plan"].optional
assert by_key["bag_ar.deck"].optional
def test_the_deck_reads_the_bag_and_never_the_web():
"""«عاوز من محتوى الحقيبة نفسه، مايجبش من برا». The planner and the writer
take covers and activities and have no search or scrape between them."""
from app.agents.arabic_bag import deck_planner, deck_writer
for module in (deck_planner, deck_writer):
source = inspect.getsource(module)
for forbidden in ("serper", "requests", "scrape", "search("):
assert forbidden not in source, f"{module.__name__}: {forbidden}"
def test_the_export_still_writes_the_bag_when_no_deck_was_asked_for():
"""The steps are optional, so the export has to cope with their absence."""
from app.pipelines.arabic_bag import steps
source = inspect.getsource(steps.ExportStep.run)
assert "if slides:" in source
assert '"files": (3 if deck else 2) + (1 if references else 0)' in source
def test_the_standard_the_prompts_carry_is_the_author_s_own():
for line in ("لا يُدرج التوثيق في المتن",
"لا تُدرج الأمثلة إلا إذا كانت ضرورية",
"الاختصار لا يعني حذف المحتوى الضروري"):
assert line in DECK_STANDARD_AR, line
def _session_blueprint():
return {"days": [{"day_number": 1, "day_title": "", "sessions": [{
"session_number": 1, "session_title": "Session 1", "topics": [
{"topic": "الأول", "covers": [{"cover": "أ"}]},
{"topic": "الثاني", "covers": [{"cover": "ب"}]},
]}]}]}
ACTS = [{"day": 1, "session": 1, "title": "تعارف", "after_topic": 0},
{"day": 1, "session": 1, "title": "تطبيق", "after_topic": 1}]
def test_an_english_session_name_does_not_reach_the_file():
lines = day_session_lines(1, 1, "", "Session 1", total_days=1, sessions_in_day=1)
assert lines == ["الجلسة الأولى"]
lines = day_session_lines(1, 2, "", "session 2", total_days=1, sessions_in_day=2)
assert lines == ["الجلسة الثانية"]
def test_activities_stand_where_the_session_runs_them_and_in_its_topics():
slides = [{"day": 1, "session": 1, "slide_type": "concept", "title": "ش١", "source_cover": "أ"},
{"day": 1, "session": 1, "slide_type": "concept", "title": "ش٢", "source_cover": "ب"},
{"day": 1, "session": 1, "slide_type": "activity_material", "title": "مادة",
"source_activity": "تطبيق"},
{"day": 1, "session": 1, "slide_type": "activity", "title": "تطبيق",
"source_activity": "تطبيق"},
{"day": 1, "session": 1, "slide_type": "activity", "title": "تعارف",
"source_activity": "تعارف"},
# the planner's copy of a slide it already made, after the activities
{"day": 1, "session": 1, "slide_type": "concept", "title": "ش٢", "source_cover": "ب"}]
pages = build_pages(_session_blueprint(), "م", "ه", slides, ACTS)
assert [p.get("title") for p in pages if p.get("slide_type")] == [
"تعارف", "ش١", "مادة", "تطبيق", "ش٢"]
topics = next(p for p in pages if p["kind"] == "session_topics")["items"]
assert topics == ["نشاط: تعارف", "الأول", "نشاط: تطبيق", "الثاني"]
def test_no_word_for_topic_before_a_title_and_tables_only_to_compare():
slides = [{"day": 1, "session": 1, "slide_type": "concept", "title": "المحور الأول: القراءة"},
{"day": 1, "session": 1, "slide_type": "comparison", "title": "أنواع الصعوبات",
"columns": ["النوع", "الأسلوب", "الخصائص"], "rows": [["القراءة", "فك", "بطء"]]},
{"day": 1, "session": 1, "slide_type": "comparison", "title": "الفرق بين النوعين",
"columns": ["البعد", "أ", "ب"], "rows": [["الأثر", "س", "ص"]]}]
pages = build_pages(_session_blueprint(), "م", "ه", slides, [])
pages = [p for p in pages if p.get("slide_type")]
assert pages[0]["title"] == "القراءة"
assert pages[1]["slide_type"] == "titled_points" and not pages[1]["rows"]
assert pages[1]["points"] == [{"title": "القراءة", "text": "الأسلوب: فك · الخصائص: بطء"}]
assert pages[2]["slide_type"] == "comparison" and pages[2]["rows"]