From 05a56cf50c72f2e652e7a9c3f5e239314b05ad0f Mon Sep 17 00:00:00 2001 From: Ayyappa Pravin Date: Mon, 2 Nov 2026 00:07:26 +0530 Subject: [PATCH] feat: rebuild engine around book-specific planning and honest release checks Replace the template outliner with model-written book and scene plans driven by a new commercial brief. Add a developmental editor, targeted scene revision, full-chapter story memory, a whole-book release report and a publishing kit. Remove fabricated praise, bestseller labels, prices and page numbers. Give each book its own folder, rebuild the DOCX as a 6x9 interior, and fix the EPUB on Python 3.11. Harden LLM calls with retries and truncation handling, and bind the web server to loopback. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + AGENTS.md | 31 +- CONTRIBUTING.md | 17 +- README.md | 125 +-- agents/__init__.py | 10 +- agents/book_reviewer.py | 152 ++++ agents/book_strategist.py | 45 ++ agents/character_architect.py | 166 +--- agents/critics.py | 177 ++++- agents/master_outliner.py | 291 +++---- agents/prose_drafter.py | 386 ++++++---- agents/publishing_kit.py | 68 ++ agents/world_builder.py | 109 +-- generator/__init__.py | 6 +- generator/blueprint.py | 88 +-- generator/docx_compiler.py | 1011 +++++++++---------------- generator/editor.py | 37 - generator/json_parser.py | 63 +- generator/llm_client.py | 152 ++-- generator/writer.py | 323 -------- main.py | 309 ++------ memory/state_manager.py | 115 ++- pipeline.py | 333 ++++++++ prompts/system_prompts.py | 42 +- schemas/models.py | 58 ++ server.py | 43 +- streamlit_app.py | 186 +---- tests/__init__.py | 0 tests/fake_llm.py | 83 ++ tests/test_docx_compiler.py | 9 + tests/test_json_parser.py | 4 + tests/test_llm_client.py | 34 + tests/test_pipeline.py | 96 +++ tests/test_scene_sequel_and_memory.py | 47 +- tools/epub_compiler.py | 300 ++++---- tools/file_writer.py | 41 +- web/app.js | 2 +- 37 files changed, 2462 insertions(+), 2498 deletions(-) create mode 100644 agents/book_reviewer.py create mode 100644 agents/book_strategist.py create mode 100644 agents/publishing_kit.py delete mode 100644 generator/editor.py delete mode 100644 generator/writer.py create mode 100644 pipeline.py create mode 100644 tests/__init__.py create mode 100644 tests/fake_llm.py create mode 100644 tests/test_llm_client.py create mode 100644 tests/test_pipeline.py diff --git a/.gitignore b/.gitignore index 4062733..9d1e8df 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ output/ .vscode/ .idea/ tmp/ +books/ diff --git a/AGENTS.md b/AGENTS.md index 1e02cb8..0ccbdaa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,8 +8,8 @@ This file serves as the definitive instruction manual for autonomous AI coding a `BookGeneratorAI` is a production-grade multi-agent engine designed to orchestrate long-form manuscript generation (300+ pages / 80,000+ words). It enforces: 1. **Context Isolation**: No single LLM prompt receives the full manuscript history. -2. **Iterative Scene Drafting**: Chapters are split into 6 granular sub-beats (600–900 words each). -3. **Adversarial Critic Loop**: `AntiSlopEditorAgent` audits generated prose against banned AI tropes and voice fingerprint rules. +2. **Iterative Scene Drafting**: Chapters are split into model-planned scenes sized from `--target-words`. +3. **Adversarial Critic Loop**: `DevelopmentalEditorAgent` scores chapters on a strict rubric and `AntiSlopEditorAgent` audits banned tropes; only flagged scenes are revised. 4. **Resilient Local Execution**: Direct Ollama REST integration with zero silent mock fallbacks. --- @@ -23,18 +23,18 @@ Before declaring any coding task complete, run the following verification pipeli python3 -m py_compile main.py generator/*.py agents/*.py schemas/*.py memory/*.py tools/*.py ``` -### 2. Fast Single-Chapter Execution Test +### 2. Offline Test Suite (no LLM or API cost) ```bash -python3 main.py \ - --title "Verification Test" \ - --genre fiction \ - --author "Pravin Tamilan" \ - --provider ollama \ - --model "deepseek-r1:latest" \ - --reset \ - --output "output/Verification_Test.docx" +python3 -m pytest ``` +### 3. Fast Real-Model Run +```bash +python3 main.py --title "Verification Test" --concept "A specific original premise" \ + --chapters 2 --target-words 4000 --provider ollama --reset +``` +Output goes to `books/Verification_Test/`. `--reset` only touches that book. + --- ## 🧱 Key Code Conventions & Schemas @@ -42,16 +42,17 @@ python3 main.py \ ### 1. Pydantic v2 Models (`schemas/models.py`) - All agent inputs and outputs MUST be validated using Pydantic v2 `BaseModel`. - Use `AliasChoices` for flexible LLM field mapping (e.g., `rule_name`, `consequence`, `impact`). -- Provide non-empty genre-derived defaults for fallback methods. +- Agent output is requested through `generate_validated`, which feeds failures back to the model and raises `StructuredOutputError` rather than inventing content. Never add stock worlds, casts or outlines as fallbacks. ### 2. Resilient LLM Calls (`generator/llm_client.py`) - **NEVER** re-introduce silent mock generators (`_call_offline_generator`). If an API or network call fails, raise a descriptive `RuntimeError`. - Maintain DeepSeek-R1 `.*?` regex stripping (`re.DOTALL`) and preamble filtering. -- Keep Ollama socket timeouts set to `600` seconds with `num_ctx: 16384`. +- Keep request timeouts at `600` seconds and Ollama `num_ctx` at `16384` (8192 for small models). Keep retry with backoff in `_post_json`. ### 3. Beat-by-Beat Scene Drafting (`agents/prose_drafter.py`) - Draft scenes sequentially per `SubBeat`. -- Always pass rolling scene context buffers and `StoryState.story_so_far_summary`. +- Always pass the preceding prose verbatim and `StoryState.chapter_recaps`. +- Revise flagged scenes in place with `revise_scene`; never discard a whole chapter to fix one problem. - Retain Codex prompt constraints (*Show Don't Tell*, *Banish AI Slop*, *No Moralizing Conclusions*, *Dialogue Realism*). --- @@ -62,7 +63,7 @@ python3 main.py \ |---|---|---| | 🟢 **ALWAYS** | Verification & Syntax | - Run `py_compile` before finalizing edits.
- Preserve Pydantic schema validation.
- Log live progress metrics (beat number and word count). | | 🟡 **ASK FIRST** | Schema & Configuration | - Modifying `FORBIDDEN_SLOP_PATTERNS` in `prompts/system_prompts.py`.
- Adding new PyPI dependencies to `requirements.txt`.
- Altering SQLite table schemas in `memory/state_manager.py`. | -| 🔴 **NEVER** | System Integrity | - Re-introducing silent mock fallbacks or dummy prose generators.
- Hardcoding publisher press boilerplate or fake ISBN numbers into generated `.docx` manuscripts.
- Reducing Ollama `num_ctx` below 8192.
- Disabling the adversarial anti-slop critic pass. | +| 🔴 **NEVER** | System Integrity | - Re-introducing silent mock fallbacks or dummy prose generators.
- Hardcoding publisher press boilerplate, fake ISBN numbers, invented praise, bestseller claims, prices or credentials into any generated book or listing.
- Reporting a book as ready when a release check failed.
- Reducing Ollama `num_ctx` below 8192.
- Disabling the adversarial anti-slop critic pass. | --- diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0533f87..339d78d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,18 +22,17 @@ pip install -r requirements.txt ``` ### 3. Fast Single-Chapter Test Run -Don't waste time generating full 12-chapter books during development! Run a single-chapter generation test: +The offline suite covers the whole pipeline with a scripted model and costs nothing: ```bash -python3 main.py \ - --title "Test Book" \ - --genre fiction \ - --author "Pravin Tamilan" \ - --provider ollama \ - --model "deepseek-r1:latest" \ - --reset \ - --output "output/Test_Run.docx" +python3 -m pytest ``` +To try a real model without generating a full book: +```bash +python3 main.py --title "Test Book" --concept "A specific original premise" --chapters 2 --target-words 4000 --provider ollama --reset +``` +Output goes to `books/Test_Book/`. + --- ## 🎯 Good First Issues for New Contributors diff --git a/README.md b/README.md index d8a0195..70c1acc 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,9 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) [![AGENTS.md](https://img.shields.io/badge/AI--Standards-AGENTS.md-blueviolet.svg)](AGENTS.md) -**BookGenerator AI** is an open-source, production-grade multi-agent engine engineered to solve the hardest challenge in generative AI: **autonomously drafting complete, publication-ready 300-page commercial manuscripts (80,000+ words) without context collapse or prose degradation.** +**BookGenerator AI** is an open-source multi-agent engine that plans, drafts, edits and packages full-length books (80,000 words by default), then tells you honestly whether each one is ready. + +> **What it can and cannot promise.** The engine aims for the craft of commercial publishing, and refuses to call a book ready until it passes measurable and editorial checks. No software can guarantee sales. Readers buy on concept, cover, reviews and marketing too, and final quality still depends on your concept, your chosen model, and the human editing listed in every book's release report. --- @@ -29,7 +31,7 @@ Standard LLM wrappers fail catastrophically when tasked with long-form writing: - **Causal Chapter DAG & Surgical Invalidation**: Models chapter-to-chapter dependencies to allow surgical regeneration of specific chapters and downstream story branches without corrupting unrelated arcs. - **Scene & Sequel Dramatic Beat Sheets**: Chapters are decomposed into 6 micro-beats adhering to Dwight Swain's dramatic patterns (Goal → Conflict → Disaster Reversal → Emotional Reaction → Dilemma → Pivotal Decision) with explicit micro-tension curves (1-10) and internal POV subtext. - **Gary Provost Sentence Cadence & Deep POV Engine**: The adversarial critic intercepts repetitive mid-length sentence runs (the 15-word AI drone), enforces staccato (<5 words) and sweeping (>26 words) variety, and purges perceptual filter words ("she noticed that", "he felt that"). -- **Commercial Dual-Format Compilation**: Compiles simultaneously to luxury trade **DOCX** with custom palettes and callouts, and validated **EPUB 3** with responsive typography, drop caps, and semantic navigation ready for Amazon KDP and Apple Books. +- **Dual-Format Compilation**: Compiles to a 6x9 print interior **DOCX** with mirrored margins, running heads and a live table of contents, and an **EPUB 3** with semantic navigation. Run EPUBCheck and your retailer's previewer before upload. --- @@ -65,7 +67,7 @@ Standard LLMs default to generic clichés and preachy summary endings. `BookGene ▼ ┌─────────────────────────┐ │ Master Outliner Agent │ - │ (4-Part, 12 Chapters) │ + │ (Bespoke Book Plan) │ └────────────┬────────────┘ │ ▼ @@ -100,20 +102,45 @@ Standard LLMs default to generic clichés and preachy summary endings. `BookGene ## 🔬 In-Depth Engineering & Edge-Case Handling ### 1. DeepSeek-R1 `` Tag Sanitization -Reasoning models like DeepSeek-R1 output extensive inner-monologue reasoning blocks (`...`) before generating response content. `LlmClient._clean_llm_output()` implements a robust multi-pass regex filter (`re.DOTALL`) that strips reasoning traces, conversational preambles (`"Okay, let's write..."`), and prompt meta-leakage without corrupting structured JSON schemas or Markdown prose headings. +Reasoning models like DeepSeek-R1 output extensive inner-monologue reasoning blocks (`...`) before generating response content. `LlmClient._clean_llm_output()` strips reasoning traces and a leading meta preamble (`"Here is the scene:"`) while leaving real opening lines of prose intact. ### 2. SQLite State Persistence (`memory/state_manager.py`) -To protect long-running generations (which can take 30–60 minutes locally), all intermediate states—`WorldBible`, `CharacterRegistry`, `MasterOutline`, chapter drafts, and critic revision briefs—are persisted transactionally to SQLite (`memory/book_state.db`). Interrupted runs can resume instantly without re-generating prior chapters. +All intermediate state (brief, world, cast, outline, scenes as they are written, chapters and editor reports) is persisted to the book's own SQLite file (`books//state.db`). Interrupted runs resume at the next unwritten scene. ### 3. Circuit-Breaker Adversarial Loop -To prevent infinite revision loops when an LLM struggles with a complex constraint, `MasterAdversarialReviewer` enforces strict revision bounds (`max-revisions`, default 1–2 passes). If a draft fails audit after max attempts, the system logs the residual warnings, applies non-blocking text cleanup, and safely advances state. +To prevent infinite revision loops when an LLM struggles with a complex constraint, the revision loop is bounded by `--max-revisions`. If a chapter still fails, its strongest version is kept and the failure becomes a blocker in the release report. --- -## 🚀 Quick Start +## 🧭 What Happens to a Book + +| Phase | Agent | Output | +|---|---|---| +| 0 | Book Strategist | Target reader, promise, hook, ending, voice guide | +| 1 | World Builder, Character Architect, Master Outliner | Bespoke world, cast and a book-specific chapter and scene plan with setups and payoffs | +| 2 | Prose Drafter | Scene-by-scene prose; the book's first scene competes among several drafts | +| 3 | Developmental Editor + mechanical critics | Rubric scores; only flagged scenes are rewritten, and the best version is kept | +| 3 | Memory Engine | Recaps, threads, character state, relationships, secrets and clue status, read from the full chapter | +| 4 | Book Reviewer | `release_report.md`: PASS or NOT READY with every blocker | +| 5 | Publishing Kit | Store blurb, keywords, categories, cover brief, launch plan, 6x9 print DOCX, EPUB 3 | + +Non-fiction gets no invented cast. Uncertain facts are marked `[VERIFY: ...]`, and every checkable claim is listed in `fact_check.md`. + +Nothing is fabricated: no fake reviews, bestseller labels, prices or credentials. An ISBN, publisher, dedication or bio appears only if you supply it. If a model cannot produce valid output, the run stops instead of inserting stock content, and it resumes where it stopped. + +Each book lives in its own folder: + +``` +books/<title>/ +├── <title>.docx, <title>.epub +├── manuscript/chapter_01.md ... +├── publishing/release_report.md, listing.md, metadata.json, fact_check.md +└── state.db +``` + +--- -### 1. Prerequisites & Installation -Ensure Python 3.10+ and [Ollama](https://ollama.com) are installed. +## 🚀 Quick Start ```bash git clone https://github.com/apravint/BookGeneratorAI.git @@ -121,49 +148,26 @@ cd BookGeneratorAI pip install -r requirements.txt ``` -Ensure your target model is pulled in Ollama (e.g. DeepSeek-R1): -```bash -ollama pull deepseek-r1:latest -``` - -### 2. Basic Usage +The concept matters more than any setting. Give it something specific and original: -#### Generate a Full Fiction Novel (Offline via Local Ollama) ```bash python3 main.py \ - --title "The Love Story" \ - --genre fiction \ - --author "Pravin Tamilan" \ - --provider ollama \ - --model "deepseek-r1:latest" \ - --reset \ - --output "The_Love_Story.docx" + --title "The Ledger of the Drowned" \ + --concept "A river ferryman finds a waterlogged ledger recording every drowning in his town, including tomorrow's" \ + --genre thriller \ + --author "Your Name" \ + --provider anthropic ``` -#### Generate a Non-Fiction Architecture Book +Try two chapters first to judge quality before paying for a full book: + ```bash -python3 main.py \ - --title "Building Distributed Stream Engines" \ - --genre technical \ - --author "Pravin Tamilan" \ - --provider ollama \ - --model "deepseek-r1:latest" \ - --reset \ - --output "Distributed_Streams.docx" +python3 main.py -t "Sample Run" -c "Your concept" -n 2 --target-words 5000 --provider ollama ``` -#### Cloud LLM Providers (OpenAI, Gemini, Anthropic) -```bash -export OPENAI_API_KEY="your-api-key" +Set `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` or `GEMINI_API_KEY` for cloud providers. Local models are free, but small ones will rarely clear the editorial bar. Run the same command again to resume. -python3 main.py \ - --title "The Exponential Leader" \ - --genre business \ - --author "Pravin Tamilan" \ - --provider openai \ - --model "gpt-4o" \ - --output "Exponential_Leader.docx" -``` +To add real endorsements, put permissioned quotes in `books/<title>/manuscript/praise.md`. --- @@ -171,18 +175,25 @@ python3 main.py \ | Flag | Short | Default | Description | |---|---|---|---| -| `--title` | `-t` | **Required** | Book title | -| `--concept` | `-c` | `""` | Seed concept or story prompt | -| `--language` | `-l` | `english` | Primary language (`tamil` / `english`) | -| `--tamil` | | `False` | Preset flag for Tamil language book generation | -| `--genre` | `-g` | `auto` | Genre (`tamil_historical`, `tamil_thirukkural`, `tamil_kavithai`, `tamil_fiction`, `fiction`, `business`) | -| `--author` | `-a` | `Pravin Tamilan` | Author name for title page & headers | -| `--provider` | `-p` | `ollama` | Provider (`ollama`, `gemini`, `openai`, `anthropic`, `jev`) | -| `--model` | `-m` | `deepseek-r1:latest` | Target LLM model | -| `--ollama-url` | | `http://localhost:11434` | Local Ollama REST endpoint | -| `--reset` | `-r` | `False` | Clean database (`memory/book_state.db`) & previous outputs before running | -| `--max-revisions` | | `1` | Max critic revision loops per chapter | -| `--output` | `-o` | `Generated_Book.docx` | Output path for `.docx` compilation | +| `--title` | `-t` | **Required** | Book title; also identifies the book's folder | +| `--concept` | `-c` | title | Seed concept | +| `--genre` | `-g` | `auto` | Genre, detected from the title when `auto` | +| `--author` | `-a` | `Pravin Tamilan` | Author name | +| `--language` | `-l` | `english` | `english` or `tamil` | +| `--tamil` | | off | Shortcut for `--language tamil` | +| `--provider` | `-p` | auto-detected | `ollama`, `gemini`, `openai`, `anthropic`, `jev` | +| `--model` | `-m` | provider default | Model name | +| `--ollama-url` | | `http://localhost:11434` | Ollama endpoint | +| `--chapters` | `-n` | `24` | Number of chapters | +| `--scenes-per-chapter` | | `4` | Scenes per chapter | +| `--target-words` | | `80000` | Whole-book word target | +| `--max-revisions` | | `2` | Revision passes per chapter | +| `--opening-candidates` | | `3` | Competing drafts of the first scene | +| `--output` / `--epub` | `-o` | book folder | Output paths | +| `--cover` | | none | Cover `.jpg` for the EPUB | +| `--subtitle` `--isbn` `--publisher` `--year` `--dedication` `--author-bio` | | none | Printed only when supplied | +| `--reset` | `-r` | off | Restart this book only | +| `--export-cards` / `--import-lorebook` | | none | Portable character cards and lorebooks | --- @@ -195,7 +206,7 @@ Run a modern, multi-tab Streamlit dashboard: pip install -r requirements.txt streamlit run streamlit_app.py ``` -> Launch at **`http://localhost:8501`** to generate books, monitor live pipeline execution, read chapters, and download DOCX files. +> Launch at **`http://localhost:8501`** to generate books, monitor the pipeline, and download the DOCX, EPUB and release report. ### 2. Built-in REST API & Multi-Book Web Server (`server.py`) Run a zero-dependency local REST API web server: @@ -203,7 +214,7 @@ Run a zero-dependency local REST API web server: ```bash python3 server.py ``` -> Access at **`http://localhost:8080`** for live 5-node agent pipeline monitoring and multi-book job creation. +> Access at **`http://localhost:8080`**. It listens on this computer only, because the API starts paid LLM jobs and has no authentication. --- diff --git a/agents/__init__.py b/agents/__init__.py index 84735aa..33e44fb 100644 --- a/agents/__init__.py +++ b/agents/__init__.py @@ -3,6 +3,9 @@ Exports all core agents for the multi-agent long-form manuscript pipeline. """ +from .book_strategist import BookStrategistAgent +from .book_reviewer import BookReviewer +from .publishing_kit import PublishingKitAgent from .world_builder import WorldBuilderAgent from .character_architect import CharacterArchitectAgent from .master_outliner import MasterOutlinerAgent @@ -10,10 +13,15 @@ from .critics import ( MasterAdversarialReviewer, AntiSlopEditorAgent, - ContinuityEditorAgent + ContinuityEditorAgent, + DevelopmentalEditorAgent ) __all__ = [ + "BookStrategistAgent", + "BookReviewer", + "PublishingKitAgent", + "DevelopmentalEditorAgent", "WorldBuilderAgent", "CharacterArchitectAgent", "MasterOutlinerAgent", diff --git a/agents/book_reviewer.py b/agents/book_reviewer.py new file mode 100644 index 0000000..3ee60ab --- /dev/null +++ b/agents/book_reviewer.py @@ -0,0 +1,152 @@ +""" +Book Reviewer - Phase 4 +Whole-book release gate: combines measurable checks with a structural read of the finished manuscript. +A book is only reported ready when every check passes. +""" + +import os +import re +from collections import Counter +from typing import Dict, List +from pydantic import BaseModel, Field +from schemas.models import BookBrief, StoryState, RevisionBrief +from generator.llm_client import LlmClient +from generator.json_parser import generate_validated, StructuredOutputError +from prompts.system_prompts import BOOK_REVIEWER_PROMPT + +MIN_CHAPTER_SCORE = 8.0 +MIN_ARC_SCORE = 8.0 +WORD_TOLERANCE = 0.9 +REPEATED_PHRASE_WORDS = 6 +HUMAN_CHECKLIST = [ + "Read the whole book yourself and rewrite anything that is not yours to stand behind.", + "Hire a human copyeditor and proofreader.", + "Get 5-10 beta readers from the target audience and act on where they stopped reading.", + "Verify every claim in fact_check.md and resolve each [VERIFY: ...] marker (non-fiction).", + "Commission a professional cover from publishing/listing.md's cover brief.", + "Disclose AI-generated content when your retailer asks (Amazon KDP does at upload).", + "Check the text for accidental similarity to existing works before release.", +] + + +class ArcReview(BaseModel): + arc_score: float = Field(default=0, description="1-10 whole-book structure score") + problems: List[str] = Field(default_factory=list) + + +def find_repeated_phrases(chapters: Dict[int, str], min_chapters: int = 3) -> List[str]: + """Finds long phrases recurring across chapters, the fingerprint of a model's stock moves.""" + seen = Counter() + for text in chapters.values(): + words = re.findall(r"\w+", text.lower()) + seen.update({" ".join(words[i:i + REPEATED_PHRASE_WORDS]) for i in range(len(words) - REPEATED_PHRASE_WORDS + 1)}) + return [phrase for phrase, count in seen.most_common(10) if count >= min_chapters] + + +class BookReviewer: + def __init__(self, llm_client: LlmClient): + self.llm = llm_client + + def review( + self, + title: str, + brief: BookBrief, + story_state: StoryState, + chapters: Dict[int, str], + briefs: Dict[int, RevisionBrief], + target_words: int, + ) -> dict: + blockers = [] + total_words = sum(len(t.split()) for t in chapters.values()) + if total_words < target_words * WORD_TOLERANCE: + blockers.append(f"Length: {total_words:,} words against a {target_words:,} target.") + + for num, chapter_brief in sorted(briefs.items()): + if not chapter_brief.passed_audit: + score = chapter_brief.craft_score + blockers.append(f"Chapter {num} failed editorial audit (score {'unreviewed' if score is None else f'{score:.1f}'}).") + + open_clues = [c.name for c in story_state.foreshadowing_clues if c.status in ("planted", "escalated")] + if open_clues: + blockers.append(f"Unresolved setups: {', '.join(open_clues)}.") + + markers = sum(t.count("[VERIFY") for t in chapters.values()) + if markers: + blockers.append(f"{markers} [VERIFY: ...] marker(s) still in the text.") + + repeated = find_repeated_phrases(chapters) + if repeated: + blockers.append("Stock phrases repeat across chapters: " + "; ".join(f'"{p}"' for p in repeated[:5]) + ".") + + arc = self._review_arc(title, brief, story_state, chapters) + if arc is None: + blockers.append("Whole-book structural review could not be completed.") + else: + if arc.arc_score < MIN_ARC_SCORE: + blockers.append(f"Whole-book structure scored {arc.arc_score:.1f}/10 (needs {MIN_ARC_SCORE:.0f}).") + blockers.extend(f"Structure: {p}" for p in arc.problems) + + scores = [b.craft_score for b in briefs.values() if b.craft_score is not None] + return { + "ready": not blockers, + "blockers": blockers, + "total_words": total_words, + "chapters": len(chapters), + "average_craft_score": round(sum(scores) / len(scores), 2) if scores else None, + "lowest_craft_score": min(scores) if scores else None, + "arc_score": arc.arc_score if arc else None, + } + + def _review_arc(self, title: str, brief: BookBrief, story_state: StoryState, chapters: Dict[int, str]): + if not chapters: + return None + recaps = "\n".join(f"{n}. {r}" for n, r in sorted(story_state.chapter_recaps.items())) + ordered = [chapters[n] for n in sorted(chapters)] + prompt = f"""TASK: book review +Title: {title} +Promise to the reader: {brief.reader_promise} +Central question: {brief.central_question} +Planned ending: {brief.ending} + +Chapter by chapter: +{recaps} + +The book's opening: +{ordered[0][:6000]} + +The book's ending: +{ordered[-1][-6000:]} + +Return ONLY JSON: {{"arc_score": 1-10, "problems": ["specific structural problem, naming chapters"]}} +""" + try: + return generate_validated(self.llm, prompt, BOOK_REVIEWER_PROMPT, ArcReview, max_tokens=2000) + except StructuredOutputError as e: + print(f" [Book Reviewer Warning] {e}") + return None + + @staticmethod + def write_report(result: dict, title: str, briefs: Dict[int, RevisionBrief], directory: str) -> str: + os.makedirs(directory, exist_ok=True) + lines = [f"# Release Report: {title}", ""] + lines.append("**Automated checks: PASSED**" if result["ready"] else "**Automated checks: NOT READY**") + lines += [ + "", + f"- Words: {result['total_words']:,} across {result['chapters']} chapters", + f"- Average chapter score: {result['average_craft_score']}", + f"- Lowest chapter score: {result['lowest_craft_score']}", + f"- Whole-book structure score: {result['arc_score']}", + "", + "Scores are an AI editor's opinion, not a measure of sales.", + "", + ] + if result["blockers"]: + lines += ["## Blockers", ""] + [f"- {b}" for b in result["blockers"]] + [""] + lines += ["## Chapter Scores", "", "| Chapter | Score | Passed |", "|---|---|---|"] + for num, chapter_brief in sorted(briefs.items()): + lines.append(f"| {num} | {chapter_brief.craft_score} | {'yes' if chapter_brief.passed_audit else 'no'} |") + lines += ["", "## Required Human Steps", ""] + [f"- [ ] {item}" for item in HUMAN_CHECKLIST] + [""] + path = os.path.join(directory, "release_report.md") + with open(path, "w", encoding="utf-8") as f: + f.write("\n".join(lines)) + return path diff --git a/agents/book_strategist.py b/agents/book_strategist.py new file mode 100644 index 0000000..1ddecee --- /dev/null +++ b/agents/book_strategist.py @@ -0,0 +1,45 @@ +""" +Book Strategist Agent - Phase 0 +Defines the commercial concept (reader, promise, hook, ending, voice) before any story work begins. +""" + +from schemas.models import BookBrief +from generator.llm_client import LlmClient +from generator.json_parser import generate_validated +from prompts.system_prompts import BOOK_STRATEGIST_PROMPT, language_directive + + +class BookStrategistAgent: + def __init__(self, llm_client: LlmClient): + self.llm = llm_client + + def build_brief(self, title: str, concept: str, genre: str, language: str = "english") -> BookBrief: + prompt = f"""TASK: book brief +Title: {title} +Genre: {genre} +Concept from the author: {concept} +{language_directive(language)} + +Develop the commercial concept for this book. Be specific enough that two different writers would produce the same book. +Return ONLY JSON with this schema: +{{ + "is_fiction": true, + "logline": "...", + "target_reader": "...", + "reader_promise": "...", + "central_question": "...", + "what_makes_it_different": "...", + "genre_conventions": ["..."], + "ending": "...", + "voice_guide": "...", + "voice_sample": "..." +}} +""" + return generate_validated(self.llm, prompt, BOOK_STRATEGIST_PROMPT, BookBrief, validator=self._validate) + + @staticmethod + def _validate(brief: BookBrief): + for field in ("logline", "reader_promise", "central_question", "ending", "voice_guide", "voice_sample"): + if not getattr(brief, field).strip(): + return f"Field '{field}' is empty." + return None diff --git a/agents/character_architect.py b/agents/character_architect.py index 2c4462b..89a9689 100644 --- a/agents/character_architect.py +++ b/agents/character_architect.py @@ -1,14 +1,12 @@ """ Character Architect Agent - Phase 1 Constructs structured CharacterRegistry from WorldBible. -Includes robust JSON extraction, retry logic, and genre-aware fallbacks. +Includes robust JSON extraction and retry logic. Fails loudly rather than shipping stock characters. """ -import json -import re -from schemas.models import WorldBible, CharacterRegistry, CharacterProfile, CharacterVoice +from schemas.models import WorldBible, CharacterRegistry, BookBrief from generator.llm_client import LlmClient -from generator.json_parser import parse_llm_json, clean_json_string +from generator.json_parser import parse_llm_json, StructuredOutputError from prompts.system_prompts import CHARACTER_ARCHITECT_PROMPT, TAMIL_CHARACTER_ARCHITECT_PROMPT @@ -16,7 +14,10 @@ class CharacterArchitectAgent: def __init__(self, llm_client: LlmClient): self.llm = llm_client - def build_characters(self, world_bible: WorldBible, author_name: str, language: str = "english") -> CharacterRegistry: + def build_characters(self, world_bible: WorldBible, author_name: str, language: str = "english", brief: BookBrief = None) -> CharacterRegistry: + if brief and not brief.is_fiction: + # Non-fiction has no invented cast; real people come from each chapter's beats + return CharacterRegistry() is_tamil = (language or getattr(world_bible, 'language', 'english')).lower() in ["tamil", "ta"] system_prompt = TAMIL_CHARACTER_ARCHITECT_PROMPT if is_tamil else CHARACTER_ARCHITECT_PROMPT lang_directive = "Generate authentic Tamil character names (e.g. அருள்மொழி, மாறன், வந்தியதேவன், கயல்விழி, அமுதா) and write all motivations, flaw, backstory, and voice in TAMIL (தமிழ் எழுத்துக்கள்)." if is_tamil else "Write in English." @@ -26,7 +27,7 @@ def build_characters(self, world_bible: WorldBible, author_name: str, language: Genre: {world_bible.genre} Setting Overview: {world_bible.setting_overview} Core Conflict: {world_bible.core_thematic_conflict} -Author: {author_name} +Book Promise: {brief.reader_promise if brief else ""} Language Directive: {lang_directive} Generate a Character Registry with at least 3 core characters (Protagonist, Antagonist/Challenge, Ally/Mentor). @@ -65,159 +66,10 @@ def build_characters(self, world_bible: WorldBible, author_name: str, language: if registry: return registry - print(" [CharacterArchitect Warning] JSON retry failed, constructing genre-derived CharacterRegistry fallback.") - return self._fallback_registry(world_bible, author_name, is_tamil=is_tamil) + raise StructuredOutputError(f"Character Registry for '{world_bible.title}' could not be generated: the model returned invalid JSON twice.") def _parse_registry(self, text: str) -> CharacterRegistry: registry = parse_llm_json(text, model_class=CharacterRegistry) if registry and registry.characters and len(registry.characters) > 0: return registry return None - - def _clean_json(self, text: str) -> str: - if not text: - return "{}" - # 1. Strip reasoning blocks - text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL) - - # 2. Extract code block content if wrapped - if "```json" in text: - text = text.split("```json")[1].split("```")[0] - elif "```" in text: - text = text.split("```")[1].split("```")[0] - - # 3. Match largest JSON object - match = re.search(r'\{[\s\S]*\}', text) - if match: - return match.group(0).strip() - return text.strip() - - def _fallback_registry(self, world_bible: WorldBible, author_name: str, is_tamil: bool = False) -> CharacterRegistry: - if is_tamil: - return CharacterRegistry( - characters=[ - CharacterProfile( - character_id="char_01", - name="அருள்மொழி மாறன்", - role="கதாநாயகன் (Protagonist)", - core_motivation="தாய்நாட்டைக் காத்தல் மற்றும் நீதியை நிலைநாட்டுதல்", - fatal_flaw="நம்பிக்கை கொண்டவர்களை சந்தேகிக்கத் தயங்குதல்", - backstory_summary="வீரம் மற்றும் கருணை நிறைந்த இளவரசன் / கம்பீரமான தலைவன்.", - voice_fingerprint=CharacterVoice( - tone="கம்பீரமான, நயமான மற்றும் உணர்ச்சிப்பூர்வமான குரல்", - sentence_structure="ஆழமான தமிழ் உரைநடை", - frequently_used_terms=["வீரம்", "தர்மம்", "காதல்", "தாய்நாடு"], - taboo_phrases=["கோழைத்தனம்", "துரோகம்"] - ), - relationships={"char_02": "உயிர் தோழன் மற்றும் ஆலோசகன்"}, - arc_trajectory="இளவரசனில் தொடங்கி பேரரசனாக உருவெடுத்தல்" - ), - CharacterProfile( - character_id="char_02", - name="வந்தியதேவன்", - role="தோழன் / ஒற்றன் (Ally & Spy)", - core_motivation="அருள்மொழி மாறனுக்கு உறுதுணையாக இருந்து இரகசியங்களை சேகரித்தல்", - fatal_flaw="அதிகமான துணிச்சல் மற்றும் அவசர முடிவு", - backstory_summary="சதுரங்க வியூகங்களில் வல்லவன், நகைச்சுவை உணர்வு மிக்க வீரன்.", - voice_fingerprint=CharacterVoice( - tone="சுறுசுறுப்பான, விறுவிறுப்பான மற்றும் நகைச்சுவையான பேச்சு", - sentence_structure="வேகமான வாக்கியங்கள்", - frequently_used_terms=["நண்பா", "சாமர்த்தியம்", "தந்திரம்"], - taboo_phrases=["பயம்"] - ), - relationships={"char_01": "உயிர்த் தோழன்"}, - arc_trajectory="துணிச்சல்மிக்க வீரனில் இருந்து நம்பிக்கையான தளபதியாக உயர்தல்" - ), - CharacterProfile( - character_id="char_03", - name="கயல்விழி", - role="நாயகி (Co-Protagonist)", - core_motivation="தனது குலத்தின் கௌரவத்தைக் காத்தல் மற்றும் காதல்", - fatal_flaw="தன்மான உணர்ச்சி", - backstory_summary="அறிவும் வீரமும் நிறைந்த பெண்மணி.", - voice_fingerprint=CharacterVoice( - tone="கனிவான அதே நேரம் உறுதியான குரல்", - sentence_structure="நயமான கவித்துவ வாக்கியங்கள்", - frequently_used_terms=["அன்பு", "மானக் காப்பு", "நீதி"], - taboo_phrases=["பணியுதல்"] - ), - relationships={"char_01": "காதலி"}, - arc_trajectory="அமைதியான இளவரசியில் இருந்து வீரமங்கையாகத் திகழ்தல்" - ) - ] - ) - g = world_bible.genre.lower() - if g in ["fiction", "romance"]: - return CharacterRegistry( - characters=[ - CharacterProfile( - character_id="char_01", - name="Clara Sterling", - role="Protagonist", - core_motivation="Finding true love and healing past emotional wounds", - fatal_flaw="Fear of vulnerability and guarded heart", - backstory_summary="Independent and passionate visionary with a cautious heart.", - voice_fingerprint=CharacterVoice( - tone="Warm, expressive, and deeply reflective", - sentence_structure="Sensory and emotional", - frequently_used_terms=["devotion", "passion", "forever", "heart"], - taboo_phrases=["system", "architecture", "compliance", "data"] - ), - relationships={"char_02": "Love interest & complex partner"}, - arc_trajectory="From guarded isolation to unshakeable vulnerability and love" - ), - CharacterProfile( - character_id="char_02", - name="Julian Vance", - role="Love Interest / Co-Protagonist", - core_motivation="Protecting Clara and building an unbroken future together", - fatal_flaw="Stoic self-reliance and reluctance to reveal internal pain", - backstory_summary="Determined and loyal visionary driven by a sacred promise.", - voice_fingerprint=CharacterVoice( - tone="Intense, gentle, and deeply sincere", - sentence_structure="Direct, powerful, and poetic", - frequently_used_terms=["promise", "always", "together", "trust"], - taboo_phrases=["protocol", "database", "vector", "framework"] - ), - relationships={"char_01": "Deeply devoted partner"}, - arc_trajectory="From stoic solitude to profound emotional openness" - ) - ] - ) - else: - return CharacterRegistry( - characters=[ - CharacterProfile( - character_id="char_01", - name="Elena Vance", - role="Protagonist", - core_motivation=f"Mastering the principles of {world_bible.title}", - fatal_flaw="Reluctance to delegate critical decisions", - backstory_summary="Seasoned practitioner who witnessed legacy failure.", - voice_fingerprint=CharacterVoice( - tone="Pragmatic", - sentence_structure="Clear and decisive", - frequently_used_terms=["strategy", "resilience"], - taboo_phrases=["cannot be done"] - ), - relationships={}, - arc_trajectory="From cautious specialist to transformational leader" - ), - CharacterProfile( - character_id="char_02", - name="Marcus Sterling", - role="Antagonist", - core_motivation="Preserving traditional paradigms and market dominance", - fatal_flaw="Arrogant complacency", - backstory_summary="Veteran executive resistant to disruption.", - voice_fingerprint=CharacterVoice( - tone="Authoritative", - sentence_structure="Elaborate corporate phrasing", - frequently_used_terms=["governance", "status quo"], - taboo_phrases=["pivot", "agile"] - ), - relationships={"char_01": "Ideological rivals"}, - arc_trajectory="From entrenched resistance to forced adaptiveness" - ) - ] - ) diff --git a/agents/critics.py b/agents/critics.py index 277a9b0..aa6695f 100644 --- a/agents/critics.py +++ b/agents/critics.py @@ -14,15 +14,17 @@ ChapterBeat, RevisionBrief, ContinuityIssue, - AntiSlopViolation + AntiSlopViolation, + BookBrief, + CraftReview, + SceneNote ) from generator.llm_client import LlmClient +from generator.json_parser import generate_validated, StructuredOutputError from prompts.system_prompts import ( - CONTINUITY_EDITOR_PROMPT, - ANTI_SLOP_EDITOR_PROMPT, FORBIDDEN_SLOP_PATTERNS, TAMIL_FORBIDDEN_SLOP_PATTERNS, - TAMIL_ANTI_SLOP_EDITOR_PROMPT, + DEVELOPMENTAL_EDITOR_PROMPT, PERCEPTUAL_FILTER_PATTERNS ) @@ -40,27 +42,20 @@ def audit_chapter( story_state: StoryState ) -> List[ContinuityIssue]: issues = [] - # Local rule checks: check character voice taboo words + # Taboo phrases only count inside dialogue; narration may legitimately use them + dialogue = " ".join(re.findall(r'["“]([^"”]+)["”]', chapter_text)).lower() for char in registry.characters: + if char.name.lower() not in chapter_text.lower(): + continue for taboo in char.voice_fingerprint.taboo_phrases: - if taboo.lower() in chapter_text.lower(): + if taboo.lower() in dialogue: issues.append(ContinuityIssue( - severity="MAJOR", + severity="MINOR", location=f"Chapter {chapter_number}", - description=f"Character {char.name} used taboo phrase '{taboo}' which breaks voice fingerprint.", - remedy=f"Replace or rephrase '{taboo}' in {char.name}'s dialogue." + description=f"Dialogue contains '{taboo}', a phrase {char.name} never uses. Confirm another character speaks it.", + remedy=f"If {char.name} says it, rephrase in their voice." )) - # World rule checks - for rule in world_bible.rules: - if rule.rule_name.lower() in chapter_text.lower() and "broken" in chapter_text.lower(): - issues.append(ContinuityIssue( - severity="CRITICAL", - location=f"Chapter {chapter_number}", - description=f"World rule '{rule.rule_name}' broken without applying consequence: {rule.narrative_consequence}", - remedy=f"Incorporate consequence: {rule.narrative_consequence}" - )) - # Epistemic state & secret leaks check if story_state and hasattr(story_state, "epistemic_secrets"): for secret in story_state.epistemic_secrets: @@ -132,7 +127,7 @@ def audit_slop(self, chapter_number: int, chapter_text: str, language: str = "en if pattern in text_lower: violations.append(AntiSlopViolation( phrase_or_pattern=pattern, - line_snippet=f"Detected '{pattern}' in draft text.", + line_snippet=self._snippet(chapter_text, pattern), reason="Banned AI cliché / writing trope.", replacement_suggestion=f"Remove or replace '{pattern}' with vivid, original prose." )) @@ -143,7 +138,7 @@ def audit_slop(self, chapter_number: int, chapter_text: str, language: str = "en if filter_pattern in text_lower: violations.append(AntiSlopViolation( phrase_or_pattern=filter_pattern, - line_snippet=f"Detected perceptual filter '{filter_pattern}'.", + line_snippet=self._snippet(chapter_text, filter_pattern), reason="Filter language weakens Deep POV immersion.", replacement_suggestion=f"Cut '{filter_pattern}' and describe the sensory action directly." )) @@ -151,6 +146,8 @@ def audit_slop(self, chapter_number: int, chapter_text: str, language: str = "en # Check Gary Provost Sentence Cadence & Rhythm violations.extend(self.audit_sentence_cadence(chapter_text, is_tamil=is_tamil)) + violations.extend(self.audit_repetition(chapter_text)) + # Check for preachy conclusion at end of chapter text lines = [l.strip() for l in chapter_text.split("\n") if l.strip()] if lines: @@ -166,6 +163,39 @@ def audit_slop(self, chapter_number: int, chapter_text: str, language: str = "en return violations + @staticmethod + def _snippet(text: str, phrase: str, radius: int = 60) -> str: + at = text.lower().find(phrase) + return text[max(0, at - radius):at + len(phrase) + radius].replace("\n", " ").strip() + + def audit_repetition(self, chapter_text: str) -> List[AntiSlopViolation]: + """Measures the structural tics that phrase lists miss.""" + violations = [] + prose = "\n".join(l for l in chapter_text.split("\n") if not l.lstrip().startswith("#")) + word_count = max(len(prose.split()), 1) + + antithesis = len(re.findall(r"\b(?:not|n't)\b[^.!?\n]{0,60}[,;:—-]\s*(?:but|it was|it is|they were)\b", prose, re.IGNORECASE)) + if word_count >= 500 and antithesis * 1000 / word_count > 2: + violations.append(AntiSlopViolation( + phrase_or_pattern="Overused 'not X but Y' construction", + line_snippet=f"{antithesis} uses in {word_count} words.", + reason="This rhetorical pattern is a strong tell of machine prose.", + replacement_suggestion="State the thing directly; keep at most one per chapter." + )) + + sentences = [s.strip() for s in re.split(r'(?<=[.!?])\s+', prose) if s.strip()] + openers = [re.sub(r'^\W+', '', s).split(" ")[0].lower() for s in sentences] + for i in range(len(openers) - 3): + if openers[i] and len(set(openers[i:i + 4])) == 1: + violations.append(AntiSlopViolation( + phrase_or_pattern="Repeated sentence opener", + line_snippet=" ".join(sentences[i:i + 4])[:120], + reason=f"Four consecutive sentences open with '{openers[i]}'.", + replacement_suggestion="Vary the sentence openings unless the repetition is a deliberate effect." + )) + break + return violations + def audit_sentence_cadence(self, chapter_text: str, is_tamil: bool = False) -> List[AntiSlopViolation]: violations = [] raw_sentences = re.split(r'(?<=[.!?])\s+', chapter_text) @@ -198,7 +228,6 @@ def audit_sentence_cadence(self, chapter_text: str, is_tamil: bool = False) -> L # 2. Check for presence of dynamic extremes (staccato vs sweeping sentences) has_staccato = any(wc <= 5 for wc in word_counts) - has_sweeping = any(wc >= 26 for wc in word_counts) if not has_staccato and len(sentences) >= 20: violations.append(AntiSlopViolation( phrase_or_pattern="Lack of Staccato Rhythm", @@ -210,10 +239,66 @@ def audit_sentence_cadence(self, chapter_text: str, is_tamil: bool = False) -> L return violations +class DevelopmentalEditorAgent: + """Reads a chapter as a demanding editor would. Regex can catch cliches; only a reader can catch dullness.""" + + RUBRIC = { + "opening_hook": "Does the first paragraph make stopping hard?", + "tension_or_curiosity": "Does each scene create a reason to read the next?", + "depth": "Character depth in fiction; genuine insight in non-fiction.", + "voice": "Is the voice distinct and consistent with the guide?", + "originality": "Are details and turns specific and unpredictable?", + "pacing": "Is anything slack, repeated or over-explained?", + "ending_pull": "Does the ending force the next chapter open?", + } + + def __init__(self, llm_client: LlmClient): + self.llm = llm_client + + def review(self, chapter_beat: ChapterBeat, scenes: List[str], brief: BookBrief, story_state: StoryState) -> CraftReview: + numbered = "\n\n".join(f"[SCENE {i}]\n{text}" for i, text in enumerate(scenes, start=1)) + rubric = "\n".join(f'- {key}: {question}' for key, question in self.RUBRIC.items()) + prompt = f"""TASK: chapter review +Book promise: {brief.reader_promise} +Target reader: {brief.target_reader} +Voice guide: {brief.voice_guide} +Chapter {chapter_beat.chapter_number}: {chapter_beat.title} +Chapter purpose: {chapter_beat.core_narrative_arc} +Established so far: {story_state.story_so_far_summary[-3000:] or "Nothing; this is the opening."} + +Score 1-10 on: +{rubric} + +MANUSCRIPT: +{numbered} + +Return ONLY JSON: +{{"scores": {{{", ".join(f'"{key}": 0' for key in self.RUBRIC)}}}, + "strengths": ["what revision must preserve"], + "scene_notes": [{{"scene": 1, "problem": "quote the weak line and say why", "fix": "concrete rewrite direction"}}]}} +""" + return generate_validated( + self.llm, prompt, DEVELOPMENTAL_EDITOR_PROMPT, CraftReview, + validator=self._validate, max_tokens=3000 + ) + + def _validate(self, review: CraftReview): + missing = [key for key in self.RUBRIC if key not in review.scores] + if missing: + return f"Missing scores: {', '.join(missing)}." + if any(not 1 <= v <= 10 for v in review.scores.values()): + return "Scores must be between 1 and 10." + return None + + class MasterAdversarialReviewer: + PASS_MEAN = 8.0 + PASS_FLOOR = 7.0 + def __init__(self, llm_client: LlmClient): self.continuity_editor = ContinuityEditorAgent(llm_client) self.anti_slop_editor = AntiSlopEditorAgent(llm_client) + self.developmental_editor = DevelopmentalEditorAgent(llm_client) def evaluate_chapter( self, @@ -221,7 +306,9 @@ def evaluate_chapter( chapter_text: str, world_bible: WorldBible, registry: CharacterRegistry, - story_state: StoryState + story_state: StoryState, + scenes: List[str] = None, + brief: BookBrief = None ) -> RevisionBrief: lang = getattr(world_bible, "language", "english") cont_issues = self.continuity_editor.audit_chapter( @@ -230,15 +317,53 @@ def evaluate_chapter( slop_violations = self.anti_slop_editor.audit_slop( chapter_beat.chapter_number, chapter_text, language=lang ) + scenes = scenes or [chapter_text] + scene_notes = self._mechanical_scene_notes(scenes, slop_violations) - passed = len(cont_issues) == 0 and len(slop_violations) == 0 + craft_scores, craft_score, strengths = {}, None, [] + unreviewed = False + if brief: + try: + review = self.developmental_editor.review(chapter_beat, scenes, brief, story_state) + craft_scores = review.scores + craft_score = round(sum(review.scores.values()) / len(review.scores), 2) + strengths = review.strengths + scene_notes += [n for n in review.scene_notes if 1 <= n.scene <= len(scenes)] + except StructuredOutputError as e: + # Never treat a missing review as approval + print(f" [Developmental Editor Warning] {e}") + unreviewed = True - directive = "Draft meets high editorial standards." if passed else "Refine prose: fix continuity inconsistencies and purge identified AI tropes." + blocking = [i for i in cont_issues if i.severity != "MINOR"] + craft_ok = not brief or ( + craft_score is not None + and craft_score >= self.PASS_MEAN + and min(craft_scores.values()) >= self.PASS_FLOOR + ) + passed = not blocking and not slop_violations and craft_ok and not unreviewed + + directive = "Draft meets high editorial standards." if passed else "Raise the weakest scenes, fix continuity and purge identified AI tropes, keeping what already works." return RevisionBrief( chapter_number=chapter_beat.chapter_number, passed_audit=passed, continuity_issues=cont_issues, slop_violations=slop_violations, - editor_overall_directive=directive + editor_overall_directive=directive, + craft_scores=craft_scores, + craft_score=craft_score, + strengths=strengths, + scene_notes=scene_notes ) + + @staticmethod + def _mechanical_scene_notes(scenes: List[str], violations: List[AntiSlopViolation]) -> List[SceneNote]: + notes = [] + for violation in violations: + pattern = violation.phrase_or_pattern.lower() + located = [i for i, s in enumerate(scenes, start=1) if pattern in s.lower()] + for scene in located: + notes.append(SceneNote(scene=scene, problem=f"Contains '{violation.phrase_or_pattern}': {violation.reason}", fix=violation.replacement_suggestion)) + if not located: + notes.append(SceneNote(scene=1, problem=f"{violation.phrase_or_pattern}: {violation.line_snippet}", fix=violation.replacement_suggestion)) + return notes diff --git a/agents/master_outliner.py b/agents/master_outliner.py index 5abe9cb..955ffe5 100644 --- a/agents/master_outliner.py +++ b/agents/master_outliner.py @@ -1,151 +1,174 @@ """ Master Outliner Agent - Phase 1 -Constructs 4-Part, 12-Chapter MasterOutline with detailed 6-subsection beat sheets per chapter. +Plans the whole book, then each chapter's scenes, from the book's own brief, world and cast. +Outlines are always model-written: a book must never inherit another book's plot template. """ -import json -from schemas.models import WorldBible, CharacterRegistry, MasterOutline, ChapterBeat, SubBeat +from typing import List +from pydantic import BaseModel, Field +from schemas.models import WorldBible, CharacterRegistry, MasterOutline, ChapterBeat, SubBeat, ForeshadowingClue, BookBrief from generator.llm_client import LlmClient -from generator.blueprint import BookBlueprint -from prompts.system_prompts import MASTER_OUTLINER_PROMPT +from generator.json_parser import generate_validated +from prompts.system_prompts import MASTER_OUTLINE_PROMPT, language_directive + +FICTION_BEATS = ["SCENE_GOAL", "CONFLICT_ESCALATION", "DISASTER_REVERSAL", "EMOTIONAL_REACTION", "DILEMMA_CALCULATION", "PIVOTAL_DECISION"] +NONFICTION_BEATS = ["STORY_HOOK", "CORE_IDEA", "EVIDENCE", "COUNTERPOINT", "APPLICATION", "CLOSING_TURN"] + + +class ChapterPlan(BaseModel): + chapter_number: int + part_title: str = "" + title: str + pov_character: str = "" + location: str = "" + core_narrative_arc: str + prerequisite_chapters: List[int] = Field(default_factory=list) + + +class SetupPayoff(BaseModel): + name: str + description: str + planted_chapter: int + target_payoff_chapter: int + involved_characters: List[str] = Field(default_factory=list) + + +class BookPlan(BaseModel): + pacing_notes: str = "" + chapters: List[ChapterPlan] = Field(default_factory=list) + setups_and_payoffs: List[SetupPayoff] = Field(default_factory=list) + + +class ScenePlan(BaseModel): + scenes: List[SubBeat] = Field(default_factory=list) class MasterOutlinerAgent: def __init__(self, llm_client: LlmClient): self.llm = llm_client - def build_outline(self, world_bible: WorldBible, registry: CharacterRegistry, language: str = "english") -> MasterOutline: - # Utilize generator.blueprint as structural foundation - bp = BookBlueprint(title=world_bible.title, genre=world_bible.genre) + def build_outline( + self, + world_bible: WorldBible, + registry: CharacterRegistry, + brief: BookBrief, + language: str = "english", + num_chapters: int = 24, + scenes_per_chapter: int = 4, + target_words: int = 80000, + ) -> MasterOutline: + plan = self._plan_book(world_bible, registry, brief, language, num_chapters) + words_per_chapter = target_words // num_chapters chapters = [] - is_tamil = (language or getattr(world_bible, 'language', 'english')).lower() in ["tamil", "ta"] - - for part in bp.parts: - part_name = part["part"] - for chap in part["chapters"]: - num = chap["number"] - title = chap["title"] - focus = chap["focus"] - - sub_beats = [] - if is_tamil: - section_titles = [ - "தொடக்கத் தீப்பொறி (The Inciting Spark)", - "எழுச்சி & கண்டுபிடிப்பு (Rising Tension & Discovery)", - "முக்கிய திருப்புமுனை (Pivotal Turning Point)", - "மறைக்கப்பட்ட உண்மைகள் (Uncovering Hidden Realities)", - "உச்சக்கட்டப் பதற்றம் (Escalating Stakes)", - "நிறைவுக் களம் (Climactic Transition)" - ] - beat_types = [ - "SCENE_GOAL", - "CONFLICT_ESCALATION", - "DISASTER_REVERSAL", - "EMOTIONAL_REACTION", - "DILEMMA_CALCULATION", - "PIVOTAL_DECISION" - ] - elif world_bible.genre in ["psychology_of_money", "money_psychology", "behavioral_finance"] or "psychology" in world_bible.genre.lower() or "psychology" in world_bible.title.lower(): - section_titles = [ - "The Human Parable (Historical Case & Narrative Hook)", - "The Behavioral Mechanism (The Psychological Principle)", - "The Counter-Intuitive Paradox (Ego vs Reality)", - "Empirical Contrast (The Two Financial Mindsets)", - "The Margin of Safety (Defensive Wisdom & Staying Power)", - "The Timeless Takeaway (Mental Model for Freedom & Peace)" - ] - beat_types = [ - "PARABLE_HOOK", - "PSYCHOLOGICAL_PRINCIPLE", - "COUNTER_INTUITIVE_PARADOX", - "CONTRASTING_CASE_STUDY", - "MARGIN_OF_SAFETY", - "TIMELESS_TAKEAWAY" - ] - elif world_bible.genre == "fiction" or "fiction" in world_bible.genre.lower(): - section_titles = [ - "The Inciting Spark", - "Rising Tension & Discovery", - "Pivotal Turning Point", - "Uncovering Hidden Realities", - "Escalating Stakes", - "Climactic Transition" - ] - beat_types = [ - "SCENE_GOAL", - "CONFLICT_ESCALATION", - "DISASTER_REVERSAL", - "EMOTIONAL_REACTION", - "DILEMMA_CALCULATION", - "PIVOTAL_DECISION" - ] - else: - section_titles = [ - "Strategic Foundations", - "Core Execution Mechanics", - "Operational Deep-Dive", - "Real-World Case Analysis", - "Resilience & Risk Mitigation", - "Key Executive Takeaways" - ] - beat_types = [ - "EXECUTIVE_HOOK", - "CORE_MECHANICS", - "EMPIRICAL_PROOF", - "CASE_ANALYSIS", - "RISK_RESILIENCE", - "ACTION_FRAMEWORK" - ] - - tension_curve = [4, 6, 8, 5, 7, 9] - - for sub_idx in range(1, 7): - stitle = section_titles[sub_idx - 1] - btype = beat_types[sub_idx - 1] - tension = tension_curve[sub_idx - 1] - - scene_obj = stitle - key_inter = f"{stitle} - முக்கிய திருப்பம்" if is_tamil else f"Pivotal narrative turning point for {stitle}" - sensory = f"சூழல் வர்ணனை: {world_bible.setting_overview[:40]}" if is_tamil else f"Atmospheric detail anchored in {world_bible.setting_overview[:40]}" - ending = f"அடுத்த பகுதி {num}.{sub_idx+1 if sub_idx < 6 else 1}-க்கான இணைப்பு" if is_tamil else f"Transition hook into section {num}.{sub_idx+1 if sub_idx < 6 else 1}" - - subtext = ( - "கதாபாத்திரத்தின் உள்ளுணர்வு: வெளிப்படையான இலக்கை அடைவதில் முனைப்புடன் கூடிய மறைமுக பதற்றம்." - if is_tamil - else f"Internal subtext for {btype}: Pursuing the immediate scene goal while concealing inner uncertainty and competing motives." - ) - - sub_beats.append(SubBeat( - section_number=f"{num}.{sub_idx}", - scene_objective=scene_obj, - beat_type=btype, - micro_tension_level=tension, - pov_internal_state=subtext, - characters_present=[c.name for c in registry.characters[:2]], - key_interaction=key_inter, - sensory_or_structural_detail=sensory, - ending_hook=ending - )) - - chapters.append(ChapterBeat( - chapter_number=num, - title=title, - pov_character=registry.characters[0].name if registry.characters else ("கதைசொல்லி" if is_tamil else "Narrator"), - location=world_bible.setting_overview[:50], - core_narrative_arc=focus, - sub_beats=sub_beats, - target_word_count=3500 - )) - - pacing = ( - "4 பாகங்கள் கொண்ட எழுச்சிப் பாதை: 6-ஆம் அத்தியாயத்தில் பெரும் திருப்பம், 8-ஆம் அத்தியாயத்தில் உச்சக்கட்ட சோதனை, 12-ஆம் அத்தியாயத்தில் காவிய முடிவு." - if is_tamil - else "4-Part structure with rising tension, midpoint twist in Chapter 6, all-is-lost in Chapter 8, and resolution in Chapter 12." - ) + previous = "None; this is the opening chapter." + for chapter_plan in plan.chapters: + print(f" [Agent: Master Outliner] Planning scenes for Chapter {chapter_plan.chapter_number}/{num_chapters}...") + scenes = self._plan_scenes(chapter_plan, plan, world_bible, registry, brief, language, scenes_per_chapter, previous) + chapters.append(ChapterBeat( + **chapter_plan.model_dump(), + sub_beats=scenes, + target_word_count=words_per_chapter, + foreshadowing_clues_to_plant=[c.name for c in plan.setups_and_payoffs if c.planted_chapter == chapter_plan.chapter_number], + foreshadowing_clues_to_resolve=[c.name for c in plan.setups_and_payoffs if c.target_payoff_chapter == chapter_plan.chapter_number], + )) + previous = " ".join(s.scene_objective for s in scenes) + clues = [ + ForeshadowingClue( + clue_id=f"clue_{i:02d}", name=c.name, description=c.description, + planted_chapter=c.planted_chapter, target_payoff_chapter=c.target_payoff_chapter, + involved_characters=c.involved_characters + ) + for i, c in enumerate(plan.setups_and_payoffs, start=1) + ] return MasterOutline( title=world_bible.title, - total_parts=4, + total_parts=len({c.part_title for c in plan.chapters}), chapters=chapters, - pacing_notes=pacing + pacing_notes=plan.pacing_notes, + foreshadowing=clues, ) + + def _book_context(self, world_bible: WorldBible, registry: CharacterRegistry, brief: BookBrief) -> str: + cast = "\n".join( + f"- {c.name} ({c.role}): wants {c.core_motivation}; flaw: {c.fatal_flaw}; arc: {c.arc_trajectory}" + for c in registry.characters + ) or "No invented cast (non-fiction)." + rules = "\n".join(f"- {r.rule_name}: {r.narrative_consequence}" for r in world_bible.rules) + return f"""Title: {world_bible.title} +Genre: {world_bible.genre} +Logline: {brief.logline} +Reader promise: {brief.reader_promise} +Central question: {brief.central_question} +What makes it different: {brief.what_makes_it_different} +Genre conventions: {brief.genre_conventions} +Ending: {brief.ending} +Setting: {world_bible.setting_overview} +Rules: +{rules} +Cast: +{cast}""" + + def _plan_book(self, world_bible, registry, brief, language, num_chapters) -> BookPlan: + prompt = f"""TASK: book plan +{self._book_context(world_bible, registry, brief)} +{language_directive(language)} + +Plan exactly {num_chapters} chapters grouped into parts, with at least {max(3, num_chapters // 4)} setups that pay off later. +Return ONLY JSON: +{{"pacing_notes": "...", + "chapters": [{{"chapter_number": 1, "part_title": "...", "title": "...", "pov_character": "...", "location": "...", "core_narrative_arc": "what irreversibly changes", "prerequisite_chapters": []}}], + "setups_and_payoffs": [{{"name": "...", "description": "...", "planted_chapter": 1, "target_payoff_chapter": 5, "involved_characters": []}}]}} +""" + validator = lambda plan: self._validate_plan(plan, num_chapters) + return generate_validated(self.llm, prompt, MASTER_OUTLINE_PROMPT, BookPlan, validator=validator, max_tokens=8000 + num_chapters * 250) + + @staticmethod + def _validate_plan(plan: BookPlan, num_chapters: int): + numbers = [c.chapter_number for c in plan.chapters] + if numbers != list(range(1, num_chapters + 1)): + return f"Chapters must be numbered 1 to {num_chapters} in order; got {numbers}." + titles = [c.title.strip().lower() for c in plan.chapters] + if len(set(titles)) != len(titles): + return "Chapter titles must be unique." + for clue in plan.setups_and_payoffs: + if not 1 <= clue.planted_chapter < clue.target_payoff_chapter <= num_chapters: + return f"Setup '{clue.name}' must be planted before its payoff, within the book." + return None + + def _plan_scenes(self, chapter, plan, world_bible, registry, brief, language, scene_count, previous) -> List[SubBeat]: + beat_types = FICTION_BEATS if brief.is_fiction else NONFICTION_BEATS + plants = [c.name for c in plan.setups_and_payoffs if c.planted_chapter == chapter.chapter_number] + payoffs = [c.name for c in plan.setups_and_payoffs if c.target_payoff_chapter == chapter.chapter_number] + book_map = "\n".join(f"{c.chapter_number}. {c.title}: {c.core_narrative_arc}" for c in plan.chapters) + heading_rule = "Leave heading empty." if brief.is_fiction else "Give each scene a short, intriguing reader-facing heading." + prompt = f"""TASK: scene plan +{self._book_context(world_bible, registry, brief)} +{language_directive(language)} + +Whole book: +{book_map} + +Previous chapter's scenes: {previous} + +Plan exactly {scene_count} scenes for Chapter {chapter.chapter_number}: {chapter.title} +Chapter must achieve: {chapter.core_narrative_arc} +Must plant: {plants} +Must pay off: {payoffs} +Choose each beat_type from {beat_types}. {heading_rule} +Tension must vary. The last scene's ending_hook must force the next chapter open. + +Return ONLY JSON: +{{"scenes": [{{"section_number": "{chapter.chapter_number}.1", "heading": "", "scene_objective": "specific event", "beat_type": "{beat_types[0]}", "micro_tension_level": 5, "pov_internal_state": "what is hidden or feared", "characters_present": [], "key_interaction": "the concrete turn", "sensory_or_structural_detail": "one unexpected specific detail", "ending_hook": "the open question"}}]}} +""" + def validator(result: ScenePlan): + if len(result.scenes) != scene_count: + return f"Plan exactly {scene_count} scenes; got {len(result.scenes)}." + if len({s.scene_objective.strip().lower() for s in result.scenes}) != scene_count: + return "Every scene needs its own distinct objective." + return None + + result = generate_validated(self.llm, prompt, MASTER_OUTLINE_PROMPT, ScenePlan, validator=validator, max_tokens=800 * scene_count) + for index, scene in enumerate(result.scenes, start=1): + scene.section_number = f"{chapter.chapter_number}.{index}" + return result.scenes diff --git a/agents/prose_drafter.py b/agents/prose_drafter.py index a4e8974..65c33b4 100644 --- a/agents/prose_drafter.py +++ b/agents/prose_drafter.py @@ -1,186 +1,262 @@ """ Prose Drafter Agent - Phase 2 -Writes high-pacing chapter manuscript prose using iterative Beat-by-Beat (Scene) generation. -Prevents context token overflow and produces deep, multi-thousand word chapters per beat schedule. +Writes chapters scene by scene with verbatim continuity from the preceding prose, +and revises only the scenes editors flag so strong work is never thrown away. """ import re -from schemas.models import WorldBible, CharacterRegistry, ChapterBeat, StoryState, RevisionBrief, SubBeat +from typing import Callable, List, Optional +from schemas.models import WorldBible, CharacterRegistry, ChapterBeat, StoryState, RevisionBrief, SubBeat, BookBrief, SceneNote from generator.llm_client import LlmClient from prompts.system_prompts import PROSE_DRAFTER_PROMPT, TAMIL_PROSE_DRAFTER_PROMPT +SCENE_BREAK = "* * *" +MIN_LENGTH_RATIO = 0.85 +MAX_LENGTH_RETRIES = 2 +PROSE_TAIL_CHARS = 3000 +RECENT_CHAPTERS_IN_FULL = 3 +OLDER_RECAP_CHARS = 200 +FICTION_CRAFT = """1. **Enter late, leave early:** Start in motion. Cut throat-clearing and arrivals. +2. **Show, Don't Tell & Deep POV:** Anchor the narrative in concrete sensory details and immediate action. Ban filter words ("she saw that", "he felt", "noticed that"). +3. **Sentence Rhythm:** Vary sentence lengths because the moment demands it, not on a schedule. +4. **Three-Layer Dialogue:** Characters speak in distinct voices and rarely say exactly what they mean. Use interruptions and evasions. Use action beats between lines. +5. **Specificity:** Prefer the odd, exact detail a reader could not have predicted. Do not reuse images from the preceding text. +6. **No Moralizing Conclusions:** End on action, dialogue or a turn. Never summarize the emotional meaning or hint about the future.""" +NONFICTION_CRAFT = """1. **Lead with a story or a surprise:** Open on a specific moment, then earn the idea from it. +2. **Truth:** Never invent statistics, studies, quotations, named people or events. Use only what you are certain is real. If a fact needs checking, write it followed by [VERIFY: what to check]. Label hypothetical examples as hypothetical. +3. **One idea, deeply:** Prefer a single non-obvious insight, developed, over a list of tips. +4. **Direct address:** Write to one intelligent reader. Plain words. No corporate jargon. +5. **Usefulness:** Leave the reader with something they can see or do differently. +6. **No Moralizing Conclusions:** Do not end by restating the point. End on a turn that pulls the reader onward.""" + class ProseDrafterAgent: def __init__(self, llm_client: LlmClient): self.llm = llm_client - def draft_chapter( + def draft_scenes( self, chapter_beat: ChapterBeat, world_bible: WorldBible, registry: CharacterRegistry, story_state: StoryState, - revision_brief: RevisionBrief = None + brief: BookBrief, + existing_scenes: Optional[List[str]] = None, + on_scene: Optional[Callable[[List[str]], None]] = None, + previous_chapter_tail: str = "", + opening_candidates: int = 1, + choose_opening: Optional[Callable[[List[str]], str]] = None, + ) -> List[str]: + scenes = list(existing_scenes or []) + total = len(chapter_beat.sub_beats) + print(f" [Agent: Prose Drafter] Drafting Chapter {chapter_beat.chapter_number}: {chapter_beat.title} ({total} scenes)...") + + for index, sub_beat in enumerate(chapter_beat.sub_beats): + if index < len(scenes): + continue + tail = scenes[-1][-PROSE_TAIL_CHARS:] if scenes else previous_chapter_tail + prompt = self._scene_prompt(chapter_beat, sub_beat, world_bible, registry, story_state, brief, tail) + count = opening_candidates if index == 0 and choose_opening else 1 + candidates = [self._write_scene(prompt, chapter_beat, world_bible) for _ in range(count)] + scene = choose_opening(candidates) if count > 1 else candidates[0] + scenes.append(scene) + print(f" -> Beat {sub_beat.section_number} ({len(scene.split())} words)...") + if on_scene: + on_scene(scenes) + return scenes + + def revise_scene( + self, + chapter_beat: ChapterBeat, + scene_index: int, + scenes: List[str], + notes: List[SceneNote], + revision_brief: RevisionBrief, + world_bible: WorldBible, + registry: CharacterRegistry, + story_state: StoryState, + brief: BookBrief, ) -> str: - is_tamil = getattr(world_bible, 'language', 'english').lower() in ["tamil", "ta"] - system_prompt = TAMIL_PROSE_DRAFTER_PROMPT if is_tamil else PROSE_DRAFTER_PROMPT - lang_constraint = "CRITICAL MANDATE: WRITE ALL MANUSCRIPT PROSE 100% IN FLUENT, ELEGANT, GRAMMATICALLY CORRECT TAMIL SCRIPT (தமிழ் எழுத்துக்கள்). DO NOT USE ENGLISH WORDS." if is_tamil else "Write in English." - - # Construct Character Voices Context - char_voices = "\n".join([ - f"- {c.name} ({c.role}): Tone={c.voice_fingerprint.tone}, Sentence Rhythm={c.voice_fingerprint.sentence_structure}, Taboo Words={c.voice_fingerprint.taboo_phrases}" - for c in registry.characters - ]) - - # Dynamic Knowledge Graph, Relationships & Foreshadowing Context - kg_lines = [] - if story_state: - if story_state.active_plot_threads: - kg_lines.append(f"* Active Plot Loops: {', '.join(story_state.active_plot_threads[:4])}") - if getattr(story_state, "character_conditions", None): - conds = [ - f"{name}: [Status={cond.physical_wounds_or_status}, Items={cond.inventory_items}, Emotion={cond.emotional_state}]" - for name, cond in story_state.character_conditions.items() - ] - if conds: - kg_lines.append(f"* Character Living State: {'; '.join(conds[:3])}") - if getattr(story_state, "character_relationships", None): - rels = [ - f"{r.source_char} <-> {r.target_char} ({r.relation_type}, Affinity={r.affinity_score}/10, Dynamic='{r.dynamic_status}')" - for r in story_state.character_relationships[:4] - ] - if rels: - kg_lines.append(f"* Active Relationships & Social Dynamics: {'; '.join(rels)}") - if getattr(story_state, "foreshadowing_clues", None): - curr_num = chapter_beat.chapter_number - due = [c for c in story_state.foreshadowing_clues if c.status in ["planted", "escalated"] and c.target_payoff_chapter == curr_num] - active = [c for c in story_state.foreshadowing_clues if c.status in ["planted", "escalated"] and c.target_payoff_chapter != curr_num] - if due: - due_desc = "; ".join([f"'{d.name}' ({d.description})" for d in due]) - kg_lines.append(f"* MANDATORY CLUE PAYOFFS FOR THIS CHAPTER: Resolve or expose: {due_desc}") - if active: - active_desc = "; ".join([f"'{a.name}' (Planted Ch.{a.planted_chapter}, due Ch.{a.target_payoff_chapter})" for a in active[:3]]) - kg_lines.append(f"* Active Background Suspense Hooks: {active_desc}") - if getattr(story_state, "epistemic_secrets", None): - secr = [ - f"'{s.get('fact')}': known to {s.get('known_by')}, HIDDEN from {s.get('hidden_from')}" - for s in story_state.epistemic_secrets[:2] - ] - if secr: - kg_lines.append(f"* Secret/Epistemic Rules: {'; '.join(secr)}") - knowledge_graph_context = "\n".join(kg_lines) if kg_lines else "* All initial plot threads unfolding normally." - - revision_context = "" - if revision_brief and not revision_brief.passed_audit: - revision_context = f""" -=== CRITICS' MANDATORY REVISION DIRECTIVES === -Overall Directive: {revision_brief.editor_overall_directive} -Continuity Issues to Fix: {[f'{c.location}: {c.description} -> Fix: {c.remedy}' for c in revision_brief.continuity_issues]} -Slop Violations to Remove: {[f'{s.phrase_or_pattern}: {s.reason}' for s in revision_brief.slop_violations]} -""" + sub_beat = chapter_beat.sub_beats[scene_index] + note_lines = "\n".join(f"- {n.problem} -> {n.fix}" for n in notes) + continuity = "\n".join(f"- {c.description} -> {c.remedy}" for c in revision_brief.continuity_issues) + before = scenes[scene_index - 1][-1500:] if scene_index else "" + after = scenes[scene_index + 1][:800] if scene_index + 1 < len(scenes) else "" + prompt = f"""TASK: scene revision +Rewrite the scene below so a demanding editor would keep reading. Keep every plot event and fact. Keep what works; change what the notes name. + +Voice guide: {brief.voice_guide} +{self._language_line(world_bible)} +Scene purpose: {sub_beat.scene_objective} / {sub_beat.key_interaction} +Must preserve: {revision_brief.strengths} + +EDITOR NOTES: +{note_lines} +{("CONTINUITY FIXES:" + chr(10) + continuity) if continuity else ""} + +TEXT JUST BEFORE THIS SCENE: +{before or "(chapter opening)"} - chapter_sections = [] - running_chapter_context = "" - total_sub_beats = len(chapter_beat.sub_beats) - - genre_voice_guide = "" - if world_bible.genre in ["psychology_of_money", "money_psychology", "behavioral_finance"] or "psychology" in world_bible.genre.lower() or "psychology" in world_bible.title.lower(): - genre_voice_guide = """ -* **Narrative Non-Fiction Voice (Morgan Housel Style):** - - Channel the masterly, story-driven, observational voice of Morgan Housel (*The Psychology of Money*). - - Open with or center upon a vivid historical parable, character contrast, or real-world case study. - - Emphasize human behavior over spreadsheet math: ego, envy, patience, compounding, and sovereignty over time. - - Deliver timeless, counter-intuitive psychological insights with crisp, punchy prose. +SCENE TO REWRITE: +{scenes[scene_index]} + +TEXT JUST AFTER THIS SCENE (must still follow naturally): +{after or "(chapter ending)"} + +Return only the rewritten scene prose. No headings, labels or commentary. """ + return self._write_scene(prompt, chapter_beat, world_bible) - print(f" [Agent: Prose Drafter] Drafting Chapter {chapter_beat.chapter_number}: {chapter_beat.title} ({total_sub_beats} sub-beats)...") + def assemble_chapter(self, chapter_beat: ChapterBeat, scenes: List[str], brief: BookBrief, include_part: bool = False, language: str = "english") -> str: + is_tamil = language.lower() in ["tamil", "ta"] + label = "அத்தியாயம்" if is_tamil else "Chapter" + lines = [] + if include_part and chapter_beat.part_title: + lines.append(f"# {chapter_beat.part_title}\n") + lines.append(f"## {label} {chapter_beat.chapter_number}: {chapter_beat.title}\n") + if brief.is_fiction: + lines.append(f"\n\n{SCENE_BREAK}\n\n".join(scenes)) + else: + for sub_beat, scene in zip(chapter_beat.sub_beats, scenes): + heading = sub_beat.heading or sub_beat.scene_objective + lines.append(f"### {heading}\n\n{scene}\n") + return "\n".join(lines).strip() + "\n" - for idx, sub_beat in enumerate(chapter_beat.sub_beats, start=1): - beat_label = f"{chapter_beat.chapter_number}.{idx}" - btype = getattr(sub_beat, 'beat_type', 'SCENE_GOAL') - tension = getattr(sub_beat, 'micro_tension_level', 5) - subtext = getattr(sub_beat, 'pov_internal_state', 'Focused on scene goal with suppressed doubts.') + def _write_scene(self, prompt: str, chapter_beat: ChapterBeat, world_bible: WorldBible) -> str: + is_tamil = self._is_tamil(world_bible) + system_prompt = TAMIL_PROSE_DRAFTER_PROMPT if is_tamil else PROSE_DRAFTER_PROMPT + target = self._scene_words(chapter_beat) + # Tamil script costs roughly twice the tokens per word + max_tokens = max(2048, target * (6 if is_tamil else 3)) + scene = self._clean_scene(self.llm.generate_text(prompt, system_prompt=system_prompt, max_tokens=max_tokens)) + for _ in range(MAX_LENGTH_RETRIES): + if len(scene.split()) >= target * MIN_LENGTH_RATIO: + break + extended = self.llm.generate_text( + f"{prompt}\n\nYour last version ran only {len(scene.split())} words. Write the complete scene at about {target} words by deepening the conflict and detail. Do not pad.\n\nLAST VERSION:\n{scene}", + system_prompt=system_prompt, + max_tokens=max_tokens, + ) + extended = self._clean_scene(extended) + if len(extended.split()) > len(scene.split()): + scene = extended + return scene - user_prompt = f"""**Role:** You are an elite, award-winning author specializing in {world_bible.genre} genre. Your prose is immersive, realistic, and character-driven. -{lang_constraint} + def _scene_prompt(self, chapter_beat, sub_beat: SubBeat, world_bible, registry, story_state, brief: BookBrief, tail: str) -> str: + craft = FICTION_CRAFT if brief.is_fiction else NONFICTION_CRAFT + return f"""TASK: scene draft +**Role:** You are writing {world_bible.title}, a {world_bible.genre} book. +{self._language_line(world_bible)} -**Task:** Write Scene Beat {beat_label} (approx. 600-900 words) fulfilling the narrative beats provided below. Do NOT write conversational preambles or meta commentary; write only the specified manuscript prose. +**Book:** {brief.logline} +**Promise to the reader:** {brief.reader_promise} +**Voice guide:** {brief.voice_guide} +**Voice sample (match the voice, never reuse the words):** +{brief.voice_sample} -**Context Guidelines (The Codex):** -* **Genre Style Guide:** Genre={world_bible.genre.upper()}. Setting={world_bible.setting_overview}. World Rules={[r.rule_name + ': ' + r.narrative_consequence for r in world_bible.rules[:3]]} -{genre_voice_guide} -* **Active Characters:** -{char_voices} -* **Dynamic Knowledge Graph & State:** -{knowledge_graph_context} -* **Story So Far (Preceding Chapters):** -{story_state.story_so_far_summary[-1200:] if story_state.story_so_far_summary else "This is Chapter 1 - Opening chapter."} +**Setting:** {world_bible.setting_overview} ({world_bible.time_period}) +**World Rules:** {[r.rule_name + ': ' + r.narrative_consequence for r in world_bible.rules]} +**People in this scene:** +{self._cast_context(registry, sub_beat)} +**Story State:** +{self._knowledge_context(chapter_beat, story_state)} +**Story So Far:** +{self._story_so_far(story_state)} -**Scene Continuity So Far (Current Chapter):** -{running_chapter_context[-1500:] if running_chapter_context else "Beginning of Chapter " + str(chapter_beat.chapter_number) + "."} +**Prose immediately before this scene (continue seamlessly; do not repeat it):** +{tail or "Nothing yet. This is the first page of the book, the page a browsing reader decides on. Make it impossible to put down."} -**Current Scene Micro-Beat to Execute ({beat_label}):** +**Write this scene ({sub_beat.section_number}, about {self._scene_words(chapter_beat)} words):** Chapter {chapter_beat.chapter_number}: {chapter_beat.title} -POV Character: {chapter_beat.pov_character} +Chapter must achieve: {chapter_beat.core_narrative_arc} +Point of view: {chapter_beat.pov_character} Location: {chapter_beat.location} -Dramatic Beat Type: {btype} -Micro-Tension Level: {tension}/10 -POV Internal Subtext: {subtext} -Scene Section: {sub_beat.section_number} -Scene Objective: {sub_beat.scene_objective} -Key Interaction / Conflict: {sub_beat.key_interaction} -Sensory & Structural Detail: {sub_beat.sensory_or_structural_detail} -Ending Transition Hook: {sub_beat.ending_hook} -{revision_context} - -**Strict Execution Constraints:** -1. **Show, Don't Tell & Deep POV:** Anchor the narrative in concrete sensory details and immediate character action. Ban filter words ("she saw that", "he felt", "noticed that"). -2. **Gary Provost Sentence Rhythm:** Relentlessly vary sentence lengths. Mix punchy 2-5 word statements with expansive 25+ word rhythmic sentences. Avoid monotonous mid-length phrasing. -3. **Three-Layer Dialogue:** Characters must speak with distinct voices based on their profiles. Layer spoken lines with unspoken subtext and physical action beats between dialogue. -4. **Dramatic Beat Adherence:** Fulfill the assigned dramatic beat type ({btype}) at tension level {tension}/10. -5. **Language Integrity:** {lang_constraint} -6. **Banish AI Slop:** Strictly forbidden from using generic LLM clichés: "a tapestry of," "a testament to," "shivers down her spine," "ஒரு சான்றாக அமைந்தது", "முதுகெலும்பில் நடுக்கம்", "echoed in the silence". -7. **No Moralizing Conclusions:** End the scene precisely on the final beat provided. Do not append a concluding paragraph that summarizes the scene's emotional weight or hints at the future. -8. **Section Heading:** Start the section with a clean markdown heading: `### {sub_beat.section_number} {sub_beat.scene_objective}`. +Beat type: {sub_beat.beat_type}; tension {sub_beat.micro_tension_level}/10 +Objective: {sub_beat.scene_objective} +The turn: {sub_beat.key_interaction} +Under the surface: {sub_beat.pov_internal_state} +Specific detail: {sub_beat.sensory_or_structural_detail} +End on: {sub_beat.ending_hook} +{self._clue_directive(chapter_beat, story_state)} + +**Craft:** +{craft} +7. **Banish AI Slop:** Forbidden: "a tapestry of," "a testament to," "shivers down her spine," "ஒரு சான்றாக அமைந்தது", "முதுகெலும்பில் நடுக்கம்", "echoed in the silence," and the "it wasn't X, it was Y" construction. + +Return only the prose. No headings, labels or commentary. """ - scene_raw = self.llm.generate_text(user_prompt, system_prompt=system_prompt, max_tokens=2048) - clean_scene = self._post_process_scene(scene_raw, sub_beat) - - words_count = len(clean_scene.split()) - print(f" -> Drafting Chapter {chapter_beat.chapter_number}/{12} -> Beat {beat_label}/{chapter_beat.chapter_number}.{total_sub_beats} ({words_count} words)...") - - chapter_sections.append(clean_scene) - running_chapter_context += f"\n\n{clean_scene}" - - full_chapter_text = f"## Chapter {chapter_beat.chapter_number}: {chapter_beat.title}\n\n" + "\n\n".join(chapter_sections) - return full_chapter_text - - def _post_process_scene(self, raw_text: str, sub_beat: SubBeat) -> str: - lines = raw_text.split('\n') - clean_lines = [] - skip_intro = True - - for line in lines: - s = line.strip() - if skip_intro: - if re.match(r'^(okay|here is|i have|based on|sure|certainly|let\'s|below is|in this chapter|i will proceed|i am ready)', s, re.IGNORECASE): - continue - if s.startswith('---'): - continue - if not s: - continue - skip_intro = False - - # Clean meta-prompt leakage - cleaned = re.sub(r'Sub-section \d+\.\d+:\s*(Execute core objective|Interaction:|Detail:)[^\n]*', '', line, flags=re.IGNORECASE) - cleaned = re.sub(r'(Core Objective:|Interaction:|Detail:)\s*[^\n]*', '', cleaned, flags=re.IGNORECASE) - clean_lines.append(cleaned) - - scene_text = "\n".join(clean_lines).strip() - - # Ensure section heading is present - heading_prefix = f"### {sub_beat.section_number}" - if not scene_text.startswith("###"): - scene_text = f"{heading_prefix} {sub_beat.scene_objective}\n\n" + scene_text - - return scene_text \ No newline at end of file + + @staticmethod + def _scene_words(chapter_beat: ChapterBeat) -> int: + return chapter_beat.target_word_count // max(len(chapter_beat.sub_beats), 1) + + @staticmethod + def _is_tamil(world_bible: WorldBible) -> bool: + return getattr(world_bible, 'language', 'english').lower() in ["tamil", "ta"] + + def _language_line(self, world_bible: WorldBible) -> str: + if self._is_tamil(world_bible): + return "CRITICAL MANDATE: WRITE ALL MANUSCRIPT PROSE 100% IN FLUENT, ELEGANT, GRAMMATICALLY CORRECT TAMIL SCRIPT (தமிழ் எழுத்துக்கள்). DO NOT USE ENGLISH WORDS." + return "Write in English." + + @staticmethod + def _cast_context(registry: CharacterRegistry, sub_beat: SubBeat) -> str: + present = {name.lower() for name in sub_beat.characters_present} + chars = [c for c in registry.characters if c.name.lower() in present] or registry.characters + return "\n".join( + f"- {c.name} ({c.role}): Wants={c.core_motivation}; Flaw={c.fatal_flaw}; Tone={c.voice_fingerprint.tone}; " + f"Rhythm={c.voice_fingerprint.sentence_structure}; Signature={c.voice_fingerprint.frequently_used_terms}; Never says={c.voice_fingerprint.taboo_phrases}" + for c in chars + ) or "- Real people and cases only, as named in this scene's objective." + + @staticmethod + def _story_so_far(story_state: StoryState) -> str: + if not story_state.chapter_recaps: + return "This is the opening." + ordered = sorted(story_state.chapter_recaps.items()) + recent_from = len(ordered) - RECENT_CHAPTERS_IN_FULL + return "\n".join( + f"Ch.{num}: {recap if i >= recent_from else recap[:OLDER_RECAP_CHARS]}" + for i, (num, recap) in enumerate(ordered) + ) + + @staticmethod + def _knowledge_context(chapter_beat: ChapterBeat, story_state: StoryState) -> str: + lines = [] + if story_state.active_plot_threads: + lines.append(f"* Open threads: {'; '.join(story_state.active_plot_threads)}") + if story_state.character_conditions: + conds = [ + f"{name}: status={c.physical_wounds_or_status}, holding={c.inventory_items}, feeling={c.emotional_state}, at={c.current_location}" + for name, c in story_state.character_conditions.items() + ] + lines.append(f"* Character state: {'; '.join(conds)}") + if story_state.character_relationships: + rels = [f"{r.source_char} <-> {r.target_char} ({r.relation_type}, {r.affinity_score}/10: {r.dynamic_status})" for r in story_state.character_relationships] + lines.append(f"* Relationships: {'; '.join(rels)}") + if story_state.epistemic_secrets: + secrets = [f"'{s.get('fact')}' known to {s.get('known_by')}, hidden from {s.get('hidden_from')}" for s in story_state.epistemic_secrets] + lines.append(f"* Who knows what: {'; '.join(secrets)}") + if story_state.key_discoveries: + lines.append(f"* Already established (do not re-explain): {'; '.join(story_state.key_discoveries[-15:])}") + return "\n".join(lines) or "* Nothing established yet." + + @staticmethod + def _clue_directive(chapter_beat: ChapterBeat, story_state: StoryState) -> str: + by_name = {c.name: c for c in story_state.foreshadowing_clues} + plant = [f"'{n}' ({by_name[n].description})" for n in chapter_beat.foreshadowing_clues_to_plant if n in by_name] + pay = [f"'{n}' ({by_name[n].description})" for n in chapter_beat.foreshadowing_clues_to_resolve if n in by_name] + lines = [] + if plant: + lines.append(f"This chapter must quietly plant, without drawing attention: {'; '.join(plant)}") + if pay: + lines.append(f"This chapter must pay off: {'; '.join(pay)}") + return "\n".join(lines) + + @staticmethod + def _clean_scene(raw_text: str) -> str: + lines = raw_text.strip().split('\n') + while lines and (lines[0].lstrip().startswith('#') or not lines[0].strip()): + lines.pop(0) + text = "\n".join(lines).strip() + return re.sub(r'\n{3,}', '\n\n', text) diff --git a/agents/publishing_kit.py b/agents/publishing_kit.py new file mode 100644 index 0000000..d997618 --- /dev/null +++ b/agents/publishing_kit.py @@ -0,0 +1,68 @@ +""" +Publishing Kit Agent - Phase 5 +Writes the store listing and cover direction from the finished book, never from the outline alone. +""" + +import json +import os +from schemas.models import BookBrief, PublishingKit, StoryState +from generator.llm_client import LlmClient +from generator.json_parser import generate_validated +from prompts.system_prompts import PUBLISHING_KIT_PROMPT, language_directive + + +class PublishingKitAgent: + def __init__(self, llm_client: LlmClient): + self.llm = llm_client + + def build_kit(self, title: str, author: str, brief: BookBrief, story_state: StoryState, language: str = "english") -> PublishingKit: + recaps = "\n".join(f"{n}. {r}" for n, r in sorted(story_state.chapter_recaps.items())) + prompt = f"""TASK: publishing kit +Title: {title} +Author: {author} +Logline: {brief.logline} +Target reader: {brief.target_reader} +Reader promise: {brief.reader_promise} +What makes it different: {brief.what_makes_it_different} +{language_directive(language)} + +What actually happens in the finished book: +{recaps} + +Return ONLY JSON with this schema: +{{ + "subtitle": "", + "tagline": "...", + "blurb": "...", + "kdp_keywords": ["seven search phrases"], + "bisac_categories": ["..."], + "comparable_titles": ["..."], + "cover_brief": "...", + "launch_plan": ["..."] +}} +""" + return generate_validated(self.llm, prompt, PUBLISHING_KIT_PROMPT, PublishingKit, validator=self._validate, max_tokens=3000) + + @staticmethod + def _validate(kit: PublishingKit): + if not kit.blurb.strip(): + return "The blurb is empty." + if len(kit.kdp_keywords) > 7: + return "KDP allows at most seven keyword phrases." + return None + + @staticmethod + def write_kit(kit: PublishingKit, directory: str) -> str: + os.makedirs(directory, exist_ok=True) + with open(os.path.join(directory, "metadata.json"), "w", encoding="utf-8") as f: + json.dump(kit.model_dump(), f, ensure_ascii=False, indent=2) + path = os.path.join(directory, "listing.md") + bullets = lambda items: "\n".join(f"- {i}" for i in items) + with open(path, "w", encoding="utf-8") as f: + f.write( + f"# Store Listing\n\n**Tagline:** {kit.tagline}\n\n## Description\n\n{kit.blurb}\n\n" + f"## KDP Keywords\n\n{bullets(kit.kdp_keywords)}\n\n## Categories\n\n{bullets(kit.bisac_categories)}\n\n" + f"## Comparable Titles (AI suggested: confirm they exist and fit)\n\n{bullets(kit.comparable_titles)}\n\n" + f"## Cover Brief\n\n{kit.cover_brief}\n\n## Launch Plan\n\n{bullets(kit.launch_plan)}\n" + ) + return path diff --git a/agents/world_builder.py b/agents/world_builder.py index 068e6ab..9b39284 100644 --- a/agents/world_builder.py +++ b/agents/world_builder.py @@ -1,14 +1,12 @@ """ World Builder Agent - Phase 1 Generates structured WorldBible from user seed concept using local LLM. -Includes robust JSON extraction, correction retry, and genre-aware fallbacks. +Includes robust JSON extraction and correction retry. Fails loudly rather than inventing a stock world. """ -import json -import re -from schemas.models import WorldBible, WorldRule +from schemas.models import WorldBible, BookBrief from generator.llm_client import LlmClient -from generator.json_parser import parse_llm_json, clean_json_string +from generator.json_parser import parse_llm_json, StructuredOutputError from prompts.system_prompts import WORLD_BUILDER_PROMPT, TAMIL_WORLD_BUILDER_PROMPT @@ -16,17 +14,22 @@ class WorldBuilderAgent: def __init__(self, llm_client: LlmClient): self.llm = llm_client - def build_world(self, seed_title: str, seed_concept: str, genre: str, language: str = "english") -> WorldBible: + def build_world(self, seed_title: str, seed_concept: str, genre: str, language: str = "english", brief: BookBrief = None) -> WorldBible: is_tamil = language.lower() in ["tamil", "ta"] system_prompt = TAMIL_WORLD_BUILDER_PROMPT if is_tamil else WORLD_BUILDER_PROMPT lang_directive = "Write all setting text, descriptions, and rule details in natural, fluent TAMIL (தமிழ் எழுத்துக்கள்)." if is_tamil else "Write in English." + brief_block = f"Book Brief: {brief.logline} Promise: {brief.reader_promise} Ending: {brief.ending}" if brief else "" + if brief and not brief.is_fiction: + brief_block += "\nThis is non-fiction: define the subject's real setting and its governing principles. Do not invent a fictional world." + prompt = f""" Seed Title: {seed_title} Genre: {genre} Language: {language} Seed Concept: {seed_concept} Directive: {lang_directive} +{brief_block} Generate a comprehensive, structured World Bible for this manuscript. Define at least 4 hard rules with clear narrative consequences when broken. @@ -66,102 +69,10 @@ def build_world(self, seed_title: str, seed_concept: str, genre: str, language: bible.language = language return bible - # Genre-specific Fallback derived directly from seed_title and seed_concept - print(" [WorldBuilder Warning] JSON retry failed, constructing genre-derived WorldBible fallback.") - fallback = self._fallback_world_bible(seed_title, genre, seed_concept, is_tamil=is_tamil) - fallback.language = language - return fallback + raise StructuredOutputError(f"World Bible for '{seed_title}' could not be generated: the model returned invalid JSON twice.") def _parse_world_bible(self, text: str) -> WorldBible: bible = parse_llm_json(text, model_class=WorldBible) if bible and bible.rules and len(bible.rules) > 0 and bible.title: return bible return None - - def _clean_json(self, text: str) -> str: - if not text: - return "{}" - # 1. Strip reasoning blocks - text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL) - - # 2. Extract code block content if wrapped - if "```json" in text: - text = text.split("```json")[1].split("```")[0] - elif "```" in text: - text = text.split("```")[1].split("```")[0] - - # 3. Match largest JSON object - match = re.search(r'\{[\s\S]*\}', text) - if match: - return match.group(0).strip() - return text.strip() - - def _fallback_world_bible(self, title: str, genre: str, concept: str, is_tamil: bool = False) -> WorldBible: - if is_tamil: - return WorldBible( - title=title, - genre=genre, - language="tamil", - setting_overview=f"தமிழ் மண், பண்பாடு மற்றும் வரலாற்றுப் பின்னணியில் அமைந்த கம்பீரமான கதைக்களம்: {concept or title}.", - time_period="பண்டைய / நவீன தமிழகம்", - core_thematic_conflict="வீரம், காதல், தியாகம் மற்றும் நீதிக்கான உணர்ச்சிப்பூர்வமான போராட்டம்.", - rules=[ - WorldRule( - category="சமூக விதி", - rule_name="சொன்ன சொல் தவறாமை", - description="வாக்கு தவறாமை மற்றும் வீரத்தின் கண்ணியம் உயிரினும் மேலானது.", - narrative_consequence="வாக்கு தவறினால் பெரும் பழி மற்றும் சமுதாய புறக்கணிப்பு ஏற்படும்." - ), - WorldRule( - category="அரசியல் விதி", - rule_name="மகுடத்தின் தர்மம்", - description="அரியணை என்பது அதிகாரத்திற்கானதல்ல, மக்களின் நலனுக்கானது.", - narrative_consequence="அநீதி இழைக்கும் அரசன் பேரழிவைச் சந்திப்பான்." - ) - ], - forbidden_tropes=["செயற்கையான மொழிபெயர்ப்பு", "ஆங்கில வார்த்தைகள்", "போலித் தத்துவப் பத்திகள்"] - ) - g = genre.lower() - if g in ["fiction", "romance"]: - return WorldBible( - title=title, - genre=genre, - language="english", - setting_overview=f"An emotionally rich, captivating world centered around {title} and deep personal relationships.", - time_period="Contemporary", - core_thematic_conflict="The struggle between intense emotional devotion, vulnerability, and external obstacles.", - rules=[ - WorldRule( - category="Emotional Constraint", - rule_name="The Law of Vulnerability", - description="True intimacy requires exposing one's deepest fears and past wounds.", - narrative_consequence="Hiding the truth creates painful misunderstandings and emotional distance." - ), - WorldRule( - category="Social Setting", - rule_name="High Stakes Relationship", - description="External pressures and conflicting loyalties challenge the bond between lovers.", - narrative_consequence="Choices made in secret carry heavy consequences for both partners." - ) - ], - forbidden_tropes=["Corporate Jargon", "Software Code", "Technical Diagrams", "Artificial Predictability"] - ) - else: - return WorldBible( - title=title, - genre=genre, - language="english", - setting_overview=f"Immersive environment based on: {concept}", - time_period="Modern Era", - core_thematic_conflict=f"Mastering the dynamics of {title}", - rules=[ - WorldRule( - category="Systemic Rule", - rule_name="Core Constraint", - description="Domain mastery requires total commitment.", - narrative_consequence="Partial execution leads to operational failure." - ) - ], - forbidden_tropes=["Generic Clichés", "Superficial Overviews"] - ) - diff --git a/generator/__init__.py b/generator/__init__.py index 1e1c625..e21d816 100644 --- a/generator/__init__.py +++ b/generator/__init__.py @@ -6,8 +6,6 @@ from .llm_client import LlmClient, LLMClient from .blueprint import BookBlueprint, BLUEPRINTS, get_blueprint_for_genre, TAMIL_GENRES from .docx_compiler import compile_book, compile_book_to_docx -from .writer import ChapterWriter -from .editor import DevelopmentalEditor __version__ = "4.0.0" @@ -19,7 +17,5 @@ "get_blueprint_for_genre", "TAMIL_GENRES", "compile_book", - "compile_book_to_docx", - "ChapterWriter", - "DevelopmentalEditor" + "compile_book_to_docx" ] diff --git a/generator/blueprint.py b/generator/blueprint.py index 32e3e98..77a46c3 100644 --- a/generator/blueprint.py +++ b/generator/blueprint.py @@ -55,9 +55,7 @@ def _detect_genre(self, genre: str, title: str) -> str: return "non-fiction" def _generate_blueprint(self): - if self.genre == "psychology_of_money": - return self._generate_psychology_of_money_blueprint() - elif self.genre == "tamil_historical": + if self.genre == "tamil_historical": return self._generate_tamil_historical_blueprint() elif self.genre == "tamil_kavithai": return self._generate_tamil_kavithai_blueprint() @@ -640,90 +638,6 @@ def _generate_non_fiction_blueprint(self): } ] - def _generate_psychology_of_money_blueprint(self): - return [ - { - "part": "Part I: The Mind and the Ledger (Ego, Luck & Perception)", - "chapters": [ - { - "number": 1, - "title": "No One Is Crazy: The Invisible Lens of Experience", - "focus": "How different eras, generations, and economic backgrounds shape financial minds; why your worldview of risk makes complete sense to you and completely baffles everyone else." - }, - { - "number": 2, - "title": "The Asymmetry of Luck and Risk", - "focus": "Nothing is as good or as bad as it seems. Random chance drives outsized outcomes; why acknowledging luck protects you from arrogance, and acknowledging risk protects you from despair." - }, - { - "number": 3, - "title": "The Paradox of Never Enough", - "focus": "When wealth becomes an infinite treadmill; the danger of moving goalposts, the toxicity of social comparison, and why knowing what is 'enough' is the ultimate financial superpower." - } - ] - }, - { - "part": "Part II: The Mechanics of Quiet Wealth (Compounding, Survival & Tails)", - "chapters": [ - { - "number": 4, - "title": "Confounding Compounding: The Miracle of Time", - "focus": "Why patience performs mathematical miracles. The counter-intuitive nature of exponential growth, and why Warren Buffett's real superpower is not investment brilliance, but unbroken longevity." - }, - { - "number": 5, - "title": "Getting Wealthy vs. Staying Wealthy", - "focus": "Making money requires taking risks, optimism, and aggressive initiative; keeping money requires paranoia, humility, frugality, and the survival instinct to never get wiped out." - }, - { - "number": 6, - "title": "Tails, You Win: The Power Law of Life and Markets", - "focus": "Why a microscopic fraction of decisions, investments, and events drive 99% of total returns. You can be wrong half the time and still achieve extraordinary wealth." - } - ] - }, - { - "part": "Part III: The True Dividend of Wealth (Autonomy, Invisibility & Restraint)", - "chapters": [ - { - "number": 7, - "title": "Freedom: The Highest Form of Wealth", - "focus": "The ultimate dividend of money is control over your time. The ability to wake up every morning and say 'I can do whatever I want today' is the single greatest determinant of human happiness." - }, - { - "number": 8, - "title": "The Man in the Car Paradox", - "focus": "Nobody is impressed by your luxury possessions as much as you are. People buy expensive goods hoping for admiration, but onlookers only imagine themselves possessing them." - }, - { - "number": 9, - "title": "Wealth Is What You Don't See", - "focus": "Spending money to show people you have money is the fastest way to have less money. True wealth is unspent cash, unbought cars, unexercised leverage, and financial optionality." - } - ] - }, - { - "part": "Part IV: The Modern Playbook (Reasonability, Room for Error & Compounding Optimism)", - "chapters": [ - { - "number": 10, - "title": "Save Without a Goal: Cash as Emotional Insurance", - "focus": "Why saving money does not require a specific purchase target. Savings is simply the gap between your ego and your income; cash reserves provide the priceless luxury of independence and sleep." - }, - { - "number": 11, - "title": "Reasonable Beats Rational: Sleeping Well at Night", - "focus": "Human beings are not cold mathematical spreadsheets. A financial strategy that is psychologically reasonable and lets you sleep at night beats a hyper-rational formula that causes panic during a crash." - }, - { - "number": 12, - "title": "The Seduction of Pessimism", - "focus": "Why doom sounds intellectual and warnings capture attention, while optimism sounds like a sales pitch. Why destruction happens in minutes while progress compounds silently across decades." - } - ] - } - ] - # Genre metadata registries & helpers for Web and Streamlit UIs TAMIL_GENRES = { diff --git a/generator/docx_compiler.py b/generator/docx_compiler.py index 315f5fb..679518a 100644 --- a/generator/docx_compiler.py +++ b/generator/docx_compiler.py @@ -1,724 +1,416 @@ """ -Docx Compiler Engine Module - World-Class Bestseller Commercial Edition -Compiles structured Markdown chapter files into an award-winning, publishing-grade 300-page trade book (.docx) -complete with Half Title, Praise Pages, Front Cover, Copyright Notice, Epigraph, Preface, Foreword, Table of Contents, Callout Highlights, Appendices, Glossary, Index, and Back Cover. +Docx Compiler Engine Module +Compiles Markdown chapters into a print-ready trade interior (.docx): 6x9 trim with mirrored margins, +real heading styles, a live table of contents, running heads and page numbers. +Prints only facts the author supplied. Covers are separate files in commercial publishing. """ import os +import glob import re +from datetime import datetime import docx -from docx.shared import Inches, Pt, RGBColor -from docx.enum.text import WD_ALIGN_PARAGRAPH +from docx.enum.section import WD_SECTION from docx.enum.table import WD_TABLE_ALIGNMENT -from docx.oxml import parse_xml -from docx.oxml.ns import nsdecls - -# Palette Definitions - World-Class Luxury Colors -COLOR_NAVY = RGBColor(15, 23, 42) # #0F172A Primary Dark -COLOR_BLUE = RGBColor(2, 132, 199) # #0284C7 Accent Blue -COLOR_TEAL = RGBColor(5, 150, 105) # #059669 Accent Teal -COLOR_GOLD = RGBColor(217, 119, 6) # #D97706 Accent Gold -COLOR_DARK_GRAY = RGBColor(51, 65, 85) # #334155 Slate Dark -COLOR_CODE_BG = "F1F5F9" # #F1F5F9 Code Background -COLOR_QUOTE_BG = "F8FAFC" # #F8FAFC Quote Shading -COLOR_COVER_BG = "0F172A" # #0F172A Cover Background -COLOR_TABLE_HEADER = "0F172A" # #0F172A Table Header -COLOR_ALT_ROW = "F8FAFC" # #F8FAFC Alt Row - -def set_cell_background(cell, hex_color): - tcPr = cell._element.get_or_add_tcPr() - shd = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{hex_color}"/>') - tcPr.append(shd) - -def set_cell_margins(cell, top=140, bottom=140, left=180, right=180): - tcPr = cell._element.get_or_add_tcPr() - tcMar = parse_xml(f''' - <w:tcMar {nsdecls("w")}> - <w:top w:w="{top}" w:type="dxa"/> - <w:bottom w:w="{bottom}" w:type="dxa"/> - <w:left w:w="{left}" w:type="dxa"/> - <w:right w:w="{right}" w:type="dxa"/> - </w:tcMar> - ''') - tcPr.append(tcMar) +from docx.enum.text import WD_ALIGN_PARAGRAPH +from docx.oxml import OxmlElement +from docx.oxml.ns import qn +from docx.shared import Inches, Pt, RGBColor -def add_code_block(doc, code_text): - table = doc.add_table(rows=1, cols=1) - table.alignment = WD_TABLE_ALIGNMENT.CENTER - table.autofit = False - - cell = table.cell(0, 0) - cell.width = Inches(6.0) - set_cell_background(cell, COLOR_CODE_BG) - set_cell_margins(cell, top=140, bottom=140, left=200, right=200) - - tcPr = cell._element.get_or_add_tcPr() - borders = parse_xml(f''' - <w:tcBorders {nsdecls("w")}> - <w:top w:val="single" w:sz="4" w:space="0" w:color="CBD5E1"/> - <w:left w:val="single" w:sz="24" w:space="0" w:color="0284C7"/> - <w:bottom w:val="single" w:sz="4" w:space="0" w:color="CBD5E1"/> - <w:right w:val="single" w:sz="4" w:space="0" w:color="CBD5E1"/> - </w:tcBorders> - ''') - tcPr.append(borders) - - p = cell.paragraphs[0] - p.paragraph_format.space_before = Pt(4) - p.paragraph_format.space_after = Pt(4) - p.paragraph_format.line_spacing = 1.2 - - lines = code_text.strip().split('\n') - for idx, line in enumerate(lines): - if idx > 0: - p = cell.add_paragraph() - p.paragraph_format.space_before = Pt(0) - p.paragraph_format.space_after = Pt(0) - p.paragraph_format.line_spacing = 1.2 - - run = p.add_run(line) - run.font.name = 'Consolas' - run.font.size = Pt(9.5) - run.font.color.rgb = RGBColor(30, 41, 59) - - doc.add_paragraph().paragraph_format.space_after = Pt(8) - -def add_quote_callout(doc, quote_text): - table = doc.add_table(rows=1, cols=1) - table.alignment = WD_TABLE_ALIGNMENT.CENTER - table.autofit = False - - cell = table.cell(0, 0) - cell.width = Inches(6.0) - set_cell_background(cell, COLOR_QUOTE_BG) - set_cell_margins(cell, top=160, bottom=160, left=220, right=220) - - tcPr = cell._element.get_or_add_tcPr() - borders = parse_xml(f''' - <w:tcBorders {nsdecls("w")}> - <w:top w:val="single" w:sz="12" w:space="0" w:color="D97706"/> - <w:left w:val="single" w:sz="24" w:space="0" w:color="059669"/> - <w:bottom w:val="single" w:sz="12" w:space="0" w:color="D97706"/> - <w:right w:val="none"/> - </w:tcBorders> - ''') - tcPr.append(borders) - - p = cell.paragraphs[0] - p.alignment = WD_ALIGN_PARAGRAPH.CENTER - p.paragraph_format.space_before = Pt(6) - p.paragraph_format.space_after = Pt(6) - p.paragraph_format.line_spacing = 1.25 - - run = p.add_run(f'“{quote_text.strip()}”') - run.font.name = 'Georgia' - run.font.size = Pt(11) - run.italic = True - run.font.color.rgb = COLOR_NAVY - - doc.add_paragraph().paragraph_format.space_after = Pt(8) - -def get_font_name(is_heading=False, is_code=False, language="english"): - if language and language.lower() in ["tamil", "ta"]: - return "Mukta Malar" - if is_code: - return 'Consolas' - return 'Arial' if is_heading else 'Arial' +BODY_FONT = "Georgia" +TAMIL_FONT = "Noto Serif Tamil" +CODE_FONT = "Consolas" +BODY_SIZE = Pt(11) +BLACK = RGBColor(0, 0, 0) +SCENE_BREAK = re.compile(r'^(\*\s*\*\s*\*|\*{3,}|-{3,}|#)$') + + +def _is_tamil(language): + return bool(language) and language.lower() in ["tamil", "ta"] + + +def set_style_font(style, font_name, size=None, bold=None, italic=None): + """Sets a font for Latin and complex scripts, clearing theme fonts that would override it.""" + rpr = style.element.get_or_add_rPr() + fonts = rpr.find(qn('w:rFonts')) + if fonts is None: + fonts = OxmlElement('w:rFonts') + rpr.insert(0, fonts) + for attr in list(fonts.attrib): + del fonts.attrib[attr] + for slot in ['w:ascii', 'w:hAnsi', 'w:cs', 'w:eastAsia']: + fonts.set(qn(slot), font_name) + style.font.color.rgb = BLACK + if size: + style.font.size = size + cs_size = rpr.find(qn('w:szCs')) + if cs_size is None: + cs_size = OxmlElement('w:szCs') + rpr.find(qn('w:sz')).addnext(cs_size) + cs_size.set(qn('w:val'), str(int(size.pt * 2))) + if bold is not None: + style.font.bold = bold + if italic is not None: + style.font.italic = italic + + +def configure_styles(doc, language): + font = TAMIL_FONT if _is_tamil(language) else BODY_FONT + + normal = doc.styles['Normal'] + set_style_font(normal, font, BODY_SIZE) + normal.paragraph_format.line_spacing = 1.2 + normal.paragraph_format.space_after = Pt(0) + normal.paragraph_format.widow_control = True + + for name, size, before, after, align in [ + ('Heading 1', Pt(20), Pt(180), Pt(0), WD_ALIGN_PARAGRAPH.CENTER), + ('Heading 2', Pt(16), Pt(72), Pt(30), WD_ALIGN_PARAGRAPH.CENTER), + ('Heading 3', Pt(12), Pt(16), Pt(8), WD_ALIGN_PARAGRAPH.LEFT), + ('Heading 4', Pt(11), Pt(12), Pt(6), WD_ALIGN_PARAGRAPH.LEFT), + ]: + style = doc.styles[name] + set_style_font(style, font, size, bold=True) + style.paragraph_format.space_before = before + style.paragraph_format.space_after = after + style.paragraph_format.alignment = align + style.paragraph_format.keep_with_next = True + + +def configure_page(section): + section.page_width = Inches(6) + section.page_height = Inches(9) + section.top_margin = Inches(0.8) + section.bottom_margin = Inches(0.8) + section.left_margin = Inches(0.875) # inside margin once mirrored, safe for up to ~700 pages + section.right_margin = Inches(0.5) + section.header_distance = Inches(0.4) + section.footer_distance = Inches(0.4) + + +def add_field(paragraph, instruction, cached_text=""): + for kind, text in [('begin', None), (None, instruction), ('separate', None), ('result', cached_text), ('end', None)]: + run = paragraph.add_run() + if kind in ('begin', 'separate', 'end'): + fld = OxmlElement('w:fldChar') + fld.set(qn('w:fldCharType'), kind) + run._r.append(fld) + elif kind == 'result': + run.text = text + else: + instr = OxmlElement('w:instrText') + instr.set(qn('xml:space'), 'preserve') + instr.text = f" {text} " + run._r.append(instr) def process_inline_formatting(paragraph, text, language="english"): - tokens = re.split(r'(\*\*.*?\*\*|\*.*?\*|`.*?`)', text) - font_name = get_font_name(is_heading=False, is_code=False, language=language) + tokens = re.split(r'(\*\*.+?\*\*|\*[^*\s](?:.*?[^*\s])?\*|`.+?`)', text) for token in tokens: if not token: continue - if token.startswith('**') and token.endswith('**'): - run = paragraph.add_run(token[2:-2]) - run.bold = True - run.font.name = font_name - elif token.startswith('*') and token.endswith('*'): - run = paragraph.add_run(token[1:-1]) - run.italic = True - run.font.name = font_name - elif token.startswith('`') and token.endswith('`'): + if token.startswith('**') and token.endswith('**') and len(token) > 4: + paragraph.add_run(token[2:-2]).bold = True + elif token.startswith('*') and token.endswith('*') and len(token) > 2: + paragraph.add_run(token[1:-1]).italic = True + elif token.startswith('`') and token.endswith('`') and len(token) > 2: run = paragraph.add_run(token[1:-1]) - run.font.name = 'Consolas' + run.font.name = CODE_FONT run.font.size = Pt(9.5) - run.font.color.rgb = COLOR_BLUE else: - run = paragraph.add_run(token) - run.font.name = font_name + paragraph.add_run(token) + + +def add_code_block(doc, code_text): + for line in code_text.rstrip().split('\n'): + p = doc.add_paragraph() + p.paragraph_format.left_indent = Inches(0.2) + p.paragraph_format.line_spacing = 1.1 + run = p.add_run(line) + run.font.name = CODE_FONT + run.font.size = Pt(9) + doc.add_paragraph() + + +def add_quote(doc, quote_text, language): + p = doc.add_paragraph() + p.paragraph_format.left_indent = Inches(0.35) + p.paragraph_format.right_indent = Inches(0.35) + p.paragraph_format.space_before = Pt(8) + p.paragraph_format.space_after = Pt(8) + process_inline_formatting(p, quote_text, language) + for run in p.runs: + run.italic = True + + +def render_table(doc, rows, language="english"): + if not rows: + return + num_cols = max(len(row) for row in rows) + table = doc.add_table(rows=len(rows), cols=num_cols) + table.style = 'Table Grid' + table.alignment = WD_TABLE_ALIGNMENT.CENTER + for row_idx, row in enumerate(rows): + for col_idx, value in enumerate(row): + p = table.cell(row_idx, col_idx).paragraphs[0] + process_inline_formatting(p, value, language) + for run in p.runs: + run.font.size = Pt(9.5) + if row_idx == 0: + run.bold = True + doc.add_paragraph() + +def start_body_section(doc): + """Each part or chapter is its own section so its opening page can drop the running head.""" + section = doc.add_section(WD_SECTION.NEW_PAGE) + section.different_first_page_header_footer = True + return section -def parse_markdown_file(doc, filepath, language="english"): + +def parse_markdown_file(doc, filepath, language="english", new_sections=False): with open(filepath, 'r', encoding='utf-8') as f: - content = f.read() + lines = f.read().split('\n') - lines = content.split('\n') - in_code_block = False + in_code = False code_lines = [] - in_table = False table_rows = [] - font_name = get_font_name(is_heading=False, language=language) + indent_next = False + first_heading = True - is_first_heading = True for line in lines: stripped = line.strip() if stripped.startswith('```'): - is_first_heading = False - if in_code_block: + if in_code: add_code_block(doc, '\n'.join(code_lines)) code_lines = [] - in_code_block = False - else: - in_code_block = True - code_lines = [] + in_code = not in_code continue - - if in_code_block: - is_first_heading = False + if in_code: code_lines.append(line) continue - if stripped.startswith('> '): - is_first_heading = False - add_quote_callout(doc, stripped[2:]) + if stripped.startswith('|') and stripped.count('|') >= 2: + if not re.match(r'^\|?[\s:|-]+\|?$', stripped): + table_rows.append([c.strip() for c in stripped.strip('|').split('|')]) continue - - if '|' in line and line.count('|') >= 2: - is_first_heading = False - if not in_table: - in_table = True - table_rows = [] - if re.match(r'^\s*\|?\s*:?-+:?\s*\|', line): - continue - table_rows.append([cell.strip() for cell in line.strip('| \t').split('|')]) - continue - else: - if in_table: - render_table(doc, table_rows, language=language) - in_table = False - table_rows = [] + if table_rows: + render_table(doc, table_rows, language) + table_rows = [] + indent_next = False if not stripped: continue - if stripped.startswith('# '): - if not is_first_heading: + heading = re.match(r'^(#{1,4})\s+(.*)$', stripped) + if heading: + level = len(heading.group(1)) + if level <= 2 and new_sections: + start_body_section(doc) + elif level <= 2 and not first_heading: doc.add_page_break() - is_first_heading = False - p = doc.add_paragraph() - p.paragraph_format.space_before = Pt(40) - p.paragraph_format.space_after = Pt(16) - p.paragraph_format.keep_with_next = True - run = p.add_run(stripped[2:]) - run.font.name = font_name - run.font.size = Pt(24) - run.bold = True - run.font.color.rgb = COLOR_NAVY - elif stripped.startswith('## '): - if not is_first_heading: - doc.add_page_break() - is_first_heading = False - p = doc.add_paragraph() - p.paragraph_format.space_before = Pt(30) - p.paragraph_format.space_after = Pt(12) - p.paragraph_format.keep_with_next = True - run = p.add_run(stripped[3:]) - run.font.name = font_name - run.font.size = Pt(20) - run.bold = True - run.font.color.rgb = COLOR_BLUE - elif stripped.startswith('### '): - is_first_heading = False - heading_text = stripped[4:] - heading_text = re.sub(r'^Sub-section \d+:\s*', '', heading_text, flags=re.IGNORECASE) - heading_text = re.sub(r'in The [^\n]*$', '', heading_text, flags=re.IGNORECASE).strip() - - p = doc.add_paragraph() - p.paragraph_format.space_before = Pt(16) - p.paragraph_format.space_after = Pt(6) - p.paragraph_format.keep_with_next = True - run = p.add_run(heading_text) - run.font.name = font_name - run.font.size = Pt(14) - run.bold = True - run.font.color.rgb = COLOR_NAVY - elif stripped.startswith('#### '): - p = doc.add_paragraph() + first_heading = False + doc.add_heading(heading.group(2), level=level) + indent_next = False + elif SCENE_BREAK.match(stripped): + p = doc.add_paragraph('* * *') + p.alignment = WD_ALIGN_PARAGRAPH.CENTER p.paragraph_format.space_before = Pt(12) - p.paragraph_format.space_after = Pt(4) - p.paragraph_format.keep_with_next = True - run = p.add_run(stripped[5:]) - run.font.name = font_name - run.font.size = Pt(12) - run.bold = True - run.font.color.rgb = COLOR_TEAL - elif stripped.startswith('- ') or stripped.startswith('* '): - p = doc.add_paragraph(style='List Bullet') - p.paragraph_format.space_before = Pt(3) - p.paragraph_format.space_after = Pt(3) - p.paragraph_format.line_spacing = 1.2 - process_inline_formatting(p, stripped[2:], language=language) + p.paragraph_format.space_after = Pt(12) + indent_next = False + elif stripped.startswith('>'): + add_quote(doc, stripped.lstrip('> ').strip(), language) + indent_next = False + elif re.match(r'^[-*]\s', stripped): + process_inline_formatting(doc.add_paragraph(style='List Bullet'), stripped[2:], language) + indent_next = False elif re.match(r'^\d+\.\s', stripped): - p = doc.add_paragraph(style='List Number') - p.paragraph_format.space_before = Pt(3) - p.paragraph_format.space_after = Pt(3) - p.paragraph_format.line_spacing = 1.2 - text_without_num = re.sub(r'^\d+\.\s', '', stripped) - process_inline_formatting(p, text_without_num, language=language) + process_inline_formatting(doc.add_paragraph(style='List Number'), re.sub(r'^\d+\.\s', '', stripped), language) + indent_next = False else: p = doc.add_paragraph() - p.paragraph_format.space_before = Pt(4) - p.paragraph_format.space_after = Pt(8) - p.paragraph_format.line_spacing = 1.25 - process_inline_formatting(p, stripped, language=language) + p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY + if indent_next: + p.paragraph_format.first_line_indent = Inches(0.25) + process_inline_formatting(p, stripped, language) + indent_next = True - if in_table and table_rows: - render_table(doc, table_rows, language=language) + if table_rows: + render_table(doc, table_rows, language) -def render_table(doc, rows, language="english"): - if not rows: - return - num_cols = max(len(row) for row in rows) - table = doc.add_table(rows=len(rows), cols=num_cols) - table.alignment = WD_TABLE_ALIGNMENT.CENTER - - for row_idx, row in enumerate(rows): - for col_idx, cell_value in enumerate(row): - if col_idx < num_cols: - cell = table.cell(row_idx, col_idx) - cell.text = "" - p = cell.paragraphs[0] - p.paragraph_format.space_before = Pt(5) - p.paragraph_format.space_after = Pt(5) - p.paragraph_format.line_spacing = 1.2 - process_inline_formatting(p, cell_value, language=language) - - if row_idx == 0: - set_cell_background(cell, COLOR_TABLE_HEADER) - for run in p.runs: - run.font.bold = True - run.font.color.rgb = RGBColor(255, 255, 255) - else: - if row_idx % 2 == 1: - set_cell_background(cell, COLOR_ALT_ROW) - set_cell_margins(cell, top=100, bottom=100, left=140, right=140) - doc.add_paragraph().paragraph_format.space_after = Pt(8) - - -def build_front_cover(doc, title, domain, author, language="english"): - table = doc.add_table(rows=1, cols=1) - table.alignment = WD_TABLE_ALIGNMENT.CENTER - table.autofit = False - font_name = get_font_name(language=language) - - cell = table.cell(0, 0) - cell.width = Inches(6.0) - set_cell_background(cell, COLOR_COVER_BG) - set_cell_margins(cell, top=600, bottom=600, left=350, right=350) - - p_title = cell.paragraphs[0] - p_title.alignment = WD_ALIGN_PARAGRAPH.CENTER - p_title.paragraph_format.space_before = Pt(50) - p_title.paragraph_format.space_after = Pt(18) - r_title = p_title.add_run(title) - r_title.font.name = font_name - r_title.font.size = Pt(28) - r_title.bold = True - r_title.font.color.rgb = RGBColor(255, 255, 255) - - p_sub = cell.add_paragraph() - p_sub.alignment = WD_ALIGN_PARAGRAPH.CENTER - p_sub.paragraph_format.space_after = Pt(50) - bestseller_label = "உலகளாவிய புகழ்பெற்ற பதிப்பு" if language in ["tamil", "ta"] else "THE INTERNATIONAL BESTSELLER" - r_sub = p_sub.add_run(bestseller_label) - r_sub.font.name = font_name - r_sub.font.size = Pt(13) - r_sub.bold = True - r_sub.font.color.rgb = COLOR_BLUE - - p_domain = cell.add_paragraph() - p_domain.alignment = WD_ALIGN_PARAGRAPH.CENTER - p_domain.paragraph_format.space_after = Pt(140) - subject_label = f"முதன்மைப் பொருள்: {domain}" if language in ["tamil", "ta"] else f"CORE SUBJECT: {domain.upper()}" - r_domain = p_domain.add_run(subject_label) - r_domain.font.name = font_name - r_domain.font.size = Pt(10) - r_domain.bold = True - r_domain.font.color.rgb = COLOR_TEAL - - p_author = cell.add_paragraph() - p_author.alignment = WD_ALIGN_PARAGRAPH.CENTER - p_author.paragraph_format.space_after = Pt(40) - - author_header = "ஆசிரியர்\n" if language in ["tamil", "ta"] else "AUTHOR\n" - r_by = p_author.add_run(author_header) - r_by.font.name = font_name - r_by.font.size = Pt(10) - r_by.font.color.rgb = RGBColor(148, 163, 184) - - r_author = p_author.add_run(author) - r_author.font.name = font_name - r_author.font.size = Pt(22) - r_author.bold = True - r_author.font.color.rgb = COLOR_GOLD - - doc.add_page_break() - - -def build_half_title_page(doc, title, language="english"): - font_name = get_font_name(language=language) - p_ht = doc.add_paragraph() - p_ht.alignment = WD_ALIGN_PARAGRAPH.CENTER - p_ht.paragraph_format.space_before = Pt(200) - r_ht = p_ht.add_run(title) - r_ht.font.name = font_name - r_ht.font.size = Pt(22) - r_ht.bold = True - r_ht.font.color.rgb = COLOR_NAVY - doc.add_page_break() - - -def build_title_and_copyright_page(doc, title, author, language="english"): - font_name = get_font_name(language=language) - p_t = doc.add_paragraph() - p_t.paragraph_format.space_before = Pt(50) - p_t.paragraph_format.space_after = Pt(14) - r_t = p_t.add_run(title) - r_t.font.name = font_name - r_t.font.size = Pt(24) - r_t.bold = True - r_t.font.color.rgb = COLOR_NAVY - - p_a = doc.add_paragraph() - p_a.paragraph_format.space_after = Pt(220) - by_author = f"எழுதியவர் {author}" if language in ["tamil", "ta"] else f"By {author}" - r_a = p_a.add_run(by_author) - r_a.font.name = font_name - r_a.font.size = Pt(14) - r_a.bold = True - r_a.font.color.rgb = COLOR_BLUE - - p_c = doc.add_paragraph() - p_c.paragraph_format.space_before = Pt(120) - p_c.paragraph_format.line_spacing = 1.2 - copy_label = f"{title}\nகாப்புரிமை © 2026 - {author}. அனைத்து உரிமைகளும் பாதுகாக்கப்பட்டவை." if language in ["tamil", "ta"] else f"{title}\nCopyright © 2026 by {author}. All rights reserved." - r_c = p_c.add_run(copy_label) - r_c.font.name = font_name - r_c.font.size = Pt(9.5) - r_c.font.color.rgb = COLOR_DARK_GRAY - +def centered(doc, text, size=None, bold=False, before=0, after=0): + p = doc.add_paragraph() + p.alignment = WD_ALIGN_PARAGRAPH.CENTER + p.paragraph_format.space_before = Pt(before) + p.paragraph_format.space_after = Pt(after) + run = p.add_run(text) + run.bold = bold + if size: + run.font.size = Pt(size) + return p + + +def build_title_page(doc, title, author, metadata): + centered(doc, title, size=26, bold=True, before=130, after=8) + if metadata.get("subtitle"): + centered(doc, metadata["subtitle"], size=13, after=8) + centered(doc, author, size=14, before=30) + if metadata.get("publisher"): + centered(doc, metadata["publisher"], size=10, before=170) doc.add_page_break() -def build_toc(doc, chapters_dir, language="english"): - font_name = get_font_name(language=language) - toc_p = doc.add_paragraph() - toc_p.paragraph_format.space_before = Pt(24) - toc_p.paragraph_format.space_after = Pt(16) - toc_title = "பொருளடக்கம்" if language in ["tamil", "ta"] else "Table of Contents" - run_toc = toc_p.add_run(toc_title) - run_toc.font.name = font_name - run_toc.font.size = Pt(22) - run_toc.bold = True - run_toc.font.color.rgb = COLOR_NAVY - - toc_entries = [] - page_counter = 1 - seen_parts = set() - - # Dynamically scan chapter files - for i in range(1, 13): - chap_file = os.path.join(chapters_dir, f"chapter_{i:02d}.md") - if os.path.exists(chap_file): - with open(chap_file, "r", encoding="utf-8") as f: - lines = f.readlines() - part_title = "" - chap_title = "" - for line in lines: - line_str = line.strip() - if line_str.startswith("# Part") or line_str.startswith("# பகுதி"): - part_title = line_str.replace("#", "").strip() - elif line_str.startswith("## Chapter") or line_str.startswith("## அத்தியாயம்"): - chap_title = line_str.replace("##", "").strip() - - if part_title and part_title not in seen_parts: - seen_parts.add(part_title) - toc_entries.append((part_title, True, str(page_counter))) - page_counter += 2 - - if chap_title: - toc_entries.append((chap_title, False, str(page_counter))) - page_counter += 24 - else: - default_chap = f"அத்தியாயம் {i}" if language in ["tamil", "ta"] else f"Chapter {i}" - toc_entries.append((default_chap, False, str(page_counter))) - page_counter += 24 - - # Appendices and Glossary - if language in ["tamil", "ta"]: - toc_entries.append(("இணைப்புகள் & கலைச்சொற்கள்", True, str(page_counter))) - toc_entries.append(("இணைப்பு A: விரிவான குறிப்பேடு", False, str(page_counter + 2))) - toc_entries.append(("இணைப்பு B: ஆழ்ந்த ஆய்வுகள் & வழிகாட்டி", False, str(page_counter + 10))) - toc_entries.append(("இணைப்பு C: முக்கிய சட்டகங்கள் & வளங்கள்", False, str(page_counter + 18))) - toc_entries.append(("முக்கியக் கருத்துகள் & கலைச்சொல் வழிகாட்டி", False, str(page_counter + 24))) - toc_entries.append(("சொற்களின் அகராதி", False, str(page_counter + 28))) +def copyright_lines(title, author, language, metadata): + year = metadata.get("year") or datetime.now().year + lines = [] + if _is_tamil(language): + lines.append(f"காப்புரிமை © {year} {author}. அனைத்து உரிமைகளும் பாதுகாக்கப்பட்டவை.") + if metadata.get("is_fiction"): + lines.append("இது ஒரு கற்பனைப் படைப்பு. பெயர்கள், பாத்திரங்கள், நிகழ்வுகள் அனைத்தும் கற்பனையே.") else: - toc_entries.append(("Appendices & Glossary", True, str(page_counter))) - toc_entries.append(("Appendix A: Comprehensive Reference Guide", False, str(page_counter + 2))) - toc_entries.append(("Appendix B: Deep Case Studies & Structural Playbooks", False, str(page_counter + 10))) - toc_entries.append(("Appendix C: Executive Framework Checklists & Resources", False, str(page_counter + 18))) - toc_entries.append(("Key Concepts & Terminology Guide", False, str(page_counter + 24))) - toc_entries.append(("Index of Concepts & Terms", False, str(page_counter + 28))) - - for title_text, is_part, page_num in toc_entries: + lines.append(f"Copyright © {year} {author}. All rights reserved.") + lines.append("No part of this book may be reproduced without written permission from the copyright holder, except for brief quotations in reviews.") + if metadata.get("is_fiction"): + lines.append("This is a work of fiction. Names, characters, places and events are products of the author's imagination or are used fictitiously. Any resemblance to actual persons or events is coincidental.") + if metadata.get("isbn"): + lines.append(f"ISBN: {metadata['isbn']}") + if metadata.get("publisher"): + lines.append(metadata["publisher"]) + return lines + + +def build_copyright_page(doc, title, author, language, metadata): + for index, line in enumerate(copyright_lines(title, author, language, metadata)): p = doc.add_paragraph() - p.paragraph_format.space_before = Pt(8 if is_part else 3) - p.paragraph_format.space_after = Pt(3) - if is_part: - run = p.add_run(title_text) - run.font.name = font_name - run.font.size = Pt(11.5) - run.bold = True - run.font.color.rgb = COLOR_BLUE - else: - p.paragraph_format.left_indent = Inches(0.25) - dots = " . " * max(1, int((55 - len(title_text)) / 2)) - run = p.add_run(f"{title_text} {dots} {page_num}") - run.font.name = font_name - run.font.size = Pt(10) - run.font.color.rgb = COLOR_DARK_GRAY - + p.paragraph_format.space_before = Pt(280 if index == 0 else 0) + p.paragraph_format.space_after = Pt(6) + p.add_run(line).font.size = Pt(8.5) doc.add_page_break() -def build_index_page(doc, chapters_dir, language="english"): - font_name = get_font_name(language=language) - p_idx = doc.add_paragraph() - p_idx.paragraph_format.space_before = Pt(24) - p_idx.paragraph_format.space_after = Pt(14) - idx_title = "சொற்கள் மற்றும் கருத்துகளின் அகராதி" if language in ["tamil", "ta"] else "Index of Concepts & Terms" - run_idx = p_idx.add_run(idx_title) - run_idx.font.name = font_name - run_idx.font.size = Pt(22) - run_idx.bold = True - run_idx.font.color.rgb = COLOR_NAVY - - # Dynamically extract key terms from compiled markdown files - words = set() - for fname in os.listdir(chapters_dir): - if fname.endswith(".md"): - with open(os.path.join(chapters_dir, fname), "r", encoding="utf-8") as f: - content = f.read() - found = re.findall(r'\*\*([^\*\n]{2,30})\*\*', content) - for item in found: - words.add(item.strip()) - - if not words: - if language in ["tamil", "ta"]: - words = {"அரசியல் தந்திரம்", "காவியக் கதை", "வீரம்", "நீதிநெறி", "அரசாட்சி", "போர் உத்தி", "வாழ்க்கை தத்துவம்", "அறநெறி"} - else: - words = {"Action Frameworks", "Boundary Setting", "Core Principles", "Digital Transformation", "Emotional Alignment", "Leadership Models", "Paradigm Shift", "Resilience Vectors", "System Execution"} - - grouped = {} - for word in sorted(words): - letter = word[0].upper() - grouped.setdefault(letter, []).append(f"{word}, 15-280") - - for letter, items in sorted(grouped.items())[:12]: - p_letter = doc.add_paragraph() - p_letter.paragraph_format.space_before = Pt(10) - p_letter.paragraph_format.space_after = Pt(3) - r_l = p_letter.add_run(letter) - r_l.font.name = font_name - r_l.font.size = Pt(14) - r_l.bold = True - r_l.font.color.rgb = COLOR_BLUE - - for item in items[:5]: - p_item = doc.add_paragraph() - p_item.paragraph_format.left_indent = Inches(0.25) - p_item.paragraph_format.space_before = Pt(2) - p_item.paragraph_format.space_after = Pt(2) - r_i = p_item.add_run(item) - r_i.font.name = font_name - r_i.font.size = Pt(10) - r_i.font.color.rgb = COLOR_DARK_GRAY - - doc.add_page_break() - - -def build_back_cover(doc, title, author, language="english"): - table = doc.add_table(rows=1, cols=1) - table.alignment = WD_TABLE_ALIGNMENT.CENTER - table.autofit = False - font_name = get_font_name(language=language) - - cell = table.cell(0, 0) - cell.width = Inches(6.0) - set_cell_background(cell, COLOR_COVER_BG) - set_cell_margins(cell, top=500, bottom=500, left=350, right=350) - - p_head = cell.paragraphs[0] - p_head.alignment = WD_ALIGN_PARAGRAPH.CENTER - p_head.paragraph_format.space_before = Pt(30) - p_head.paragraph_format.space_after = Pt(18) - head_label = "உலகளாவிய புகழ்பெற்ற பதிப்பு" if language in ["tamil", "ta"] else "THE INTERNATIONAL BESTSELLER" - r_head = p_head.add_run(head_label) - r_head.font.name = font_name - r_head.font.size = Pt(16) - r_head.bold = True - r_head.font.color.rgb = COLOR_GOLD - - p_desc = cell.add_paragraph() - p_desc.paragraph_format.line_spacing = 1.25 - p_desc.paragraph_format.space_after = Pt(30) - if language in ["tamil", "ta"]: - desc_text = f"இந்த 300 பக்க காவியப் படைப்பு '{title}' தலைப்பில் ஒப்பற்ற உலகளாவிய படைப்பாகும். ஆழமான சிந்தனை, சுவையான கதைக்கூறல் மற்றும் உயர் தத்துவங்கள் அடங்கிய காவிய நூல்." - else: - desc_text = ( - f"This 300-page masterpiece delivers an unmissable blueprint for mastering {title}. " - f"Loved by readers worldwide, this book combines gripping storytelling, deep strategic insights, " - f"and actionable frameworks designed to inspire, transform, and empower." - ) - r_desc = p_desc.add_run(desc_text) - r_desc.font.name = font_name - r_desc.font.size = Pt(10.5) - r_desc.font.color.rgb = RGBColor(241, 245, 249) - - p_bio_title = cell.add_paragraph() - p_bio_title.paragraph_format.space_before = Pt(10) - p_bio_title.paragraph_format.space_after = Pt(4) - bio_title = "ஆசிரியர் பற்றி" if language in ["tamil", "ta"] else "ABOUT THE AUTHOR" - r_bio_title = p_bio_title.add_run(bio_title) - r_bio_title.font.name = font_name - r_bio_title.font.size = Pt(12) - r_bio_title.bold = True - r_bio_title.font.color.rgb = COLOR_BLUE - - p_bio = cell.add_paragraph() - p_bio.paragraph_format.line_spacing = 1.2 - p_bio.paragraph_format.space_after = Pt(40) - if language in ["tamil", "ta"]: - bio_text = f"{author} உலகப் புகழ்பெற்ற எழுத்தாளர் மற்றும் சிந்தனையாளர். ஆழமானக் கருத்துகளை எளிய தமிழ் நடையில் படைக்கும் வல்லமை படைத்தவர்." - else: - bio_text = ( - f"{author} is an Author and Global Thought Leader whose works inspire readers worldwide. " - f"Renowned for turning complex topics into captivating, clear, and actionable reads." - ) - r_bio = p_bio.add_run(bio_text) - r_bio.font.name = font_name - r_bio.font.size = Pt(10) - r_bio.font.color.rgb = RGBColor(203, 213, 225) - - p_footer = cell.add_paragraph() - p_footer.alignment = WD_ALIGN_PARAGRAPH.CENTER - footer_text = "வகை: தமிழ் இலக்கியம் / காவியம் / சிறப்புப் பதிப்பு\nவிலை: ₹499 INR" if language in ["tamil", "ta"] else "CATEGORY: NON-FICTION / BESTSELLER / SYSTEM DESIGN\nPRICE: $69.99 US / $89.99 CAN" - r_foot = p_footer.add_run(footer_text) - r_foot.font.name = font_name - r_foot.font.size = Pt(9) - r_foot.font.color.rgb = RGBColor(148, 163, 184) - - -def compile_book(title: str, domain: str, author: str, chapters_dir: str, output_path: str, language: str = "english"): +def insert_setting(doc, element, before): + """Word rejects settings.xml children that are out of schema order.""" + settings = doc.settings.element + for child in settings: + if child.tag in {qn(name) for name in before}: + child.addprevious(element) + return + settings.append(element) + + +def chapter_files(chapters_dir): + return sorted(glob.glob(os.path.join(chapters_dir, "chapter_*.md"))) + + +def build_toc(doc, chapters_dir, language): + doc.add_heading("பொருளடக்கம்" if _is_tamil(language) else "Contents", level=2) + # Exclude this page's own heading from the field by applying it as a plain paragraph style + doc.paragraphs[-1].style = doc.styles['Normal'] + title_run = doc.paragraphs[-1].runs[0] + title_run.bold = True + title_run.font.size = Pt(16) + doc.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER + doc.paragraphs[-1].paragraph_format.space_after = Pt(20) + + entries = [] + for path in chapter_files(chapters_dir): + with open(path, encoding='utf-8') as f: + entries += [m.group(1) for m in re.finditer(r'^#{1,2}\s+(.*)$', f.read(), re.MULTILINE)] + + # Word refreshes this field (and adds page numbers) on open; other readers show the cached list + p = doc.add_paragraph() + add_field(p, 'TOC \\o "1-2" \\h \\z \\u', cached_text=entries[0] if entries else "") + for entry in entries[1:]: + doc.add_paragraph(entry) + update = OxmlElement('w:updateFields') + update.set(qn('w:val'), 'true') + insert_setting(doc, update, before=('w:hdrShapeDefaults', 'w:footnotePr', 'w:endnotePr', 'w:compat', 'w:docVars', 'w:rsids', 'w:themeFontLang', 'w:clrSchemeMapping', 'w:shapeDefaults', 'w:decimalSymbol', 'w:listSeparator')) + + +def configure_running_heads(section, title, author): + section.different_first_page_header_footer = True + section.header.is_linked_to_previous = False + section.footer.is_linked_to_previous = False + section.even_page_header.is_linked_to_previous = False + section.even_page_footer.is_linked_to_previous = False + + for container, align, text in [ + (section.header, WD_ALIGN_PARAGRAPH.RIGHT, title), + (section.even_page_header, WD_ALIGN_PARAGRAPH.LEFT, author), + ]: + p = container.paragraphs[0] + p.alignment = align + p.add_run(text).font.size = Pt(8.5) + + for container, align in [ + (section.footer, WD_ALIGN_PARAGRAPH.RIGHT), + (section.even_page_footer, WD_ALIGN_PARAGRAPH.LEFT), + (section.first_page_footer, WD_ALIGN_PARAGRAPH.CENTER), + ]: + p = container.paragraphs[0] + p.alignment = align + add_field(p, 'PAGE', '1') + for run in p.runs: + run.font.size = Pt(9) + + + +def restart_page_numbers(section): + """Page 1 is the first body page; later sections continue the count.""" + pg_num = OxmlElement('w:pgNumType') + pg_num.set(qn('w:start'), '1') + margins = section._sectPr.find(qn('w:pgMar')) + margins.addnext(pg_num) + + +def compile_book(title: str, domain: str, author: str, chapters_dir: str, output_path: str, language: str = "english", metadata: dict = None): + metadata = metadata or {} doc = docx.Document() - font_name = get_font_name(language=language) - - for section in doc.sections: - section.top_margin = Inches(1.25) - section.bottom_margin = Inches(1.25) - section.left_margin = Inches(1.25) - section.right_margin = Inches(1.25) - - # 1. Front Cover - build_front_cover(doc, title, domain, author, language=language) - - # 2. Half Title Page - build_half_title_page(doc, title, language=language) + configure_styles(doc, language) + doc.settings.odd_and_even_pages_header_footer = True + insert_setting(doc, OxmlElement('w:mirrorMargins'), before=( + 'w:alignBordersAndEdges', 'w:bordersDoNotSurroundHeader', 'w:bordersDoNotSurroundFooter', 'w:gutterAtTop', + 'w:hideSpellingErrors', 'w:hideGrammaticalErrors', 'w:activeWritingStyle', 'w:proofState', 'w:formsDesign', + 'w:attachedTemplate', 'w:linkStyles', 'w:stylePaneFormatFilter', 'w:stylePaneSortMethod', 'w:documentType', + 'w:mailMerge', 'w:revisionView', 'w:trackRevisions', 'w:defaultTabStop', 'w:autoHyphenation', 'w:evenAndOddHeaders', + 'w:characterSpacingControl', 'w:compat', 'w:rsids' + )) + configure_page(doc.sections[0]) + + build_title_page(doc, title, author, metadata) + build_copyright_page(doc, title, author, language, metadata) + + if metadata.get("dedication"): + centered(doc, metadata["dedication"], before=150) + doc.add_page_break() - # 3. Praise Page + # Praise appears only if the author placed real, permissioned quotes in praise.md praise_path = os.path.join(chapters_dir, "praise.md") if os.path.exists(praise_path): parse_markdown_file(doc, praise_path, language=language) doc.add_page_break() - # 4. Title & Copyright Page - build_title_and_copyright_page(doc, title, author, language=language) - - # 5. Epigraph Page - epigraph_path = os.path.join(chapters_dir, "epigraph.md") - if os.path.exists(epigraph_path): - parse_markdown_file(doc, epigraph_path, language=language) - doc.add_page_break() - - # 6. Preface Page - preface_path = os.path.join(chapters_dir, "preface.md") - if os.path.exists(preface_path): - parse_markdown_file(doc, preface_path, language=language) - doc.add_page_break() - - # 7. Foreword Page - foreword_path = os.path.join(chapters_dir, "foreword.md") - if os.path.exists(foreword_path): - parse_markdown_file(doc, foreword_path, language=language) - doc.add_page_break() - - # 8. Table of Contents - build_toc(doc, chapters_dir, language=language) - - # 9. Header & Footer - body_section = doc.sections[0] - header = body_section.header - hp = header.paragraphs[0] - hp.alignment = WD_ALIGN_PARAGRAPH.RIGHT - hrun = hp.add_run(f"{title} | {author}") - hrun.font.name = font_name - hrun.font.size = Pt(8.5) - hrun.font.color.rgb = COLOR_DARK_GRAY - - footer = body_section.footer - fp = footer.paragraphs[0] - fp.alignment = WD_ALIGN_PARAGRAPH.RIGHT - frun = fp.add_run(title) - frun.font.name = font_name - frun.font.size = Pt(8.5) - frun.font.color.rgb = COLOR_DARK_GRAY - - # 10. Process Chapters 1 through 12 - for i in range(1, 13): - chap_filename = f"chapter_{i:02d}.md" - chap_path = os.path.join(chapters_dir, chap_filename) - - if os.path.exists(chap_path): - print(f"Compiling {chap_filename}...") - parse_markdown_file(doc, chap_path, language=language) - doc.add_page_break() - - # 11. Process Appendices - appendices = ["appendix_a.md", "appendix_b.md", "appendix_c.md"] - for idx, app_file in enumerate(appendices): - app_path = os.path.join(chapters_dir, app_file) - if os.path.exists(app_path): - print(f"Compiling {app_file}...") - parse_markdown_file(doc, app_path, language=language) - doc.add_page_break() - - # 12. Technical Glossary - glossary_path = os.path.join(chapters_dir, "glossary.md") - if os.path.exists(glossary_path): - print("Compiling Glossary...") - parse_markdown_file(doc, glossary_path, language=language) - doc.add_page_break() - - # 13. Index - build_index_page(doc, chapters_dir, language=language) - - # 14. Back Cover - build_back_cover(doc, title, author, language=language) - + build_toc(doc, chapters_dir, language) + + files = chapter_files(chapters_dir) + for index, chap_path in enumerate(files): + print(f"Compiling {os.path.basename(chap_path)}...") + parse_markdown_file(doc, chap_path, language=language, new_sections=True) + if index == 0 and len(doc.sections) > 1: + configure_running_heads(doc.sections[1], title, author) + # Set only now: add_section clones the previous section, which would restart numbering at every chapter + if len(doc.sections) > 1: + restart_page_numbers(doc.sections[1]) + + if metadata.get("author_bio"): + start_body_section(doc) + doc.add_heading("ஆசிரியர் பற்றி" if _is_tamil(language) else "About the Author", level=2) + p = doc.add_paragraph(metadata["author_bio"]) + p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY + + os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True) doc.save(output_path) print(f"\nSuccessfully compiled manuscript to: {output_path}") @@ -768,4 +460,3 @@ def compile_book_to_docx(book_data, output_path: str, language: str = "english") ) else: raise ValueError(f"Unsupported book_data format: {type(book_data)}") - diff --git a/generator/editor.py b/generator/editor.py deleted file mode 100644 index 9a509f0..0000000 --- a/generator/editor.py +++ /dev/null @@ -1,37 +0,0 @@ -""" -Multi-Agent Editorial Engine Module -Applies Developmental Editing, Line Editing, Fact Checking, and Prose Polishing passes -to elevate any generated manuscript into a world-class bestseller. -""" - -import re -from .llm_client import LlmClient - -class DevelopmentalEditor: - """Refines narrative structure, flow, clarity, and thematic depth.""" - - def __init__(self, llm_client: LlmClient): - self.llm = llm_client - - def edit_chapter(self, chapter_title: str, raw_markdown: str, genre: str) -> str: - system_prompt = f""" -You are an elite Senior Developmental Editor at a top-tier publishing house (Penguin Random House / O'Reilly / HarperCollins). -Your job is to polish, refine, and elevate the provided draft chapter titled '{chapter_title}'. - -Genre: {genre}. - -Editorial Rules: -1. Preserve all markdown section headings (##, ###), code blocks (```), tables (|), and blockquotes (>). -2. Enhance prose quality: eliminate repetitive phrasing, sharpen metaphors, add vivid transitions, and strengthen narrative hooks. -3. Ensure every sub-section ends with a strong takeaway or smooth transition into the next sub-section. -4. Add 1-2 impactful quote blockquotes (> "Quote") if missing. -5. Return ONLY the polished Markdown text. -""" - user_prompt = f"Please perform a complete Developmental Edit on this draft chapter:\n\n{raw_markdown}" - - try: - edited_text = self.llm.generate_text(user_prompt, system_prompt) - return edited_text if edited_text and len(edited_text) > 200 else raw_markdown - except Exception as e: - print(f" [Editor Warning] Developmental edit pass skipped (fallback to raw draft): {e}") - return raw_markdown diff --git a/generator/json_parser.py b/generator/json_parser.py index 5d7187c..8740d08 100644 --- a/generator/json_parser.py +++ b/generator/json_parser.py @@ -6,7 +6,7 @@ import json import re -from typing import Any, Optional, Type +from typing import Any, Callable, Optional, Type from pydantic import BaseModel @@ -18,6 +18,7 @@ def clean_json_string(text: str) -> str: # 1. Strip reasoning blocks text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL) text = re.sub(r'<thought>.*?</thought>', '', text, flags=re.DOTALL) + text = re.sub(r'^.*?</think>', '', text, flags=re.DOTALL) # 2. Extract markdown code block if present if "```json" in text: @@ -41,13 +42,24 @@ def clean_json_string(text: str) -> str: elif arr_match: candidate = arr_match.group(1).strip() - # 4. Remove trailing commas before closing braces/brackets - candidate = re.sub(r',\s*([\]\}])', r'\1', candidate) + return candidate - # 5. Replace smart quotes with standard double quotes - candidate = candidate.replace('“', '"').replace('”', '"').replace('’', "'").replace('‘', "'") - return candidate +def _load_json(candidate: str) -> Any: + """Parses strictly first so valid strings containing smart quotes or commas stay untouched.""" + try: + return json.loads(candidate) + except json.JSONDecodeError: + pass + # Remove trailing commas before closing braces/brackets + repaired = re.sub(r',\s*([\]\}])', r'\1', candidate) + try: + return json.loads(repaired) + except json.JSONDecodeError: + pass + # Last resort: model used smart quotes as JSON delimiters + repaired = repaired.replace('“', '"').replace('”', '"').replace('’', "'").replace('‘', "'") + return json.loads(repaired) def parse_llm_json(text: str, model_class: Optional[Type[BaseModel]] = None) -> Optional[Any]: @@ -65,17 +77,14 @@ def parse_llm_json(text: str, model_class: Optional[Type[BaseModel]] = None) -> data = None try: - data = json.loads(cleaned) + data = _load_json(cleaned) except json.JSONDecodeError: # Secondary repair attempt: strip leading/trailing garbage try: - # Try finding substring between first { and last } first_brace = cleaned.find('{') last_brace = cleaned.rfind('}') if first_brace != -1 and last_brace != -1 and last_brace > first_brace: - sub = cleaned[first_brace:last_brace + 1] - sub = re.sub(r',\s*([\]\}])', r'\1', sub) - data = json.loads(sub) + data = _load_json(cleaned[first_brace:last_brace + 1]) except Exception: return None @@ -89,3 +98,35 @@ def parse_llm_json(text: str, model_class: Optional[Type[BaseModel]] = None) -> return None return data + + +class StructuredOutputError(RuntimeError): + """The model never produced output that satisfied the requested schema.""" + + +def generate_validated( + llm, + prompt: str, + system_prompt: str, + model_class: Type[BaseModel], + validator: Optional[Callable[[Any], Optional[str]]] = None, + max_tokens: int = 4096, + attempts: int = 3, +) -> Any: + """ + Requests JSON, validating it and feeding each failure back to the model. + validator returns a problem description, or None when the object is acceptable. + Raises StructuredOutputError instead of inventing content. + """ + problem = "" + for _ in range(attempts): + correction = f"\n\nYOUR PREVIOUS RESPONSE WAS REJECTED: {problem}\nReturn ONLY corrected raw JSON." if problem else "" + text = llm.generate_text(prompt + correction, system_prompt=system_prompt, max_tokens=max_tokens) + parsed = parse_llm_json(text, model_class=model_class) if isinstance(text, str) else None + if parsed is None: + problem = "It was not valid JSON matching the requested schema." + continue + problem = validator(parsed) if validator else None + if not problem: + return parsed + raise StructuredOutputError(f"{model_class.__name__} rejected after {attempts} attempts: {problem}") diff --git a/generator/llm_client.py b/generator/llm_client.py index a6be085..9d62119 100644 --- a/generator/llm_client.py +++ b/generator/llm_client.py @@ -7,9 +7,16 @@ import os import json import re +import time import urllib.request import urllib.error +RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504, 529} +MAX_ATTEMPTS = 5 +REQUEST_TIMEOUT = 600 +META_PREAMBLE = re.compile(r"^(okay|ok|sure|certainly|of course|here is|here's|below is|as an ai)\b", re.IGNORECASE) +META_SUBJECT = re.compile(r"\b(chapter|scene|draft|manuscript|prose|revis|rewrit|json|beat|section)", re.IGNORECASE) + class LlmClient: def __init__( @@ -38,6 +45,7 @@ def __init__( self.api_key = os.getenv("LLM_API_KEY") or os.getenv("OPENAI_API_KEY") or os.getenv("GEMINI_API_KEY") or os.getenv("ANTHROPIC_API_KEY") self.ollama_url = (ollama_url or "http://localhost:11434").rstrip("/") + self._truncated = False if self.provider == "ollama": self.model = self._resolve_ollama_model(model or os.getenv("OLLAMA_MODEL")) @@ -45,6 +53,8 @@ def __init__( self.model = model or "jev-system1" elif self.provider == "gemini": self.model = model or os.getenv("GEMINI_MODEL", "gemini-3.5-flash-lite") + elif self.provider == "anthropic": + self.model = model or "claude-opus-5-5" else: self.model = model or "gpt-4o" @@ -72,6 +82,19 @@ def _resolve_ollama_model(self, user_model: str = None) -> str: return target def generate_text(self, prompt: str, system_prompt: str = "", max_tokens: int = 4096) -> str: + """Generates text; a reply cut off at the token limit is retried once with double the room.""" + text = self._dispatch(prompt, system_prompt, max_tokens) + if self._truncated: + print(f" [LLM Retry] Response hit the {max_tokens}-token limit. Retrying with {max_tokens * 2}...") + text = self._dispatch(prompt, system_prompt, max_tokens * 2) + if self._truncated: + print(" [LLM Warning] Response is still cut off at the token limit.") + if not text: + raise RuntimeError(f"{self.provider} returned no text for model '{self.model}'.") + return text + + def _dispatch(self, prompt: str, system_prompt: str, max_tokens: int) -> str: + self._truncated = False if self.provider == "ollama": return self._call_ollama(prompt, system_prompt, max_tokens) elif self.provider in ["jev", "typesafe"]: @@ -87,26 +110,38 @@ def generate_text(self, prompt: str, system_prompt: str = "", max_tokens: int = def _call_jev(self, prompt: str, system_prompt: str, max_tokens: int) -> str: """TypeSafe AI Jev System-One Model API Client (70ms Parallel Decision Sampling).""" - url = "https://api.typesafe.ai/v1/predict" - headers = { - "Authorization": f"Bearer {self.api_key or 'jev_early_access_key'}", - "Content-Type": "application/json" - } + if not self.api_key: + raise ValueError("JEV_API_KEY environment variable is missing.") payload = { "model": "jev-system1", "state": (system_prompt + "\n\n" + prompt).strip(), "questions": ["decision", "classification", "output"] } - req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers) - try: - with urllib.request.urlopen(req, timeout=10) as response: - res_data = json.loads(response.read().decode("utf-8")) - decisions = res_data.get("decisions", {}) - return json.dumps(decisions, ensure_ascii=False) - except Exception as e: - # Fallback for Jev when running local structured extraction - return f"{{\"status\": \"evaluated\", \"model\": \"jev-system1\", \"note\": \"{e}\"}}" + headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"} + res_data = self._post_json("https://api.typesafe.ai/v1/predict", payload, headers) + return json.dumps(res_data.get("decisions", {}), ensure_ascii=False) + def _post_json(self, url: str, payload: dict, headers: dict) -> dict: + """POST with exponential backoff on rate limits, server errors and dropped connections.""" + body = json.dumps(payload).encode("utf-8") + last_error = None + for attempt in range(MAX_ATTEMPTS): + if attempt: + delay = min(2 ** attempt, 60) + print(f" [LLM Retry] {last_error}. Attempt {attempt + 1}/{MAX_ATTEMPTS} in {delay}s...") + time.sleep(delay) + req = urllib.request.Request(url, data=body, headers=headers) + try: + with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as response: + return json.loads(response.read().decode("utf-8")) + except urllib.error.HTTPError as e: + detail = e.read().decode("utf-8", errors="replace")[:500] + last_error = f"HTTP {e.code} from {self.provider}: {detail}" + if e.code not in RETRYABLE_STATUS: + break + except (urllib.error.URLError, TimeoutError, ConnectionError, json.JSONDecodeError) as e: + last_error = f"{self.provider} request failed: {e}" + raise RuntimeError(f"LLM call failed for model '{self.model}': {last_error}") def _call_ollama(self, prompt: str, system_prompt: str, max_tokens: int) -> str: url = f"{self.ollama_url}/api/chat" @@ -130,18 +165,15 @@ def _call_ollama(self, prompt: str, system_prompt: str, max_tokens: int) -> str: } - req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers) try: - # 600s timeout prevents killing DeepSeek-R1 during long reasoning chains - with urllib.request.urlopen(req, timeout=600) as response: - res_data = json.loads(response.read().decode("utf-8")) - content = res_data.get("message", {}).get("content", "") - return self._clean_llm_output(content) - except Exception as e: + res_data = self._post_json(url, payload, headers) + except RuntimeError as e: raise RuntimeError( - f"Ollama API call failed for model '{self.model}' at {self.ollama_url}: {e}\n" - f"Please ensure Ollama is running (`ollama serve`) and model '{self.model}' is pulled (`ollama run {self.model}`)." + f"{e}\nPlease ensure Ollama is running (`ollama serve`) at {self.ollama_url} " + f"and model '{self.model}' is pulled (`ollama run {self.model}`)." ) + self._truncated = res_data.get("done_reason") == "length" + return self._require_text(res_data.get("message", {}).get("content", ""), res_data) def _call_openai(self, prompt: str, system_prompt: str, max_tokens: int) -> str: if not self.api_key: @@ -160,23 +192,27 @@ def _call_openai(self, prompt: str, system_prompt: str, max_tokens: int) -> str: "max_tokens": max_tokens, "temperature": 0.7 } - req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers) - with urllib.request.urlopen(req, timeout=120) as response: - res_data = json.loads(response.read().decode("utf-8")) - return self._clean_llm_output(res_data["choices"][0]["message"]["content"]) + res_data = self._post_json(url, payload, headers) + choices = res_data.get("choices") or [{}] + self._truncated = choices[0].get("finish_reason") == "length" + return self._require_text(choices[0].get("message", {}).get("content", ""), res_data) def _call_gemini(self, prompt: str, system_prompt: str, max_tokens: int) -> str: if not self.api_key: raise ValueError("GEMINI_API_KEY environment variable is missing.") - url = f"https://generativelanguage.googleapis.com/v1beta/models/{self.model or 'gemini-3.5-flash-lite'}:generateContent?key={self.api_key}" - headers = {"Content-Type": "application/json"} + url = f"https://generativelanguage.googleapis.com/v1beta/models/{self.model or 'gemini-3.5-flash-lite'}:generateContent" + headers = {"Content-Type": "application/json", "x-goog-api-key": self.api_key} payload = { - "contents": [{"parts": [{"text": (system_prompt + "\n\n" + prompt)}]}] + "contents": [{"parts": [{"text": prompt}]}], + "generationConfig": {"maxOutputTokens": max_tokens, "temperature": 0.7} } - req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers) - with urllib.request.urlopen(req, timeout=120) as response: - res_data = json.loads(response.read().decode("utf-8")) - return self._clean_llm_output(res_data["candidates"][0]["content"]["parts"][0]["text"]) + if system_prompt: + payload["systemInstruction"] = {"parts": [{"text": system_prompt}]} + res_data = self._post_json(url, payload, headers) + candidates = res_data.get("candidates") or [{}] + self._truncated = candidates[0].get("finishReason") == "MAX_TOKENS" + parts = candidates[0].get("content", {}).get("parts", []) + return self._require_text("".join(p.get("text", "") for p in parts if not p.get("thought")), res_data) def _call_anthropic(self, prompt: str, system_prompt: str, max_tokens: int) -> str: if not self.api_key: @@ -188,44 +224,36 @@ def _call_anthropic(self, prompt: str, system_prompt: str, max_tokens: int) -> s "Content-Type": "application/json" } payload = { - "model": self.model or "claude-3-5-sonnet-20240620", + "model": self.model, "max_tokens": max_tokens, "system": system_prompt, "messages": [{"role": "user", "content": prompt}] } - req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers) - with urllib.request.urlopen(req, timeout=120) as response: - res_data = json.loads(response.read().decode("utf-8")) - return self._clean_llm_output(res_data["content"][0]["text"]) + res_data = self._post_json(url, payload, headers) + self._truncated = res_data.get("stop_reason") == "max_tokens" + text = "".join(b.get("text", "") for b in res_data.get("content", []) if b.get("type") == "text") + return self._require_text(text, res_data) + + def _require_text(self, text: str, res_data: dict) -> str: + cleaned = self._clean_llm_output(text) + # A model can spend its whole allowance on thinking; generate_text retries that case + if not cleaned and not self._truncated: + raise RuntimeError(f"{self.provider} returned no text for model '{self.model}': {json.dumps(res_data)[:500]}") + return cleaned def _clean_llm_output(self, text: str) -> str: if not text: return "" - # 1. Strip DeepSeek R1 reasoning blocks <think>...</think> + # 1. Strip DeepSeek R1 reasoning blocks <think>...</think>, including an unopened closing tag cleaned = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL) + cleaned = re.sub(r'^.*?</think>', '', cleaned, flags=re.DOTALL).strip() - # 2. Strip conversational preambles - lines = cleaned.split('\n') - filtered_lines = [] - skip_intro = True - - for line in lines: - stripped = line.strip() - if skip_intro: - if re.match(r'^(okay|here is|i have|based on|sure|certainly|let\'s|below is|in this chapter|i will proceed|as an ai)', stripped, re.IGNORECASE): - continue - if stripped.startswith('---'): - continue - if not stripped: - continue - skip_intro = False - - # Clean prompt meta-leakage tags - line = re.sub(r'Sub-section \d+\.\d+:\s*(Execute core objective|Interaction:|Detail:)[^\n]*', '', line, flags=re.IGNORECASE) - line = re.sub(r'(Core Objective:|Interaction:|Detail:)\s*[^\n]*', '', line, flags=re.IGNORECASE) - filtered_lines.append(line) - - return "\n".join(filtered_lines).strip() + # 2. Strip one leading conversational preamble; opening lines of real prose must survive + first_line, _, rest = cleaned.partition('\n') + first = first_line.strip() + if META_PREAMBLE.match(first) and (first.endswith(':') or META_SUBJECT.search(first)): + cleaned = rest.strip() + return re.sub(r'^-{3,}\s*\n', '', cleaned).strip() # Backward compatibility alias diff --git a/generator/writer.py b/generator/writer.py deleted file mode 100644 index fd9e923..0000000 --- a/generator/writer.py +++ /dev/null @@ -1,323 +0,0 @@ -""" -Writer Engine Module - World-Class Bestseller Edition -Drafts markdown manuscript chapters, epigraphs, praise pages, preface, foreword, glossary, and appendices tailored to ANY book genre with viral engagement hooks. -""" - -import os -from .blueprint import BookBlueprint -from .llm_client import LlmClient -from .editor import DevelopmentalEditor - -class ChapterWriter: - def __init__(self, blueprint: BookBlueprint, llm_client: LlmClient, output_dir: str, enable_editor: bool = True, incremental_callback = None): - self.blueprint = blueprint - self.llm = llm_client - self.output_dir = output_dir - self.enable_editor = enable_editor - self.incremental_callback = incremental_callback - self.editor = DevelopmentalEditor(llm_client) if enable_editor else None - self.preceding_summary = "" - self.master_outline_summary = self._build_master_outline_summary() - self.character_and_setting_sheet = self._build_character_and_setting_sheet() - os.makedirs(self.output_dir, exist_ok=True) - - def _build_master_outline_summary(self) -> str: - lines = [f"BOOK TITLE: {self.blueprint.title}", f"GENRE: {self.blueprint.genre.upper()}", "MASTER OUTLINE:"] - for part in self.blueprint.parts: - lines.append(f" {part['part']}:") - for chap in part["chapters"]: - lines.append(f" - Chapter {chap['number']}: {chap['title']} ({chap['focus']})") - return "\n".join(lines) - - def _build_character_and_setting_sheet(self) -> str: - genre = self.blueprint.genre - if genre == "fiction": - return f"""CHARACTER & WORLD MATRIX: -- Protagonist: Reluctant visionary driven by core values, navigating {self.blueprint.domain}. -- Antagonist: Systemic opposing force / formidable adversary challenging the protagonist. -- Setting: Immersive, high-stakes environment centered around {self.blueprint.domain}. -- Key Motifs: Sacrifice, destiny, transformation, unyielding resolve.""" - elif genre == "business": - return f"""EXECUTIVE STRATEGY MATRIX: -- Subject: {self.blueprint.title} ({self.blueprint.domain}). -- Core Frameworks: Unit economics, competitive moats, leadership mental models, data intelligence. -- Case Studies: Fortune 500 turnarounds, unicorn scaling, operational failure post-mortems.""" - elif genre == "self-help": - return f"""TRANSFORMATION MATRIX: -- Target Mindset: From limiting beliefs to unshakeable self-mastery in {self.blueprint.domain}. -- Core Pillars: Habit design, emotional resilience, deep focus, long-term vitality.""" - else: - return f"""ARCHITECTURAL & SYSTEM MATRIX: -- Core Domain: {self.blueprint.domain}. -- Core Principles: Concurrency, scalability, resilience, zero trust governance, native tool integration. -- Target Metric: Sub-millisecond latency, zero downtime, modular extensibility.""" - - def _summarize_chapter(self, chap_num: int, chap_title: str, content: str) -> str: - prompt = f"""Provide a concise 3-bullet summary of Chapter {chap_num}: {chap_title}. -Focus on key plot shifts, major decisions, character arc developments, or technical breakthroughs that happened in this chapter. -Keep total summary under 120 words. - -Chapter Text (Excerpt): -{content[:2000]} -""" - return self.llm.generate_text(prompt, system_prompt="You are a narrative continuity editor creating rolling context summaries.") - - def generate_all_chapters(self): - generated_files = [] - - # 0. Praise & Endorsements Page - praise_file = os.path.join(self.output_dir, "praise.md") - print("Drafting Praise & Critical Acclaim Page...") - with open(praise_file, "w", encoding="utf-8") as f: - f.write(self._draft_praise()) - generated_files.append(praise_file) - - # 1. Epigraph Page - epigraph_file = os.path.join(self.output_dir, "epigraph.md") - print("Drafting Epigraph & Dedication Page...") - with open(epigraph_file, "w", encoding="utf-8") as f: - f.write(self._draft_epigraph()) - generated_files.append(epigraph_file) - - # 2. Preface - preface_file = os.path.join(self.output_dir, "preface.md") - print("Drafting Preface & Readers' Guide...") - with open(preface_file, "w", encoding="utf-8") as f: - f.write(self._draft_preface()) - generated_files.append(preface_file) - - # 3. Foreword - foreword_file = os.path.join(self.output_dir, "foreword.md") - print("Drafting Foreword...") - with open(foreword_file, "w", encoding="utf-8") as f: - f.write(self._draft_foreword()) - generated_files.append(foreword_file) - - # 4. Chapters 1-12 with Iterative Rolling Context Memory & Local Disk Persistence - for part_info in self.blueprint.parts: - part_title = part_info["part"] - for chap_info in part_info["chapters"]: - chap_num = chap_info["number"] - chap_title = chap_info["title"] - chap_focus = chap_info["focus"] - - filename = f"chapter_{chap_num:02d}.md" - filepath = os.path.join(self.output_dir, filename) - - print(f"\n[Iterative Generation] Drafting Chapter {chap_num}: {chap_title}...") - - raw_content = self._draft_chapter(part_title, chap_num, chap_title, chap_focus) - - # Apply Developmental Editor Pass if enabled - if self.enable_editor and self.editor: - print(f" [Editorial Pass] Refining prose, hooks, and pacing for Chapter {chap_num}...") - final_content = self.editor.edit_chapter(chap_title, raw_content, self.blueprint.genre) - else: - final_content = raw_content - - # Local Disk File Writer Tool Integration - with open(filepath, "w", encoding="utf-8") as f: - f.write(final_content) - print(f" ✓ [Local File Writer] Persisted {filename} directly to hard drive.") - - generated_files.append(filepath) - - # Summarize Chapter for Preceding Rolling Context Payload for Chapter N+1 - print(f" [Context Memory] Summarizing Chapter {chap_num} for rolling context window...") - self.preceding_summary = self._summarize_chapter(chap_num, chap_title, final_content) - - # Trigger Incremental Compilation Callback if provided - if self.incremental_callback: - try: - self.incremental_callback(chap_num) - except Exception as ex: - print(f" [Incremental Sync Warning] Callback failed: {ex}") - - # 5. Appendices - appendices = [ - ("appendix_a.md", f"Appendix A: Comprehensive Master Reference Guide for {self.blueprint.title}"), - ("appendix_b.md", f"Appendix B: Deep Case Studies & Structural Playbooks"), - ("appendix_c.md", f"Appendix C: Executive Framework Checklists & Resources") - ] - - for app_file, app_title in appendices: - filepath = os.path.join(self.output_dir, app_file) - print(f"Drafting {app_title}...") - content = f"# {app_title}\n\n" + self.llm.generate_text(f"Generate exhaustive reference content for {app_title} in the context of {self.blueprint.title}.") - with open(filepath, "w", encoding="utf-8") as f: - f.write(content) - generated_files.append(filepath) - - # 6. Technical Glossary - glossary_file = os.path.join(self.output_dir, "glossary.md") - print("Drafting Technical Glossary & Terminology Guide...") - with open(glossary_file, "w", encoding="utf-8") as f: - f.write(self._draft_glossary()) - generated_files.append(glossary_file) - - return generated_files - - def _draft_praise(self) -> str: - return f"""# Praise for {self.blueprint.title} - -> “A masterwork of extraordinary vision and clarity. Pravin Tamilan has written what will undoubtedly be remembered as the definitive guide on {self.blueprint.domain}. Unputdownable from page one.” -> -> — **The Global Architecture & Literary Review** - -> “Required reading for every executive, engineer, and strategic thinker. Pravin synthesizes complex concepts into an unforgettable, transformative narrative.” -> -> — **Dr. Marcus Vance**, Principal Fellow, Enterprise Systems Institute - -> “An absolute tour de force. Equal parts gripping, intellectually rigorous, and profoundly practical. This book sets a new standard for excellence.” -> -> — **Elena Rostova**, Managing Director, Global Technology Strategy -""" - - def _draft_epigraph(self) -> str: - return f"""# Epigraph & Dedication - -## Dedication -*To curious minds, leaders, and readers everywhere who dare to explore new horizons, challenge legacy paradigms, and master the art of {self.blueprint.domain}.* - ---- - -> “The difficulty lies, not in the new ideas, but in escaping from the old ones, which ramify, for those brought up as most of us have been, into every corner of our minds.” -> -> — **John Maynard Keynes** -""" - - def _draft_preface(self) -> str: - return f"""# Preface & Readers' Guide - -> “The secret to extraordinary impact is not discovering something new, but seeing what everyone else has missed.” - -## Preface -Every great story, framework, or paradigm shift begins with a single realization. **{self.blueprint.title}** was written to explore the deepest dimensions of {self.blueprint.domain}. - -Whether you are reading this as a practitioner, a strategic thinker, or an avid reader seeking an immersive narrative, this book is crafted to deliver profound insights, actionable knowledge, and lasting impact. - ---- - -## How to Read This Book -This manuscript is organized into four distinct parts designed to guide your journey: - -- **Part I: Foundations and Origins (Chapters 1–3)** -- **Part II: Deep Explorations & Core Dynamics (Chapters 4–6)** -- **Part III: Transformation, Applications & Pivotal Moments (Chapters 7–9)** -- **Part IV: Horizons, Legacy & Future Mastery (Chapters 10–12)** - ---- - -## Target Audience -Designed for readers, leaders, and thinkers seeking comprehensive mastery over {self.blueprint.domain}. -""" - - def _draft_foreword(self) -> str: - return f"""# Foreword - -> “True innovation happens at the intersection of deep mastery and unyielding curiosity.” - -**{self.blueprint.title}** represents a landmark achievement. Grounded in deep expertise and vivid storytelling, this volume establishes a definitive blueprint for understanding {self.blueprint.domain}. - -*— Executive Editorial & Review Board* -""" - - def _draft_glossary(self) -> str: - return f"""# Key Concepts & Glossary - -## Terminology Guide for {self.blueprint.title} - -### Core Catalyst -The initial event or fundamental principle that sets the primary trajectory of {self.blueprint.domain} in motion. - -### Strategic Leverage -The key mechanisms or habits that amplify impact while minimizing friction. - -### Resilience Vector -The capacity of a system, character, or organization to recover, adapt, and thrive in the face of disruption. - -### Paradigm Shift -A fundamental change in the basic concepts and experimental practices of a discipline or narrative. -""" - - def _draft_chapter(self, part_title: str, chap_num: int, chap_title: str, chap_focus: str) -> str: - genre = self.blueprint.genre - - context_payload = f"""=== MASTER BOOK OUTLINE === -{self.master_outline_summary} - -=== GLOBAL CHARACTER & CONCEPT MATRIX === -{self.character_and_setting_sheet} - -=== PRECEDING CHAPTER SUMMARY (CHAPTER {chap_num - 1}) === -{self.preceding_summary if self.preceding_summary else "This is Chapter 1 - The opening chapter."} -""" - - if genre == "fiction": - system_prompt = f"You are a #1 New York Times Bestselling Fiction Author writing an unforgettable epic novel titled '{self.blueprint.title}'. Write with gripping hooks, sensory descriptions, unforgettable character dialogue, high-stakes tension, and memorable quotes." - user_prompt = f"""{context_payload} - -=== TARGET INSTRUCTION === -Write Chapter {chap_num}: {chap_title} -Part: {part_title} -Focus: {chap_focus} - -Requirements: -1. Maintain strict continuity with the Preceding Chapter Summary above. -2. Start with an irresistible, high-stakes opening sentence hook. -3. Write 6 complete sub-sections (### {chap_num}.1, ### {chap_num}.2, ### {chap_num}.3, ### {chap_num}.4, ### {chap_num}.5, ### {chap_num}.6). -4. Include 2 viral quote blockquotes (> "Quote") that readers will share on social media. -5. Write realistic dialogue blocks between key characters. -6. Conclude with a page-turning cliffhanger. -""" - elif genre == "business": - system_prompt = f"You are a #1 Wall Street Journal Bestselling Business Author writing an unputdownable book titled '{self.blueprint.title}'." - user_prompt = f"""{context_payload} - -=== TARGET INSTRUCTION === -Write Chapter {chap_num}: {chap_title} -Part: {part_title} -Focus: {chap_focus} - -Requirements: -1. Maintain strict continuity with the Preceding Chapter Summary above. -2. Start with a captivating business question or story hook. -3. Write 6 complete sub-sections (### {chap_num}.1, ### {chap_num}.2, ### {chap_num}.3, ### {chap_num}.4, ### {chap_num}.5, ### {chap_num}.6). -4. Include 2 viral leadership quote blockquotes (> "Quote"). -5. Include corporate case studies and structured strategy tables. -""" - elif genre == "self-help": - system_prompt = f"You are a world-renowned #1 Bestselling Self-Help Author writing a life-changing book titled '{self.blueprint.title}'." - user_prompt = f"""{context_payload} - -=== TARGET INSTRUCTION === -Write Chapter {chap_num}: {chap_title} -Part: {part_title} -Focus: {chap_focus} - -Requirements: -1. Maintain strict continuity with the Preceding Chapter Summary above. -2. Start with a deeply resonant opening hook. -3. Write 6 complete sub-sections (### {chap_num}.1, ### {chap_num}.2, ### {chap_num}.3, ### {chap_num}.4, ### {chap_num}.5, ### {chap_num}.6). -4. Include 2 powerful quote blockquotes (> "Quote"). -5. Include habit design frameworks and reflection prompts. -""" - else: - system_prompt = f"You are a #1 Bestselling Author writing a masterwork titled '{self.blueprint.title}'." - user_prompt = f"""{context_payload} - -=== TARGET INSTRUCTION === -Write Chapter {chap_num}: {chap_title} -Part: {part_title} -Focus: {chap_focus} - -Requirements: -1. Maintain strict continuity with the Preceding Chapter Summary above. -2. Start with an arresting opening sentence. -3. Write 6 complete sub-sections (### {chap_num}.1, ### {chap_num}.2, ### {chap_num}.3, ### {chap_num}.4, ### {chap_num}.5, ### {chap_num}.6). -4. Include 2 viral takeaway blockquotes (> "Quote"). -5. Include detailed diagrams or data tables. -""" - - content = self.llm.generate_text(user_prompt, system_prompt) - return f"# {part_title}\n\n## Chapter {chap_num}: {chap_title}\n\n" + content diff --git a/main.py b/main.py index 30aecca..15fd1f0 100644 --- a/main.py +++ b/main.py @@ -1,297 +1,82 @@ #!/usr/bin/env python3 """ -BookGenerator AI Engine v4.0 - Multi-Agent Adversarial Pipeline -Hierarchical Multi-Agent Architecture with Context Isolation, Iterative Beat-by-Beat Drafting, -Adversarial Anti-Slop Critics, Database Reset Flag, and Local Ollama Integration. +BookGenerator AI Engine - Command Line Interface +Runs the multi-agent pipeline: brief, world, cast, outline, scene drafting, editorial revision, +whole-book release review, publishing kit and DOCX/EPUB compilation. """ import argparse import os -import sys -import glob -from pathlib import Path from generator.llm_client import LlmClient -from memory.state_manager import StateManager -from schemas.models import StoryState -from agents.world_builder import WorldBuilderAgent -from agents.character_architect import CharacterArchitectAgent -from agents.master_outliner import MasterOutlinerAgent -from agents.prose_drafter import ProseDrafterAgent -from agents.critics import MasterAdversarialReviewer -from tools.file_writer import FileWriterTool -from tools.card_manager import CardManager - - -def reset_environment(db_path: str = "memory/book_state.db", output_dir: str = "output"): - """Wipes state database and cleans output directory to prevent state corruption.""" - print(" [Environment Reset] Wiping state database and cleaning output files...") - if os.path.exists(db_path): - try: - os.remove(db_path) - print(f" ✓ Database file '{db_path}' removed.") - except Exception as e: - print(f" ⚠️ Warning removing database: {e}") - - if os.path.exists(output_dir): - for f in glob.glob(os.path.join(output_dir, "*.md")) + glob.glob(os.path.join(output_dir, "*.docx")): - try: - os.remove(f) - print(f" ✓ Output file '{os.path.basename(f)}' cleaned.") - except Exception as e: - print(f" ⚠️ Warning cleaning file '{f}': {e}") +from pipeline import BookConfig, BookPipeline, book_dir_for def main(): - parser = argparse.ArgumentParser( - description="BookGenerator AI v4.0: Production-Grade Multi-Agent Manuscript Generation Engine." - ) + parser = argparse.ArgumentParser(description="BookGenerator AI: multi-agent manuscript generation engine.") parser.add_argument("--title", "-t", required=True, help="Title of the book") - parser.add_argument("--concept", "-c", default="", help="Seed concept or prompt for the book") - parser.add_argument("--genre", "-g", default="auto", help="Genre: fiction, romance, business, self-help, technical, non-fiction, tamil_historical, tamil_kavithai, tamil_thirukkural, tamil_fiction") - parser.add_argument("--author", "-a", default="Pravin Tamilan", help="Author Name (default: 'Pravin Tamilan')") - parser.add_argument("--language", "-l", default="tamil", choices=["english", "tamil", "auto"], help="Target language: english, tamil, auto (default: 'tamil')") - parser.add_argument("--tamil", action="store_true", help="Shortcut preset flag to generate rich authentic Tamil content") - parser.add_argument("--provider", "-p", default=None, choices=["auto", "ollama", "jev", "openai", "gemini", "anthropic"], help="LLM Provider (default: auto-detected from environment)") - parser.add_argument("--model", "-m", default=None, help="Model name (e.g. gemini-3.5-flash-lite, qwen2.5:1.5b, gpt-4o)") - parser.add_argument("--chapters", "-n", type=int, default=12, help="Number of chapters to generate (default: 12)") + parser.add_argument("--concept", "-c", default="", help="Seed concept. The more specific and original, the better the book") + parser.add_argument("--genre", "-g", default="auto", help="Genre: fiction, romance, thriller, business, self-help, technical, non-fiction, tamil_historical, tamil_kavithai, tamil_thirukkural, tamil_fiction") + parser.add_argument("--author", "-a", default="Pravin Tamilan", help="Author name (default: 'Pravin Tamilan')") + parser.add_argument("--language", "-l", default="english", choices=["english", "tamil"], help="Target language (default: english)") + parser.add_argument("--tamil", action="store_true", help="Shortcut for --language tamil") + parser.add_argument("--provider", "-p", default=None, choices=["auto", "ollama", "jev", "openai", "gemini", "anthropic"], help="LLM provider (default: auto-detected from environment)") + parser.add_argument("--model", "-m", default=None, help="Model name") parser.add_argument("--ollama-url", default="http://localhost:11434", help="Ollama server URL") - parser.add_argument("--max-revisions", type=int, default=1, help="Max adversarial critic revision loops per chapter") - parser.add_argument("--output", "-o", default="Generated_Book.docx", help="Output .docx file path") - parser.add_argument("--epub", default=None, help="Output .epub file path (default: auto-named from output)") - parser.add_argument("--reset", "-r", action="store_true", help="Reset state database and output directory before run") - parser.add_argument("--resume", action="store_true", default=True, help="Resume generation skipping previously completed chapters (default: True)") - parser.add_argument("--export-cards", default=None, help="Directory to export portable character cards and lorebook JSON (MuMu style)") - parser.add_argument("--import-lorebook", default=None, help="Path to pre-existing lorebook JSON pack to import World Bible & Characters from") - + parser.add_argument("--chapters", "-n", type=int, default=24, help="Number of chapters (default: 24)") + parser.add_argument("--scenes-per-chapter", type=int, default=4, help="Scenes in each chapter (default: 4)") + parser.add_argument("--target-words", type=int, default=80000, help="Whole-book word target (default: 80000)") + parser.add_argument("--max-revisions", type=int, default=2, help="Max revision passes per chapter (default: 2)") + parser.add_argument("--opening-candidates", type=int, default=3, help="Competing drafts of the book's first scene (default: 3)") + parser.add_argument("--output", "-o", default=None, help="Output .docx path (default: inside the book's directory)") + parser.add_argument("--epub", default=None, help="Output .epub path (default: next to the .docx)") + parser.add_argument("--cover", default=None, help="Cover image (.jpg) for the EPUB") + parser.add_argument("--subtitle", default=None, help="Subtitle for the title page") + parser.add_argument("--isbn", default=None, help="Your ISBN. Omitted when not provided") + parser.add_argument("--publisher", default=None, help="Publisher or imprint name. Omitted when not provided") + parser.add_argument("--year", default=None, help="Copyright year (default: current year)") + parser.add_argument("--dedication", default=None, help="Dedication text. Omitted when not provided") + parser.add_argument("--author-bio", default=None, help="About the Author text. Omitted when not provided") + parser.add_argument("--reset", "-r", action="store_true", help="Delete this book's saved progress and start it over. Other books are untouched") + parser.add_argument("--export-cards", default=None, help="Directory to export portable character cards and lorebook JSON") + parser.add_argument("--import-lorebook", default=None, help="Lorebook JSON pack to import World Bible & Characters from") args = parser.parse_args() - concept = args.concept or args.title language = "tamil" if args.tamil else args.language - # Auto-resolve provider if not explicitly passed resolved_provider = args.provider if not resolved_provider or resolved_provider == "auto": resolved_provider = "gemini" if (os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")) else "ollama" - if args.reset: - reset_environment(db_path="memory/book_state.db", output_dir="output") - - # Initialize Clients & State Manager early to display resolved model - llm_client = LlmClient( - provider=resolved_provider, - model=args.model, - ollama_url=args.ollama_url - ) + llm_client = LlmClient(provider=resolved_provider, model=args.model, ollama_url=args.ollama_url) print("\n" + "=" * 80) - print(" BOOKGENERATOR AI v4.0 - PRODUCTION-GRADE MULTI-AGENT PIPELINE") + print(" BOOKGENERATOR AI - MULTI-AGENT PIPELINE") print("=" * 80) print(f" Title: {args.title}") print(f" Author: {args.author}") print(f" Genre: {args.genre.upper()}") - print(f" Language: {language.upper()} (தமிழ்)") + print(f" Language: {language.upper()}") print(f" Provider: {llm_client.provider.upper()}") print(f" Model: {llm_client.model}") - print(f" Chapters: {args.chapters}") - if llm_client.provider == "ollama": - print(f" Ollama URL: {args.ollama_url}") - print(f" Output File: {args.output}") - print(f" Reset Flag: {args.reset}") + print(f" Plan: {args.chapters} chapters, {args.scenes_per_chapter} scenes each, {args.target_words:,} words") + print(f" Book Folder: {book_dir_for(args.title)}") print("=" * 80 + "\n") - state_mgr = StateManager(db_path="memory/book_state.db") - file_writer = FileWriterTool(output_dir="output") - file_writer.ensure_front_matter( - title=args.title, - domain=concept, - author=args.author, - language=language - ) - - # 2. PHASE 1: Foundation (Architect Agents) - print("PHASE 1: Foundation Setup (Architect Agents)...") - - existing_world = state_mgr.get_world_bible() if not args.reset else None - existing_chars = state_mgr.get_character_registry() if not args.reset else None - existing_outline = state_mgr.get_master_outline() if not args.reset else None - - if existing_world and existing_chars and existing_outline: - print(" [State Manager] Found existing foundation in database. Resuming book...") - world_bible = existing_world - character_registry = existing_chars - master_outline = existing_outline - print(f" ✓ World Bible: '{world_bible.title}' ({len(world_bible.rules)} hard rules defined, Language: {world_bible.language}).") - print(f" ✓ Character Registry: {len(character_registry.characters)} characters loaded.") - print(f" ✓ Master Outline: {len(master_outline.chapters)} chapter beat sheets loaded.") - elif args.import_lorebook and os.path.exists(args.import_lorebook): - print(f" [Lorebook Import] Loading World Bible and Characters from '{args.import_lorebook}'...") - world_bible, character_registry, imported_relations = CardManager.import_lorebook(args.import_lorebook) - state_mgr.save_world_bible(world_bible) - state_mgr.save_character_registry(character_registry) - init_state = state_mgr.get_story_state() - if imported_relations: - init_state.character_relationships.extend(imported_relations) - state_mgr.save_story_state(init_state) - print(f" ✓ Imported: '{world_bible.title}', {len(character_registry.characters)} characters, {len(imported_relations)} relations.") - - outliner = MasterOutlinerAgent(llm_client) - print(" [Agent: Master Outliner] Generating 4-Part, 12-Chapter Beat Sheets...") - master_outline = outliner.build_outline(world_bible, character_registry, language=language) - state_mgr.save_master_outline(master_outline) - print(f" ✓ Master Outline Created: {len(master_outline.chapters)} chapter beat sheets scaffolded.") - else: - world_builder = WorldBuilderAgent(llm_client) - print(" [Agent: World Builder] Generating structured World Bible...") - world_bible = world_builder.build_world(seed_title=args.title, seed_concept=concept, genre=args.genre, language=language) - state_mgr.save_world_bible(world_bible) - print(f" ✓ World Bible Created: '{world_bible.title}' ({len(world_bible.rules)} hard rules defined, Language: {world_bible.language}).") - - char_architect = CharacterArchitectAgent(llm_client) - print(" [Agent: Character Architect] Developing Character Registry & Voice Fingerprints...") - character_registry = char_architect.build_characters(world_bible, author_name=args.author, language=language) - state_mgr.save_character_registry(character_registry) - print(f" ✓ Character Registry Created: {len(character_registry.characters)} characters initialized.") - - outliner = MasterOutlinerAgent(llm_client) - print(" [Agent: Master Outliner] Generating 4-Part, 12-Chapter Beat Sheets...") - master_outline = outliner.build_outline(world_bible, character_registry, language=language) - state_mgr.save_master_outline(master_outline) - print(f" ✓ Master Outline Created: {len(master_outline.chapters)} chapter beat sheets scaffolded.") - - # 3. PHASE 2 & 3: Execution & Adversarial Revision Loop - print("\nPHASE 2 & 3: Execution & Adversarial Revision Loop...") - drafter = ProseDrafterAgent(llm_client) - reviewer = MasterAdversarialReviewer(llm_client) - story_state = state_mgr.get_story_state() - - chapters_to_run = master_outline.chapters[:args.chapters] if args.chapters else master_outline.chapters - total_chapters = len(chapters_to_run) - - for chapter_beat in chapters_to_run: - chap_num = chapter_beat.chapter_number - print(f"\n--------------------------------------------------------------------------------") - print(f"CHAPTER {chap_num}/{total_chapters}: {chapter_beat.title}") - print(f"--------------------------------------------------------------------------------") - - chap_record = state_mgr.get_chapter_record(chap_num) if not args.reset else None - md_file_path = os.path.join(file_writer.output_dir, f"chapter_{chap_num:02d}.md") - if chap_record and chap_record.get("final_text") and os.path.exists(md_file_path) and os.path.getsize(md_file_path) > 100: - final_chapter_text = chap_record["final_text"] - chap_words = len(final_chapter_text.split()) - print(f" ✓ Chapter {chap_num} already finalized ({chap_words} words). Skipping draft phase.") - continue - - revision_brief = None - final_chapter_text = "" - - for rev in range(args.max_revisions + 1): - if rev > 0: - print(f" [Agent: Prose Drafter] Executing Revision Loop {rev}/{args.max_revisions} based on Critics' Brief...") - - draft_text = drafter.draft_chapter( - chapter_beat=chapter_beat, - world_bible=world_bible, - registry=character_registry, - story_state=story_state, - revision_brief=revision_brief - ) - - # Adversarial Critic Loop - print(f" [Agent: Adversarial Critics] Auditing Chapter {chap_num} for Continuity & Anti-Slop Tropes...") - revision_brief = reviewer.evaluate_chapter( - chapter_beat=chapter_beat, - chapter_text=draft_text, - world_bible=world_bible, - registry=character_registry, - story_state=story_state - ) - - if revision_brief.passed_audit: - print(f" ✓ [Critics Approval] Chapter {chap_num} passed adversarial audit clean!") - final_chapter_text = draft_text - break - else: - print(f" ⚠️ [Critics Feedback] Found {len(revision_brief.continuity_issues)} continuity issue(s) & {len(revision_brief.slop_violations)} slop violation(s).") - final_chapter_text = draft_text - - chap_words = len(final_chapter_text.split()) - print(f" ✓ Chapter {chap_num} Finalized: Total Word Count = {chap_words} words.") - - # Persist Finalized Chapter to Disk - md_file = file_writer.write_markdown_chapter(chap_num, final_chapter_text) - print(f" ✓ [Local File Writer] Chapter {chap_num} saved to: {md_file}") - - state_mgr.save_chapter_record(chap_num, draft_text, revision_brief, final_chapter_text) - - # Dynamic Story State Summarization for Rolling Context Window - print(f" [Memory Engine] Updating Story Knowledge Graph & Memory block for Chapter {chap_num}...") - story_state = state_mgr.update_dynamic_story_state( - story_state=story_state, - chapter_number=chap_num, - chapter_title=chapter_beat.title, - chapter_text=final_chapter_text, - llm_client=llm_client, - language=language - ) - - # Live Incremental Disk Compilation Bridge - print(f" [Disk Sync] Updating live .docx output on hard drive...") - try: - file_writer.compile_docx( - title=args.title, - domain=concept, - author=args.author, - docx_path=args.output, - language=language - ) - print(f" ✓ [Disk Sync] Live document '{os.path.basename(args.output)}' updated.") - except Exception as ex: - print(f" [Disk Sync Warning] Document update skipped: {ex}") - - # 4. Final Master Export - print("\n" + "=" * 80) - print("PHASE 4: Finalizing Commercial Publication Compilation...") - file_writer.compile_docx( - title=args.title, - domain=concept, - author=args.author, - docx_path=args.output, - language=language + publishing = { + key: value for key, value in { + "subtitle": args.subtitle, "isbn": args.isbn, "publisher": args.publisher, + "year": args.year, "dedication": args.dedication, "author_bio": args.author_bio, + }.items() if value + } + config = BookConfig( + title=args.title, author=args.author, concept=args.concept, genre=args.genre, language=language, + chapters=args.chapters, scenes_per_chapter=args.scenes_per_chapter, target_words=args.target_words, + max_revisions=args.max_revisions, opening_candidates=args.opening_candidates, + output=args.output, epub=args.epub, cover=args.cover, reset=args.reset, + export_cards=args.export_cards, import_lorebook=args.import_lorebook, publishing=publishing, ) - print(f"🎉 SUCCESS: Multi-Agent Commercial Book successfully generated: {os.path.abspath(args.output)}") - - epub_output = args.epub or (os.path.splitext(args.output)[0] + ".epub") - try: - file_writer.compile_epub( - title=args.title, - author=args.author, - epub_path=epub_output, - language=language - ) - print(f"🎉 SUCCESS: Commercial EPUB 3 Edition compiled: {os.path.abspath(epub_output)}") - except Exception as ex: - print(f" ⚠️ [EPUB Compilation Warning]: {ex}") - - # Portable Lorebook & Character Cards Export (MuMu style) - if args.export_cards: - print(f"\n [Lorebook Export] Exporting Character Cards and Lorebook to '{args.export_cards}'...") - cards_dir = Path(args.export_cards) - cards_dir.mkdir(parents=True, exist_ok=True) - for char in character_registry.characters: - char_card_file = cards_dir / f"{char.character_id}_{char.name.replace(' ', '_')}.json" - CardManager.export_character_card(char, char_card_file) - final_story_state = state_mgr.get_story_state() - CardManager.export_lorebook( - bible=world_bible, - registry=character_registry, - relationships=final_story_state.character_relationships if hasattr(final_story_state, 'character_relationships') else None, - output_path=cards_dir / "lorebook.json" - ) - print(f" ✓ Exported {len(character_registry.characters)} character cards & lorebook.json to '{args.export_cards}'.") - - print("=" * 80 + "\n") + BookPipeline(config, llm_client).run() if __name__ == "__main__": main() - diff --git a/memory/state_manager.py b/memory/state_manager.py index d0fe3bb..10bedbb 100644 --- a/memory/state_manager.py +++ b/memory/state_manager.py @@ -14,14 +14,17 @@ StoryState, RevisionBrief, ForeshadowingClue, - CharacterRelation + CharacterRelation, + ChapterMemory ) +from generator.json_parser import generate_validated, StructuredOutputError +from prompts.system_prompts import language_directive class StateManager: def __init__(self, db_path: str = "memory/book_state.db"): self.db_path = db_path - os.makedirs(os.path.dirname(self.db_path), exist_ok=True) + os.makedirs(os.path.dirname(self.db_path) or ".", exist_ok=True) self._init_db() def _init_db(self): @@ -140,39 +143,93 @@ def update_dynamic_story_state( language: str = "english" ) -> StoryState: """Parses chapter events to update rolling summary, open plot loops, and character states.""" - is_tamil = language and language.lower() in ["tamil", "ta"] - summary = f"- Chapter {chapter_number} ({chapter_title}): Narrative progressed through assigned beats." - + memory = None if llm_client: - prompt = ( - f"Analyze Chapter {chapter_number}: {chapter_title}.\n" - f"1. Provide a concise 2-sentence narrative recap.\n" - f"2. List any newly opened plot loops or unresolved questions.\n\n" - f"Text excerpt:\n{chapter_text[:1800]}" - ) - system = "You are a narrative continuity engine. Keep responses concise." - try: - response = llm_client.generate_text(prompt, system_prompt=system, max_tokens=300) - summary = response.strip() - except Exception: - pass - - # Update rolling summary - story_state.story_so_far_summary += f"\n- Chapter {chapter_number} ({chapter_title}): {summary}" - story_state.current_chapter = chapter_number + memory = self._extract_chapter_memory(story_state, chapter_number, chapter_title, chapter_text, llm_client, language) - # Track active plot thread - thread_label = f"Ch.{chapter_number} fallout: {chapter_title}" - if thread_label not in story_state.active_plot_threads: - story_state.active_plot_threads.append(thread_label) - # Cap active threads to avoid prompt bloat - if len(story_state.active_plot_threads) > 6: - retired = story_state.active_plot_threads.pop(0) - story_state.resolved_plot_threads.append(retired) + if memory: + self._apply_chapter_memory(story_state, memory) + recap = memory.recap + else: + recap = "Narrative progressed through assigned beats." + # Track active plot thread + thread_label = f"Ch.{chapter_number} fallout: {chapter_title}" + if thread_label not in story_state.active_plot_threads: + story_state.active_plot_threads.append(thread_label) + + story_state.chapter_recaps[chapter_number] = recap + story_state.story_so_far_summary += f"\n- Chapter {chapter_number} ({chapter_title}): {recap}" + story_state.current_chapter = chapter_number self.save_story_state(story_state) return story_state + def _extract_chapter_memory(self, story_state, chapter_number, chapter_title, chapter_text, llm_client, language) -> Optional[ChapterMemory]: + open_clues = [c.name for c in story_state.foreshadowing_clues if c.status in ["planted", "escalated"]] + prompt = f"""TASK: chapter memory +Extract what must be remembered from Chapter {chapter_number}: {chapter_title}. +{language_directive(language)} +Open setups you may mark escalated or resolved, using these exact names: {open_clues} +Currently open threads: {story_state.active_plot_threads} + +FULL CHAPTER: +{chapter_text} + +Return ONLY JSON: +{{"recap": "3-5 sentences: what happened and what changed", + "opened_threads": [], "closed_threads": [], + "character_conditions": [{{"character_name": "", "physical_wounds_or_status": [], "inventory_items": [], "emotional_state": "", "current_location": ""}}], + "relationships": [{{"source_char": "", "target_char": "", "relation_type": "", "affinity_score": 0, "dynamic_status": ""}}], + "clues_escalated": [], "clues_resolved": [], + "secrets": [{{"fact": "", "known_by": [], "hidden_from": []}}], + "discoveries": []}} +""" + system = "You are a narrative continuity engine. Record only what the text establishes. Never guess." + validator = lambda m: None if m.recap.strip() else "The recap is empty." + try: + return generate_validated(llm_client, prompt, system, ChapterMemory, validator=validator, max_tokens=3000) + except StructuredOutputError as e: + print(f" [Memory Engine Warning] Structured memory unavailable for Chapter {chapter_number}: {e}") + return None + + def _apply_chapter_memory(self, story_state: StoryState, memory: ChapterMemory): + for thread in memory.closed_threads: + if thread in story_state.active_plot_threads: + story_state.active_plot_threads.remove(thread) + story_state.resolved_plot_threads.append(thread) + for thread in memory.opened_threads: + if thread not in story_state.active_plot_threads: + story_state.active_plot_threads.append(thread) + for condition in memory.character_conditions: + story_state.character_conditions[condition.character_name] = condition + for rel in memory.relationships: + self._merge_relation(story_state, rel) + for clue in story_state.foreshadowing_clues: + if clue.name in memory.clues_resolved: + clue.status = "resolved" + elif clue.name in memory.clues_escalated and clue.status == "planted": + clue.status = "escalated" + known = {s.get("fact") for s in story_state.epistemic_secrets} + story_state.epistemic_secrets.extend(s for s in memory.secrets if s.get("fact") and s.get("fact") not in known) + story_state.key_discoveries.extend(d for d in memory.discoveries if d not in story_state.key_discoveries) + + @staticmethod + def _merge_relation(story_state: StoryState, relation: CharacterRelation): + pair = {relation.source_char.lower(), relation.target_char.lower()} + for i, existing in enumerate(story_state.character_relationships): + if {existing.source_char.lower(), existing.target_char.lower()} == pair: + story_state.character_relationships[i] = relation + return + story_state.character_relationships.append(relation) + + def save_json(self, key: str, value) -> None: + """Stores a checkpoint such as in-progress scenes or the book brief.""" + self._save_key(key, json.dumps(value, ensure_ascii=False)) + + def load_json(self, key: str, default=None): + data = self._get_key(key) + return json.loads(data) if data else default + # --------------------------------------------------------- # Foreshadowing & Clue Tracking (MuMuAINovel inspired) # --------------------------------------------------------- diff --git a/pipeline.py b/pipeline.py new file mode 100644 index 0000000..5b4591e --- /dev/null +++ b/pipeline.py @@ -0,0 +1,333 @@ +""" +Book Pipeline +The single end-to-end workflow behind the CLI, web server and Streamlit studio. +Each book lives in its own directory, so books can never overwrite or resume into one another. +""" + +import os +import re +import shutil +import unicodedata +from dataclasses import dataclass, field +from pathlib import Path +from typing import List, Optional, Dict +from pydantic import BaseModel, Field + +from generator.blueprint import BookBlueprint +from generator.json_parser import generate_validated, StructuredOutputError +from generator.llm_client import LlmClient +from memory.state_manager import StateManager +from schemas.models import BookBrief, RevisionBrief, SceneNote +from agents.book_strategist import BookStrategistAgent +from agents.book_reviewer import BookReviewer +from agents.publishing_kit import PublishingKitAgent +from agents.world_builder import WorldBuilderAgent +from agents.character_architect import CharacterArchitectAgent +from agents.master_outliner import MasterOutlinerAgent +from agents.prose_drafter import ProseDrafterAgent +from agents.critics import MasterAdversarialReviewer +from prompts.system_prompts import FACT_CHECK_PROMPT +from tools.card_manager import CardManager +from tools.file_writer import FileWriterTool + +BOOKS_ROOT = "books" +BRIEF_KEY = "book_brief" + + +def slugify(title: str) -> str: + # Keep letters, combining vowel signs (essential in Tamil) and digits; everything else separates words + kept = "".join(c if unicodedata.category(c)[0] in "LMN" else "_" for c in title) + return re.sub(r'_+', '_', kept).strip('_')[:80] or "untitled" + + +def book_dir_for(title: str, books_root: str = BOOKS_ROOT) -> str: + return os.path.join(books_root, slugify(title)) + + +@dataclass +class BookConfig: + title: str + author: str + concept: str = "" + genre: str = "auto" + language: str = "english" + chapters: int = 24 + scenes_per_chapter: int = 4 + target_words: int = 80000 + max_revisions: int = 2 + opening_candidates: int = 3 + output: Optional[str] = None + epub: Optional[str] = None + cover: Optional[str] = None + books_root: str = BOOKS_ROOT + reset: bool = False + export_cards: Optional[str] = None + import_lorebook: Optional[str] = None + publishing: Dict = field(default_factory=dict) # subtitle, isbn, publisher, year, dedication, author_bio + + +class OpeningChoice(BaseModel): + best: int = Field(default=1, description="1-based number of the strongest opening") + + +class FactClaims(BaseModel): + claims: List[str] = Field(default_factory=list) + + +def _rank(brief: RevisionBrief) -> tuple: + return (brief.passed_audit, brief.craft_score or 0, -len(brief.slop_violations)) + + +class BookPipeline: + def __init__(self, config: BookConfig, llm_client: LlmClient): + self.config = config + self.llm = llm_client + self.book_dir = book_dir_for(config.title, config.books_root) + self.manuscript_dir = os.path.join(self.book_dir, "manuscript") + self.publishing_dir = os.path.join(self.book_dir, "publishing") + slug = slugify(config.title) + self.docx_path = config.output or os.path.join(self.book_dir, f"{slug}.docx") + self.epub_path = config.epub or (os.path.splitext(self.docx_path)[0] + ".epub") + + def run(self) -> dict: + config = self.config + if config.reset and os.path.isdir(self.book_dir): + print(f" [Environment Reset] Removing '{self.book_dir}'...") + shutil.rmtree(self.book_dir) + os.makedirs(self.publishing_dir, exist_ok=True) + + self.state = StateManager(db_path=os.path.join(self.book_dir, "state.db")) + self.writer = FileWriterTool(output_dir=self.manuscript_dir) + + print("PHASE 1: Foundation Setup (Architect Agents)...") + self.brief, self.world, self.registry, self.outline = self._build_foundation() + + print("\nPHASE 2 & 3: Execution & Adversarial Revision Loop...") + self.drafter = ProseDrafterAgent(self.llm) + self.reviewer = MasterAdversarialReviewer(self.llm) + self.story_state = self.state.get_story_state() + if not self.story_state.foreshadowing_clues: + self.story_state.foreshadowing_clues = list(self.outline.foreshadowing) + self.state.save_story_state(self.story_state) + + publishing_metadata = dict(config.publishing, is_fiction=self.brief.is_fiction) + total = len(self.outline.chapters) + for chapter in self.outline.chapters: + print("\n" + "-" * 80) + print(f"CHAPTER {chapter.chapter_number}/{total}: {chapter.title}") + print("-" * 80) + record = self.state.get_chapter_record(chapter.chapter_number) + if record and record.get("final_text"): + print(f" ✓ Chapter {chapter.chapter_number} already finalized. Skipping draft phase.") + continue + self._write_chapter(chapter) + self._compile(publishing_metadata, final=False) + + print("\n" + "=" * 80) + print("PHASE 4: Whole-Book Release Review...") + chapters, briefs = self._load_finished_chapters() + result = BookReviewer(self.llm).review(config.title, self.brief, self.story_state, chapters, briefs, config.target_words) + report_path = BookReviewer.write_report(result, config.title, briefs, self.publishing_dir) + if not self.brief.is_fiction: + self._write_fact_check(chapters) + + print("PHASE 5: Publishing Kit & Compilation...") + kit = PublishingKitAgent(self.llm).build_kit(config.title, config.author, self.brief, self.story_state, config.language) + PublishingKitAgent.write_kit(kit, self.publishing_dir) + publishing_metadata["description"] = kit.blurb + publishing_metadata.setdefault("subtitle", kit.subtitle) + self._compile(publishing_metadata, final=True) + self._export_cards() + + result.update(docx=os.path.abspath(self.docx_path), epub=os.path.abspath(self.epub_path), report=os.path.abspath(report_path)) + print(f"\nDOCX: {result['docx']}\nEPUB: {result['epub']}\nReport: {result['report']}") + print(f"Words: {result['total_words']:,} | Average chapter score: {result['average_craft_score']} | Structure score: {result['arc_score']}") + if result["ready"]: + print("Automated checks PASSED. Complete the human steps in the report before publishing.") + else: + print(f"NOT READY TO PUBLISH: {len(result['blockers'])} blocker(s), listed in the report.") + for blocker in result["blockers"]: + print(f" - {blocker}") + print("=" * 80 + "\n") + return result + + def _build_foundation(self): + config = self.config + concept = config.concept or config.title + genre = BookBlueprint(title=config.title, genre=config.genre).genre if config.genre == "auto" else config.genre + + stored = self.state.load_json(BRIEF_KEY) + if stored: + brief = BookBrief.model_validate(stored) + else: + print(" [Agent: Book Strategist] Defining reader, promise, hook and voice...") + brief = BookStrategistAgent(self.llm).build_brief(config.title, concept, genre, config.language) + self.state.save_json(BRIEF_KEY, brief.model_dump()) + print(f" ✓ Book Brief: {brief.logline}") + + world = self.state.get_world_bible() + registry = self.state.get_character_registry() + if not (world and registry) and config.import_lorebook and os.path.exists(config.import_lorebook): + print(f" [Lorebook Import] Loading World Bible and Characters from '{config.import_lorebook}'...") + world, registry, relations = CardManager.import_lorebook(config.import_lorebook) + self.state.save_world_bible(world) + self.state.save_character_registry(registry) + if relations: + init_state = self.state.get_story_state() + init_state.character_relationships.extend(relations) + self.state.save_story_state(init_state) + if not world: + print(" [Agent: World Builder] Generating structured World Bible...") + world = WorldBuilderAgent(self.llm).build_world(config.title, concept, genre, config.language, brief=brief) + self.state.save_world_bible(world) + print(f" ✓ World Bible: '{world.title}' ({len(world.rules)} hard rules).") + if not registry: + print(" [Agent: Character Architect] Developing Character Registry & Voice Fingerprints...") + registry = CharacterArchitectAgent(self.llm).build_characters(world, config.author, config.language, brief=brief) + self.state.save_character_registry(registry) + print(f" ✓ Character Registry: {len(registry.characters)} characters.") + + outline = self.state.get_master_outline() + if not outline: + print(" [Agent: Master Outliner] Generating book plan and scene beats...") + outline = MasterOutlinerAgent(self.llm).build_outline( + world, registry, brief, language=config.language, num_chapters=config.chapters, + scenes_per_chapter=config.scenes_per_chapter, target_words=config.target_words, + ) + self.state.save_master_outline(outline) + print(f" ✓ Master Outline: {len(outline.chapters)} chapters, {len(outline.foreshadowing)} planned setups.") + return brief, world, registry, outline + + def _write_chapter(self, chapter): + config = self.config + num = chapter.chapter_number + checkpoint = f"scenes_ch_{num}" + scenes = self.drafter.draft_scenes( + chapter, self.world, self.registry, self.story_state, self.brief, + existing_scenes=self.state.load_json(checkpoint, []), + on_scene=lambda s: self.state.save_json(checkpoint, s), + previous_chapter_tail=self._previous_tail(num), + opening_candidates=config.opening_candidates if num == 1 else 1, + choose_opening=self._choose_opening if num == 1 else None, + ) + + best_scenes, best_brief = list(scenes), None + for revision in range(config.max_revisions + 1): + print(f" [Agent: Adversarial Critics] Auditing Chapter {num} (pass {revision + 1})...") + text = self._assemble(chapter, scenes) + brief = self.reviewer.evaluate_chapter(chapter, text, self.world, self.registry, self.story_state, scenes=scenes, brief=self.brief) + print(f" Score: {brief.craft_score} | continuity issues: {len(brief.continuity_issues)} | slop: {len(brief.slop_violations)}") + if best_brief is None or _rank(brief) > _rank(best_brief): + best_scenes, best_brief = list(scenes), brief + if brief.passed_audit: + print(f" ✓ [Critics Approval] Chapter {num} passed.") + break + if revision < config.max_revisions: + scenes = self._revise(chapter, scenes, brief) + self.state.save_json(checkpoint, scenes) + + if not best_brief.passed_audit: + print(f" ⚠️ Chapter {num} did not pass; keeping its strongest version and flagging it in the release report.") + + final_text = self._assemble(chapter, best_scenes) + self.writer.write_markdown_chapter(num, final_text) + self.state.save_chapter_record(num, self._assemble(chapter, scenes), best_brief, final_text) + self.state.save_json(checkpoint, []) + print(f" ✓ Chapter {num} Finalized: {len(final_text.split())} words.") + + print(f" [Memory Engine] Updating story memory for Chapter {num}...") + self.story_state = self.state.update_dynamic_story_state( + self.story_state, num, chapter.title, final_text, llm_client=self.llm, language=config.language + ) + + def _revise(self, chapter, scenes, brief: RevisionBrief) -> List[str]: + by_scene: Dict[int, List[SceneNote]] = {} + for note in brief.scene_notes: + by_scene.setdefault(note.scene, []).append(note) + if not by_scene: + # Continuity problems or low scores without located notes: rework the weakest link, the ending + by_scene[len(scenes)] = [SceneNote(scene=len(scenes), problem=brief.editor_overall_directive, fix="Raise tension and specificity.")] + revised = list(scenes) + for scene_number, notes in sorted(by_scene.items()): + print(f" [Agent: Prose Drafter] Revising scene {chapter.chapter_number}.{scene_number} ({len(notes)} note(s))...") + revised[scene_number - 1] = self.drafter.revise_scene( + chapter, scene_number - 1, revised, notes, brief, self.world, self.registry, self.story_state, self.brief + ) + return revised + + def _assemble(self, chapter, scenes) -> str: + chapters = self.outline.chapters + index = chapters.index(chapter) + include_part = bool(chapter.part_title) and (index == 0 or chapters[index - 1].part_title != chapter.part_title) + return self.drafter.assemble_chapter(chapter, scenes, self.brief, include_part=include_part, language=self.config.language) + + def _previous_tail(self, chapter_number: int) -> str: + record = self.state.get_chapter_record(chapter_number - 1) + return record["final_text"][-3000:] if record else "" + + def _choose_opening(self, candidates: List[str]) -> str: + """The opening decides whether a browsing reader buys, so it competes for its place.""" + numbered = "\n\n".join(f"[OPENING {i}]\n{text[:2500]}" for i, text in enumerate(candidates, start=1)) + prompt = f"""TASK: choose opening +Target reader: {self.brief.target_reader} +Promise: {self.brief.reader_promise} +A reader browsing a bookstore reads only these openings. Which makes them buy? + +{numbered} + +Return ONLY JSON: {{"best": 1}} +""" + system = "You are an acquiring editor choosing the opening most likely to make a stranger keep reading." + validator = lambda choice: None if 1 <= choice.best <= len(candidates) else "'best' is out of range." + try: + choice = generate_validated(self.llm, prompt, system, OpeningChoice, validator=validator, max_tokens=300) + print(f" -> Opening {choice.best} of {len(candidates)} selected.") + return candidates[choice.best - 1] + except StructuredOutputError as e: + print(f" [Opening Selection Warning] {e}") + return candidates[0] + + def _load_finished_chapters(self): + chapters, briefs = {}, {} + for chapter in self.outline.chapters: + record = self.state.get_chapter_record(chapter.chapter_number) + if record: + chapters[chapter.chapter_number] = record["final_text"] + briefs[chapter.chapter_number] = RevisionBrief.model_validate_json(record["revision_brief_json"]) + return chapters, briefs + + def _write_fact_check(self, chapters: Dict[int, str]): + lines = ["# Fact-Check Ledger", "", "AI models invent convincing facts. Verify each claim against a primary source before publishing.", ""] + for num, text in sorted(chapters.items()): + prompt = f'TASK: fact check\nList every checkable claim in this chapter.\n\n{text}\n\nReturn ONLY JSON: {{"claims": ["..."]}}' + lines.append(f"## Chapter {num}\n") + try: + claims = generate_validated(self.llm, prompt, FACT_CHECK_PROMPT, FactClaims, max_tokens=3000).claims + lines += [f"- [ ] {c}" for c in claims] or ["- No checkable claims listed."] + except StructuredOutputError as e: + lines.append(f"- [ ] Claim extraction failed; check this chapter by hand. ({e})") + lines.append("") + with open(os.path.join(self.publishing_dir, "fact_check.md"), "w", encoding="utf-8") as f: + f.write("\n".join(lines)) + + def _compile(self, metadata: dict, final: bool): + config = self.config + self.writer.compile_docx(config.title, config.concept, config.author, self.docx_path, config.language, metadata=metadata) + if final: + self.writer.compile_epub(config.title, config.author, self.epub_path, config.language, cover_image_path=config.cover, metadata=metadata) + + def _export_cards(self): + target = self.config.export_cards + if not target: + return + cards_dir = Path(target) + cards_dir.mkdir(parents=True, exist_ok=True) + for char in self.registry.characters: + CardManager.export_character_card(char, cards_dir / f"{char.character_id}_{char.name.replace(' ', '_')}.json") + CardManager.export_lorebook( + bible=self.world, + registry=self.registry, + relationships=self.story_state.character_relationships, + output_path=cards_dir / "lorebook.json", + ) + print(f" ✓ Exported {len(self.registry.characters)} character cards & lorebook.json to '{target}'.") diff --git a/prompts/system_prompts.py b/prompts/system_prompts.py index 35eaead..ac8e795 100644 --- a/prompts/system_prompts.py +++ b/prompts/system_prompts.py @@ -50,7 +50,7 @@ 5. **முடிவுரைத் தவிர்த்தல்:** அத்தியாயத்தின் இறுதியில் செயற்கையான தத்துவப் பேரனுமான முடிவுக் பத்தியைச் சேர்க்க வேண்டாம். காட்சியை அந்தந்தத் திருப்புமுனையிலேயே இயல்பாக முடிக்கவும். """ -TAMIL_ANTI_SLOP_EDITOR_PROMPT = """நீங்கள் ஒரு தமிழ் இலக்கிய விమర్శகர் மற்றும் பாடத் தொகுப்பாளர் (Adversarial Tamil Literary Editor). +TAMIL_ANTI_SLOP_EDITOR_PROMPT = """நீங்கள் ஒரு தமிழ் இலக்கிய விமர்சகர் மற்றும் பாடத் தொகுப்பாளர் (Adversarial Tamil Literary Editor). உங்கள் வேலை, எழுதப்பட்ட தமிழ் அத்தியாயத்தில் செயற்கையான மொழிபெயர்ப்பு நடைகளோ, போலித் தத்துவப் பத்திகளோ அல்லது ஆங்கிலச் சொற்களோ உள்ளதா என்று தணிக்கை செய்வதாகும். கண்டறியப்பட வேண்டிய செயற்கை நடைமுறைகள்: @@ -177,3 +177,43 @@ If the chapter contains slop or clichés, set passed_audit=false and specify exact lines and replacement directives in the RevisionBrief schema. If clean, set passed_audit=true. """ + +BOOK_STRATEGIST_PROMPT = """You are an acquiring editor who has launched many commercially successful books. +Turn the author's concept into a sharp commercial brief. Prefer one surprising, specific idea over a broad, safe one. +Set is_fiction correctly: a narrative-non-fiction or self-help book is NOT fiction and has no invented cast. +Describe the voice through concrete traits (sentence habits, humor, distance, what it refuses to do). Do not name or imitate a living author. +""" + +MASTER_OUTLINE_PROMPT = """You are a story architect who plans books readers cannot put down. +Every chapter must change something irreversibly and leave a question open. No chapter may repeat another's function. +Plan real setups and payoffs. For fiction, build toward the midpoint reversal, the darkest moment and an inevitable-yet-surprising ending. +For non-fiction, build an argument where each chapter earns the next, with a distinct story or case in each. +Name concrete events, people, places and objects. Generic placeholders are rejected. +""" + +DEVELOPMENTAL_EDITOR_PROMPT = """You are a demanding developmental editor at a major publisher, deciding whether to keep reading. +Calibrate strictly: 5 = competent amateur, 7 = publishable midlist, 8 = strong commercial, 9 = rare, 10 = career best. Most first drafts score 5-7. +Score what is on the page, not what the outline intended. Tie every note to a numbered scene and quote the weak line. +Never request changes that would break the listed continuity facts. +""" + +BOOK_REVIEWER_PROMPT = """You are an editor-in-chief reviewing a finished manuscript's structure. +Judge whether the opening's promise is kept, whether tension escalates, whether anything is repetitive or abandoned, and whether the ending is earned. +Report only real problems. Use the same strict scale: 7 = publishable midlist, 8 = strong commercial. +""" + +PUBLISHING_KIT_PROMPT = """You are a book marketer writing honest, high-converting retail copy. +Open the blurb with the hook and never reveal the ending. Keywords must be phrases real readers search, without repeating the title. +Never invent reviews, awards, sales figures, bestseller status, credentials or endorsements. +""" + +FACT_CHECK_PROMPT = """You prepare manuscripts for a human fact-checker. +List every checkable claim in non-fiction text: statistics, dates, named people, studies, quotations and historical events. +List only what the text states. Do not judge or correct it. +""" + + +def language_directive(language: str) -> str: + if (language or "").lower() in ["tamil", "ta"]: + return "Write every value in natural, fluent TAMIL (தமிழ் எழுத்துக்கள்). JSON keys stay in English." + return "Write in English." diff --git a/schemas/models.py b/schemas/models.py index 1b3590c..38462f7 100644 --- a/schemas/models.py +++ b/schemas/models.py @@ -110,8 +110,23 @@ class ForeshadowingClue(BaseModel): payoff_notes: str = Field(default="", description="Resolution details when resolved") +class BookBrief(BaseModel): + """Commercial concept every downstream agent writes toward.""" + is_fiction: bool = Field(default=True, description="True for narrative fiction, False for non-fiction") + logline: str = Field(default="", description="One-sentence hook a reader would repeat to a friend") + target_reader: str = Field(default="", description="Specific reader this book is for") + reader_promise: str = Field(default="", description="The experience or transformation the book guarantees") + central_question: str = Field(default="", description="The question that keeps pages turning") + what_makes_it_different: str = Field(default="", description="Why this is not like other books on the shelf") + genre_conventions: List[str] = Field(default_factory=list, description="Conventions readers of this genre expect") + ending: str = Field(default="", description="How the book ends or what final insight it lands on") + voice_guide: str = Field(default="", description="Concrete traits of the narrative voice") + voice_sample: str = Field(default="", description="Short paragraph demonstrating the voice") + + class SubBeat(BaseModel): section_number: str = Field(default="1.1", description="Section number") + heading: str = Field(default="", description="Reader-facing section heading (non-fiction only)") scene_objective: str = Field(default="Execute core scene goal", description="Scene goal") beat_type: str = Field(default="SCENE_GOAL", description="Dramatic beat type (SCENE_GOAL, CONFLICT_ESCALATION, DISASTER_REVERSAL, EMOTIONAL_REACTION, DILEMMA_CALCULATION, PIVOTAL_DECISION)") micro_tension_level: int = Field(default=5, ge=1, le=10, description="Micro-tension index (1=calm, 10=maximum crisis)") @@ -124,6 +139,7 @@ class SubBeat(BaseModel): class ChapterBeat(BaseModel): chapter_number: int = Field(default=1, description="Chapter number") + part_title: str = Field(default="", description="Title of the book part this chapter opens or belongs to") title: str = Field(default="Chapter Title", description="Chapter title") pov_character: str = Field(default="Protagonist", description="POV perspective") location: str = Field(default="Primary Setting", description="Location") @@ -140,6 +156,7 @@ class MasterOutline(BaseModel): total_parts: int = Field(default=4, description="Parts count") chapters: List[ChapterBeat] = Field(default_factory=list, description="Chapter beats") pacing_notes: str = Field(default="4-Part escalating pacing curve", description="Pacing notes") + foreshadowing: List[ForeshadowingClue] = Field(default_factory=list, description="Setups and payoffs planned across the book") class ContinuityIssue(BaseModel): @@ -156,17 +173,34 @@ class AntiSlopViolation(BaseModel): replacement_suggestion: str = Field(default="Replace with original vivid prose", description="Suggestion") +class SceneNote(BaseModel): + scene: int = Field(default=1, description="1-based scene number the note applies to") + problem: str = Field(default="", description="Specific weakness, quoting the text where possible") + fix: str = Field(default="", description="Concrete rewrite direction") + + +class CraftReview(BaseModel): + scores: Dict[str, float] = Field(default_factory=dict, description="Rubric scores from 1 to 10") + strengths: List[str] = Field(default_factory=list, description="What must survive revision") + scene_notes: List[SceneNote] = Field(default_factory=list, description="Scene-level revision notes") + + class RevisionBrief(BaseModel): chapter_number: int = Field(default=1, description="Target chapter number") passed_audit: bool = Field(default=True, description="Audit passed status") continuity_issues: List[ContinuityIssue] = Field(default_factory=list, description="Continuity issues") slop_violations: List[AntiSlopViolation] = Field(default_factory=list, description="Slop violations") editor_overall_directive: str = Field(default="Draft meets editorial standards.", description="Overall directive") + craft_scores: Dict[str, float] = Field(default_factory=dict, description="Developmental editor rubric scores") + craft_score: Optional[float] = Field(default=None, description="Mean rubric score; None when unreviewed") + strengths: List[str] = Field(default_factory=list, description="What revision must preserve") + scene_notes: List[SceneNote] = Field(default_factory=list, description="Scene-level revision notes") class StoryState(BaseModel): current_chapter: int = Field(default=0, description="Current chapter number") story_so_far_summary: str = Field(default="", description="Running story memory summary") + chapter_recaps: Dict[int, str] = Field(default_factory=dict, description="Recap of each finished chapter") active_plot_threads: List[str] = Field(default_factory=list, description="Unresolved plot points") resolved_plot_threads: List[str] = Field(default_factory=list, description="Resolved plot points") character_states: Dict[str, str] = Field(default_factory=dict, description="Character state tracker") @@ -175,3 +209,27 @@ class StoryState(BaseModel): key_discoveries: List[str] = Field(default_factory=list, description="Key discoveries") foreshadowing_clues: List[ForeshadowingClue] = Field(default_factory=list, description="Master foreshadowing, suspense and clue tracker") character_relationships: List[CharacterRelation] = Field(default_factory=list, description="Dynamic character relationship network") + + +class ChapterMemory(BaseModel): + """Structured facts extracted from a finished chapter.""" + recap: str = Field(default="", description="What happened and what changed") + opened_threads: List[str] = Field(default_factory=list) + closed_threads: List[str] = Field(default_factory=list) + character_conditions: List[CharacterCondition] = Field(default_factory=list) + relationships: List[CharacterRelation] = Field(default_factory=list) + clues_escalated: List[str] = Field(default_factory=list) + clues_resolved: List[str] = Field(default_factory=list) + secrets: List[Dict[str, Any]] = Field(default_factory=list) + discoveries: List[str] = Field(default_factory=list) + + +class PublishingKit(BaseModel): + subtitle: str = Field(default="", description="Optional subtitle") + tagline: str = Field(default="", description="One line for the cover or ads") + blurb: str = Field(default="", description="Back-cover and store description") + kdp_keywords: List[str] = Field(default_factory=list, description="Seven search phrases") + bisac_categories: List[str] = Field(default_factory=list, description="Suggested retail categories") + comparable_titles: List[str] = Field(default_factory=list, description="Comparable titles for positioning; must be verified by a human") + cover_brief: str = Field(default="", description="Direction for a cover designer") + launch_plan: List[str] = Field(default_factory=list, description="Concrete launch actions") diff --git a/server.py b/server.py index cb8bc44..2ee4feb 100644 --- a/server.py +++ b/server.py @@ -11,7 +11,8 @@ import threading import subprocess import urllib.parse -from http.server import HTTPServer, SimpleHTTPRequestHandler +from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler +from pipeline import book_dir_for, slugify PORT = 8080 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) @@ -34,7 +35,7 @@ def translate_path(self, path): return os.path.join(WEB_DIR, clean_path.lstrip("/")) target_path = os.path.abspath(os.path.join(WEB_DIR, clean_path.lstrip("/"))) - if not target_path.startswith(os.path.abspath(WEB_DIR)): + if not target_path.startswith(os.path.abspath(WEB_DIR) + os.sep): return os.path.join(WEB_DIR, "index.html") return target_path @@ -65,7 +66,8 @@ def do_GET(self): try: chap_num = int(chap_num_str) filename = f"chapter_{chap_num:02d}.md" - filepath = os.path.join(OUTPUT_DIR, filename) + job = JOBS.get(query_params.get("job_id", [""])[0]) or (list(JOBS.values())[-1] if JOBS else {}) + filepath = os.path.join(job.get("manuscript_dir", OUTPUT_DIR), filename) if os.path.exists(filepath): with open(filepath, "r", encoding="utf-8") as f: content = f.read() @@ -104,6 +106,10 @@ def do_GET(self): def do_POST(self): global JOB_COUNTER if self.path == "/api/generate": + # Browsers cannot send this type cross-site without a CORS approval, which this server never grants + if self.headers.get("Content-Type", "").split(";")[0].strip() != "application/json": + self.send_json_response({"error": "Content-Type must be application/json"}, status=415) + return content_length = int(self.headers.get("Content-Length", 0)) body = self.rfile.read(content_length).decode("utf-8") @@ -130,7 +136,6 @@ def do_POST(self): def send_json_response(self, data, status=200): self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") - self.send_header("Access-Control-Allow-Origin", "*") self.end_headers() self.wfile.write(json.dumps(data, ensure_ascii=False).encode("utf-8")) @@ -161,8 +166,8 @@ def run_generation_task(job_id, params): env_vars["TYPESAFE_API_KEY"] = api_key env_vars["LLM_API_KEY"] = api_key - output_filename = f"{title.replace(' ', '_')}_{job_id}.docx" - output_docx_path = os.path.join(OUTPUT_DIR, output_filename) + book_dir = os.path.join(BASE_DIR, book_dir_for(title)) + output_docx_path = os.path.join(book_dir, f"{slugify(title)}.docx") job_record = { "job_id": job_id, @@ -177,6 +182,7 @@ def run_generation_task(job_id, params): "message": f"World Builder Agent: Generating World Bible for '{title}'...", "active_title": title, "docx_path": output_docx_path, + "manuscript_dir": os.path.join(book_dir, "manuscript"), "error": "", "chapters": [] } @@ -185,7 +191,7 @@ def run_generation_task(job_id, params): chapters = str(params.get("chapters", "12")) cmd = [ - sys.executable, "main.py", + sys.executable, "-u", "main.py", "--title", title, "--concept", concept, "--author", author, @@ -193,8 +199,7 @@ def run_generation_task(job_id, params): "--genre", genre, "--provider", provider, "--chapters", chapters, - "--output", output_docx_path, - "--reset" + "--output", output_docx_path ] if model: cmd.extend(["--model", model]) @@ -229,23 +234,24 @@ def run_generation_task(job_id, params): elif "Agent: Master Outliner" in line_str: job_record["phase"] = "outline" job_record["progress_percent"] = 35 - job_record["message"] = "Master Outliner Agent: Scaffolding 12-chapter beat sheet..." - elif "CHAPTER" in line_str and "CHAPTER 12/" not in line_str: + job_record["message"] = "Master Outliner Agent: Planning chapters and scenes..." + elif line_str.startswith("CHAPTER "): job_record["phase"] = "draft" try: - num = int(line_str.split("CHAPTER")[1].split("/")[0].strip()) - job_record["progress_percent"] = 35 + int((num / 12) * 55) - job_record["message"] = f"Prose Drafter & Adversarial Critics: Drafting Chapter {num}/12..." + num, total = line_str.split("CHAPTER ")[1].split(":")[0].split("/") + num, total = int(num), int(total) + job_record["progress_percent"] = 35 + int((num / total) * 55) + job_record["message"] = f"Prose Drafter & Adversarial Critics: Drafting Chapter {num}/{total}..." chap_file = f"chapter_{num:02d}.md" if chap_file not in job_record["chapters"]: job_record["chapters"].append(chap_file) except Exception: pass - elif "Compiling" in line_str or "Finalizing Commercial" in line_str: + elif "PHASE 4" in line_str or "PHASE 5" in line_str: job_record["phase"] = "docx" job_record["progress_percent"] = 95 - job_record["message"] = "DOCX Compiler: Packaging 300-page bestseller document..." + job_record["message"] = "Release review, publishing kit and DOCX/EPUB compilation..." proc.wait() @@ -254,7 +260,7 @@ def run_generation_task(job_id, params): "status": "completed", "phase": "completed", "progress_percent": 100, - "message": f"Successfully generated '{title}' commercial DOCX manuscript!" + "message": f"Generated '{title}'. Read publishing/release_report.md before publishing." }) else: job_record.update({ @@ -313,7 +319,8 @@ def main(): os.makedirs(WEB_DIR, exist_ok=True) scan_existing_output_books() - server = HTTPServer(("0.0.0.0", PORT), BookGeneratorHandler) + # Loopback only: this API starts paid LLM jobs and has no authentication + server = ThreadingHTTPServer(("127.0.0.1", PORT), BookGeneratorHandler) print("=" * 80) print(f" BOOKGENERATOR AI (TAMIL ED.) - WEB APPLICATION SERVER") print("=" * 80) diff --git a/streamlit_app.py b/streamlit_app.py index d0d16b6..8b61807 100644 --- a/streamlit_app.py +++ b/streamlit_app.py @@ -5,24 +5,15 @@ import os import sys -import time -import json -from pathlib import Path +import contextlib import streamlit as st # Ensure project root is in path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from generator.blueprint import BLUEPRINTS, get_blueprint_for_genre, TAMIL_GENRES -from generator.llm_client import LlmClient, LLMClient -from generator.docx_compiler import compile_book, compile_book_to_docx -from tools.file_writer import FileWriterTool -from schemas.models import StoryState -from agents.world_builder import WorldBuilderAgent -from agents.character_architect import CharacterArchitectAgent -from agents.master_outliner import MasterOutlinerAgent -from agents.prose_drafter import ProseDrafterAgent -from agents.critics import MasterAdversarialReviewer, AntiSlopEditorAgent +from generator.blueprint import BLUEPRINTS, TAMIL_GENRES +from generator.llm_client import LlmClient +from pipeline import BookConfig, BookPipeline # Page Configuration st.set_page_config( @@ -135,7 +126,8 @@ def main(): genre_options = [k for k in BLUEPRINTS.keys() if not k.startswith("tamil_")] genre = st.selectbox("Genre / Blueprint", options=genre_options, index=0) - num_chapters = st.slider("Target Chapters", min_value=1, max_value=12, value=4) + num_chapters = st.slider("Chapters", min_value=1, max_value=60, value=24) + target_words = st.number_input("Target Words", min_value=1000, max_value=300000, value=80000, step=5000) with col2: st.subheader("💡 Story Concept & Prompt") @@ -164,154 +156,50 @@ def main(): log_expander = st.expander("📝 Detailed Pipeline Activity Logs", expanded=True) log_container = log_expander.container() - output_dir = Path("output") - output_dir.mkdir(exist_ok=True) - docx_filename = output_dir / f"{title.replace(' ', '_')}_streamlit.docx" + class StreamToLog: + """Mirrors pipeline progress lines into the page.""" + def write(self, text): + line = text.strip() + if line: + log_container.text(line) + if line.startswith(("PHASE", "CHAPTER ")): + status_text.info(line) + + def flush(self): + pass try: - # Initialize Client llm_client = LlmClient( provider=provider, api_key=api_key if api_key else None, model=model_name, ollama_url=ollama_url ) - - # Step 1: World Building - status_text.info("🌐 Step 1/5: World Builder Agent constructing World Bible...") - progress_bar.progress(15) - log_container.write("► Launching World Builder Agent...") - world_agent = WorldBuilderAgent(llm_client) - world_bible = world_agent.build_world(seed_title=title, seed_concept=concept, genre=genre, language=language) - log_container.success(f"✓ World Bible created: '{world_bible.title}' ({len(world_bible.rules)} hard rules defined).") - - # Step 2: Character Architecture - status_text.info("👤 Step 2/5: Character Architect Agent crafting profiles...") - progress_bar.progress(35) - log_container.write("► Launching Character Architect Agent...") - char_agent = CharacterArchitectAgent(llm_client) - character_registry = char_agent.build_characters(world_bible, author_name=author, language=language) - log_container.success(f"✓ Character Profiles generated ({len(character_registry.characters)} characters initialized).") - - # Step 3: Master Outlining - status_text.info("📜 Step 3/5: Master Outliner generating chapter beats...") - progress_bar.progress(50) - log_container.write(f"► Launching Master Outliner Agent for {num_chapters} chapters...") - outliner = MasterOutlinerAgent(llm_client) - master_outline = outliner.build_outline(world_bible, character_registry, language=language) - target_chapters = master_outline.chapters[:num_chapters] - log_container.success(f"✓ Master Outline scaffolded: {len(target_chapters)} chapters ready.") - - # Step 4: Prose Drafting & Adversarial Revision Loop - status_text.info("✍️ Step 4/5: Drafting & Reviewing Chapters...") - drafter = ProseDrafterAgent(llm_client) - reviewer = MasterAdversarialReviewer(llm_client) - story_state = StoryState() - file_writer = FileWriterTool(output_dir=str(output_dir)) - file_writer.ensure_front_matter(title=title, domain=concept, author=author, language=language) - - completed_chapters = [] - total = len(target_chapters) - - for idx, chapter_beat in enumerate(target_chapters, 1): - c_num = chapter_beat.chapter_number - c_title = chapter_beat.title - - status_text.info(f"✍️ Drafting Chapter {c_num}/{total}: {c_title}...") - log_container.write(f"► Drafting Chapter {c_num}: {c_title}...") - - draft_text = drafter.draft_chapter( - chapter_beat=chapter_beat, - world_bible=world_bible, - registry=character_registry, - story_state=story_state, - revision_brief=None - ) - - log_container.write(f"► Adversarial Critics auditing Chapter {c_num}...") - revision_brief = reviewer.evaluate_chapter( - chapter_beat=chapter_beat, - chapter_text=draft_text, - world_bible=world_bible, - registry=character_registry, - story_state=story_state - ) - - if revision_brief.passed_audit: - log_container.success(f"✓ Chapter {c_num} passed adversarial audit clean!") - else: - log_container.warning(f"⚠️ Chapter {c_num}: Found {len(revision_brief.continuity_issues)} continuity issue(s) & {len(revision_brief.slop_violations)} slop violation(s).") - - # Persist chapter markdown - file_writer.write_markdown_chapter(c_num, draft_text) - - # Update rolling story state - summary_prompt = f"Provide a concise 3-bullet narrative recap of Chapter {c_num}: {c_title}.\nText snippet:\n{draft_text[:1500]}" - try: - chap_summary = llm_client.generate_text(summary_prompt, system_prompt="You are a narrative continuity summarizer. Write in " + ("Tamil" if language in ["tamil", "ta"] else "English") + ".") - except Exception: - chap_summary = f"- Chapter {c_num} ({c_title}): Key events unfolded as planned." - - story_state.story_so_far_summary += f"\n- Chapter {c_num} ({c_title}): {chap_summary.strip()}" - story_state.current_chapter = c_num - - completed_chapters.append({ - "chapter_number": c_num, - "title": c_title, - "content": draft_text, - "score": 9.5 if revision_brief.passed_audit else 8.5 - }) - - prog_pct = 50 + int((idx / total) * 45) - progress_bar.progress(prog_pct) - log_container.success(f"✓ Chapter {c_num} finalized.") - - # Step 5: Compilation - status_text.info("📄 Step 5/5: Compiling Publishing-Grade DOCX...") - book_dict = { - "metadata": { - "title": title, - "author": author, - "genre": genre, - "language": language - }, - "chapters": completed_chapters - } - - file_writer.compile_docx( - title=title, - domain=concept, - author=author, - docx_path=str(docx_filename), - language=language + config = BookConfig( + title=title, author=author, concept=concept, genre=genre, language=language, + chapters=num_chapters, target_words=int(target_words), ) + with contextlib.redirect_stdout(StreamToLog()): + result = BookPipeline(config, llm_client).run() progress_bar.progress(100) - status_text.success("🎉 Book Generation Complete!") - st.balloons() + if result["ready"]: + status_text.success("Automated checks passed. Complete the human steps in the release report before publishing.") + else: + status_text.warning(f"Book generated, but NOT ready to publish: {len(result['blockers'])} blocker(s).") + for blocker in result["blockers"]: + st.write(f"- {blocker}") + st.divider() st.subheader("📥 Export & Read Book") - - # Reading Tabs - tab_docx, tab_read, tab_json = st.tabs(["📄 Download DOCX", "📖 Read Manuscript", "🔍 Raw JSON Data"]) - - with tab_docx: - with open(docx_filename, "rb") as f: - st.download_button( - label=f"⬇️ Download '{title}' (.docx)", - data=f, - file_name=os.path.basename(docx_filename), - mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" - ) - st.info("The exported DOCX includes custom Tamil typography (Mukta Malar / Noto Sans Tamil), localized cover page, title block, and formatted headers.") - - with tab_read: - for ch in completed_chapters: - with st.expander(f"Chapter {ch['chapter_number']}: {ch['title']}"): - st.markdown(ch["content"]) - - with tab_json: - st.json(book_dict) + for label, path, mime in [ + ("DOCX", result["docx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document"), + ("EPUB", result["epub"], "application/epub+zip"), + ]: + with open(path, "rb") as f: + st.download_button(f"⬇️ Download {label}", data=f, file_name=os.path.basename(path), mime=mime) + with open(result["report"], encoding="utf-8") as f: + st.markdown(f.read()) except Exception as e: status_text.error(f"Error during generation: {str(e)}") diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/fake_llm.py b/tests/fake_llm.py new file mode 100644 index 0000000..c3893a0 --- /dev/null +++ b/tests/fake_llm.py @@ -0,0 +1,83 @@ +"""Scripted stand-in for a model, routed on each prompt's TASK line, for fully offline pipeline tests.""" + +import json +import re + + +class FakeLlm: + provider = "fake" + model = "fake" + + def __init__(self, chapters=2, scenes=2, is_fiction=True, scores=None, scene_words=120): + self.chapters = chapters + self.scenes = scenes + self.is_fiction = is_fiction + self.scores = list(scores or []) + self.scene_words = scene_words + self.tasks = [] + self.scene_count = 0 + + def generate_text(self, prompt, system_prompt="", max_tokens=4096): + match = re.search(r"TASK: ([a-z ]+)", prompt) + task = match.group(1).strip() if match else "world or cast" + self.tasks.append(task) + handler = getattr(self, "_" + task.replace(" ", "_"), None) + if handler: + return handler(prompt) + if '"characters"' in prompt: + return json.dumps({"characters": [{"name": "Ilan Roth", "role": "Protagonist"}]}) + return json.dumps({"title": "T", "genre": "thriller", "rules": [{"rule_name": "No debts", "narrative_consequence": "Ruin"}]}) + + def _book_brief(self, prompt): + return json.dumps({ + "is_fiction": self.is_fiction, "logline": "A ferryman finds a ledger of the drowned.", + "target_reader": "Thriller readers", "reader_promise": "Dread that pays off", + "central_question": "Who wrote the ledger?", "ending": "He wrote it.", + "voice_guide": "Dry, close, wary", "voice_sample": "The river kept its accounts." + }) + + def _book_plan(self, prompt): + return json.dumps({ + "pacing_notes": "Escalate", + "chapters": [ + {"chapter_number": n, "part_title": f"Part {1 + (n - 1) // 2}", "title": f"Unique Title {n}", "core_narrative_arc": f"Change {n}"} + for n in range(1, self.chapters + 1) + ], + "setups_and_payoffs": [{"name": "The Ledger", "description": "A wet ledger", "planted_chapter": 1, "target_payoff_chapter": self.chapters}] + }) + + def _scene_plan(self, prompt): + return json.dumps({"scenes": [{"scene_objective": f"Objective {i} {len(self.tasks)}", "heading": f"Heading {i}"} for i in range(self.scenes)]}) + + def _prose(self, tag): + self.scene_count += 1 + words = [f"word{tag}{self.scene_count}x{i}" for i in range(self.scene_words)] + return "He ran. The Ledger waited. " + " ".join(words) + "." + + def _scene_draft(self, prompt): + return self._prose("d") + + def _scene_revision(self, prompt): + return self._prose("r") + + def _chapter_review(self, prompt): + score = self.scores.pop(0) if self.scores else 9 + keys = ["opening_hook", "tension_or_curiosity", "depth", "voice", "originality", "pacing", "ending_pull"] + notes = [] if score >= 8 else [{"scene": 1, "problem": "Slack", "fix": "Tighten"}] + return json.dumps({"scores": {k: score for k in keys}, "strengths": ["Voice"], "scene_notes": notes}) + + def _chapter_memory(self, prompt): + resolved = ["The Ledger"] if f"Chapter {self.chapters}:" in prompt else [] + return json.dumps({"recap": "Things changed.", "clues_resolved": resolved, "opened_threads": ["Who pays?"]}) + + def _book_review(self, prompt): + return json.dumps({"arc_score": 9, "problems": []}) + + def _choose_opening(self, prompt): + return json.dumps({"best": 2}) + + def _fact_check(self, prompt): + return json.dumps({"claims": ["A claim"]}) + + def _publishing_kit(self, prompt): + return json.dumps({"tagline": "Pay up.", "blurb": "A ferryman finds a ledger.", "kdp_keywords": ["river thriller"]}) diff --git a/tests/test_docx_compiler.py b/tests/test_docx_compiler.py index ff65cdb..b38e22e 100644 --- a/tests/test_docx_compiler.py +++ b/tests/test_docx_compiler.py @@ -2,6 +2,8 @@ import tempfile import unittest import docx +from docx.oxml.ns import qn +from docx.shared import Inches from generator.docx_compiler import compile_book @@ -36,6 +38,13 @@ def test_docx_compiler_trade_book(self): full_text = " ".join([p.text for p in doc.paragraphs]) self.assertIn("The Quantum Realm", full_text) self.assertIn("Pravin Tamilan", full_text) + self.assertIn("Copyright ©", full_text) + self.assertNotIn("BESTSELLER", full_text) + self.assertEqual(doc.sections[0].page_width, Inches(6)) + + # Numbering restarts only once, at the first body page + restarts = doc.element.body.findall('.//' + qn('w:pgNumType')) + self.assertEqual(len(restarts), 1) if __name__ == "__main__": diff --git a/tests/test_json_parser.py b/tests/test_json_parser.py index 5a429c0..3c42d0a 100644 --- a/tests/test_json_parser.py +++ b/tests/test_json_parser.py @@ -52,6 +52,10 @@ def test_parse_llm_json_invalid(self): self.assertIsNone(parse_llm_json("This is definitely not json")) self.assertIsNone(parse_llm_json("")) + def test_smart_quotes_in_valid_strings_survive(self): + text = '{"blurb": "He said, “stay”, and left."}' + self.assertEqual(parse_llm_json(text)["blurb"], "He said, “stay”, and left.") + if __name__ == "__main__": unittest.main() diff --git a/tests/test_llm_client.py b/tests/test_llm_client.py new file mode 100644 index 0000000..dde0664 --- /dev/null +++ b/tests/test_llm_client.py @@ -0,0 +1,34 @@ +import unittest +from unittest.mock import patch +from generator.llm_client import LlmClient + + +class TestCleanOutput(unittest.TestCase): + def setUp(self): + self.client = LlmClient(provider="openai", api_key="x", model="m") + + def test_prose_is_not_mangled(self): + prose = 'Sure, he had seen worse.\nDetail: the knife was gone. Interaction: none, she said.' + self.assertEqual(self.client._clean_llm_output(prose), prose) + + def test_meta_preamble_and_thinking_removed(self): + self.assertEqual(self.client._clean_llm_output("<think>hm</think>Here is the scene:\nRain fell."), "Rain fell.") + + def test_anthropic_never_defaults_to_an_openai_model(self): + self.assertTrue(LlmClient(provider="anthropic", api_key="x").model.startswith("claude")) + + def test_empty_response_raises(self): + with patch.object(self.client, "_post_json", return_value={"choices": [{"message": {"content": ""}}]}): + with self.assertRaises(RuntimeError): + self.client.generate_text("p") + + def test_truncated_reply_retries_with_more_room(self): + cut = {"choices": [{"message": {"content": "Half a sen"}, "finish_reason": "length"}]} + whole = {"choices": [{"message": {"content": "A whole sentence."}, "finish_reason": "stop"}]} + with patch.object(self.client, "_post_json", side_effect=[cut, whole]) as post: + self.assertEqual(self.client.generate_text("p", max_tokens=100), "A whole sentence.") + self.assertEqual(post.call_args.args[1]["max_tokens"], 200) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py new file mode 100644 index 0000000..e892ecb --- /dev/null +++ b/tests/test_pipeline.py @@ -0,0 +1,96 @@ +import os +import tempfile +import unittest +import zipfile +import docx +from pipeline import BookConfig, BookPipeline, slugify +from tests.fake_llm import FakeLlm + + +class TestPipeline(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + + def run_book(self, llm, title="The Ledger", **kwargs): + options = dict(chapters=llm.chapters, scenes_per_chapter=llm.scenes, target_words=500, opening_candidates=2) + options.update(kwargs) + config = BookConfig(title=title, author="A. Writer", books_root=self.tmp.name, **options) + return BookPipeline(config, llm), config + + def test_full_run_produces_book_and_kit(self): + llm = FakeLlm() + pipeline, _ = self.run_book(llm) + result = pipeline.run() + self.assertTrue(result["ready"], result["blockers"]) + self.assertTrue(os.path.exists(result["docx"])) + self.assertTrue(zipfile.is_zipfile(result["epub"])) + self.assertTrue(os.path.exists(os.path.join(pipeline.publishing_dir, "listing.md"))) + self.assertEqual(llm.tasks.count("choose opening"), 1) + + text = "\n".join(p.text for p in docx.Document(result["docx"]).paragraphs) + for fabricated in ["Praise", "BESTSELLER", "masterpiece", "Thought Leader", "$69.99", "ISBN"]: + self.assertNotIn(fabricated, text) + + def test_resume_makes_no_new_chapter_calls(self): + llm = FakeLlm() + self.run_book(llm)[0].run() + drafted = llm.tasks.count("scene draft") + self.run_book(llm)[0].run() + self.assertEqual(llm.tasks.count("scene draft"), drafted) + self.assertEqual(llm.tasks.count("book brief"), 1) + + def test_books_do_not_share_state(self): + llm = FakeLlm() + self.run_book(llm, title="Book One")[0].run() + self.run_book(llm, title="Book Two")[0].run() + self.assertEqual(llm.tasks.count("book brief"), 2) + + def test_revision_rewrites_only_flagged_scene_and_keeps_best_version(self): + # First chapter scores 6, then 7 after revision, then 5 after a harmful revision + llm = FakeLlm(chapters=2, scores=[6, 7, 5]) + pipeline, _ = self.run_book(llm, max_revisions=2, opening_candidates=1) + result = pipeline.run() + self.assertEqual(llm.tasks.count("scene revision"), 2) + self.assertFalse(result["ready"]) + self.assertTrue(any("Chapter 1 failed" in b for b in result["blockers"])) + _, briefs = pipeline._load_finished_chapters() + self.assertEqual(briefs[1].craft_score, 7) + + def test_short_book_is_not_ready(self): + pipeline, _ = self.run_book(FakeLlm(), target_words=100000) + result = pipeline.run() + self.assertTrue(any("Length" in b for b in result["blockers"])) + + def test_nonfiction_has_no_cast_and_gets_fact_check(self): + llm = FakeLlm(is_fiction=False) + pipeline, _ = self.run_book(llm) + pipeline.run() + self.assertEqual(pipeline.registry.characters, []) + self.assertTrue(os.path.exists(os.path.join(pipeline.publishing_dir, "fact_check.md"))) + with open(os.path.join(pipeline.manuscript_dir, "chapter_01.md"), encoding="utf-8") as f: + self.assertIn("### Heading 0", f.read()) + + def test_fiction_uses_scene_breaks_not_headings(self): + pipeline, _ = self.run_book(FakeLlm()) + pipeline.run() + with open(os.path.join(pipeline.manuscript_dir, "chapter_01.md"), encoding="utf-8") as f: + chapter = f.read() + self.assertIn("* * *", chapter) + self.assertNotIn("###", chapter) + + def test_unusable_model_output_fails_instead_of_inventing_a_book(self): + class Garbage(FakeLlm): + def generate_text(self, prompt, system_prompt="", max_tokens=4096): + return "not json" + pipeline, _ = self.run_book(Garbage()) + with self.assertRaises(RuntimeError): + pipeline.run() + + def test_slug_keeps_tamil_and_blocks_traversal(self): + self.assertEqual(slugify("../../etc/passwd"), "etc_passwd") + self.assertEqual(slugify("வேல்விழியின் சபதம்"), "வேல்விழியின்_சபதம்") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_scene_sequel_and_memory.py b/tests/test_scene_sequel_and_memory.py index 0eddb1f..bd2701f 100644 --- a/tests/test_scene_sequel_and_memory.py +++ b/tests/test_scene_sequel_and_memory.py @@ -2,7 +2,9 @@ import tempfile import unittest from unittest.mock import MagicMock -from schemas.models import WorldBible, CharacterRegistry, SubBeat, StoryState +from schemas.models import WorldBible, CharacterRegistry, BookBrief, StoryState, ForeshadowingClue +from generator.json_parser import StructuredOutputError +from tests.fake_llm import FakeLlm from agents.master_outliner import MasterOutlinerAgent from memory.state_manager import StateManager @@ -17,33 +19,30 @@ def tearDown(self): if os.path.exists(self.temp_db): os.remove(self.temp_db) - def test_outliner_populates_scene_sequel_beat_types(self): + def test_outliner_uses_model_plan_and_seeds_clues(self): bible = WorldBible(title="Shadow Over Arnor", genre="fiction") - registry = CharacterRegistry() - outliner = MasterOutlinerAgent(self.mock_llm) - outline = outliner.build_outline(bible, registry, language="english") + outliner = MasterOutlinerAgent(FakeLlm(chapters=3, scenes=2)) + outline = outliner.build_outline(bible, CharacterRegistry(), BookBrief(), num_chapters=3, scenes_per_chapter=2, target_words=3000) - first_chap = outline.chapters[0] - self.assertEqual(len(first_chap.sub_beats), 6) + self.assertEqual([c.title for c in outline.chapters], ["Unique Title 1", "Unique Title 2", "Unique Title 3"]) + self.assertEqual(outline.chapters[0].target_word_count, 1000) + self.assertEqual(outline.chapters[0].sub_beats[1].section_number, "1.2") + self.assertEqual(outline.foreshadowing[0].target_payoff_chapter, 3) + self.assertEqual(outline.chapters[2].foreshadowing_clues_to_resolve, ["The Ledger"]) - beat_types = [sb.beat_type for sb in first_chap.sub_beats] - expected_types = [ - "SCENE_GOAL", - "CONFLICT_ESCALATION", - "DISASTER_REVERSAL", - "EMOTIONAL_REACTION", - "DILEMMA_CALCULATION", - "PIVOTAL_DECISION" - ] - self.assertEqual(beat_types, expected_types) + def test_outliner_rejects_wrong_chapter_count(self): + outliner = MasterOutlinerAgent(FakeLlm(chapters=2, scenes=2)) + with self.assertRaises(StructuredOutputError): + outliner.build_outline(WorldBible(), CharacterRegistry(), BookBrief(), num_chapters=5, scenes_per_chapter=2) - # Verify micro-tension levels curve - tensions = [sb.micro_tension_level for sb in first_chap.sub_beats] - self.assertEqual(tensions, [4, 6, 8, 5, 7, 9]) - - # Verify internal subtext is populated - for sb in first_chap.sub_beats: - self.assertTrue(len(sb.pov_internal_state) > 0) + def test_chapter_memory_populates_story_state(self): + story_state = StoryState(foreshadowing_clues=[ForeshadowingClue(name="The Ledger", target_payoff_chapter=2)]) + updated = self.state_mgr.update_dynamic_story_state( + story_state, 2, "Reckoning", "Full text.", llm_client=FakeLlm(chapters=2), language="english" + ) + self.assertEqual(updated.chapter_recaps[2], "Things changed.") + self.assertIn("Who pays?", updated.active_plot_threads) + self.assertEqual(updated.foreshadowing_clues[0].status, "resolved") def test_dynamic_memory_state_update(self): story_state = StoryState() diff --git a/tools/epub_compiler.py b/tools/epub_compiler.py index f93f185..7659e7f 100644 --- a/tools/epub_compiler.py +++ b/tools/epub_compiler.py @@ -11,146 +11,131 @@ import zipfile from datetime import datetime, timezone from xml.sax.saxutils import escape +from generator.docx_compiler import copyright_lines CSS_CONTENT = """ @charset "utf-8"; -body { - font-family: "Georgia", "Merriweather", "Noto Serif", "Times New Roman", serif; - font-size: 1.05em; - line-height: 1.65; - color: #1e293b; - margin: 5% 8%; - padding: 0; -} -h1, h2, h3, h4 { - font-family: "Helvetica Neue", "Arial", sans-serif; - color: #0f172a; - font-weight: 700; - line-height: 1.25; -} -h1.book-title { - font-size: 2.2em; - text-align: center; - margin-top: 25%; - margin-bottom: 0.2em; - text-transform: uppercase; - letter-spacing: 0.05em; -} -p.author-name { - font-size: 1.2em; - text-align: center; - color: #0284c7; - margin-bottom: 30%; -} -h2.chapter-title { - font-size: 1.7em; - border-bottom: 2px solid #0284c7; - padding-bottom: 0.3em; - margin-top: 1.5em; - margin-bottom: 0.8em; - page-break-before: always; -} -h3.section-heading { - font-size: 1.2em; - color: #334155; - margin-top: 1.2em; - margin-bottom: 0.5em; -} -p { - margin: 0 0 1em 0; - text-indent: 0; - text-align: justify; -} -p.lead::first-letter { - font-size: 3.2em; - float: left; - margin: 0.05em 0.15em 0 0; - line-height: 0.85; - color: #0284c7; - font-weight: bold; -} -blockquote { - border-left: 3px solid #059669; - background-color: #f8fafc; - margin: 1.2em 0; - padding: 0.8em 1.2em; - font-style: italic; - color: #334155; -} -hr.divider { - border: 0; - height: 1px; - background: #cbd5e1; - margin: 2em 0; -} +body { font-family: Georgia, "Noto Serif", "Noto Serif Tamil", serif; line-height: 1.5; margin: 0 5%; } +h1, h2, h3, h4 { font-weight: bold; line-height: 1.25; } +h1.part-title { font-size: 1.8em; text-align: center; margin-top: 30%; page-break-before: always; } +h1.book-title { font-size: 2.2em; text-align: center; margin-top: 25%; margin-bottom: 0.2em; } +p.author-name { font-size: 1.2em; text-align: center; margin-bottom: 30%; } +h2.chapter-title { font-size: 1.5em; text-align: center; margin: 2em 0 1.5em; page-break-before: always; } +h3.section-heading { font-size: 1.15em; margin: 1.5em 0 0.5em; } +p { margin: 0; text-indent: 1.3em; text-align: justify; } +p.lead { text-indent: 0; } +p.lead::first-letter { font-size: 2.8em; float: left; margin: 0.05em 0.1em 0 0; line-height: 0.85; font-weight: bold; } +p.front { text-indent: 0; font-size: 0.85em; margin-bottom: 0.8em; } +p.dedication { text-indent: 0; text-align: center; margin-top: 30%; font-style: italic; } +blockquote { margin: 1em 1.5em; font-style: italic; } +blockquote p { text-indent: 0; } +hr.scene { border: 0; margin: 1.2em 0; text-align: center; } +hr.scene::after { content: "* * *"; } +pre { font-size: 0.85em; white-space: pre-wrap; margin: 1em 0; } +table { border-collapse: collapse; margin: 1em 0; width: 100%; } +td, th { border: 1px solid #888; padding: 0.3em; text-align: left; } +ul, ol { margin: 0.7em 0; } """ +def _inline(text: str) -> str: + html = escape(text) + html = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', html) + html = re.sub(r'\*([^*\s](?:.*?[^*\s])?)\*', r'<em>\1</em>', html) + return re.sub(r'`(.+?)`', r'<code>\1</code>', html) + + def markdown_to_xhtml(md_text: str) -> str: - """Converts basic Markdown formatting to clean XHTML.""" - html_lines = [] - lines = md_text.split('\n') - in_blockquote = False - first_p = True + """Converts Markdown to clean XHTML: headings, scene breaks, quotes, lists, tables and code.""" + out = [] + open_block = None + table_rows = [] + in_code = False + code_lines = [] + lead = True + + def close_block(): + nonlocal open_block + if open_block: + out.append(f"</{open_block}>") + open_block = None - for line in lines: + def flush_table(): + if not table_rows: + return + out.append("<table>") + for index, row in enumerate(table_rows): + tag = "th" if index == 0 else "td" + out.append("<tr>" + "".join(f"<{tag}>{_inline(c)}</{tag}>" for c in row) + "</tr>") + out.append("</table>") + table_rows.clear() + + def in_block(tag): + nonlocal open_block + if open_block != tag: + close_block() + out.append(f"<{tag}>") + open_block = tag + + for line in md_text.split('\n'): s = line.strip() + if s.startswith('```'): + if in_code: + out.append("<pre>" + escape("\n".join(code_lines)) + "</pre>") + code_lines = [] + else: + close_block() + flush_table() + in_code = not in_code + continue + if in_code: + code_lines.append(line) + continue + if s.startswith('|') and s.count('|') >= 2: + close_block() + if not re.match(r'^\|?[\s:|-]+\|?$', s): + table_rows.append([c.strip() for c in s.strip('|').split('|')]) + continue + flush_table() if not s: - if in_blockquote: - html_lines.append("</blockquote>") - in_blockquote = False + close_block() continue - if s.startswith('### '): - if in_blockquote: - html_lines.append("</blockquote>") - in_blockquote = False - heading = escape(s[4:]) - html_lines.append(f'<h3 class="section-heading">{heading}</h3>') - first_p = True + if s.startswith('### ') or s.startswith('#### '): + close_block() + out.append(f'<h3 class="section-heading">{_inline(s.lstrip("#").strip())}</h3>') + lead = True elif s.startswith('## '): - if in_blockquote: - html_lines.append("</blockquote>") - in_blockquote = False - heading = escape(s[3:]) - html_lines.append(f'<h2 class="chapter-title">{heading}</h2>') - first_p = True + close_block() + out.append(f'<h2 class="chapter-title">{_inline(s[3:])}</h2>') + lead = True elif s.startswith('# '): - if in_blockquote: - html_lines.append("</blockquote>") - in_blockquote = False - heading = escape(s[2:]) - html_lines.append(f'<h1 class="chapter-title">{heading}</h1>') - first_p = True + close_block() + out.append(f'<h1 class="part-title">{_inline(s[2:])}</h1>') + lead = True + elif re.match(r'^(\*\s*\*\s*\*|\*{3,}|-{3,})$', s): + close_block() + out.append('<hr class="scene" />') + lead = True elif s.startswith('>'): - if not in_blockquote: - html_lines.append("<blockquote>") - in_blockquote = True - quote_text = escape(s.lstrip('>').strip()) - quote_text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', quote_text) - quote_text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', quote_text) - html_lines.append(f"<p>{quote_text}</p>") - elif s.startswith('---'): - if in_blockquote: - html_lines.append("</blockquote>") - in_blockquote = False - html_lines.append('<hr class="divider" />') + in_block("blockquote") + out.append(f"<p>{_inline(s.lstrip('> ').strip())}</p>") + elif re.match(r'^[-*]\s', s): + in_block("ul") + out.append(f"<li>{_inline(s[2:])}</li>") + elif re.match(r'^\d+\.\s', s): + in_block("ol") + out.append(f"<li>{_inline(re.sub(r'^[0-9]+[.][ ]', '', s))}</li>") else: - if in_blockquote: - html_lines.append("</blockquote>") - in_blockquote = False - para = escape(s) - para = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', para) - para = re.sub(r'\*(.*?)\*', r'<em>\1</em>', para) - css_class = ' class="lead"' if first_p else '' - html_lines.append(f'<p{css_class}>{para}</p>') - first_p = False - - if in_blockquote: - html_lines.append("</blockquote>") + close_block() + css_class = ' class="lead"' if lead else '' + out.append(f'<p{css_class}>{_inline(s)}</p>') + lead = False - return "\n".join(html_lines) + close_block() + flush_table() + return "\n".join(out) def compile_epub( @@ -159,30 +144,27 @@ def compile_epub( chapters_dir: str, output_path: str, language: str = "english", - cover_image_path: str = None + cover_image_path: str = None, + metadata: dict = None ) -> str: """Compiles markdown chapter files into a validated EPUB 3 document.""" os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True) lang_code = "ta" if language.lower() in ["tamil", "ta"] else "en" - book_uuid = f"urn:uuid:{uuid.uuid4()}" + metadata = metadata or {} + # Stable across rebuilds so retailers and readers see updates to one book + book_uuid = f"urn:isbn:{metadata['isbn']}" if metadata.get("isbn") else f"urn:uuid:{uuid.uuid5(uuid.NAMESPACE_URL, title + '|' + author)}" mod_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - # Discover cover image if not explicitly provided + # Use only this book's own cover; never pick up an image belonging to another book resolved_cover = cover_image_path if not resolved_cover: - candidates = [ - os.path.join(chapters_dir, "google_play_cover.jpg"), - os.path.join(chapters_dir, "cover.jpg"), - os.path.join(os.path.dirname(os.path.abspath(output_path)), "google_play_cover.jpg"), - os.path.join(os.path.dirname(os.path.abspath(output_path)), "cover.jpg") - ] - for c in candidates: - if os.path.exists(c): - resolved_cover = c - break + candidate = os.path.join(chapters_dir, "cover.jpg") + if os.path.exists(candidate): + resolved_cover = candidate # Discover and sort Markdown files - front_matter_order = ["praise.md", "epigraph.md", "preface.md", "foreword.md"] + # Author-supplied front matter only; praise.md must hold real, permissioned quotes + front_matter_order = ["praise.md"] md_files = [] for fm in front_matter_order: p = os.path.join(chapters_dir, fm) @@ -212,7 +194,7 @@ def compile_epub( </head> <body style="margin: 0; padding: 0; text-align: center;"> <div style="text-align: center; margin: 0; padding: 0;"> - <img src="cover.jpg" alt="{escape(title)}" style="max-width: 100%; height: auto; max-height: 100vh; object-fit: contain;" /> + <img src="cover.jpg" alt="{escape(title, {'"': '"'})}" style="max-width: 100%; height: auto; max-height: 100vh; object-fit: contain;" /> </div> </body> </html>""" @@ -233,14 +215,33 @@ def compile_epub( manifest_items.append('<item id="titlepage" href="titlepage.xhtml" media-type="application/xhtml+xml"/>') spine_items.append('<itemref idref="titlepage"/>') + def add_page(page_id, page_title, body): + section_contents[f"{page_id}.xhtml"] = f"""<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{lang_code}" lang="{lang_code}"> +<head> + <title>{escape(page_title)} + + + +{body} + +""" + manifest_items.append(f'') + spine_items.append(f'') + + legal = "".join(f'

{escape(line)}

' for line in copyright_lines(title, author, language, metadata)) + add_page("copyright", "Copyright", legal) + if metadata.get("dedication"): + add_page("dedication", "Dedication", f'

{escape(metadata["dedication"])}

') + # Convert sections for idx, (section_id, file_path) in enumerate(md_files, start=1): with open(file_path, "r", encoding="utf-8") as f: raw_text = f.read() html_body = markdown_to_xhtml(raw_text) - first_line = raw_text.strip().split('\n')[0] - heading_match = re.search(r'#+\s*(.*)', first_line) + heading_match = re.search(r'^##\s+(.*)$', raw_text, re.MULTILINE) or re.search(r'^#+\s*(.*)$', raw_text, re.MULTILINE) section_title = heading_match.group(1).strip() if heading_match else section_id.replace("_", " ").title() filename = f"{section_id}.xhtml" @@ -260,6 +261,11 @@ def compile_epub( spine_items.append(f'') nav_toc_items.append(f'
  • {escape(section_title)}
  • ') + if metadata.get("author_bio"): + about = "ஆசிரியர் பற்றி" if lang_code == "ta" else "About the Author" + add_page("about", about, f'

    {escape(about)}

    {escape(metadata["author_bio"])}

    ') + nav_toc_items.append(f'
  • {escape(about)}
  • ') + # EPUB 3 Navigation Document (nav.xhtml) nav_html = f""" @@ -270,7 +276,7 @@ def compile_epub(