# Project: Thập Ngũ Niên — Ep01 Re-production Campaign (Scenes 01-10)

## Architecture
The campaign implements an AI-driven cinematic re-production system with a 2-Tier Critic Quality Gate, clean asset boundaries, and sample-accurate audio preservation:
1. **Critic & Verification Layer (`05_Production_Pipeline/antigravity_critic_gate.py`)**:
   - Google Antigravity SDK (`Agent` + `LocalAgentConfig(response_schema=VideoCriticVerdict)`) with Google GenAI fallback and OpenCV heuristic validation.
   - Shot Gate (Tầng 1, 10s): Character Bible conformance, visual artifact detection, Audio Guard verification, approval score >= 0.8.
   - Scene Gate (Tầng 2, 30-40s): Junction boundary check, 180-degree rule, eye-line continuity, color match trigger, tempo trim trigger, approval score >= 0.8.
2. **Deterministic Start Frame Dispatch (`production_orchestrator.py:resolve_start_frame_v2`)**:
   - Deterministic classification: `Cinematic Cut` (new scene, actor switch, reverse angle -> independent Start Frame from Character Bible or Imagen 3 Banana prompt) vs `Continuous Take` (same actor, continuous action -> tail frame 239).
   - Eliminates 100% of "Thúy Kiều face leakage" onto other characters.
3. **Hygiene & Archival Layer (`04_Assets/archive/ep01_legacy_v1/`)**:
   - Preserves 184 legacy Ep01 video files (2.14 GB) with legal IP documentation (`README.md`).
   - Purges 155 contaminated keyframe folders (`ep01_*`) while preserving 100% of `04_Assets/characters/`.
4. **Production & Audio Mastering Pipeline (`05_Production_Pipeline/`)**:
   - 10 Scenes (140 shots = 23m20s) mapped to 188 prompt library (`02_AI_Prompts/gemini_banana_prompts.json`) and Character Bible masters.
   - FFmpeg `filter_complex concat` preserving 100% AAC audio.
   - Two-pass EBU R128 (-14 LUFS, TP -1.0 dBTP) normalization with 4-stem architecture and dynamic ducking (-14dB).

```
[Character Bible (04_Assets/characters/)] ──┐
                                            ├──► [resolve_start_frame_v2] ──► [Muse.ai Worker]
[188 Prompts (02_AI_Prompts/)] ─────────────┘         │                                │
                                                      ▼                                ▼
                                             [Cinematic Cut vs Take]            [Raw 10s Shot]
                                                                                       │
                                                                                       ▼
                                                                           [Shot Gate (Tầng 1)] ──(score < 0.8)──► Retake
                                                                                       │ (score >= 0.8)
                                                                                       ▼
                                                                           [Scene Gate (Tầng 2)] ──(score < 0.8)──► Trim / Color Match
                                                                                       │ (score >= 0.8)
                                                                                       ▼
                                                                           [FFmpeg Concat & EBU R128]
                                                                                       │
                                                                                       ▼
                                                                           [Scene Master & Ep01 Master]
```

## Feature Inventory
| # | Feature | Description | Milestone | Source |
|---|---------|-------------|-----------|--------|
| F1 | Antigravity 2-Tier Quality Gate Module | Implement `antigravity_critic_gate.py` with `VideoCriticVerdict` (Pydantic v2), Shot Gate (>= 0.8) and Scene Gate (>= 0.8) | M1 | ORIGINAL_REQUEST §R1 |
| F2 | Deterministic Cut vs Take Classifier | Refactor `resolve_start_frame()` in `production_orchestrator.py` to compare `character_anchor` and prevent blind `prev_tail` chaining | M1 | ORIGINAL_REQUEST §R1 |
| F3 | Fix Asset References in Prompts | Correct 11 misassigned `character_asset_ref` entries in `episodes/ep01/prompts/muse_prompts.json` (Kim Trọng vs Thúy Kiều) | M1 | ORIGINAL_REQUEST §R1 |
| F4 | Legacy Video Archival Migration | Move 184 Ep01 legacy video files (2.14 GB) to `04_Assets/archive/ep01_legacy_v1/` with IP evidence documentation | M2 | ORIGINAL_REQUEST §R2 |
| F5 | IP Documentation Authoring | Author `04_Assets/archive/ep01_legacy_v1/README.md` with Vietnamese IP law arguments and Human-in-the-Loop creative evidence | M2 | ORIGINAL_REQUEST §R2 |
| F6 | Contaminated Keyframe Purging | Safely purge 155 `ep01_*` keyframe folders and 1 root file while preserving 100% of character portraits | M2 | ORIGINAL_REQUEST §R2 |
| F7 | Start Frame Generation & Ingestion | Prepare and verify pristine Start Frames for all 140 shots of Scenes 01 to 10 from 188 prompts and master portraits | M3 | ORIGINAL_REQUEST §R3 |
| F8 | Quality Gate Pipeline Integration | Integrate Shot Gate and Scene Gate into batch render and test runners with automated retake loop | M3 | ORIGINAL_REQUEST §R3 |
| F9 | Audio-Preserving FFmpeg Concat | Concat all 10 Scenes using FFmpeg `filter_complex concat` preserving 100% AAC audio | M4 | ORIGINAL_REQUEST §R3 |
| F10 | EBU R128 Audio Normalization | Master all 10 Scenes and full Ep01 to YouTube Green Dollar standard (-14 LUFS, TP -1.0 dBTP, 48kHz stereo) | M4 | ORIGINAL_REQUEST §R3 |
| F11 | Ep01 Master Assembly & E2E Validation | Assemble full 10-Scene Ep01 feature cut and run full verification test suite | M4 | ORIGINAL_REQUEST §R3 |

