File size: 12,250 Bytes
ea1dd9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258a360
ea1dd9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""Step 5 - the visual direction, scene by scene. Cell [15].

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 visual_agent
from app.agents.case_study.analysis import build_prompt

from app.agents.batch_calls import one_call_then_fill

VISUAL_SKELETON = """{
  "scene_number": 1,
  "beats": [
    {"line_index": 0, "visual_idea": "الفكرة البصرية لهذا السطر", "shot": "نوع اللقطة والزاوية",
     "action": "الحركة/التكوين وما تفعله الشخصية وتعبير وجهها", "on_screen_text": "نص يظهر على الشاشة أو فارغ",
     "text_position": "موضع النص (أعلى/أسفل/فقاعة...)", "effect": "Pop / Fade In / Pulse ...",
     "sfx": "المؤثر الصوتي ومستواه تحت التعليق الصوتي", "transition": "الانتقال إلى اللقطة التالية"}
  ],
  "narrative": "وصف سردي تنفيذي متصل لما تظهره الشاشة لحظة بلحظة",
  "description": {"background": "الخلفية والبيئة", "characters": "الشخصيات وملامحها وتعبيرات وجوهها",
                  "actions": "الحركات والأفعال", "shots": "اللقطات والزوايا", "visual_effects": "المؤثرات البصرية",
                  "sound_effects": "المؤثرات الصوتية ومستوياتها (لا تطغى على VO)", "graphics_notes": "ملحوظات لفريق الجرافيك"},
  "freeze_at_end": false,
  "freeze_description": "",
  "interaction_visual": null,
  "reference_suggestions": ["مرجع بصري مقترح بوصف نصي (بلا روابط)"]
}"""

INTERACTION_VISUAL_SKELETON = """"interaction_visual": {
    "question_frame": "ظهور إطار السؤال (Fade In) وموضعه وشكله",
    "option_cards": [{"item_id": "A", "visual": "مشهد المحاكاة المصغّر لهذه البطاقة/النقطة وتأثير ظهورها (Pop/Pulse)"}],
    "instruction_frame": "إطار الجملة التوجيهية أسفل الشاشة",
    "check_button_visual": "متى وأين يظهر زر «تحقّق من الإجابة» (أو فارغ)",
    "hint_visual": "أيقونة 💡 وموضعها وما يظهر عند الضغط (أو فارغ)",
    "feedback_correct_visual": "✅ خضراء + صوت إنجاز + ما يظهر",
    "feedback_incorrect_visual": "❌ حمراء + صوت تنبيه + إعادة المحاولة أو الانتقال",
    "mechanism_visual": ["ما يحدث بصريًا وصوتيًا عند كل استجابة"]
  }"""

def direct_scene_prompt(inp: CaseInput, bp: Blueprint, plan: ScenePlan, lines: list[Line],
                        it: Optional[Interaction], neighbors: list[dict],
                        fix_notes: str = "", current: Optional[SceneVisual] = None) -> str:
    """The per-scene prompt, lifted out of `direct_scene` unchanged.

    The batched call below builds the same brief for every scene in a group,
    so there is one copy of it rather than two that drift - which is what
    happened to `kind_rules` in the interactive infographic.
    """
    n = len(lines)
    numbered = [{"line_index": i, "role": l.role, "speaker": l.speaker, "text": l.text} for i, l in enumerate(lines)]
    prev = {"النظام البصري والشخصيات": {"visual_system": bp.visual_system.model_dump(),
                                         "characters": [c.model_dump() for c in bp.characters]},
            "خطة المشهد": plan,
            f"أسطر النص المسموع ({n} سطر)": numbered,
            "المشاهد المجاورة (للاستمرارية وتنويع الأفكار)": neighbors}
    if it is not None:
        prev["التفاعل"] = it
    if current is not None:
        prev["الوصف الحالي (عدّله)"] = current
    task = f"""\
- اكتب **{n} beats بالضبط** (line_index من 0 إلى {n - 1})؛ beat لكل سطر: الفكرة البصرية، اللقطة والزاوية، الحركة/التكوين وتعبير الوجه، النص على الشاشة وموضعه، تأثير الظهور، المؤثر الصوتي، الانتقال.
- ثم narrative: وصف سردي تنفيذي متصل، وdescription بالمكونات السبعة الإلزامية كاملة.
- تعبيرات الوجه تتغير حسب السياق ولا تبقى جامدة؛ نوّع التكوين عن المشاهد المجاورة؛ التزم بالسياق الجغرافي والثقافي والزي والحيادية وقيود الشخصيات.
- وصف تنفيذي لا يُترك للتخمين: سمِّ نوع اللقطة والزاوية صراحةً (واسعة/متوسطة/مقرّبة/من الخلف/فوق الكتف...)، وحدِّد تعبير الوجه بدقة، واكتب النص الظاهر على الشاشة حرفيًا وموضعه، ولوّن العناصر الدالة (✅ أخضر، ❌ أحمر، تنبيه أصفر)، وانصّ على تزامن كل ظهور بصري مع صوته المخصص.
- النقاط الإرشادية (bullet) تُعرض بطاقات متتالية بتأثير Pop، كل بطاقة بمشهد مصغّر وأيقونة معبرة وعلامة ✅ وصوت إنجاز خفيف.
- المصطلحات الثنائية على الشاشة (عربي/إنجليزي) فقط عند الحاجة لتعزيز التعرف البصري.
- {'freeze_at_end=true: صف تجمّد الشاشة في نهاية المشهد مع موجة تنبيه صفراء خفيفة وصوت تنبيه قصير هادئ (freeze_description).' if plan.freeze_at_end else 'freeze_at_end=false.'}
- {'مشهد تفاعل: املأ interaction_visual كاملًا — بطاقة لكل عنصر بمعرّفه ' + str([x.id for x in it.items]) + '، وصف زر التحقق ' + ('(مطلوب)' if it.check_button else '(لا يوجد)') + '، والتلميح ' + ('(مطلوب)' if it.hint else '(لا يوجد)') + '، ومشهدي التغذية الراجعة. الشكل:' + chr(10) + INTERACTION_VISUAL_SKELETON if it is not None else 'interaction_visual=null.'}
- reference_suggestions: مراجع بصرية مقترحة بوصف نصي فقط عند الحاجة (لا روابط ولا صور مولّدة).{chr(10) + '### ملاحظات إصلاح يجب تنفيذها:' + chr(10) + fix_notes if fix_notes else ''}"""
    standards = "\n\n".join([STD_SCENE_DESCRIPTION, STD_NEUTRALITY, STD_LANGUAGE] + ([STD_INTERACTION_SCREEN] if it is not None else []))
    items = len(it.items) if it is not None else 0
    marker = f"#TASK={'fix_visual' if fix_notes else 'visual'} #SCENE={plan.scene_number} #KIND={plan.kind} #LINES={n} " \
             f"#ITEMS={items} #FREEZE={int(plan.freeze_at_end)} #CHECK={int(bool(it and it.check_button))} #HINTV={int(bool(it and it.hint))}"
    return build_prompt(marker, inp, prev, standards, task, VISUAL_SKELETON)


