Claude Opus 5.5
Deploy 9e83dee: case study revision, text_image, simulation_game, interactive_activities, dna_microlearning (founder-only preview)
258a360 Download apps/api/app/agents/case_study/scripts.py from aliroya/contiai: direct link, hf CLI and curl.
- Browser
- Download file 9.45 kB
-
https://huggingface.co/spaces/aliroya/contiai/resolve/main/apps/api/app/agents/case_study/scripts.py
- Command line
-
hf download hf://spaces/aliroya/contiai/apps/api/app/agents/case_study/scripts.py
-
curl -L -o scripts.py https://huggingface.co/spaces/aliroya/contiai/resolve/main/apps/api/app/agents/case_study/scripts.py
9.45 kB
| """Step 4 - the voice-over, held to length. Cell [14]. | |
| 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.lint import * # noqa: F403 | |
| from app.agents.case_study.profiles import * # noqa: F403 | |
| from app.agents.case_study.runner import * # noqa: F403 | |
| from app.agents.case_study.schemas import * # noqa: F403 | |
| from app.agents.case_study.standards import * # noqa: F403 | |
| # The notebook was one namespace; these are read below and were | |
| # not carried over by the split into modules. | |
| from app.agents.case_study.agents import writer_agent | |
| from app.agents.case_study.analysis import build_prompt | |
| SCRIPTS_SKELETON = """{ | |
| "scenes": [ | |
| {"scene_number": 1, "kind": "situation", "lines": [ | |
| {"role": "narration", "text": "سطر مسموع واحد = فكرة/لقطة واحدة.", "speaker": "الراوي"}, | |
| {"role": "dialogue", "text": "\\"جملة الحوار\\"", "speaker": "اسم الشخصية"} | |
| ]}, | |
| {"scene_number": 4, "kind": "reflection", "lines": [ | |
| {"role": "character_action", "text": "وهذا بالضبط ما فعله ...، إذ ...", "speaker": "الراوي"}, | |
| {"role": "link", "text": "فـ... يلتزم دائمًا بـ... التالية:", "speaker": "الراوي"}, | |
| {"role": "bullet", "text": "نقطة إرشادية موجزة.", "speaker": "الراوي"} | |
| ]}, | |
| {"scene_number": 9, "kind": "closing", "lines": [ | |
| {"role": "closing_scene", "text": "وهكذا، ...", "speaker": "الراوي"}, | |
| {"role": "closing_sentence", "text": "جملة ختامية واحدة ذات أثر مرتبطة بالموضوع.", "speaker": "الراوي"}, | |
| {"role": "teaser", "text": "وفي الدرس القادم، سنتعرف معًا على ...", "speaker": "الراوي"} | |
| ]} | |
| ] | |
| }""" | |
| def _roles_text(inp: CaseInput) -> str: | |
| rows = [] | |
| for k, r in KIND_ROLES.items(): | |
| req = set(r["required"]) | |
| if k == "closing" and PROFILES[inp.product_type]["closing_requires_scene"]: | |
| req.add("closing_scene") | |
| if k == "closing" and inp.next_context: | |
| req.add("teaser") | |
| rows.append(f"- {k}: المسموح {sorted(r['allowed'])} | الإلزامي {sorted(req)}") | |
| return "الأدوار (role) لكل نوع مشهد:\n" + "\n".join(rows) + \ | |
| "\n- thanks تُضاف آليًا من الإعدادات (لا تكتبها). لا teaser إن لم يوجد تسلسل." | |
| def _inter_summary(inters: dict[int, Interaction]) -> list[dict]: | |
| return [{"scene_number": k, "type": v.type_ar, "question": f"{v.situation_sentence} {v.question}", | |
| "correct_answer": v.correct_answer_text, "after_action": v.after_action} for k, v in sorted(inters.items())] | |
| def _writer_task(inp: CaseInput, bp: Blueprint) -> str: | |
| targets = ", ".join(f"م{s.scene_number}({s.kind})≈{s.target_words}" for s in bp.scenes if s.kind != "interaction") | |
| return f"""\ | |
| - اكتب أسطر النص المسموع (VO) لكل المشاهد **غير التفاعلية** فقط: {[s.scene_number for s in bp.scenes if s.kind != 'interaction']} (مشاهد التفاعل تُبنى آليًا من interactions). | |
| - كل سطر = فكرة/لقطة واحدة قصيرة (سيُبنى لكل سطر beat بصري). الأطوال المستهدفة بالكلمات: {targets}؛ الإجمالي مع التفاعلات ≈ {inp.size.resolved_target_words} كلمة. | |
| - ترابط سردي واحد من أول مشهد لآخره؛ المشهد السابق لكل تفاعل ينتهي **عند لحظة القرار نفسها** التي يطرحها سؤال التفاعل تمامًا (لا قبلها ولا بعدها). | |
| - كتابة درامية احترافية: تفاصيل حسّية ملموسة (مكان، زمن، صوت، حركة) تُدخل المتدرب في الموقف، وتوتر يتصاعد نحو القرار؛ لا جُمل تقريرية جافة ولا حشو ولا تكرار لفكرة سبق ذكرها. | |
| - reflection: (1) character_action يعكس after_action للتفاعل السابق ويذكر اسم الشخصية («وهذا بالضبط ما فعله ...»)، (2) link تمهيدية تنتهي بـ«:»، (3) من 3 إلى 6 bullet مستخلصة من المحتوى. | |
| - guidance: link تنتهي بـ«:» ثم bullet (من 3 إلى 6) مرتبطة بالموقف السابق. | |
| - الحوار: role=dialogue وspeaker باسم الشخصية، والنص بين علامتي تنصيص. | |
| - closing: {'closing_scene يُغلق الموقف ويوضح كيف آلت الأمور، ثم ' if PROFILES[inp.product_type]['closing_requires_scene'] else ''}closing_sentence واحدة ذات أثر مرتبطة بالموضوع تحديدًا (لا قوالب){'، ثم teaser مشوّق عن: ' + inp.next_context if inp.next_context else ''}. | |
| - {'جملة ربط (role=link) بعد المقدمة تعلن المحاور — إلزامية.' if bp.intro_link_required else 'جملة الربط بعد المقدمة اختيارية.'} | |
| - التزم بكل معلومة وردت في المحتوى وبالمصطلحات الدقيقة؛ فصحى سليمة؛ بلا حروف لاتينية في النص المسموع. | |
| {_roles_text(inp)}""" | |
| async def _write_all(inp, analysis, bp, inters, extra: str = "", current: Optional[Scripts] = None, marker_task="script") -> Scripts: | |
| scenes_meta = ",".join(f"{s.scene_number}:{s.kind}" for s in bp.scenes if s.kind != "interaction") | |
| prev = {"تحليل المحتوى": analysis, | |
| "المخطط (المحاور والشخصيات والمشاهد)": {"title": bp.title, "axes": [a.model_dump() for a in bp.axes], | |
| "intro_type": bp.intro_type, "intro_idea": bp.intro_idea, | |
| "characters": [c.model_dump() for c in bp.characters], | |
| "scenes": [s.model_dump() for s in bp.scenes], | |
| "closing_idea": bp.closing_idea, "next_teaser_idea": bp.next_teaser_idea}, | |
| "التفاعلات (ما يسأل عنه كل تفاعل وما فعلته الشخصية)": _inter_summary(inters)} | |
| if current is not None: | |
| prev["النص الحالي"] = current | |
| prompt = build_prompt(f"#TASK={marker_task} #SCENE=0 #SCENES={scenes_meta}", inp, prev, | |
| std_block(inp) + "\n\n" + STYLE_EXAMPLE, _writer_task(inp, bp) + extra, SCRIPTS_SKELETON) | |
| sc = await run_json_task(writer_agent, prompt, Scripts, marker_task, lambda o: v_scripts(o, bp, inp)) | |
| plans = {s.scene_number: s for s in bp.scenes} | |
| for s in sc.scenes: | |
| normalize_scene_script(s, plans[s.scene_number], inp) | |
| sc.scenes.sort(key=lambda s: s.scene_number) | |
| return sc | |
| async def step_write(inp: CaseInput, analysis: Analysis, bp: Blueprint, inters: dict[int, Interaction]) -> Scripts: | |
| scripts = await _write_all(inp, analysis, bp, inters) | |
| target, tol = inp.size.resolved_target_words, inp.size.tolerance | |
| for loop in range(RUN_CONFIG["length_loops"] + 1): | |
| total = total_vo_words(all_scene_lines(bp, scripts, inters)) | |
| dev = (total - target) / target | |
| log(f" الطول: {total} كلمة (المستهدف {target}، الانحراف {dev:+.0%})") | |
| if abs(dev) <= tol: | |
| break | |
| if loop == RUN_CONFIG["length_loops"]: | |
| qa("script", "length", [f"الطول النهائي {total} كلمة مقابل {target} (خارج ±{int(tol * 100)}%) — قُبل بعد {loop} دورات ضبط."]) | |
| break | |
| per = {s.scene_number: sum(word_count(l.text) for l in s.lines) for s in scripts.scenes} | |
| direction = "اختصر" if dev > 0 else "وسّع" | |
| extra = (f"\n### ضبط الطول (دورة {loop + 1}): الإجمالي الحالي {total} كلمة والمستهدف {target} (±{int(tol * 100)}%). " | |
| f"{direction} النص بنحو {abs(total - target)} كلمة دون إسقاط أي معلومة أو مكوّن إلزامي. " | |
| f"أطوال المشاهد الحالية: {per}. أعد كل المشاهد كاملة.") | |
| scripts = await _write_all(inp, analysis, bp, inters, extra, current=scripts, marker_task="script_length") | |
| save_json("scripts.json", {"scenes": [{"scene_number": n, "kind": next(s.kind for s in bp.scenes if s.scene_number == n), | |
| "lines": [l.model_dump() for l in lines]} | |
| for n, lines in sorted(all_scene_lines(bp, scripts, inters).items())]}) | |
| log(f"✓ النص: {len(scripts.scenes)} مشاهد سردية") | |
| return scripts | |
| # scripts = await step_write(INPUT, analysis, blueprint, interactions) | |