File size: 11,244 Bytes
325b94c
 
 
 
 
 
 
 
 
ad2f07f
325b94c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2f07f
325b94c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2f07f
 
325b94c
 
 
 
 
f07fe0d
 
325b94c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# app/core/books/content_services.py
import json
from copy import deepcopy
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, Any, List, Tuple

from .content_crew_config import safe_run_once, build_rag_block
from agents.books.book_content import make_writer_crew, make_quality_crew
from agents.books.book_content_gpt import make_writer_crew_gpt, make_quality_crew_gpt
# from agents.books import make_writer_editor_crew

MAX_CHAPTER_WORKERS = 3

# ู„ูˆ True: quality ูŠู‚ุฏุฑ ูŠูˆู„ุฏ ู…ุญุชูˆู‰ ุญุชู‰ ู„ูˆ writer ุฑุฌู‘ุน ูุงุถูŠ
# ู„ูˆ False: quality ูŠุฑุงุฌุน ูู‚ุทุŒ ูˆู„ูˆ draft ูุงุถูŠ ูŠูุถู„ ูุงุถูŠ
ALLOW_QUALITY_FROM_EMPTY_DRAFT = False

# ู…ูุงุชูŠุญ ู„ุงุฒู…ุฉ ู„ู„ู€ writer prompt
WRITER_REQUIRED_KEYS = [
    "book_title",
    "book_description",
    "target_audience",
    "chapter_title",
    "chapter_outcome",
    "section_title",
    "section_overview",
    "subsection_title",
    "subsection_purpose",
    "style_profile_json",
    "writing_mode",
    "tone",
    "target_pages",
    "core_idea",
    "key_points",
    "scope_limit",
    "avoid_overlap_with",
    "depth_level",
    # "citations_required",
    "planner_notes",
    "rag_block",
]


def _iter_section_plans(section: dict):
    """
    ูŠุฏุนู… ุงู„ุดูƒู„ ุงู„ุฌุฏูŠุฏ:
      section["plans"] = { "ุนู†ูˆุงู† ุงู„ู…ุญูˆุฑ": { ...plan... }, ... }

    + fallback ู„ู„ุดูƒู„ ุงู„ู‚ุฏูŠู…:
      section["subsections"] = [ {...}, ... ]
    """
    plans = section.get("plans")
    if isinstance(plans, dict) and plans:
        for subsection_title, plan in plans.items():
            yield subsection_title, plan if isinstance(plan, dict) else {}
        return

    # fallback legacy
    for sub in section.get("subsections", []):
        subsection_title = sub.get("title") or sub.get("subsection_title") or ""
        yield subsection_title, sub if isinstance(sub, dict) else {}


def _normalize_plan(raw_plan: dict) -> dict:
    """
    ูŠูˆุญู‘ุฏ ุดูƒู„ plan ุณูˆุงุก ุฌุงูŠ ุจุงู„ุดูƒู„ ุงู„ุฌุฏูŠุฏ ุฃูˆ ุงู„ู‚ุฏูŠู….
    """
    if not isinstance(raw_plan, dict):
        return {}

    # ุงู„ุดูƒู„ ุงู„ู‚ุฏูŠู…: subsection ููŠู‡ planning + rag_context
    if "planning" in raw_plan and isinstance(raw_plan.get("planning"), dict):
        planning = deepcopy(raw_plan.get("planning", {}))
        planning.setdefault("purpose", raw_plan.get("purpose", ""))
        planning.setdefault("rag_context", raw_plan.get("rag_context", {}))
        planning.setdefault("status", raw_plan.get("status", "ready"))
        return planning

    # ุงู„ุดูƒู„ ุงู„ุฌุฏูŠุฏ: plan ุฌุงู‡ุฒ ู…ุจุงุดุฑุฉ
    return deepcopy(raw_plan)


def _as_json_string(value, fallback=None) -> str:
    if value is None:
        value = fallback if fallback is not None else {}
    if isinstance(value, str):
        return value
    try:
        return json.dumps(value, ensure_ascii=False)
    except Exception:
        return str(value)


def _as_text(value) -> str:
    if value is None:
        return ""
    return str(value).strip()


