File size: 4,447 Bytes
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
"""Step 1 - reading the content. Cell [11].

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 analyst_agent

def build_prompt(marker: str, inp: CaseInput, prev: dict[str, Any], standards: str, task: str, skeleton: str) -> str:
    """ترتيب ثابت: marker ← سياق المشروع ← المدخلات السابقة (JSON) ← المعايير الملزمة ← المطلوب ← skeleton."""
    parts = [marker, project_context_block(inp)]
    for title, obj in prev.items():
        body = obj if isinstance(obj, str) else dump(obj)
        parts.append(f"### {title}\n```\n{body}\n```")
    parts.append("### المعايير الملزمة\n" + standards)
    parts.append("### المطلوب\n" + task)
    parts.append("### هيكل المخرج (JSON حرفي — التزم بالمفاتيح والأنواع)\n```json\n" + skeleton.strip() +
                 "\n```\nأخرج كائن JSON واحدًا فقط دون أي شرح.")
    return "\n\n".join(parts)


ANALYSIS_SKELETON = """{
  "domain": "المجال",
  "audience_profile": "وصف الفئة وما يناسبها",
  "central_idea": "الفكرة المحورية في جملة",
  "learning_need": "المشكلة الأدائية التي يعالجها المحتوى",
  "content_blocks": [
    {"id": "B1", "heading": "عنوان الكتلة", "summary": "ملخص أمين",
     "key_points": ["نقطة كما وردت", "..."], "facts": ["رقم/إحصائية/خطوة كما وردت حرفيًا"]}
  ],
  "candidate_axes": ["محور مقترح يبدأ بمصدر", "..."],
  "suggested_intro": {"type": "realistic_situation", "idea": "فكرة المقدمة"},
  "cultural_notes": ["ملاحظة ثقافية/جغرافية تنعكس على المشاهد"],
  "risks": ["نقطة علمية أو حساسة تحتاج انتباهًا"]
}"""

async def step_analyze(inp: CaseInput) -> Analysis:
    task = """\
- حدّد المجال والفئة والفكرة المحورية والحاجة الأدائية.
- قسّم المحتوى إلى content_blocks **بترتيبه الأصلي** (id: B1, B2...)، وانقل كل معلومة وكل رقم وكل خطوة دون إسقاط أو تحريف (key_points وfacts).
- اقترح candidate_axes (من {lo} إلى {hi}) تبدأ بمصدر معرّف دون أفعال.
- اقترح أسلوب المقدمة الأنسب (type من: provocative_question | realistic_situation | surprising_fact) مع الفكرة.
- cultural_notes حسب السياق الجغرافي والثقافي المحدد (أو «عام» إن كان فارغًا)، وrisks للنقاط العلمية الحساسة.""".format(
        lo=inp.type_settings.axes_min, hi=inp.type_settings.axes_max)
    prompt = build_prompt("#TASK=analysis #SCENE=0", inp, {"المحتوى الخام": inp.content},
                          "\n\n".join([STD_CONTENT_FIRST, STD_INTRO,
                                       STD_META.format(axes_min=inp.type_settings.axes_min, axes_max=inp.type_settings.axes_max)]),
                          task, ANALYSIS_SKELETON)
    analysis = await run_json_task(analyst_agent, prompt, Analysis, "analysis", v_analysis)
    save_json("analysis.json", analysis)
    log(f"✓ التحليل: {len(analysis.content_blocks)} كتل محتوى")
    return analysis

# analysis = await step_analyze(INPUT)