shadow / compile_final_manuscript.py
garywelz's picture
Initial commit: Shadow of Lillya project (Markdown files only, no binaries)
73e99c6
#!/usr/bin/env python3
"""
Compile Final Manuscript with Clear Attribution
Organizes Audrey's original material, AI-generated content, and suggested additions
"""
import re
from pathlib import Path
from typing import List, Dict
from datetime import datetime
import json
class ManuscriptCompiler:
"""Compile final manuscript with clear source attribution"""
def __init__(self):
self.audrey_edited_dir = Path("manuscripts/Shadow_of_Lillya/audrey_edited")
self.completion_dir = Path("completion_attempts")
self.final_dir = Path("manuscripts/Shadow_of_Lillya/final_compilation")
self.final_dir.mkdir(parents=True, exist_ok=True)
def load_audrey_edited(self) -> str:
"""Load Audrey's edited original material"""
edited_file = self.audrey_edited_dir / "audrey_edited_clean.md"
if not edited_file.exists():
raise FileNotFoundError("Audrey's edited material not found. Run edit_audrey_material.py first.")
with open(edited_file, 'r', encoding='utf-8') as f:
return f.read()
def load_ai_completions(self) -> List[Dict]:
"""Load AI-generated completion attempts"""
completions = []
if not self.completion_dir.exists():
return completions
for completion_file in self.completion_dir.rglob("*.md"):
with open(completion_file, 'r', encoding='utf-8') as f:
content = f.read()
# Extract completion text
if '## Generated Continuation' in content:
completion_text = content.split('## Generated Continuation')[1].split('---')[0].strip()
else:
completion_text = content
# Extract metadata
metadata = {}
if '```json' in content:
try:
json_start = content.find('```json') + 7
json_end = content.find('```', json_start)
metadata = json.loads(content[json_start:json_end])
except:
pass
completions.append({
'file': str(completion_file),
'content': completion_text,
'model': metadata.get('model', 'Unknown'),
'timestamp': metadata.get('timestamp', ''),
'source': 'AI-generated'
})
return completions
def create_attributed_manuscript(self, audrey_text: str, ai_completions: List[Dict],
suggested_material: List[Dict] = None) -> str:
"""Create final manuscript with clear attribution"""
# Extract Audrey's content (skip headers)
audrey_content = audrey_text.split('---')[-1].strip()
manuscript = f"""# The Shadow of Lillya
## A Novel by Audrey Berger Welz
### Completed with AI Assistance
**Compilation Date:** {datetime.now().strftime('%Y-%m-%d')}
---
## Attribution and Source Information
This manuscript is organized into clearly labeled sections:
### 1. AUDREY'S ORIGINAL MATERIAL
All material in this section is the original writing of Audrey Berger Welz, extracted from her draft manuscripts and edited minimally for clarity. This represents her authentic voice and vision.
### 2. AI-GENERATED MATERIAL (Inspired by Audrey's Work)
Material in this section was generated by AI language models, using Audrey's original writing as context and inspiration. These sections are clearly marked and represent continuations that attempt to match her style and voice.
### 3. SUGGESTED ADDITIONS
Material suggested by editors, readers, or other contributors. These are clearly marked and represent additions that complement but do not replace Audrey's original work.
---
## Part I: Audrey's Original Material
{audrey_content}
---
## Part II: AI-Generated Continuations
*The following sections were generated by AI language models, using Audrey's original material as context and inspiration.*
"""
# Add AI completions with clear labels
for i, completion in enumerate(ai_completions, 1):
manuscript += f"""
### AI-Generated Section {i}
**Source:** {completion['model']}
**Generated:** {completion['timestamp']}
**Note:** This section was generated by an AI language model inspired by Audrey's writing style and the context of her manuscripts.
---
{completion['content'][:2000]}...
*[Full completion available in: {completion['file']}]*
---
"""
# Add suggested material if provided
if suggested_material:
manuscript += "\n## Part III: Suggested Additions\n\n"
manuscript += "*Material suggested by editors or contributors.*\n\n"
for i, material in enumerate(suggested_material, 1):
manuscript += f"""
### Suggested Addition {i}
**Source:** {material.get('source', 'Editor/Contributor')}
**Date:** {material.get('date', '')}
**Note:** {material.get('note', 'Suggested addition to complement Audrey's work')}
---
{material['content']}
---
"""
manuscript += f"""
---
## Final Notes
This compilation prioritizes Audrey Berger Welz's original writing above all else. AI-generated and suggested material are included only to complete the narrative, and are clearly marked to maintain transparency about the source of each section.
The goal is to honor Audrey's vision while providing readers with a complete story that remains as faithful as possible to her original intent and voice.
---
*Compiled: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
"""
return manuscript
def save_final_manuscript(self, manuscript: str):
"""Save the final compiled manuscript"""
output_file = self.final_dir / "shadow_of_lillya_final.md"
with open(output_file, 'w', encoding='utf-8') as f:
f.write(manuscript)
# Also create a version with just Audrey's material
audrey_only_file = self.final_dir / "shadow_of_lillya_audrey_only.md"
audrey_section = manuscript.split('## Part II:')[0] # Everything before AI sections
with open(audrey_only_file, 'w', encoding='utf-8') as f:
f.write(audrey_section)
return output_file, audrey_only_file
def main():
print("πŸ“š Compiling Final Manuscript with Attribution...\n")
compiler = ManuscriptCompiler()
# Load Audrey's material
print("πŸ“– Loading Audrey's edited material...")
try:
audrey_text = compiler.load_audrey_edited()
print(" βœ“ Loaded\n")
except FileNotFoundError as e:
print(f" βœ— Error: {e}")
print("\n Please run edit_audrey_material.py first to create edited version.")
return 1
# Load AI completions
print("πŸ€– Loading AI-generated completions...")
ai_completions = compiler.load_ai_completions()
print(f" βœ“ Found {len(ai_completions)} completion(s)\n")
# Create final manuscript
print("πŸ“ Creating final manuscript with attribution...")
final_manuscript = compiler.create_attributed_manuscript(audrey_text, ai_completions)
# Save
print("πŸ’Ύ Saving final manuscript...")
final_file, audrey_only_file = compiler.save_final_manuscript(final_manuscript)
print(f"\nβœ… Complete!")
print(f" πŸ“„ Full manuscript: {final_file}")
print(f" πŸ“„ Audrey's material only: {audrey_only_file}")
print(f"\nπŸ“‹ Structure:")
print(f" - Part I: Audrey's Original Material")
print(f" - Part II: AI-Generated Continuations ({len(ai_completions)} sections)")
print(f"\n✨ All material is clearly attributed to maintain transparency.")
if __name__ == '__main__':
exit(main())