def _as_text_list(value) -> str:
    """
    ุชุญูˆูŠู„ list/string ุฅู„ู‰ ู†ุต ุซุงุจุช ู„ู„ู€ interpolation.
    """
    if value is None:
        return ""
    if isinstance(value, list):
        cleaned = [str(x).strip() for x in value if str(x).strip()]
        return " | ".join(cleaned)
    return str(value).strip()


def _ensure_required_inputs(inputs: dict, required_keys: List[str], ctx: str = ""):
    missing = [k for k in required_keys if k not in inputs]
    if missing:
        prefix = f"[{ctx}] " if ctx else ""
        raise ValueError(f"{prefix}Missing required input keys: {missing}")


def build_inputs(
    book_meta: Dict[str, Any],
    chapter: Dict[str, Any],
    section: Dict[str, Any],
    subsection_title: str,
    plan: Dict[str, Any],
) -> Dict[str, Any]:
    chapter_intro = chapter.get("chapter_intro", {})
    if not isinstance(chapter_intro, dict):
        chapter_intro = {}

    rag_context = plan.get("rag_context", {})
    if not isinstance(rag_context, dict):
        rag_context = {}

    rag_block = build_rag_block(rag_context.get("chunks", []))

    # style_profile ุบุงู„ุจู‹ุง ุนู„ู‰ ู…ุณุชูˆู‰ chapter
    style_profile = chapter.get("style_profile")
    if style_profile is None:
        style_profile = section.get("style_profile")

    # chapter_outcome fallback ู…ู† chapter_intro
    chapter_outcome = chapter.get("outcome") or chapter_intro.get(
        "why_this_chapter_now", ""
    )

    safe_subsection_title = (
        _as_text(subsection_title)
        or _as_text(plan.get("subsection_title", ""))
        or "ู…ุญูˆุฑ ูุฑุนูŠ"
    )

    return {
        "book_title": _as_text(book_meta.get("book_title", "")),
        "book_description": _as_text(book_meta.get("book_description", "")),
        "target_audience": _as_text(book_meta.get("target_audience", "")),
        "chapter_title": _as_text(chapter.get("chapter_title", "")),
        "chapter_outcome": _as_text(chapter_outcome),
        "section_title": _as_text(
            section.get("section_title", "") or section.get("title", "")
        ),
        "section_overview": _as_text(section.get("overview", "")),
        "subsection_title": safe_subsection_title,
        "subsection_purpose": _as_text(plan.get("purpose", "")),
        "style_profile_json": _as_json_string(style_profile, fallback={}),
        "writing_mode": _as_text(plan.get("writing_mode", "")),
        "tone": _as_text(plan.get("tone", "")),
        "target_pages": plan.get("estimated_pages", 1) or 1,
        "core_idea": _as_text(plan.get("core_idea", "")),
        "key_points": _as_text_list(plan.get("key_points", [])),
        "scope_limit": _as_text(plan.get("scope_limit", "")),
        "avoid_overlap_with": _as_text_list(plan.get("avoid_overlap_with", [])),
        "depth_level": _as_text(plan.get("depth_level", "")),
        # "citations_required": bool(plan.get("citations_required", False)),
        "planner_notes": _as_text(plan.get("notes", "")),
        "rag_block": _as_text(rag_block),
        # ุงุฎุชูŠุงุฑูŠ
        "chapter_intro_json": _as_json_string(chapter_intro, fallback={}),
    }