async def direct_scene(inp: CaseInput, bp: Blueprint, plan: ScenePlan, lines: list[Line], it: Optional[Interaction],
                       neighbors: list[dict], fix_notes: str = "", current: Optional[SceneVisual] = None) -> SceneVisual:
    n = len(lines)
    prompt = direct_scene_prompt(inp, bp, plan, lines, it, neighbors, fix_notes, current)
    sv = await run_json_task(visual_agent, prompt, SceneVisual, f"visual[{plan.scene_number}]",
                             lambda o: v_visual(o, lines, plan, it, inp))
    return normalize_visual(sv, n)

def _neighbors(bp: Blueprint, lines_by: dict[int, list[Line]], num: int) -> list[dict]:
    out = []
    for s in bp.scenes:
        if abs(s.scene_number - num) == 1:
            out.append({"scene_number": s.scene_number, "kind": s.kind, "purpose": s.purpose,
                        "first_line": lines_by[s.scene_number][0].text if lines_by.get(s.scene_number) else ""})
    return out

async def step_visual(inp: CaseInput, bp: Blueprint, scripts: Scripts, inters: dict[int, Interaction]) -> dict[int, SceneVisual]:
    lines_by = all_scene_lines(bp, scripts, inters)
    # Grouped rather than one call per scene. A ten-scene element paid for
    # ten copies of the visual system, the characters and the standards; the
    # weight is the number of lines, because a beat is about four hundred
    # tokens of output and a long scene is what runs a reply past the
    # completion ceiling.
    res = await one_call_then_fill(
        list(bp.scenes),
        together=lambda group: direct_scenes(inp, bp, group, lines_by, inters),
        alone=lambda s: direct_scene(inp, bp, s, lines_by[s.scene_number],
                                     inters.get(s.scene_number),
                                     _neighbors(bp, lines_by, s.scene_number)),
        key=lambda v: v.scene_number,
        wanted=lambda s: s.scene_number,
        label="الوصف البصري",
        weight=lambda s: max(len(lines_by.get(s.scene_number, [])), 1),
        budget=24,
    )
    visual = {v.scene_number: v for v in res}
    save_json("visual.json", [visual[k] for k in sorted(visual)])
    log(f"✓ الوصف البصري: {len(visual)} مشاهد، {sum(len(v.beats) for v in visual.values())} beats")
    return visual

# visual = await step_visual(INPUT, blueprint, scripts, interactions)


# ── نداء واحد لمجموعة مشاهد، أضافته المنصة ─────────────────────────────────

class _AllVisuals(BaseModel):
    scenes: list[SceneVisual]


async def direct_scenes(inp, bp, group: list, lines_by: dict, inters: dict) -> list[SceneVisual]:
    briefs = [direct_scene_prompt(inp, bp, s, lines_by[s.scene_number],
                                  inters.get(s.scene_number),
                                  _neighbors(bp, lines_by, s.scene_number))
              for s in group]
    joined = "\n\n" + ("\n\n" + "─" * 60 + "\n\n").join(briefs)
    numbers = [s.scene_number for s in group]
    prompt = (f"#TASK=visual #ALL #SCENES={numbers}\n"
              f"اكتب وصف {len(group)} مشاهد، واحدًا واحدًا وبالترتيب، كلٌّ وفق بريفه كاملًا أدناه.\n"
              f"البريفات مفصولة بخط؛ التزم في كل مشهد بعدد الأسطر المذكور فيه: beat لكل سطر."
              f"{joined}\n\n"
              f"أعد JSON واحدًا بالشكل {{\"scenes\": [ ... ]}} حيث كل عنصر مشهد كامل بهيكله.")
    got = await run_json_task(visual_agent, prompt, _AllVisuals,
                              f"visual[all:{len(group)}]")
    plans = {s.scene_number: s for s in group}
    out = []
    for v in got.scenes:
        plan = plans.get(v.scene_number)
        if plan is None:
            continue
        v = normalize_visual(v, len(lines_by[v.scene_number]))
        hard, _soft = v_visual(v, lines_by[v.scene_number], plan,
                               inters.get(v.scene_number), inp)
        if hard:
            continue                      # هيكلي: يُعاد طلبه وحده
        out.append(v)
    return out