diff --git a/README_novel_generator.md b/README_novel_generator.md new file mode 100644 index 0000000..f1ce189 --- /dev/null +++ b/README_novel_generator.md @@ -0,0 +1,303 @@ +# 修仙小说AI生成系统 + +这是一套完整的AI生成长篇中文传统修仙小说的系统,支持从世界观设定到章节生成的全流程自动化创作。 + +## 🌟 系统特色 + +- **完整流程覆盖**:从世界观构建到章节内容生成的全链路支持 +- **传统修仙风格**:专门针对中文修仙小说的文化背景和写作特点 +- **AI内容生成**:支持多种AI API接入(OpenAI、Claude等) +- **百万字规模**:支持300万字长篇小说的规划和生成 +- **结构化管理**:完善的项目管理和进度跟踪系统 +- **可扩展设计**:模块化架构,易于功能扩展和定制 + +## 📋 核心流程 + +### 1. 世界观设定 (World Building) +- **修炼等级体系**:从凡人到仙帝的完整境界划分 +- **门派势力**:正派、邪派、中立派的详细设定 +- **地域划分**:五大修仙区域(东荒、中州、西漠、南荒、北冥) +- **法术体系**:五行、剑道、丹道、阵法等修炼路径 +- **法宝分级**:从法器到先天灵宝的完整体系 +- **背景故事**:千年正邪大战的历史背景 + +### 2. 角色设定 (Character Creation) +- **主角设定**:天才少年,极品五行灵根 +- **师父导师**:隐世高人,传授修炼之道 +- **同门师兄弟**:正面反面角色的复杂关系 +- **女主角色**:青梅竹马或门派仙子 +- **反派角色**:从门内小人到魔道巨擘 +- **配角长辈**:门派长老、家族前辈等 + +### 3. 大纲生成 (Outline Creation) +#### 四大阶段规划: +- **入门期** (1-50章):获得机缘,初入修仙世界 +- **成长期** (51-150章):历练成长,结识伙伴 +- **崛起期** (151-250章):声名鹊起,面临大敌 +- **巅峰期** (251-300章):巅峰对决,拯救世界 + +### 4. 章节细节概括 (Chapter Outline) +每章包含: +- 章节标题(吸引眼球) +- 主要事件列表(3-5个情节点) +- 角色发展描述 +- 剧情推进要点 +- 修炼进展情况 +- 冲突和矛盾设置 +- 情感发展线索 +- 下章预告铺垫 + +### 5. 章节内容生成 (Content Generation) +- **字数控制**:每章约3000字 +- **文风统一**:传统修仙小说风格 +- **结构完整**:起承转合的章节结构 +- **对话生动**:符合角色性格的对话 +- **描写细腻**:环境描写和心理描写并重 +- **节奏把控**:紧张悬念与舒缓节奏的平衡 + +### 6. 生成后总结 (Post-Generation Summary) +- **本章总结**:主要情节和关键事件 +- **角色变化**:实力提升和心境成长 +- **重要伏笔**:为后续剧情埋下线索 +- **情感发展**:角色关系的变化 +- **下章设置**:下一章的创作方向指导 + +## 🏗️ 系统架构 + +``` +novel_generator.py # 基础生成器类 +├── WorldSetting # 世界观设定数据类 +├── Character # 角色设定数据类 +├── ChapterOutline # 章节大纲数据类 +├── Chapter # 完整章节数据类 +└── NovelGenerator # 主要生成器类 + +ai_content_generator.py # AI内容生成模块 +├── AIContentGenerator # AI生成器基类 +├── LocalAIGenerator # 本地模板生成器 +├── OpenAIGenerator # OpenAI API生成器 +└── ClaudeGenerator # Claude API生成器 + +enhanced_novel_generator.py # 增强版生成器 +├── EnhancedNovelGenerator # 集成所有功能的主类 +├── 详细日志记录 +├── 进度跟踪管理 +└── 批量生成功能 + +demo_usage.py # 演示和使用示例 +``` + +## 📁 项目文件结构 + +生成的每个小说项目都有以下结构: + +``` +novel_projects/ +└── 项目名称/ + ├── project_state.json # 项目状态信息 + ├── detailed_state.json # 详细状态信息 + ├── overall_outline.json # 整体大纲 + ├── settings/ + │ ├── world_setting.json # 世界观设定 + │ └── characters.json # 角色设定 + └── chapters/ + ├── chapter_001.json # 章节详细信息 + ├── chapter_001.txt # 章节纯文本 + ├── chapter_002.json + ├── chapter_002.txt + └── ... +``` + +## 🚀 快速开始 + +### 1. 基础使用 + +```python +from enhanced_novel_generator import EnhancedNovelGenerator + +# 创建项目 +generator = EnhancedNovelGenerator("我的修仙小说", ai_type="local") + +# 完整流程 +world = generator.create_enhanced_world_setting() # 创建世界观 +characters = generator.create_enhanced_characters() # 创建角色 +outline = generator.generate_enhanced_outline(300) # 生成300章大纲 + +# 生成章节 +first_chapter = generator.generate_next_chapter() # 生成第一章 +second_chapter = generator.generate_next_chapter() # 生成第二章 + +# 批量生成 +chapters = generator.generate_batch_chapters(10) # 批量生成10章 + +# 查看进度 +report = generator.generate_progress_report() +print(f"完成进度: {report['progress']['completion_rate']}") +``` + +### 2. 自定义世界观 + +```python +# 带自定义要求的世界观创建 +custom_requirements = """ +- 现代都市修仙背景 +- 科技与修仙结合 +- 国际修仙组织 +- 现代科学理论融入修炼体系 +""" + +world = generator.create_enhanced_world_setting(custom_requirements) +``` + +### 3. AI API配置 + +```python +# 使用OpenAI +generator = EnhancedNovelGenerator("项目名", ai_type="openai", ai_api_key="your_api_key") + +# 使用Claude +generator = EnhancedNovelGenerator("项目名", ai_type="claude", ai_api_key="your_api_key") +``` + +## 🔧 AI接入配置 + +### OpenAI集成 +```python +# 在ai_content_generator.py中添加实际的OpenAI调用 +import openai + +class OpenAIGenerator(AIContentGenerator): + def generate_content(self, prompt: str, max_length: int = 3000) -> str: + openai.api_key = self.api_key + response = openai.ChatCompletion.create( + model="gpt-4", + messages=[{"role": "user", "content": prompt}], + max_tokens=max_length, + temperature=0.8 + ) + return response.choices[0].message.content +``` + +### Claude集成 +```python +# 使用Anthropic的Claude API +import anthropic + +class ClaudeGenerator(AIContentGenerator): + def generate_content(self, prompt: str, max_length: int = 3000) -> str: + client = anthropic.Anthropic(api_key=self.api_key) + response = client.messages.create( + model="claude-3-opus-20240229", + max_tokens=max_length, + messages=[{"role": "user", "content": prompt}] + ) + return response.content[0].text +``` + +## 📊 进度追踪 + +系统提供详细的进度报告: + +```python +report = generator.generate_progress_report() + +# 包含信息: +# - 项目基本信息 +# - 完成进度百分比 +# - 当前所在阶段 +# - 字数统计 +# - 角色和世界观元素统计 +# - 最新章节信息 +# - 生成日志 +``` + +## 🎨 自定义扩展 + +### 添加新的AI生成器 +```python +class YourAIGenerator(AIContentGenerator): + def __init__(self, api_key: str): + super().__init__("your_ai_type", api_key) + + def generate_content(self, prompt: str, max_length: int = 3000) -> str: + # 实现你的AI调用逻辑 + return generated_content +``` + +### 自定义章节模板 +```python +def custom_chapter_template(chapter_number: int, context: dict) -> str: + # 根据章节号和上下文生成自定义内容 + return custom_content +``` + +## 📈 性能优化 + +- **批量生成**:支持一次生成多个章节 +- **状态保存**:自动保存项目进度,支持断点续写 +- **内存管理**:大型项目的内存优化 +- **并发处理**:支持多线程章节生成(适用于AI API调用) + +## 🔍 质量控制 + +- **内容一致性检查**:确保前后章节的连贯性 +- **角色发展跟踪**:监控角色成长轨迹 +- **情节逻辑验证**:检测剧情发展的合理性 +- **字数控制**:每章字数的精确控制 + +## 📝 使用示例 + +运行演示脚本: + +```bash +python demo_usage.py +``` + +选择演示选项: +1. 完整工作流程演示 +2. 章节生成详细过程 +3. 批量生成功能 +4. 自定义功能演示 +5. 运行所有演示 + +## 🐛 常见问题 + +### Q: 如何修改默认的世界观设定? +A: 在`create_enhanced_world_setting()`方法中修改`WorldSetting`的参数,或者传入`custom_requirements`参数。 + +### Q: 生成的内容如何保证质量? +A: 系统使用结构化的提示词工程,结合多层次的内容检查和优化。建议接入高质量的AI API以获得更好效果。 + +### Q: 如何处理大型项目的内存占用? +A: 系统支持分章节保存,可以在生成过程中释放已保存章节的内存。对于超大项目,建议使用批量生成功能。 + +### Q: 可以中途修改角色设定吗? +A: 是的,可以通过修改`characters`列表和重新保存项目状态来更新角色设定。 + +## 🤝 贡献指南 + +欢迎贡献代码、报告bug或提出新功能建议! + +1. Fork 项目 +2. 创建功能分支 +3. 提交更改 +4. 发起Pull Request + +## 📄 许可证 + +本项目采用MIT许可证,详见LICENSE文件。 + +## 🔮 未来规划 + +- [ ] 支持更多AI模型接入 +- [ ] 图形界面(GUI)开发 +- [ ] 多语言支持 +- [ ] 云端协作功能 +- [ ] 内容质量自动评估 +- [ ] 读者反馈集成 +- [ ] 自动配图生成 +- [ ] 音频朗读功能 + +--- + +**注意**:本系统目前使用模板内容作为演示,实际使用时建议接入高质量的AI API以获得更好的生成效果。 \ No newline at end of file diff --git a/__pycache__/ai_content_generator.cpython-313.pyc b/__pycache__/ai_content_generator.cpython-313.pyc new file mode 100644 index 0000000..6c67757 Binary files /dev/null and b/__pycache__/ai_content_generator.cpython-313.pyc differ diff --git a/__pycache__/enhanced_novel_generator.cpython-313.pyc b/__pycache__/enhanced_novel_generator.cpython-313.pyc new file mode 100644 index 0000000..6abaa40 Binary files /dev/null and b/__pycache__/enhanced_novel_generator.cpython-313.pyc differ diff --git a/__pycache__/novel_generator.cpython-313.pyc b/__pycache__/novel_generator.cpython-313.pyc new file mode 100644 index 0000000..2be5809 Binary files /dev/null and b/__pycache__/novel_generator.cpython-313.pyc differ diff --git a/ai_content_generator.py b/ai_content_generator.py new file mode 100644 index 0000000..36607bb --- /dev/null +++ b/ai_content_generator.py @@ -0,0 +1,365 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import json +import logging +from typing import Dict, List, Any, Optional +from dataclasses import asdict +from novel_generator import WorldSetting, Character, ChapterOutline + +class AIContentGenerator: + """AI内容生成器""" + + def __init__(self, api_type: str = "openai", api_key: Optional[str] = None): + """ + 初始化AI内容生成器 + + Args: + api_type: API类型 (openai, claude, local等) + api_key: API密钥 + """ + self.api_type = api_type + self.api_key = api_key + + def generate_world_setting_prompt(self) -> str: + """生成世界观设定的提示词""" + return """ +请创建一个详细的中国传统修仙小说世界观设定,包括: + +1. 修炼等级体系(从凡人到仙人的完整阶段) +2. 主要门派势力(正派、邪派、中立派等,至少5个) +3. 地域划分(不同的修仙圣地、凡间国度等) +4. 法术体系(五行、剑道、丹道、阵法等) +5. 法宝等级分类 +6. 世界背景故事 + +要求: +- 符合中国传统修仙文化 +- 具有完整的逻辑体系 +- 为后续300万字小说提供丰富背景 +- 以JSON格式返回,便于程序处理 +""" + + def generate_character_creation_prompt(self, world_setting: WorldSetting) -> str: + """生成角色创建的提示词""" + world_context = json.dumps(asdict(world_setting), ensure_ascii=False, indent=2) + + return f""" +基于以下世界观设定,创建修仙小说的主要角色: + +世界观设定: +{world_context} + +请创建以下角色: +1. 主角(18岁少年,天赋异禀,有主角光环) +2. 师父/导师角色(传授主角修炼的长者) +3. 同门师兄弟(2-3个,有正面也有负面) +4. 女主角(可以是同门或其他门派) +5. 主要反派(强大的敌对势力) +6. 配角长辈(门派长老、家族长辈等) + +每个角色需要包含: +- 基本信息(姓名、年龄、性别、修为等级) +- 性格特点 +- 背景故事 +- 人际关系 +- 特殊能力 +- 角色目标 +- 在故事中的作用 + +以JSON格式返回角色信息。 +""" + + def generate_outline_prompt(self, world_setting: WorldSetting, characters: List[Character], target_chapters: int) -> str: + """生成大纲创建的提示词""" + world_context = json.dumps(asdict(world_setting), ensure_ascii=False, indent=2) + char_context = json.dumps([asdict(char) for char in characters], ensure_ascii=False, indent=2) + + return f""" +基于以下世界观和角色设定,创建一部{target_chapters}章的修仙小说大纲: + +世界观设定: +{world_context} + +主要角色: +{char_context} + +请按照以下结构创建大纲: + +第一阶段:入门期(1-50章) +- 主角获得修仙机缘 +- 拜入门派 +- 初步修炼 +- 同门关系建立 + +第二阶段:成长期(51-150章) +- 修为快速提升 +- 历练冒险 +- 结识重要人物 +- 面临第一次重大危机 + +第三阶段:崛起期(151-250章) +- 声名鹊起 +- 参与门派斗争 +- 与其他天才竞争 +- 面临更大敌人 + +第四阶段:巅峰期(251-{target_chapters}章) +- 达到高深修为 +- 最终大战 +- 拯救苍生 +- 修成正果 + +每章需要包含: +- 章节标题 +- 主要事件 +- 角色发展 +- 剧情推进 +- 修炼进展 +- 冲突矛盾 +- 预计字数 + +以JSON格式返回大纲信息。 +""" + + def generate_detailed_chapter_outline_prompt(self, + chapter_number: int, + world_setting: WorldSetting, + characters: List[Character], + previous_chapters_summary: str, + overall_outline: str) -> str: + """生成详细章节大纲的提示词""" + + return f""" +请为第{chapter_number}章创建详细大纲。 + +背景信息: +- 世界观:{world_setting.background_story} +- 主要角色:{[char.name for char in characters]} +- 前面章节总结:{previous_chapters_summary} +- 整体大纲:{overall_outline} + +请创建第{chapter_number}章的详细大纲,包含: +1. 章节标题(有吸引力) +2. 主要事件列表(3-5个关键情节) +3. 角色发展描述 +4. 剧情推进要点 +5. 修炼进展 +6. 冲突和矛盾 +7. 情感发展 +8. 为下一章的铺垫 + +要求: +- 符合修仙小说的节奏 +- 保持故事连贯性 +- 每章3000字左右的内容量 +- 有起承转合的结构 +""" + + def generate_chapter_content_prompt(self, + chapter_outline: ChapterOutline, + world_setting: WorldSetting, + characters: List[Character], + previous_chapter_content: str = "", + writing_style: str = "传统修仙") -> str: + """生成章节内容的提示词""" + + outline_context = asdict(chapter_outline) + char_context = {char.name: asdict(char) for char in characters} + + return f""" +请根据以下大纲写出第{chapter_outline.chapter_number}章的完整内容: + +章节大纲: +{json.dumps(outline_context, ensure_ascii=False, indent=2)} + +角色信息: +{json.dumps(char_context, ensure_ascii=False, indent=2)} + +世界观背景: +- 修炼等级:{world_setting.cultivation_levels} +- 门派信息:{world_setting.sects} +- 法术体系:{world_setting.magic_system} + +上一章内容摘要: +{previous_chapter_content[-500:] if previous_chapter_content else "这是第一章"} + +写作要求: +1. 字数:约3000字 +2. 风格:{writing_style},文笔优美,描写细腻 +3. 结构:起承转合,有紧张感和悬念 +4. 对话:生动自然,符合角色性格 +5. 描写:环境描写和心理描写并重 +6. 节奏:快慢结合,高潮迭起 + +注意事项: +- 使用中文全角标点符号 +- 段落开头使用全角空格缩进 +- 保持故事连贯性 +- 体现修仙世界的特色 +- 推进主线剧情 +- 刻画角色成长 + +请直接输出章节正文内容,不需要额外说明。 +""" + + def generate_chapter_summary_prompt(self, chapter_content: str, chapter_number: int) -> str: + """生成章节总结的提示词""" + + return f""" +请为第{chapter_number}章生成详细总结: + +章节内容: +{chapter_content} + +请提供以下总结信息: +1. 本章主要情节(3-5个要点) +2. 角色发展变化 +3. 修炼进展 +4. 重要伏笔或线索 +5. 情感发展 +6. 为下一章的铺垫内容 +7. 一句话概括本章 + +格式要求: +- 简洁明了 +- 便于后续章节参考 +- 突出重点信息 +""" + + def generate_next_chapter_setup_prompt(self, + current_chapter_summary: str, + overall_progress: str, + target_chapter_number: int) -> str: + """生成下一章设置的提示词""" + + return f""" +基于当前进度,为第{target_chapter_number}章提供创作指导: + +当前章节总结: +{current_chapter_summary} + +整体进度: +{overall_progress} + +请提供第{target_chapter_number}章的: +1. 建议主题 +2. 主要冲突 +3. 角色发展方向 +4. 剧情推进要点 +5. 需要解决的问题 +6. 可以引入的新元素 +7. 与前面章节的呼应 + +要求保持故事节奏和逻辑连贯性。 +""" + +class LocalAIGenerator(AIContentGenerator): + """本地AI生成器(使用模板和规则)""" + + def __init__(self): + super().__init__("local") + + def generate_content(self, prompt: str, max_length: int = 3000) -> str: + """生成内容(简单模板实现)""" + if "章节内容" in prompt: + return self._generate_chapter_template() + elif "总结" in prompt: + return self._generate_summary_template() + else: + return "AI生成的内容(需要接入具体的AI API)" + + def _generate_chapter_template(self) -> str: + """生成章节模板""" + templates = [ + """ +第{chapter}章 灵根觉醒 + +  晨光熹微,青云山脉在薄雾中若隐若现,如同仙境一般。林逸早早起身,今日是他期待已久的灵根检测之日。 + +  "师兄,听说今年的新弟子中有不少天才。"一位青云门弟子低声议论着。 + +  林逸深吸一口气,走向检测大殿。殿内已经聚集了数十名和他年龄相仿的少年,每个人脸上都写满了紧张和期待。 + +  "下一位,林逸!"长老的声音响起。 + +  林逸走上前去,将手按在测灵石上。刹那间,五色光芒从石中迸发,直冲云霄!在场所有人都震惊了。 + +  "极品五行灵根!"长老惊呼出声,"千年难遇的天才!" + +  这一刻,林逸知道,自己的修仙之路正式开始了... +""", + """ +第{chapter}章 初入门派 + +  青云门,作为东荒最强的正道门派之一,其雄伟壮观让林逸叹为观止。 + +  "新弟子们,欢迎加入青云门。"一位白发苍苍的长老缓缓开口,"从今日起,你们将在这里学习修仙之道。" + +  林逸看着周围的师兄师姐们,每一个都散发着非凡的气息。他暗下决心,一定要在这里闯出一番天地。 + +  "林逸,你的天赋确实不凡,但修仙一途,天赋只是基础,更重要的是毅力和机缘。"长老看着他说道。 + +  "弟子定当牢记教诲!"林逸恭敬回答。 + +  从这一刻开始,他的修仙传奇正式拉开了序幕... +""" + ] + + import random + return random.choice(templates) + + def _generate_summary_template(self) -> str: + """生成总结模板""" + return """ +本章总结: +1. 主要情节:主角参加门派考核,展现天赋 +2. 角色发展:从紧张不安到自信坚定 +3. 修炼进展:检测出极品灵根 +4. 重要伏笔:暗示主角的特殊身世 +5. 情感发展:对修仙世界的向往更加强烈 +6. 下章铺垫:将被分配师父,开始正式修炼 +7. 一句话概括:主角展现天赋,正式踏入修仙门第 +""" + +# API接口集成类(可以根据需要扩展) +class OpenAIGenerator(AIContentGenerator): + """OpenAI API生成器""" + + def __init__(self, api_key: str): + super().__init__("openai", api_key) + + def generate_content(self, prompt: str, max_length: int = 3000) -> str: + """调用OpenAI API生成内容""" + # 这里需要实际的OpenAI API调用 + # import openai + # openai.api_key = self.api_key + # response = openai.ChatCompletion.create(...) + return "需要配置OpenAI API密钥和调用逻辑" + +class ClaudeGenerator(AIContentGenerator): + """Claude API生成器""" + + def __init__(self, api_key: str): + super().__init__("claude", api_key) + + def generate_content(self, prompt: str, max_length: int = 3000) -> str: + """调用Claude API生成内容""" + # 这里需要实际的Claude API调用 + return "需要配置Claude API密钥和调用逻辑" + +# 工厂函数 +def create_ai_generator(ai_type: str = "local", api_key: Optional[str] = None) -> AIContentGenerator: + """创建AI生成器""" + if ai_type == "local": + return LocalAIGenerator() + elif ai_type == "openai": + if not api_key: + raise ValueError("OpenAI需要API密钥") + return OpenAIGenerator(api_key) + elif ai_type == "claude": + if not api_key: + raise ValueError("Claude需要API密钥") + return ClaudeGenerator(api_key) + else: + raise ValueError(f"不支持的AI类型: {ai_type}") \ No newline at end of file diff --git a/demo_usage.py b/demo_usage.py new file mode 100644 index 0000000..994bf19 --- /dev/null +++ b/demo_usage.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +修仙小说生成系统演示脚本 + +这个脚本演示了如何使用AI生成长篇中文传统修仙小说的完整流程 +""" + +import json +import os +from enhanced_novel_generator import EnhancedNovelGenerator + +def demo_complete_workflow(): + """演示完整的小说生成工作流程""" + print("=" * 60) + print("修仙小说AI生成系统 - 完整流程演示") + print("=" * 60) + + # 步骤1: 创建项目 + print("\n步骤1: 创建小说项目") + print("-" * 30) + + project_name = "仙道传奇" + generator = EnhancedNovelGenerator(project_name, ai_type="local") + print(f"✓ 项目 '{project_name}' 创建成功") + print(f"✓ 项目目录: {generator.project_dir}") + + # 步骤2: 世界观设定 + print("\n步骤2: 创建世界观设定") + print("-" * 30) + + world_setting = generator.create_enhanced_world_setting() + print(f"✓ 修炼等级体系: {len(world_setting.cultivation_levels)} 个等级") + print(f"✓ 门派势力: {len(world_setting.sects)} 个门派") + print(f"✓ 地域划分: {len(world_setting.regions)} 个区域") + print(f"✓ 法宝类型: {len(world_setting.artifacts)} 种法宝") + + # 步骤3: 角色设定 + print("\n步骤3: 创建主要角色") + print("-" * 30) + + characters = generator.create_enhanced_characters() + for char in characters: + print(f"✓ {char.name} ({char.role_type}) - {char.cultivation_level}") + + # 步骤4: 整体大纲 + print("\n步骤4: 生成整体大纲") + print("-" * 30) + + target_chapters = 50 # 演示用较少章节 + outline = generator.generate_enhanced_outline(target_chapters) + print(f"✓ 生成了 {len(outline)} 章的详细大纲") + + # 显示各阶段分布 + phases = ["入门期", "成长期", "崛起期", "巅峰期"] + phase_chapters = [12, 20, 13, 5] # 演示分配 + for phase, count in zip(phases, phase_chapters): + print(f" - {phase}: {count} 章") + + # 步骤5: 生成章节内容 + print("\n步骤5: 生成章节内容") + print("-" * 30) + + # 生成前5章作为演示 + demo_chapters = 5 + for i in range(demo_chapters): + chapter = generator.generate_next_chapter() + word_count = chapter.actual_word_count + print(f"✓ 第{chapter.outline.chapter_number}章: {chapter.outline.title} ({word_count}字)") + print(f" 主要情节: {', '.join(chapter.key_plot_points)}") + print(f" 下章预告: {chapter.next_chapter_setup}") + print() + + # 步骤6: 进度报告 + print("\n步骤6: 生成进度报告") + print("-" * 30) + + report = generator.generate_progress_report() + print_progress_report(report) + + # 步骤7: 项目文件结构 + print("\n步骤7: 项目文件结构") + print("-" * 30) + + show_project_structure(generator.project_dir) + + print("\n" + "=" * 60) + print("演示完成!") + print("=" * 60) + + return generator + +def print_progress_report(report): + """打印进度报告""" + print(f"项目名称: {report['project_info']['project_name']}") + print(f"完成进度: {report['progress']['completion_rate']}") + print(f"当前阶段: {report['progress']['current_phase']}") + print(f"已完成章节: {report['progress']['current_chapter']}/{report['progress']['total_planned_chapters']}") + print(f"总字数: {report['content_stats']['total_words']:,} 字") + print(f"平均每章: {report['content_stats']['average_words_per_chapter']} 字") + print(f"预计总字数: {report['content_stats']['estimated_total_words']:,} 字") + print(f"角色数量: {report['story_elements']['main_characters_count']} 个") + print(f"门派数量: {report['story_elements']['sects_count']} 个") + +def show_project_structure(project_dir): + """显示项目文件结构""" + if not os.path.exists(project_dir): + print("项目目录不存在") + return + + print(f"项目根目录: {project_dir}") + + # 遍历目录结构 + for root, dirs, files in os.walk(project_dir): + level = root.replace(project_dir, '').count(os.sep) + indent = ' ' * 2 * level + print(f"{indent}{os.path.basename(root)}/") + + subindent = ' ' * 2 * (level + 1) + for file in files: + file_path = os.path.join(root, file) + file_size = os.path.getsize(file_path) + print(f"{subindent}{file} ({file_size} bytes)") + +def demo_chapter_generation_details(): + """演示章节生成的详细过程""" + print("\n" + "=" * 60) + print("章节生成详细过程演示") + print("=" * 60) + + # 创建一个简单的演示项目 + generator = EnhancedNovelGenerator("演示项目", ai_type="local") + + # 快速设置 + generator.create_enhanced_world_setting() + generator.create_enhanced_characters() + generator.generate_enhanced_outline(10) + + print("\n1. 生成详细章节大纲") + print("-" * 30) + + chapter_outline = generator.generate_detailed_chapter_outline(1) + print(f"章节标题: {chapter_outline.title}") + print(f"主要事件:") + for event in chapter_outline.main_events: + print(f" - {event}") + print(f"角色发展: {chapter_outline.character_development}") + print(f"剧情推进: {chapter_outline.plot_progression}") + print(f"修炼进展: {chapter_outline.cultivation_progress}") + + print("\n2. 生成章节内容") + print("-" * 30) + + chapter = generator.generate_enhanced_chapter_content(chapter_outline) + print(f"实际字数: {chapter.actual_word_count}") + print(f"关键剧情点: {', '.join(chapter.key_plot_points)}") + print(f"角色变化: {', '.join(chapter.character_changes)}") + + print("\n3. 章节内容预览") + print("-" * 30) + + # 显示章节内容的前300字 + preview = chapter.content[:300] + "..." if len(chapter.content) > 300 else chapter.content + print(preview) + + print("\n4. 章节总结") + print("-" * 30) + + print(f"本章总结: {chapter.summary}") + print(f"下章设定: {chapter.next_chapter_setup}") + +def demo_batch_generation(): + """演示批量生成功能""" + print("\n" + "=" * 60) + print("批量生成功能演示") + print("=" * 60) + + # 创建项目 + generator = EnhancedNovelGenerator("批量生成测试", ai_type="local") + + # 设置基础要素 + generator.create_enhanced_world_setting() + generator.create_enhanced_characters() + generator.generate_enhanced_outline(20) + + print("\n开始批量生成5个章节...") + print("-" * 30) + + chapters = generator.generate_batch_chapters(5) + + print(f"\n批量生成完成,共生成 {len(chapters)} 章") + + # 显示每章的基本信息 + for chapter in chapters: + print(f"第{chapter.outline.chapter_number}章: {chapter.outline.title} ({chapter.actual_word_count}字)") + + # 显示总体统计 + total_words = sum(chapter.actual_word_count for chapter in chapters) + print(f"\n总字数: {total_words}") + print(f"平均每章: {total_words // len(chapters)} 字") + +def demo_customization(): + """演示自定义功能""" + print("\n" + "=" * 60) + print("自定义功能演示") + print("=" * 60) + + # 创建自定义项目 + generator = EnhancedNovelGenerator("自定义仙侠", ai_type="local") + + print("\n1. 自定义世界观要求") + print("-" * 30) + + custom_requirements = """ + - 主要背景为现代都市修仙 + - 包含科技与修仙结合的元素 + - 有国际修仙组织设定 + - 修炼体系结合现代科学理论 + """ + + print("自定义要求:") + print(custom_requirements) + + world_setting = generator.create_enhanced_world_setting(custom_requirements) + print("✓ 基于自定义要求创建世界观") + + print("\n2. 查看生成的门派信息") + print("-" * 30) + + for sect in world_setting.sects: + print(f"门派: {sect['name']} ({sect['type']})") + print(f" 特色: {sect['specialty']}") + print(f" 位置: {sect['location']}") + print() + +def main(): + """主函数 - 运行所有演示""" + print("欢迎使用修仙小说AI生成系统!") + print("\n可用的演示选项:") + print("1. 完整工作流程演示") + print("2. 章节生成详细过程") + print("3. 批量生成功能") + print("4. 自定义功能演示") + print("5. 运行所有演示") + + choice = input("\n请选择要运行的演示 (1-5): ").strip() + + if choice == "1": + demo_complete_workflow() + elif choice == "2": + demo_chapter_generation_details() + elif choice == "3": + demo_batch_generation() + elif choice == "4": + demo_customization() + elif choice == "5": + demo_complete_workflow() + demo_chapter_generation_details() + demo_batch_generation() + demo_customization() + else: + print("无效选择,运行完整演示...") + demo_complete_workflow() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/enhanced_novel_generator.py b/enhanced_novel_generator.py new file mode 100644 index 0000000..34f80b5 --- /dev/null +++ b/enhanced_novel_generator.py @@ -0,0 +1,793 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import json +import os +import datetime +import logging +from typing import Dict, List, Any, Optional +from dataclasses import dataclass, asdict + +from novel_generator import NovelGenerator, WorldSetting, Character, ChapterOutline, Chapter +from ai_content_generator import create_ai_generator, AIContentGenerator + +class EnhancedNovelGenerator(NovelGenerator): + """增强版修仙小说生成器""" + + def __init__(self, project_name: str, ai_type: str = "local", ai_api_key: Optional[str] = None): + super().__init__(project_name) + self.ai_generator = create_ai_generator(ai_type, ai_api_key) + self.chapter_history = [] # 存储章节历史记录 + self.generation_log = [] # 生成日志 + + def log_generation_step(self, step: str, details: str): + """记录生成步骤""" + log_entry = { + 'timestamp': datetime.datetime.now().isoformat(), + 'step': step, + 'details': details + } + self.generation_log.append(log_entry) + logging.info(f"{step}: {details}") + + def create_enhanced_world_setting(self, custom_requirements: str = "") -> WorldSetting: + """创建增强的世界观设定""" + self.log_generation_step("世界观设定", "开始创建详细世界观") + + prompt = self.ai_generator.generate_world_setting_prompt() + if custom_requirements: + prompt += f"\n\n特殊要求:\n{custom_requirements}" + + # 如果使用AI生成,这里调用AI API + # ai_response = self.ai_generator.generate_content(prompt) + + # 目前使用增强的默认模板 + world_setting = WorldSetting( + cultivation_levels=[ + "凡人", "练气初期", "练气中期", "练气后期", "练气大圆满", + "筑基初期", "筑基中期", "筑基后期", "筑基大圆满", + "金丹初期", "金丹中期", "金丹后期", "金丹大圆满", + "元婴初期", "元婴中期", "元婴后期", "元婴大圆满", + "化神初期", "化神中期", "化神后期", "化神大圆满", + "合体初期", "合体中期", "合体后期", "合体大圆满", + "大乘初期", "大乘中期", "大乘后期", "大乘大圆满", + "渡劫初期", "渡劫中期", "渡劫后期", "渡劫大圆满", + "真仙", "金仙", "太乙金仙", "大罗金仙", "仙帝" + ], + sects=[ + { + "name": "青云门", + "type": "正派", + "specialty": "剑修", + "location": "青云山脉", + "strength": "超级势力", + "founder": "青云真仙", + "disciples": 50000, + "territory": "东荒三分之一" + }, + { + "name": "天音宗", + "type": "正派", + "specialty": "音律修炼", + "location": "天音谷", + "strength": "一流势力", + "founder": "天音仙子", + "disciples": 30000, + "territory": "中州北部" + }, + { + "name": "魔音寺", + "type": "邪派", + "specialty": "魔音攻击", + "location": "黑风谷", + "strength": "一流势力", + "founder": "魔音老祖", + "disciples": 20000, + "territory": "西漠边缘" + }, + { + "name": "万药谷", + "type": "中立", + "specialty": "炼丹医道", + "location": "药王山", + "strength": "超级势力", + "founder": "药王仙人", + "disciples": 15000, + "territory": "南荒核心" + }, + { + "name": "器宗", + "type": "中立", + "specialty": "炼器制宝", + "location": "炼器峰", + "strength": "一流势力", + "founder": "器祖", + "disciples": 10000, + "territory": "北冥火山" + } + ], + regions=[ + { + "name": "东荒", + "type": "修仙圣地", + "features": ["灵气最浓郁", "宗门最多", "天才辈出"], + "dangers": ["妖兽王者", "上古秘境", "天劫频繁"], + "special_locations": ["青云山", "万兽森林", "无极海"] + }, + { + "name": "中州", + "type": "繁华地带", + "features": ["交通枢纽", "贸易中心", "文化荟萃"], + "dangers": ["势力复杂", "暗流涌动", "争斗不断"], + "special_locations": ["天音谷", "帝都", "拍卖行"] + }, + { + "name": "西漠", + "type": "荒凉之地", + "features": ["环境恶劣", "邪修聚集", "宝物埋藏"], + "dangers": ["魔修横行", "沙暴肆虐", "诅咒之地"], + "special_locations": ["黑风谷", "血沙漠", "镇魔塔"] + }, + { + "name": "南荒", + "type": "原始森林", + "features": ["古树参天", "灵药遍地", "部族众多"], + "dangers": ["毒虫猛兽", "瘴气弥漫", "古咒陷阱"], + "special_locations": ["药王山", "毒龙潭", "精灵王国"] + }, + { + "name": "北冥", + "type": "极地冰原", + "features": ["千年不化", "寒气逼人", "矿藏丰富"], + "dangers": ["极寒之力", "冰魄妖兽", "雪崩冰裂"], + "special_locations": ["炼器峰", "冰宫", "玄冰洞"] + } + ], + magic_system={ + "five_elements": { + "金": {"properties": "锋利、坚硬", "colors": "金白", "creatures": "金鸾"}, + "木": {"properties": "生长、治愈", "colors": "青绿", "creatures": "青龙"}, + "水": {"properties": "柔韧、变化", "colors": "蓝黑", "creatures": "玄武"}, + "火": {"properties": "炽热、毁灭", "colors": "红橙", "creatures": "朱雀"}, + "土": {"properties": "厚重、防御", "colors": "黄褐", "creatures": "白虎"} + }, + "special_paths": { + "剑道": {"difficulty": "困难", "power": "极高", "description": "以剑为本,剑心通明"}, + "丹道": {"difficulty": "极难", "power": "辅助", "description": "炼制丹药,医人救世"}, + "阵法": {"difficulty": "极难", "power": "群攻", "description": "布置阵法,困敌杀敌"}, + "符箓": {"difficulty": "中等", "power": "中等", "description": "制作符箓,快速施法"}, + "炼器": {"difficulty": "困难", "power": "辅助", "description": "炼制法宝,装备提升"}, + "驭兽": {"difficulty": "中等", "power": "中高", "description": "驯服妖兽,并肩作战"}, + "音律": {"difficulty": "困难", "power": "群攻", "description": "以音为攻,乱人心智"} + }, + "cultivation_resources": { + "灵石": ["下品", "中品", "上品", "极品", "仙石"], + "丹药": ["聚气丹", "筑基丹", "结金丹", "破婴丹", "化神丹"], + "功法": ["黄级", "玄级", "地级", "天级", "仙级"], + "法宝": ["法器", "宝器", "灵器", "仙器", "先天灵宝"] + } + }, + artifacts=[ + { + "name": "青锋剑", + "grade": "上品法器", + "description": "锋利无比的飞剑,可破金断石", + "origin": "青云门传承宝物" + }, + { + "name": "炼心鼎", + "grade": "极品宝器", + "description": "炼丹神鼎,可提高丹药品质", + "origin": "万药谷镇谷之宝" + }, + { + "name": "天音琴", + "grade": "灵器", + "description": "音律攻击法宝,琴音杀人于无形", + "origin": "天音宗传承至宝" + } + ], + background_story=""" +这是一个修仙者追求长生不老的世界。天地分为五大区域:东荒、中州、西漠、南荒、北冥。 +东荒灵气最为浓郁,是各大正派宗门的聚集地,其中青云门实力最强。 +中州为各势力交汇之地,既有繁华也有暗流。 +西漠环境恶劣,多为邪修盘踞。 +南荒原始森林密布,隐藏着古老的秘密。 +北冥冰天雪地,是炼器师的天堂。 + +在这个世界中,修仙者按修为分为练气、筑基、金丹、元婴、化神、合体、大乘、渡劫、真仙等境界。 +每个境界又分初期、中期、后期、大圆满四个小境界。 +修仙者可以修炼五行法术,也可以专精剑道、丹道、阵法等特殊道路。 + +千年前,魔道大兴,正邪大战,最终正道获胜,邪修退居西漠。 +但近年来又有魔道复苏的迹象,暗流涌动,大世将临... +""" + ) + + self.world_setting = world_setting + self.save_world_setting() + self.log_generation_step("世界观设定", "详细世界观创建完成") + return world_setting + + def create_enhanced_characters(self) -> List[Character]: + """创建增强的角色设定""" + self.log_generation_step("角色设定", "开始创建主要角色") + + characters = [ + # 主角 + Character( + name="林逸", + age=18, + gender="男", + cultivation_level="凡人", + personality="坚韧不拔,重情重义,天赋异禀,心思敏捷", + background="出身贫寒山村,父母早亡,意外获得修仙传承", + relationships=[], + abilities=["极品五行灵根", "过目不忘", "天生剑心", "超强悟性"], + goals="成为绝世强者,保护重要的人,探索修仙大道", + role_type="主角" + ), + + # 师父 + Character( + name="玄机真人", + age=800, + gender="男", + cultivation_level="化神后期", + personality="睿智深沉,亦师亦友,神秘莫测", + background="青云门太上长老,隐世高人,主角的引路人", + relationships=[{"relation": "师父", "target": "林逸"}], + abilities=["阵法大师", "丹道宗师", "剑道通神", "占卜预知"], + goals="培养优秀弟子,守护青云门", + role_type="导师" + ), + + # 青梅竹马/女主角 + Character( + name="苏婉儿", + age=17, + gender="女", + cultivation_level="练气期", + personality="温柔善良,聪慧坚强,对主角情深", + background="同村少女,与主角青梅竹马,也有修仙天赋", + relationships=[{"relation": "青梅竹马", "target": "林逸"}], + abilities=["上品水灵根", "医术精通", "心灵手巧"], + goals="跟随林逸修仙,成为他的助力", + role_type="女主角" + ), + + # 师兄 + Character( + name="张浩然", + age=25, + gender="男", + cultivation_level="筑基中期", + personality="豪爽正直,义薄云天,护短", + background="青云门内门弟子,主角的师兄", + relationships=[{"relation": "师兄", "target": "林逸"}], + abilities=["上品金灵根", "剑法精湛", "领导能力强"], + goals="保护师弟,振兴青云门", + role_type="师兄" + ), + + # 反派师兄 + Character( + name="李冥", + age=30, + gender="男", + cultivation_level="筑基后期", + personality="阴险狡诈,嫉妒心重,心狠手辣", + background="青云门内门弟子,因嫉妒主角天赋而生恨", + relationships=[{"relation": "敌对师兄", "target": "林逸"}], + abilities=["中品火灵根", "阴毒功法", "诡计多端"], + goals="除掉林逸,获得更多资源", + role_type="早期反派" + ), + + # 门派长老 + Character( + name="青云子", + age=1200, + gender="男", + cultivation_level="合体初期", + personality="威严慈祥,公正严明,德高望重", + background="青云门掌门,实力强大的修仙者", + relationships=[{"relation": "掌门", "target": "林逸"}], + abilities=["极品风灵根", "青云剑诀", "门派管理"], + goals="守护青云门,培养后辈", + role_type="门派长者" + ), + + # 主要反派 + Character( + name="血魔老祖", + age=2000, + gender="男", + cultivation_level="大乘中期", + personality="嗜血残忍,野心勃勃,城府极深", + background="魔道巨擘,千年前正邪大战的幸存者", + relationships=[{"relation": "宿敌", "target": "林逸"}], + abilities=["血道魔功", "魅惑之术", "不死之身"], + goals="魔道复兴,统治修仙界", + role_type="最终反派" + ) + ] + + self.characters = characters + self.save_characters() + self.log_generation_step("角色设定", f"创建了{len(characters)}个主要角色") + return self.characters + + def generate_enhanced_outline(self, target_chapters: int = 300) -> List[ChapterOutline]: + """生成增强的整体大纲""" + self.log_generation_step("大纲生成", f"开始生成{target_chapters}章的详细大纲") + + # 详细的阶段规划 + phases = [ + { + "name": "入门期", + "chapters": 50, + "theme": "获得机缘,初入修仙世界", + "key_events": ["获得传承", "拜入青云门", "初次修炼", "同门交往", "小试身手"], + "cultivation_range": ["凡人", "练气大圆满"], + "main_conflicts": ["资质怀疑", "门内竞争", "基础挑战"] + }, + { + "name": "成长期", + "chapters": 100, + "theme": "历练成长,结识伙伴", + "key_events": ["门派试炼", "秘境探险", "结识盟友", "初恋情愫", "强敌出现"], + "cultivation_range": ["筑基初期", "金丹初期"], + "main_conflicts": ["生死历练", "情感纠葛", "宗门危机"] + }, + { + "name": "崛起期", + "chapters": 100, + "theme": "声名鹊起,面临大敌", + "key_events": ["名震一方", "跨域冒险", "强者对决", "门派大战", "身世揭秘"], + "cultivation_range": ["金丹中期", "元婴后期"], + "main_conflicts": ["正邪对立", "权力斗争", "命运抉择"] + }, + { + "name": "巅峰期", + "chapters": 50, + "theme": "巅峰对决,拯救世界", + "key_events": ["魔道复苏", "最终决战", "牺牲拯救", "大道圆满", "飞升成仙"], + "cultivation_range": ["化神期", "真仙"], + "main_conflicts": ["存亡之战", "道心考验", "终极选择"] + } + ] + + outlines = [] + chapter_num = 1 + + for phase in phases: + chapters_per_event = phase["chapters"] // len(phase["key_events"]) + + for i, event in enumerate(phase["key_events"]): + for j in range(chapters_per_event): + if chapter_num > target_chapters: + break + + # 计算修炼进度 + progress = (i * chapters_per_event + j) / phase["chapters"] + + outline = ChapterOutline( + chapter_number=chapter_num, + title=f"第{chapter_num}章 {event}相关情节", + main_events=[f"{event}的具体展开", "角色互动", "剧情推进"], + character_development=f"主角在{phase['name']}的成长", + plot_progression=f"推进{event}相关剧情", + cultivation_progress=f"修为提升-{phase['cultivation_range'][0]}向{phase['cultivation_range'][1]}发展", + conflicts=phase["main_conflicts"], + estimated_word_count=3000 + ) + outlines.append(outline) + chapter_num += 1 + + self.overall_outline = outlines[:target_chapters] + self.save_overall_outline() + self.log_generation_step("大纲生成", f"生成了{len(self.overall_outline)}章的详细大纲") + return self.overall_outline + + def generate_detailed_chapter_outline(self, chapter_number: int) -> ChapterOutline: + """生成详细章节大纲""" + self.log_generation_step("详细大纲", f"生成第{chapter_number}章的详细大纲") + + if chapter_number > len(self.overall_outline): + raise ValueError(f"章节号{chapter_number}超出范围") + + base_outline = self.overall_outline[chapter_number - 1] + + # 根据章节位置和前面章节的内容生成更详细的大纲 + previous_summary = "" + if self.chapters: + previous_summary = self.chapters[-1].summary if self.chapters else "故事开始" + + # 生成具体的章节内容大纲 + if chapter_number == 1: + detailed_outline = ChapterOutline( + chapter_number=1, + title="第一章 山村少年", + main_events=[ + "介绍主角林逸的出身和现状", + "展现山村的贫困生活", + "意外发现修仙传承", + "决心踏上修仙之路" + ], + character_development="从普通山村少年到有志修仙者的转变", + plot_progression="故事开端,为后续修仙之路做铺垫", + cultivation_progress="尚未开始修炼,但获得修仙机缘", + conflicts=["内心的渴望与现实的差距", "对未知世界的恐惧"], + estimated_word_count=3000 + ) + elif chapter_number <= 10: + detailed_outline = ChapterOutline( + chapter_number=chapter_number, + title=f"第{chapter_number}章 初入修仙", + main_events=[ + "学习基础修炼知识", + "第一次感应灵气", + "遇到修仙界的人或事", + "对修仙世界的初步了解" + ], + character_development="逐渐适应修仙者的身份", + plot_progression="建立修仙世界观,为拜师做准备", + cultivation_progress="练气初期的修炼", + conflicts=["修炼的困难", "对力量的渴望"], + estimated_word_count=3000 + ) + else: + # 基于基础大纲生成详细内容 + detailed_outline = ChapterOutline( + chapter_number=chapter_number, + title=f"第{chapter_number}章 " + base_outline.title.split(' ')[-1] if ' ' in base_outline.title else base_outline.title, + main_events=base_outline.main_events, + character_development=base_outline.character_development, + plot_progression=base_outline.plot_progression, + cultivation_progress=base_outline.cultivation_progress, + conflicts=base_outline.conflicts, + estimated_word_count=3000 + ) + + return detailed_outline + + def generate_enhanced_chapter_content(self, chapter_outline: ChapterOutline) -> Chapter: + """生成增强的章节内容""" + self.log_generation_step("内容生成", f"生成第{chapter_outline.chapter_number}章的内容") + + # 获取前面章节的内容摘要用于保持连贯性 + previous_content = "" + if self.chapters: + previous_content = self.chapters[-1].content[-500:] # 获取上一章的最后500字 + + # 生成章节内容的提示词 + prompt = self.ai_generator.generate_chapter_content_prompt( + chapter_outline, + self.world_setting, + self.characters, + previous_content + ) + + # 调用AI生成内容(这里使用模板,实际可以接入AI API) + content = self._generate_specific_chapter_content(chapter_outline.chapter_number) + + # 分析生成的内容,提取关键信息 + key_plot_points = self._extract_plot_points(content) + character_changes = self._extract_character_changes(content, chapter_outline.chapter_number) + next_chapter_setup = self._generate_next_chapter_setup(chapter_outline.chapter_number) + summary = self._generate_chapter_summary(content, chapter_outline.chapter_number) + + chapter = Chapter( + outline=chapter_outline, + content=content, + actual_word_count=len(content), + key_plot_points=key_plot_points, + character_changes=character_changes, + next_chapter_setup=next_chapter_setup, + summary=summary + ) + + self.log_generation_step("内容生成", f"第{chapter_outline.chapter_number}章内容生成完成,共{len(content)}字") + return chapter + + def _generate_specific_chapter_content(self, chapter_number: int) -> str: + """生成特定章节的内容""" + if chapter_number == 1: + return """ +第一章 山村少年 + +  青山如黛,白云悠悠。 + +  在东荒边陲的一个小山村里,一个十八岁的少年正坐在村口的大石头上,望着远方连绵不绝的青云山脉,眼中满含着向往和不甘。 + +  这少年名叫林逸,出身贫寒,父母早亡,只靠着村里的接济勉强度日。虽然生活艰难,但他从小就聪慧过人,听村里的老人讲述修仙者的传说时,总是听得最认真的那一个。 + +  "要是我也能修仙就好了..."林逸轻声自语,目光中闪过一丝渴望。 + +  就在这时,一阵奇异的光芒从山林深处传来,紧接着是一声惊天动地的巨响! + +  林逸心中一惊,本能地向光芒传来的方向看去,只见山林中有一道金光冲天而起,随即又迅速消失不见。 + +  "那是什么?"林逸喃喃自语,心中涌起一股强烈的好奇心。 + +  犹豫了片刻,林逸还是决定去看看。他沿着山路向着光芒消失的地方走去,越走越深入,不知不觉已经来到了平时很少有人涉足的深山之中。 + +  在一个隐蔽的山洞里,林逸发现了一个身着道袍、仙风道骨的老者。老者已经没有了呼吸,但脸上却带着安详的笑容。 + +  在老者身边,有一枚散发着微光的玉简。 + +  林逸小心翼翼地拿起玉简,刚一触碰,大量的信息就涌入了他的脑海:《基础练气法》、修仙者的等级、灵根的重要性... + +  原来,这位老者是一位修仙者,在寿元将尽之时回到此地,留下了自己的传承。 + +  "这...这是真的吗?"林逸的手在颤抖,不敢相信自己竟然如此幸运。 + +  按照玉简中的记录,林逸开始尝试感应天地灵气。令他惊喜的是,他竟然很快就感应到了丝丝缕缕的灵气! + +  "我真的可以修仙!"林逸激动得几乎要跳起来。 + +  从这一刻起,他知道自己的命运将彻底改变。他要走出这个小山村,去见识更广阔的修仙世界! + +  夜幕降临,林逸怀着激动的心情回到村中,开始暗自修炼起来。他知道,这只是万里长征的第一步,前路充满未知和挑战,但他已经做好了准备。 + +  修仙之路,从此开始! +""" + elif chapter_number == 2: + return """ +第二章 初修练气 + +  接下来的几天里,林逸一边维持着平常的生活,一边暗中修炼着《基础练气法》。 + +  每当夜深人静的时候,他就会按照玉简中的法门,尝试感应和吸收天地间的灵气。 + +  修炼的过程比想象中更加困难。灵气虽然存在,但想要将其引入体内并加以炼化,却需要极大的专注力和毅力。 + +  "呼..."林逸睁开眼睛,额头已经渗出了细密的汗珠。 + +  经过三天的努力,他终于成功地将一丝灵气引入了体内,虽然微弱,但这已经是巨大的进步了。 + +  "按照玉简中的记载,我现在算是踏入了练气期的门槛。"林逸心中欣喜,但很快又冷静下来。 + +  他知道这只是开始,练气期分为九个层次,而他现在连第一层都没有稳固。 + +  更重要的是,他需要更好的修炼环境和资源。村子里的灵气实在太稀薄了,而且他也不能一直隐瞒自己的修炼。 + +  正当林逸为未来的修炼之路发愁时,村子里来了一个意想不到的客人。 + +  那是一个中年道士,仙风道骨,眼神深邃,身上散发着一股让人不敢直视的威压。 + +  "这位道长,您这是?"村长小心翼翼地询问着。 + +  "贫道路过此地,感应到这里有修仙的气息,特来查看一二。"道士的声音平和,但林逸听了却心中一紧。 + +  难道是自己修炼的事情被发现了? + +  道士的目光在村民中扫过,最终停留在了林逸身上。 + +  "就是你吧,小友。"道士微微一笑,"贫道青云门外门长老王青松,感应到你身上有修仙者的气息。" + +  林逸的心跳加速,但还是硬着头皮上前行礼:"晚辈林逸,见过道长。" + +  王青松仔细打量着林逸,突然伸出手按在了他的手腕上。一股温和的真元流入林逸体内,探查着他的情况。 + +  "有趣..."王青松收回手,眼中闪过一丝惊讶,"小友不仅有修仙根基,而且是极品五行灵根!这等天赋,万中无一啊!" + +  "什么是五行灵根?"林逸疑惑地问道。 + +  "灵根是修仙者的天赋所在,分为金木水火土五行。普通人能有一种上品灵根就已经很了不起了,而你竟然五种灵根俱全,且都是极品!"王青松越说越激动,"小友,你可愿意拜入我青云门?" + +  林逸心中狂喜,但表面还是保持冷静:"青云门是什么样的门派?" + +  "青云门乃是东荒第一大派,门中弟子十万余人,实力强大。如果你能拜入门中,必定前途无量!" + +  林逸没有立即答应,而是问道:"那我需要做什么?" + +  "三日后,青云门将在此地举行入门考核。以你的天赋,通过考核不在话下。"王青松说道,"不过在此之前,你还需要将修为稍作提升,至少要达到练气期一层。" + +  "多谢道长指点!"林逸心中感激不已。 + +  王青松点点头,留下了一瓶丹药和一本更详细的修炼法决后便离开了。 + +  看着道士远去的身影,林逸握紧了拳头。三天时间,他要全力冲击练气期一层! + +  修仙世界的大门,即将向他敞开! +""" + else: + # 其他章节使用通用模板 + return f""" +第{chapter_number}章 修炼之路 + +  随着修为的不断提升,林逸对修仙世界的了解也越来越深入。 + +  在青云门的这段时间里,他不仅学会了更多的修炼法门,还结识了许多志同道合的师兄弟。 + +  然而,修仙之路从来不是一帆风顺的。在这个强者为尊的世界里,每一步都充满了挑战和危险。 + +  今日,林逸又将面临新的考验... + +  "林师弟,听说今天有一个重要的任务需要我们去完成。"张浩然走过来对林逸说道。 + +  "什么任务?"林逸询问。 + +  "据说是门派附近出现了妖兽作乱,需要我们去清除。这对我们来说既是任务,也是历练的好机会。" + +  林逸点点头,心中既有紧张也有期待。自从修炼以来,他还没有真正经历过实战,这次正好是检验自己实力的机会。 + +  准备好必要的法器和丹药后,几人踏上了执行任务的道路... + +  (此处为第{chapter_number}章的内容,实际使用时会根据具体大纲生成更详细的内容) +""" + + def _extract_plot_points(self, content: str) -> List[str]: + """从内容中提取关键剧情点""" + # 简单的关键词提取,实际可以用NLP技术 + plot_points = [] + if "修仙" in content: + plot_points.append("修仙相关情节") + if "青云门" in content: + plot_points.append("青云门相关") + if "灵根" in content: + plot_points.append("天赋展现") + if "考核" in content: + plot_points.append("入门考核") + + return plot_points or ["主要剧情推进"] + + def _extract_character_changes(self, content: str, chapter_number: int) -> List[str]: + """提取角色变化""" + changes = [] + if chapter_number == 1: + changes = ["林逸获得修仙传承", "从普通人向修仙者转变"] + elif chapter_number == 2: + changes = ["林逸开始正式修炼", "被青云门长老发现"] + else: + changes = ["角色实力或认知的进一步发展"] + + return changes + + def _generate_next_chapter_setup(self, chapter_number: int) -> str: + """生成下一章的铺垫""" + if chapter_number == 1: + return "林逸将开始正式修炼,为加入修仙门派做准备" + elif chapter_number == 2: + return "林逸将参加青云门的入门考核" + else: + return f"第{chapter_number + 1}章将继续推进主线剧情,角色面临新的挑战" + + def _generate_chapter_summary(self, content: str, chapter_number: int) -> str: + """生成章节总结""" + if chapter_number == 1: + return "第1章:林逸在山村发现修仙传承,获得《基础练气法》,决心踏上修仙之路。" + elif chapter_number == 2: + return "第2章:林逸开始修炼,被青云门长老发现其极品五行灵根的天赋,获得入门考核机会。" + else: + return f"第{chapter_number}章:主角修炼成长,剧情继续推进。" + + def generate_progress_report(self) -> Dict[str, Any]: + """生成详细的进度报告""" + total_words = sum(chapter.actual_word_count for chapter in self.chapters) + + # 计算各阶段进度 + phase_progress = {} + current_phase = "入门期" + if self.current_chapter > 50: + current_phase = "成长期" + if self.current_chapter > 150: + current_phase = "崛起期" + if self.current_chapter > 250: + current_phase = "巅峰期" + + report = { + 'project_info': { + 'project_name': self.project_name, + 'creation_time': datetime.datetime.now().isoformat(), + 'ai_type': self.ai_generator.api_type + }, + 'progress': { + 'current_chapter': self.current_chapter, + 'total_planned_chapters': len(self.overall_outline), + 'completion_rate': f"{(self.current_chapter / len(self.overall_outline) * 100):.1f}%", + 'current_phase': current_phase + }, + 'content_stats': { + 'total_words': total_words, + 'average_words_per_chapter': total_words // max(1, len(self.chapters)), + 'estimated_total_words': len(self.overall_outline) * 3000, + 'estimated_remaining_words': (len(self.overall_outline) - self.current_chapter) * 3000 + }, + 'story_elements': { + 'world_setting_created': self.world_setting is not None, + 'main_characters_count': len(self.characters), + 'cultivation_levels': len(self.world_setting.cultivation_levels) if self.world_setting else 0, + 'sects_count': len(self.world_setting.sects) if self.world_setting else 0 + }, + 'latest_chapter': { + 'summary': self.chapters[-1].summary if self.chapters else "暂无章节", + 'key_points': self.chapters[-1].key_plot_points if self.chapters else [], + 'next_setup': self.chapters[-1].next_chapter_setup if self.chapters else "" + }, + 'generation_log': self.generation_log[-10:] # 最近10条日志 + } + + return report + + def save_detailed_project_state(self): + """保存详细的项目状态""" + # 保存基础状态 + super().save_project_state() + + # 保存额外的详细信息 + detailed_state = { + 'chapter_history': self.chapter_history, + 'generation_log': self.generation_log, + 'ai_generator_type': self.ai_generator.api_type, + 'enhanced_features': True + } + + with open(f"{self.project_dir}/detailed_state.json", 'w', encoding='utf-8') as f: + json.dump(detailed_state, f, ensure_ascii=False, indent=2) + + def generate_batch_chapters(self, count: int) -> List[Chapter]: + """批量生成多个章节""" + self.log_generation_step("批量生成", f"开始批量生成{count}个章节") + + generated_chapters = [] + + for i in range(count): + try: + chapter = self.generate_next_chapter() + generated_chapters.append(chapter) + + # 保存每个章节后更新状态 + self.save_detailed_project_state() + + self.log_generation_step("批量生成", f"第{chapter.outline.chapter_number}章生成完成") + + except Exception as e: + self.log_generation_step("批量生成", f"第{self.current_chapter + 1}章生成失败: {str(e)}") + break + + self.log_generation_step("批量生成", f"批量生成完成,共生成{len(generated_chapters)}章") + return generated_chapters + +if __name__ == "__main__": + # 示例使用增强版生成器 + print("=== 增强版修仙小说生成系统 ===") + + # 创建生成器实例 + generator = EnhancedNovelGenerator("修仙传说", ai_type="local") + + # 完整流程演示 + try: + # 1. 创建世界观 + world = generator.create_enhanced_world_setting() + print("✓ 增强世界观设定完成") + + # 2. 创建角色 + characters = generator.create_enhanced_characters() + print(f"✓ 创建了{len(characters)}个主要角色") + + # 3. 生成整体大纲 + outline = generator.generate_enhanced_outline(300) + print(f"✓ 生成了{len(outline)}章的详细大纲") + + # 4. 生成前几章 + for i in range(3): + chapter = generator.generate_next_chapter() + print(f"✓ 第{chapter.outline.chapter_number}章生成完成") + + # 5. 生成详细报告 + report = generator.generate_progress_report() + print("\n=== 详细进度报告 ===") + print(f"项目名称: {report['project_info']['project_name']}") + print(f"当前进度: {report['progress']['completion_rate']}") + print(f"总字数: {report['content_stats']['total_words']}") + print(f"当前阶段: {report['progress']['current_phase']}") + print(f"最新章节: {report['latest_chapter']['summary']}") + + print("\n✓ 小说生成系统演示完成!") + + except Exception as e: + print(f"✗ 生成过程中出现错误: {str(e)}") + logging.error(f"生成错误: {str(e)}") \ No newline at end of file diff --git a/novel_generator.py b/novel_generator.py new file mode 100644 index 0000000..9ae2e9c --- /dev/null +++ b/novel_generator.py @@ -0,0 +1,405 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import json +import os +import datetime +from typing import Dict, List, Any +from dataclasses import dataclass, asdict +import logging + +# 配置日志 +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +@dataclass +class WorldSetting: + """世界观设定""" + cultivation_levels: List[str] # 修炼等级 + sects: List[Dict[str, Any]] # 门派信息 + regions: List[Dict[str, Any]] # 地域设定 + magic_system: Dict[str, Any] # 法术体系 + artifacts: List[Dict[str, Any]] # 法宝设定 + background_story: str # 背景故事 + +@dataclass +class Character: + """角色设定""" + name: str + age: int + gender: str + cultivation_level: str + personality: str + background: str + relationships: List[Dict[str, str]] + abilities: List[str] + goals: str + role_type: str # 主角、配角、反派等 + +@dataclass +class ChapterOutline: + """章节大纲""" + chapter_number: int + title: str + main_events: List[str] + character_development: str + plot_progression: str + cultivation_progress: str + conflicts: List[str] + estimated_word_count: int + +@dataclass +class Chapter: + """完整章节""" + outline: ChapterOutline + content: str + actual_word_count: int + key_plot_points: List[str] + character_changes: List[str] + next_chapter_setup: str + summary: str + +class NovelGenerator: + """修仙小说生成器主类""" + + def __init__(self, project_name: str): + self.project_name = project_name + self.project_dir = f"novel_projects/{project_name}" + self.world_setting: WorldSetting = None + self.characters: List[Character] = [] + self.overall_outline: List[ChapterOutline] = [] + self.chapters: List[Chapter] = [] + self.current_chapter = 0 + + # 创建项目目录 + os.makedirs(self.project_dir, exist_ok=True) + os.makedirs(f"{self.project_dir}/chapters", exist_ok=True) + os.makedirs(f"{self.project_dir}/settings", exist_ok=True) + + def save_project_state(self): + """保存项目状态""" + state = { + 'project_name': self.project_name, + 'current_chapter': self.current_chapter, + 'world_setting': asdict(self.world_setting) if self.world_setting else None, + 'characters': [asdict(char) for char in self.characters], + 'overall_outline': [asdict(outline) for outline in self.overall_outline], + 'last_updated': datetime.datetime.now().isoformat() + } + + with open(f"{self.project_dir}/project_state.json", 'w', encoding='utf-8') as f: + json.dump(state, f, ensure_ascii=False, indent=2) + + def load_project_state(self): + """加载项目状态""" + state_file = f"{self.project_dir}/project_state.json" + if os.path.exists(state_file): + with open(state_file, 'r', encoding='utf-8') as f: + state = json.load(f) + + self.current_chapter = state.get('current_chapter', 0) + + if state.get('world_setting'): + self.world_setting = WorldSetting(**state['world_setting']) + + self.characters = [Character(**char_data) for char_data in state.get('characters', [])] + self.overall_outline = [ChapterOutline(**outline_data) for outline_data in state.get('overall_outline', [])] + + def create_world_setting(self) -> WorldSetting: + """第一步:创建世界观设定""" + logging.info("开始创建世界观设定...") + + # 默认修仙世界观模板 + world_setting = WorldSetting( + cultivation_levels=[ + "凡人", "练气期", "筑基期", "金丹期", "元婴期", + "化神期", "合体期", "大乘期", "渡劫期", "真仙" + ], + sects=[ + { + "name": "青云门", + "type": "正派", + "specialty": "剑修", + "location": "青云山", + "strength": "强大" + }, + { + "name": "魔音寺", + "type": "邪派", + "specialty": "音律攻击", + "location": "黑风谷", + "strength": "中等" + } + ], + regions=[ + { + "name": "东荒", + "type": "修仙圣地", + "features": ["灵气浓郁", "宗门林立", "机缘众多"], + "dangers": ["妖兽横行", "秘境危险"] + } + ], + magic_system={ + "five_elements": ["金", "木", "水", "火", "土"], + "special_paths": ["剑道", "丹道", "阵法", "符箓", "炼器"], + "cultivation_resources": ["灵石", "丹药", "功法", "法宝"] + }, + artifacts=[ + { + "name": "青锋剑", + "grade": "法器", + "description": "锋利无比的飞剑" + } + ], + background_story="这是一个修仙者追求长生不老的世界,强者为尊,弱肉强食..." + ) + + self.world_setting = world_setting + self.save_world_setting() + logging.info("世界观设定创建完成") + return world_setting + + def save_world_setting(self): + """保存世界观设定""" + if self.world_setting: + with open(f"{self.project_dir}/settings/world_setting.json", 'w', encoding='utf-8') as f: + json.dump(asdict(self.world_setting), f, ensure_ascii=False, indent=2) + + def create_main_characters(self) -> List[Character]: + """第二步:创建主要角色""" + logging.info("开始创建主要角色...") + + # 主角设定 + protagonist = Character( + name="林逸", + age=18, + gender="男", + cultivation_level="凡人", + personality="坚韧不拔,重情重义,天赋异禀", + background="出身贫寒,意外获得修仙机缘", + relationships=[], + abilities=["超强感知力", "快速修炼"], + goals="成为绝世强者,保护重要的人", + role_type="主角" + ) + + # 主要配角 + mentor = Character( + name="玄机老人", + age=800, + gender="男", + cultivation_level="化神期", + personality="睿智深沉,亦师亦友", + background="隐世高人,主角的引路人", + relationships=[{"relation": "师父", "target": "林逸"}], + abilities=["阵法大师", "丹道宗师"], + goals="培养优秀弟子", + role_type="导师" + ) + + self.characters = [protagonist, mentor] + self.save_characters() + logging.info("主要角色创建完成") + return self.characters + + def save_characters(self): + """保存角色设定""" + characters_data = [asdict(char) for char in self.characters] + with open(f"{self.project_dir}/settings/characters.json", 'w', encoding='utf-8') as f: + json.dump(characters_data, f, ensure_ascii=False, indent=2) + + def generate_overall_outline(self, target_chapters: int = 300) -> List[ChapterOutline]: + """第三步:生成整体大纲""" + logging.info(f"开始生成{target_chapters}章的整体大纲...") + + # 分阶段规划 + phases = [ + {"name": "入门期", "chapters": 50, "theme": "获得机缘,初入修仙世界"}, + {"name": "成长期", "chapters": 100, "theme": "历练成长,结识伙伴"}, + {"name": "崛起期", "chapters": 100, "theme": "声名鹊起,面临大敌"}, + {"name": "巅峰期", "chapters": 50, "theme": "巅峰对决,拯救世界"} + ] + + outlines = [] + chapter_num = 1 + + for phase in phases: + for i in range(phase["chapters"]): + outline = ChapterOutline( + chapter_number=chapter_num, + title=f"第{chapter_num}章", + main_events=[f"{phase['theme']}相关情节"], + character_development="主角实力和心境成长", + plot_progression="推进主线剧情", + cultivation_progress="修为提升", + conflicts=["内在冲突", "外在挑战"], + estimated_word_count=3000 + ) + outlines.append(outline) + chapter_num += 1 + + self.overall_outline = outlines[:target_chapters] + self.save_overall_outline() + logging.info("整体大纲生成完成") + return self.overall_outline + + def save_overall_outline(self): + """保存整体大纲""" + outlines_data = [asdict(outline) for outline in self.overall_outline] + with open(f"{self.project_dir}/overall_outline.json", 'w', encoding='utf-8') as f: + json.dump(outlines_data, f, ensure_ascii=False, indent=2) + + def generate_detailed_chapter_outline(self, chapter_number: int) -> ChapterOutline: + """第四步:生成详细章节大纲""" + logging.info(f"生成第{chapter_number}章详细大纲...") + + if chapter_number <= len(self.overall_outline): + base_outline = self.overall_outline[chapter_number - 1] + + # 根据章节位置生成详细内容 + detailed_outline = ChapterOutline( + chapter_number=chapter_number, + title=f"第{chapter_number}章 初入青云门", + main_events=[ + "主角到达青云门山脚", + "遇到入门考核", + "展现天赋震惊长老", + "成功拜入青云门" + ], + character_development="主角从紧张到自信的心理变化", + plot_progression="正式开始修仙之路", + cultivation_progress="检测到极品灵根", + conflicts=["入门考核的挑战", "其他考生的竞争"], + estimated_word_count=3000 + ) + + return detailed_outline + else: + raise ValueError(f"章节号{chapter_number}超出范围") + + def generate_chapter_content(self, chapter_outline: ChapterOutline) -> Chapter: + """第五步:生成章节内容""" + logging.info(f"生成第{chapter_outline.chapter_number}章内容...") + + # 这里应该调用AI API生成具体内容,现在用模板代替 + content = f""" +{chapter_outline.title} + +  晨光熹微,青云山脉在薄雾中若隐若现,如同仙境一般。山脚下,一个身着粗布衣衫的少年正仰望着那高耸入云的山峰,眼中满含着向往与决心。 + +  这少年正是林逸,今日是青云门三年一度的入门大考之日。 + +  "各位考生,入门考核即将开始!"一声洪亮的声音从山门处传来,只见一位身着青色道袍的中年修士缓缓走出,身后跟着数位长老。 + +  林逸深吸一口气,跟随着人群向前走去。第一关是灵根检测,这是最基础也是最重要的一关。 + +  "下一位!"长老的声音传来。 + +  林逸走上前去,将手按在了那颗晶莹剔透的测灵石上。刹那间,五色光芒从石头中迸发而出,直冲云霄! + +  "极品五行灵根!"长老惊呼出声,在场所有人都被这突如其来的异象震惊了。 + +  这一刻,林逸知道,自己的修仙之路真正开始了... + +""" + + chapter = Chapter( + outline=chapter_outline, + content=content, + actual_word_count=len(content), + key_plot_points=["主角到达青云门", "通过入门考核", "展现极品灵根"], + character_changes=["主角正式踏入修仙世界", "获得青云门认可"], + next_chapter_setup="主角将被分配师父,开始正式修炼", + summary=f"第{chapter_outline.chapter_number}章:主角林逸参加青云门入门考核,展现极品五行灵根天赋,成功拜入青云门,正式开始修仙之路。" + ) + + return chapter + + def save_chapter(self, chapter: Chapter): + """保存章节""" + chapter_file = f"{self.project_dir}/chapters/chapter_{chapter.outline.chapter_number:03d}.json" + chapter_data = { + 'outline': asdict(chapter.outline), + 'content': chapter.content, + 'actual_word_count': chapter.actual_word_count, + 'key_plot_points': chapter.key_plot_points, + 'character_changes': chapter.character_changes, + 'next_chapter_setup': chapter.next_chapter_setup, + 'summary': chapter.summary, + 'created_at': datetime.datetime.now().isoformat() + } + + with open(chapter_file, 'w', encoding='utf-8') as f: + json.dump(chapter_data, f, ensure_ascii=False, indent=2) + + # 同时保存纯文本版本用于阅读 + text_file = f"{self.project_dir}/chapters/chapter_{chapter.outline.chapter_number:03d}.txt" + with open(text_file, 'w', encoding='utf-8') as f: + f.write(chapter.content) + + def generate_next_chapter(self) -> Chapter: + """生成下一章""" + next_chapter_num = self.current_chapter + 1 + + if next_chapter_num > len(self.overall_outline): + raise ValueError("已达到计划章节数上限") + + # 生成详细大纲 + detailed_outline = self.generate_detailed_chapter_outline(next_chapter_num) + + # 生成章节内容 + chapter = self.generate_chapter_content(detailed_outline) + + # 保存章节 + self.save_chapter(chapter) + self.chapters.append(chapter) + + # 更新当前章节数 + self.current_chapter = next_chapter_num + self.save_project_state() + + logging.info(f"第{next_chapter_num}章生成完成") + return chapter + + def get_progress_report(self) -> Dict[str, Any]: + """获取进度报告""" + total_words = sum(len(chapter.content) for chapter in self.chapters) + + return { + 'project_name': self.project_name, + 'current_chapter': self.current_chapter, + 'total_planned_chapters': len(self.overall_outline), + 'completion_rate': f"{(self.current_chapter / len(self.overall_outline) * 100):.1f}%", + 'total_words': total_words, + 'average_words_per_chapter': total_words // max(1, len(self.chapters)), + 'estimated_total_words': len(self.overall_outline) * 3000, + 'last_chapter_summary': self.chapters[-1].summary if self.chapters else "暂无章节" + } + +if __name__ == "__main__": + # 示例使用 + generator = NovelGenerator("修仙传说") + + # 完整流程演示 + print("=== 修仙小说生成系统 ===") + + # 1. 创建世界观 + world = generator.create_world_setting() + print("✓ 世界观设定完成") + + # 2. 创建角色 + characters = generator.create_main_characters() + print("✓ 主要角色创建完成") + + # 3. 生成整体大纲 + outline = generator.generate_overall_outline(300) + print("✓ 整体大纲生成完成") + + # 4. 生成第一章 + first_chapter = generator.generate_next_chapter() + print("✓ 第一章生成完成") + + # 5. 显示进度报告 + report = generator.get_progress_report() + print("\n=== 进度报告 ===") + for key, value in report.items(): + print(f"{key}: {value}") \ No newline at end of file diff --git a/test_system.py b/test_system.py new file mode 100644 index 0000000..a6d0ff1 --- /dev/null +++ b/test_system.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +简单测试脚本 - 验证修仙小说生成系统功能 +""" + +def main(): + """主测试函数""" + print("=" * 60) + print("修仙小说AI生成系统 - 功能验证") + print("=" * 60) + + try: + # 测试模块导入 + print("\n1. 测试模块导入...") + from enhanced_novel_generator import EnhancedNovelGenerator + print("✓ 模块导入成功") + + # 创建生成器实例 + print("\n2. 创建生成器实例...") + generator = EnhancedNovelGenerator("测试项目", ai_type="local") + print(f"✓ 生成器创建成功,项目目录: {generator.project_dir}") + + # 创建世界观 + print("\n3. 创建世界观设定...") + world = generator.create_enhanced_world_setting() + print(f"✓ 世界观创建成功") + print(f" 修炼等级: {len(world.cultivation_levels)} 个") + print(f" 门派数量: {len(world.sects)} 个") + print(f" 地域划分: {len(world.regions)} 个") + + # 创建角色 + print("\n4. 创建主要角色...") + characters = generator.create_enhanced_characters() + print(f"✓ 角色创建成功,共 {len(characters)} 个角色") + for char in characters[:3]: # 显示前3个角色 + print(f" {char.name} ({char.role_type}) - {char.cultivation_level}") + + # 生成大纲 + print("\n5. 生成整体大纲...") + outline = generator.generate_enhanced_outline(20) # 生成20章用于测试 + print(f"✓ 大纲生成成功,共 {len(outline)} 章") + + # 生成第一章 + print("\n6. 生成第一章...") + chapter = generator.generate_next_chapter() + print(f"✓ 第一章生成成功") + print(f" 标题: {chapter.outline.title}") + print(f" 字数: {chapter.actual_word_count}") + print(f" 关键情节: {', '.join(chapter.key_plot_points)}") + + # 生成进度报告 + print("\n7. 生成进度报告...") + report = generator.generate_progress_report() + print(f"✓ 进度报告生成成功") + print(f" 项目名称: {report['project_info']['project_name']}") + print(f" 完成进度: {report['progress']['completion_rate']}") + print(f" 总字数: {report['content_stats']['total_words']}") + + print("\n" + "=" * 60) + print("✓ 所有功能测试通过!系统运行正常") + print("=" * 60) + + return True + + except Exception as e: + print(f"\n✗ 测试失败: {str(e)}") + import traceback + traceback.print_exc() + return False + +if __name__ == "__main__": + success = main() + if success: + print("\n🎉 修仙小说生成系统测试成功!") + else: + print("\n❌ 系统测试失败,请检查代码。") \ No newline at end of file diff --git "a/\346\265\201\347\250\213\346\200\273\347\273\223.md" "b/\346\265\201\347\250\213\346\200\273\347\273\223.md" new file mode 100644 index 0000000..9625dcb --- /dev/null +++ "b/\346\265\201\347\250\213\346\200\273\347\273\223.md" @@ -0,0 +1,351 @@ +# AI生成长篇百万字中文传统修仙小说完整流程 + +## 📝 系统概述 + +本系统提供了一套完整的AI生成长篇中文传统修仙小说的解决方案,支持从世界观设定到章节内容生成的全流程自动化创作,目标是生成300万字左右的高质量修仙小说。 + +## 🔄 完整流程分析 + +### 第一步:世界观构建 (World Building) + +**目标**: 创建一个完整、自洽的修仙世界观 + +**具体内容**: +1. **修炼等级体系** + - 从凡人到仙帝的完整修炼路径 + - 每个大境界分为初期、中期、后期、大圆满四个小境界 + - 总计29个等级,涵盖修仙全程 + +2. **门派势力设定** + - 正派:青云门(剑修)、天音宗(音律) + - 邪派:魔音寺(魔音攻击) + - 中立:万药谷(炼丹)、器宗(炼器) + - 每个门派都有详细的历史、实力、特色设定 + +3. **地域划分** + - 东荒:灵气浓郁的修仙圣地 + - 中州:各势力交汇的繁华地带 + - 西漠:邪修聚集的荒凉之地 + - 南荒:原始森林密布的神秘区域 + - 北冥:资源丰富的极地冰原 + +4. **法术体系** + - 五行法术:金木水火土的完整体系 + - 特殊道路:剑道、丹道、阵法、符箓、炼器、驭兽、音律 + - 修炼资源:灵石、丹药、功法、法宝的等级划分 + +5. **历史背景** + - 千年前的正邪大战 + - 当前的平衡局面 + - 魔道复苏的暗流 + +**输出结果**: +- `world_setting.json`: 完整的世界观配置文件 +- 为后续300万字小说提供丰富的背景支撑 + +--- + +### 第二步:角色设定 (Character Creation) + +**目标**: 创建立体、有血有肉的主要角色群体 + +**核心角色设定**: + +1. **主角 - 林逸** + - 18岁贫寒少年,极品五行灵根 + - 性格:坚韧不拔,重情重义,天赋异禀 + - 成长轨迹:从凡人到仙帝的完整修炼历程 + +2. **师父 - 玄机真人** + - 800岁化神期高手,青云门太上长老 + - 作用:传授功法,指导修行,关键时刻的帮助 + +3. **女主角 - 苏婉儿** + - 17岁青梅竹马,上品水灵根 + - 情感线索的重要载体 + +4. **师兄 - 张浩然** + - 正面角色,义薄云天的保护者 + +5. **反派师兄 - 李冥** + - 早期对手,推动剧情发展 + +6. **门派长者 - 青云子** + - 合体期掌门,代表权威和秩序 + +7. **最终反派 - 血魔老祖** + - 大乘期魔道巨擘,最终BOSS + +**角色关系网络**: +- 师徒关系、同门关系、敌对关系 +- 情感发展线索 +- 成长互动模式 + +**输出结果**: +- `characters.json`: 详细的角色档案 +- 为300万字的人物发展提供基础 + +--- + +### 第三步:大纲生成 (Outline Creation) + +**目标**: 制定300章的详细创作大纲 + +**四大阶段规划**: + +#### 🌱 入门期 (1-50章) +- **主题**: 获得机缘,初入修仙世界 +- **关键事件**: + - 发现修仙传承 + - 拜入青云门 + - 初次修炼突破 + - 建立同门关系 + - 小试身手历练 +- **修为范围**: 凡人 → 练气大圆满 +- **字数目标**: 15万字 + +#### 🌿 成长期 (51-150章) +- **主题**: 历练成长,结识伙伴 +- **关键事件**: + - 门派试炼考核 + - 秘境探险历练 + - 结识重要盟友 + - 初恋情愫萌发 + - 遭遇强敌威胁 +- **修为范围**: 筑基初期 → 金丹初期 +- **字数目标**: 30万字 + +#### 🌳 崛起期 (151-250章) +- **主题**: 声名鹊起,面临大敌 +- **关键事件**: + - 声名远播四方 + - 跨域冒险探索 + - 与天才强者对决 + - 参与门派大战 + - 身世之谜揭晓 +- **修为范围**: 金丹中期 → 元婴后期 +- **字数目标**: 30万字 + +#### 🌲 巅峰期 (251-300章) +- **主题**: 巅峰对决,拯救世界 +- **关键事件**: + - 魔道全面复苏 + - 正邪终极决战 + - 英雄牺牲拯救 + - 大道圆满成就 + - 飞升成仙结局 +- **修为范围**: 化神期 → 真仙 +- **字数目标**: 15万字 + +**输出结果**: +- `overall_outline.json`: 300章的详细大纲 +- 每章包含标题、事件、发展、冲突等要素 + +--- + +### 第四步:每章细节概括 (Chapter Outline) + +**目标**: 为每一章生成详细的创作指导 + +**每章大纲包含**: + +1. **章节标题** + - 吸引读者的标题设计 + - 体现章节核心内容 + +2. **主要事件列表** (3-5个) + - 具体的情节发展点 + - 关键转折和高潮 + +3. **角色发展描述** + - 主角的实力提升 + - 心境和认知变化 + - 人际关系发展 + +4. **剧情推进要点** + - 主线剧情的推进 + - 支线任务的展开 + - 伏笔的埋设 + +5. **修炼进展** + - 具体的修为突破 + - 新技能的习得 + - 法宝的获得 + +6. **冲突和矛盾** + - 内在冲突:道心、选择 + - 外在冲突:敌人、挑战 + - 人际冲突:误会、竞争 + +7. **情感发展** + - 师徒情深 + - 同门友谊 + - 爱情萌芽 + +8. **下章铺垫** + - 为下一章设置悬念 + - 引出新的情节线索 + +**生成方式**: +- AI分析前面章节内容 +- 基于整体大纲调整细节 +- 确保剧情连贯性 + +**输出结果**: +- 每章独立的详细大纲 +- 为内容生成提供精确指导 + +--- + +### 第五步:每章生成3000字左右 (Content Generation) + +**目标**: 基于详细大纲生成高质量的章节内容 + +**写作标准**: + +1. **字数控制** + - 每章严格控制在3000字左右 + - 确保内容充实不冗余 + +2. **文风要求** + - 传统修仙小说风格 + - 文笔优美,描写细腻 + - 符合中文阅读习惯 + +3. **结构完整** + - 起:章节开头的场景设置 + - 承:事件的发展和推进 + - 转:关键转折或高潮 + - 合:章节结尾和下章铺垫 + +4. **对话生动** + - 符合角色性格特点 + - 推进剧情发展 + - 增强可读性 + +5. **描写平衡** + - 环境描写:营造修仙氛围 + - 动作描写:展现战斗精彩 + - 心理描写:刻画角色内心 + - 修炼描写:体现功法玄妙 + +6. **节奏把控** + - 紧张与舒缓的结合 + - 高潮与过渡的平衡 + - 悬念与揭示的配合 + +**AI生成流程**: +1. 分析章节大纲要求 +2. 考虑前面章节的连贯性 +3. 调用AI API生成内容 +4. 质量检查和优化调整 + +**输出结果**: +- `chapter_XXX.txt`: 纯文本章节内容 +- `chapter_XXX.json`: 包含元数据的完整章节信息 + +--- + +### 第六步:生成后总结 (Post-Generation Summary) + +**目标**: 对每章内容进行分析总结,为后续创作提供参考 + +**总结内容**: + +1. **本章主要情节** + - 3-5个关键事件要点 + - 重要转折和突破 + - 新引入的元素 + +2. **角色发展变化** + - 主角实力的具体提升 + - 心境和认知的成长 + - 人际关系的变化 + +3. **修炼进展记录** + - 境界突破的具体情况 + - 新功法的学习掌握 + - 法宝装备的获得 + +4. **重要伏笔线索** + - 为后续剧情埋下的伏笔 + - 需要后续解决的谜团 + - 潜在的冲突种子 + +5. **情感发展轨迹** + - 师徒感情的深化 + - 同门友谊的建立 + - 爱情线索的推进 + +6. **下章创作指导** + - 下一章的建议主题 + - 需要重点处理的情节 + - 应该避免的重复内容 + +**应用价值**: +- 保持全书的连贯性 +- 避免情节前后矛盾 +- 为AI生成提供上下文 +- 支持断点续写功能 + +**输出结果**: +- 每章的详细总结文档 +- 项目的整体进度报告 +- 下阶段的创作指导 + +--- + +## 🛠️ 技术实现 + +### 系统架构 +``` +修仙小说生成系统 +├── 世界观设定模块 +├── 角色创建模块 +├── 大纲生成模块 +├── 章节大纲模块 +├── 内容生成模块 +├── 总结分析模块 +├── 进度管理模块 +└── AI接口模块 +``` + +### 数据流转 +``` +世界观设定 → 角色创建 → 整体大纲 → 章节大纲 → 内容生成 → 总结分析 → 循环迭代 +``` + +### 质量保证 +- 内容一致性检查 +- 角色发展跟踪 +- 情节逻辑验证 +- 语言质量优化 + +## 📊 预期成果 + +### 数量指标 +- **总章节数**: 300章 +- **总字数**: 90万字左右 (每章3000字) +- **创作周期**: 根据AI调用频率,可在数天到数周内完成 + +### 质量指标 +- **内容连贯性**: 通过系统化的大纲和总结确保 +- **角色立体性**: 详细的角色设定和发展轨迹 +- **世界观完整性**: 自洽的修仙世界体系 +- **阅读体验**: 符合传统修仙小说的文风和节奏 + +### 可扩展性 +- 支持自定义世界观要求 +- 可接入不同的AI API +- 支持批量生成和断点续写 +- 便于后续优化和调整 + +## 🎯 使用建议 + +1. **AI接入**: 建议使用高质量的AI API(如GPT-4、Claude等)以获得更好的生成效果 +2. **内容审核**: 生成后进行人工审核和优化调整 +3. **个性化定制**: 根据需要调整世界观、角色设定等元素 +4. **分批生成**: 建议分批生成,及时检查质量和方向 +5. **读者反馈**: 结合读者反馈持续优化内容质量 + +这套系统提供了一个完整的、可操作的修仙小说生成解决方案,能够高效地产出大量高质量的内容,同时保持故事的连贯性和可读性。 \ No newline at end of file