def process_chapter(chapter: dict, book_meta: dict, chapter_idx: int) -> dict:
    """
    ู…ุนุงู„ุฌุฉ ูุตู„ ูƒุงู…ู„ (sequential ุฏุงุฎู„ู‡) โ€” ุชูุณุชุฏุนู‰ ุฏุงุฎู„ Thread.
    """
    print(f"\n๐Ÿ“˜ Processing Chapter {chapter_idx}")

    chapter_out = {
        "chapter_title": chapter.get("chapter_title", ""),
        "chapter_intro": deepcopy(chapter.get("chapter_intro", {})),
        "style_profile": deepcopy(chapter.get("style_profile", {})),
        "sections": [],
    }

    if chapter.get("outcome") is not None:
        chapter_out["outcome"] = chapter.get("outcome", "")

    for section in chapter.get("sections", []):
        section_title = section.get("section_title", "") or section.get("title", "")
        section_out = {
            "section_title": section_title,
            "overview": section.get("overview", ""),
            "section_intro_paragraph": section.get("section_intro_paragraph", ""),
            "section_closing_paragraph": section.get("section_closing_paragraph", ""),
            "plans": {},
        }
        writer_crew = make_writer_crew()
        quality_crew = make_quality_crew()
        # writer_editor_crew = make_writer_editor_crew()

        for subsection_title, raw_plan in _iter_section_plans(section):

            plan = _normalize_plan(raw_plan)
            print(f"๐ŸŸข Writing: {subsection_title}")

            plan_out = deepcopy(plan)
            try:
                inputs = build_inputs(
                    book_meta, chapter, section, subsection_title, plan
                )

                _ensure_required_inputs(
                    inputs,
                    WRITER_REQUIRED_KEYS,
                    ctx=f"chapter={chapter_idx}, section={section_title}, subsection={subsection_title}",
                )

                # 1) Writer + retry (ุฏุงุฎู„ safe_run_once)
                # generated, sources = safe_run_once(writer_editor_crew, inputs)
                generated, sources = safe_run_once(writer_crew, inputs)
                content_before_review = generated
                sources_before_review = sources

                # 2) Quality gate
                reviewed_generated, reviewed_sources = "", []
                if generated.strip() or ALLOW_QUALITY_FROM_EMPTY_DRAFT:
                # if reviewed_generated.strip() or ALLOW_QUALITY_FROM_EMPTY_DRAFT:
                    draft_json = json.dumps(
                        {"generated_content": generated, "sources": sources},
                        ensure_ascii=False,
                    )
                    quality_inputs = dict(inputs)
                    quality_inputs["draft_json"] = draft_json
                    reviewed_generated, reviewed_sources = safe_run_once(
                        quality_crew, quality_inputs
                    )

                if reviewed_generated.strip():
                    generated = reviewed_generated
                    sources = reviewed_sources

                plan_out["generated_content"] = content_before_review
                plan_out["sources"] = sources_before_review
                plan_out["generated_content_reviewed"] = generated
                plan_out["sources_reviewed"] = sources
                plan_out["content_status"] = (
                    "generated" if generated.strip() else "empty"
                )

            except Exception as e:
                plan_out["generated_content"] = ""
                plan_out["sources"] = []
                plan_out["generated_content_reviewed"] = ""
                plan_out["sources_reviewed"] = []
                plan_out["content_status"] = "error"
                plan_out["error"] = str(e)

            section_out["plans"][subsection_title] = plan_out

        chapter_out["sections"].append(section_out)

    return chapter_out


def process_book(data: dict) -> dict:
    """
    - parallel ุนู„ู‰ ู…ุณุชูˆู‰ chapters
    - ุงู„ุญูุงุธ ุนู„ู‰ ุชุฑุชูŠุจ chapters
    """
    book_meta = {
        "book_title": data.get("book_title", ""),
        "book_description": data.get("book_description", ""),
        "target_audience": data.get("target_audience", ""),
    }

    chapters = data.get("chapters", [])
    chapters_out = [None] * len(chapters)

    futures = []
    with ThreadPoolExecutor(max_workers=MAX_CHAPTER_WORKERS) as executor:
        for idx, chapter in enumerate(chapters):
            future = executor.submit(process_chapter, chapter, book_meta, idx + 1)
            futures.append((idx, future))

        for idx, future in futures:
            try:
                chapters_out[idx] = future.result()
            except Exception as e:
                ch = chapters[idx] if idx < len(chapters) else {}
                chapters_out[idx] = {
                    "chapter_title": ch.get("chapter_title", f"Chapter {idx+1}"),
                    "sections": [],
                    "error": str(e),
                }

    return {
        "message": "Book Content Generated Successfully ๐Ÿš€",
        "content_phase": "generated",
        **book_meta,
        "chapters": chapters_out,
    }