## Milestones
| # | Name | Scope | Dependencies | Status |
|---|------|-------|-------------|--------|
| M1 | 2-Tier Quality Gate & Classifier | Implement `antigravity_critic_gate.py`, refactor `resolve_start_frame_v2`, fix prompt asset refs | none | DONE |
| M2 | Archival & Workspace Hygiene | Migrate 184 legacy videos to archive, author IP README.md, purge 155 keyframe folders, verify character assets | none | DONE |
| M3 | Ep01 10-Scene Production Pipeline | Prepare 140 Start Frames, integrate critic gate into pipeline runner, verify retake logic | M1, M2 | DONE |
| M4 | Scene Concat, Audio Mastering & Final Assembly | Concat 10 Scenes via FFmpeg, master to EBU R128 -14 LUFS, assemble Ep01 Master, run validation suite | M3 | DONE |

## Interface Contracts
### `antigravity_critic_gate.py` ↔ `production_orchestrator.py`
- Function: `evaluate_shot_gate(shot_id: str, video_path: str, expected_character: str, prompt: str) -> VideoCriticVerdict`
- Function: `evaluate_scene_gate(scene_id: str, shot_video_paths: list[str]) -> VideoCriticVerdict`
- Return model: `VideoCriticVerdict` (Pydantic v2):
  - `overall_score`: float (0.0 to 1.0)
  - `approved`: bool (overall_score >= 0.8)
  - `shot_eval`: `ShotEvaluation` (character_match, visual_defects, audio_guard_ok, score)
  - `scene_eval`: `SceneEvaluation` (junction_smoothness, axis_180_ok, eyeline_ok, color_continuity, tempo_ok, score)
  - `suggested_action`: str ("APPROVE", "RETAKE_SHOT", "APPLY_COLOR_MATCH", "TRIM_STATIC")

### `resolve_start_frame_v2()` ↔ Asset Store
- Inputs: `shot_id: str`, `banana_prompt_data: dict`, `muse_prompt_data: dict`
- Deterministic check:
  - If `banana_prompt_data.character_anchor != prev_shot.character_anchor` or `shot_num == 1`:
    - Class: `Cinematic Cut`
    - Source: `04_Assets/characters/<character_path>` or contextual start frame. NEVER `prev_tail`.
  - Else:
    - Class: `Continuous Take`
    - Source: `04_Assets/keyframes/<prev_shot_id>/clean_frame_239.jpg`.

### Concat & Audio Mastering ↔ FFmpeg
- Concat command: `ffmpeg -y -i s1.mp4 -i s2.mp4 ... -filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]...concat=n=N:v=1:a=1[v][a]" -map "[v]" -map "[a]" -c:v libx264 -crf 18 -preset slow -c:a aac -b:a 192k -ar 48000 <scene_master>.mp4`
- Normalization command: `ffmpeg -y -i <in.mp4> -af "loudnorm=I=-14:TP=-1.0:LRA=10:print_format=json" ...`

## Code Layout
- `05_Production_Pipeline/antigravity_critic_gate.py`: 2-Tier Quality Gate implementation
- `05_Production_Pipeline/production_orchestrator.py`: Orchestrator with `resolve_start_frame_v2`
- `05_Production_Pipeline/audio_continuity_engine.py`: Audio mastering and EBU R128 normalization
- `04_Assets/archive/ep01_legacy_v1/`: Legacy Ep01 video files and IP README.md
- `04_Assets/characters/`: Pristine master character portraits (14 files + supporting)
- `04_Assets/keyframes/`: Clean keyframes generated by new pipeline
- `04_Assets/videos/`: Re-produced Ep01 raw shots and scene masters
- `tests/`: Quality gate and pipeline test suite
