Update app.py
Browse files
app.py
CHANGED
|
@@ -8,6 +8,7 @@ import traceback
|
|
| 8 |
import gradio as gr
|
| 9 |
from huggingface_hub import InferenceClient
|
| 10 |
|
|
|
|
| 11 |
from storywriter import (
|
| 12 |
OutlineAgent,
|
| 13 |
PlanningAgent,
|
|
@@ -24,7 +25,7 @@ from storywriter.planning_agent import (
|
|
| 24 |
class ImageGenerator:
|
| 25 |
def __init__(self, token=None):
|
| 26 |
self.token = token
|
| 27 |
-
self.model_id = "cagliostrolab/animagine-xl-3.1"
|
| 28 |
self.client = InferenceClient(model=self.model_id, token=token)
|
| 29 |
|
| 30 |
def _translate_prompt(self, text):
|
|
@@ -75,7 +76,7 @@ class ImageGenerator:
|
|
| 75 |
time.sleep(2)
|
| 76 |
|
| 77 |
# ==========================================
|
| 78 |
-
# UI 渲染辅助函数
|
| 79 |
# ==========================================
|
| 80 |
def render_persona_html(personas_data, image_map=None, generation_started=False):
|
| 81 |
if not personas_data: return ""
|
|
@@ -85,24 +86,25 @@ def render_persona_html(personas_data, image_map=None, generation_started=False)
|
|
| 85 |
html = """
|
| 86 |
<style>
|
| 87 |
.persona-container { display: flex; flex-wrap: wrap; gap: 20px; justify-content: center; font-family: 'Noto Sans SC', sans-serif; }
|
| 88 |
-
.persona-card { width:
|
| 89 |
.persona-card:hover { transform: translateY(-4px); box-shadow: 0 12px 20px rgba(0,0,0,0.12); }
|
| 90 |
-
.card-img-wrapper { width: 100%; height:
|
| 91 |
.card-img { width: 100%; height: 100%; object-fit: cover; transition: transform 0.5s ease; }
|
| 92 |
.card-img:hover { transform: scale(1.03); }
|
| 93 |
.card-placeholder { color: #9ca3af; font-size: 0.9rem; font-style: italic; text-align: center; padding: 20px; }
|
| 94 |
-
.card-content { padding:
|
| 95 |
.card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
|
| 96 |
-
.card-name { font-size: 1.
|
| 97 |
-
.card-age { font-size: 0.
|
| 98 |
-
.card-role-badge { align-self: flex-start; display: inline-block; padding:
|
| 99 |
-
.card-tags { display: flex; flex-wrap: wrap; gap:
|
| 100 |
-
.card-tag { font-size: 0.
|
| 101 |
-
.card-section { margin-bottom:
|
| 102 |
.label { font-weight: 700; color: #1f2937; margin-right: 4px; }
|
| 103 |
</style>
|
| 104 |
<div class='persona-container'>
|
| 105 |
"""
|
|
|
|
| 106 |
MAX_IMAGES = 3
|
| 107 |
for idx, p in enumerate(personas_list):
|
| 108 |
name = p.get("name", "Unknown")
|
|
@@ -113,50 +115,38 @@ def render_persona_html(personas_data, image_map=None, generation_started=False)
|
|
| 113 |
tags_html = "".join([f"<span class='card-tag'>#{t}</span>" for t in archetypes[:4]])
|
| 114 |
|
| 115 |
img_src = image_map.get(name, "") if image_map else ""
|
| 116 |
-
placeholder_text = "No Image" if idx >= MAX_IMAGES else ("Generating Art..." if generation_started else "Waiting
|
| 117 |
img_html = f"<div class='card-img-wrapper'><img src='{img_src}' class='card-img' alt='{name}'></div>" if img_src else f"<div class='card-img-wrapper'><div class='card-placeholder'>{placeholder_text}</div></div>"
|
| 118 |
|
| 119 |
html += f"""
|
| 120 |
<div class="persona-card">{img_html}<div class="card-content">
|
| 121 |
<div class="card-header"><div class="card-name">{name}</div><div class="card-age">{age} {gender}</div></div>
|
| 122 |
<div class="card-role-badge">{role}</div><div class="card-tags">{tags_html}</div>
|
| 123 |
-
<div class="card-section"><span class="label">外貌:</span>{appearance[:
|
| 124 |
</div></div>"""
|
| 125 |
return html + "</div>"
|
| 126 |
|
| 127 |
-
#
|
|
|
|
|
|
|
| 128 |
def render_book_page(story_data, page_index):
|
| 129 |
-
"""
|
| 130 |
-
story_data: List[Dict] -> [{"title": "Chapter 1", "content": "..."}]
|
| 131 |
-
page_index: int
|
| 132 |
-
"""
|
| 133 |
if not story_data or not isinstance(story_data, list) or len(story_data) == 0:
|
| 134 |
return "<div style='text-align:center; padding: 50px; color: #999;'><i>等待故事生成...</i></div>"
|
| 135 |
|
| 136 |
-
# 边界检查
|
| 137 |
page_index = max(0, min(page_index, len(story_data) - 1))
|
| 138 |
chapter = story_data[page_index]
|
| 139 |
-
|
| 140 |
title = chapter.get("title", f"Chapter {page_index + 1}")
|
| 141 |
content = chapter.get("content", "")
|
| 142 |
|
| 143 |
-
# 将换行符转换为 HTML 段落
|
| 144 |
paragraphs = content.split('\n')
|
| 145 |
content_html = "".join([f"<p>{p.strip()}</p>" for p in paragraphs if p.strip()])
|
| 146 |
|
| 147 |
html = f"""
|
| 148 |
<style>
|
| 149 |
.book-wrapper {{
|
| 150 |
-
background-color: #fdf6e3;
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
|
| 154 |
-
font-family: 'Noto Serif SC', serif;
|
| 155 |
-
color: #2c3e50;
|
| 156 |
-
min-height: 600px;
|
| 157 |
-
max-width: 800px;
|
| 158 |
-
margin: 0 auto;
|
| 159 |
-
position: relative;
|
| 160 |
}}
|
| 161 |
.book-wrapper::before {{
|
| 162 |
content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 4px;
|
|
@@ -169,9 +159,7 @@ def render_book_page(story_data, page_index):
|
|
| 169 |
.chapter-content p {{
|
| 170 |
font-size: 1.15em; line-height: 1.8; margin-bottom: 1.2em; text-align: justify; text-indent: 2em;
|
| 171 |
}}
|
| 172 |
-
.page-number {{
|
| 173 |
-
text-align: center; margin-top: 40px; font-size: 0.9em; color: #888;
|
| 174 |
-
}}
|
| 175 |
</style>
|
| 176 |
<div class="book-wrapper">
|
| 177 |
<div class="chapter-title">{title}</div>
|
|
@@ -182,7 +170,7 @@ def render_book_page(story_data, page_index):
|
|
| 182 |
return html
|
| 183 |
|
| 184 |
# ==========================================
|
| 185 |
-
#
|
| 186 |
# ==========================================
|
| 187 |
def generate_novel(premise):
|
| 188 |
msg = "🚀 [Backend] Process initialized...\n"
|
|
@@ -192,10 +180,9 @@ def generate_novel(premise):
|
|
| 192 |
current_outline = None
|
| 193 |
current_plan = None
|
| 194 |
current_personas = None
|
| 195 |
-
current_story = None #
|
| 196 |
persona_images_map = {}
|
| 197 |
|
| 198 |
-
# 初始化 yield
|
| 199 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 200 |
|
| 201 |
if not premise or not premise.strip():
|
|
@@ -207,7 +194,7 @@ def generate_novel(premise):
|
|
| 207 |
hf_token = os.environ.get("HF_TOKEN")
|
| 208 |
img_gen = ImageGenerator(token=hf_token)
|
| 209 |
|
| 210 |
-
# --- Phase 1 ---
|
| 211 |
msg = f"📝 [1/5] Generating outline & initial profiles...\n"
|
| 212 |
print(msg.strip())
|
| 213 |
current_log += msg
|
|
@@ -234,10 +221,8 @@ def generate_novel(premise):
|
|
| 234 |
current_log += msg
|
| 235 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 236 |
|
|
|
|
| 237 |
if hf_token and isinstance(personas_raw_data, dict):
|
| 238 |
-
msg = "🎨 [Art] Generating initial character images (Top 3)...\n"
|
| 239 |
-
print(msg.strip())
|
| 240 |
-
current_log += msg
|
| 241 |
p_list = personas_raw_data.get("personas", [])
|
| 242 |
if isinstance(p_list, list):
|
| 243 |
for i, p in enumerate(p_list[:3]):
|
|
@@ -258,7 +243,7 @@ def generate_novel(premise):
|
|
| 258 |
print(msg.strip())
|
| 259 |
current_log += msg
|
| 260 |
elif not hf_token:
|
| 261 |
-
msg = "⚠️ [Art] HF_TOKEN
|
| 262 |
print(msg.strip())
|
| 263 |
current_log += msg
|
| 264 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
|
@@ -271,7 +256,7 @@ def generate_novel(premise):
|
|
| 271 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 272 |
return
|
| 273 |
|
| 274 |
-
# --- Phase 2 ---
|
| 275 |
msg = "📅 [2/5] Splitting events into sub-events...\n"
|
| 276 |
print(msg.strip())
|
| 277 |
current_log += msg
|
|
@@ -298,8 +283,8 @@ def generate_novel(premise):
|
|
| 298 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 299 |
return
|
| 300 |
|
| 301 |
-
# --- Phase 3 ---
|
| 302 |
-
msg = "👥 [3/5] Refining Personas (Text Only)
|
| 303 |
print(msg.strip())
|
| 304 |
current_log += msg
|
| 305 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
|
@@ -326,23 +311,21 @@ def generate_novel(premise):
|
|
| 326 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 327 |
return
|
| 328 |
|
| 329 |
-
# --- Phase 4: Writing (
|
| 330 |
msg = "✍️ [4/5] Writing chapters (Stream starting)...\n"
|
| 331 |
print(msg.strip())
|
| 332 |
current_log += msg
|
| 333 |
-
|
| 334 |
-
current_story = [{"title": "系统消息", "content": "正在撰写正文,请稍候..."}]
|
| 335 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 336 |
|
| 337 |
try:
|
| 338 |
writer = WritingAgent()
|
| 339 |
outputs = writer.write_from_subevents_json(events_json=current_outline, subevents_json=current_plan, personas=personas_data if 'personas_data' in locals() else {}, max_turns=500)
|
| 340 |
|
| 341 |
-
# --- 关键修改:将输出格式化为章节列表 ---
|
| 342 |
structured_story = []
|
| 343 |
if isinstance(outputs, dict):
|
| 344 |
for title, content in outputs.items():
|
| 345 |
-
structured_story.append({"title": title, "content": str(content)})
|
| 346 |
elif isinstance(outputs, list):
|
| 347 |
for i, content in enumerate(outputs):
|
| 348 |
structured_story.append({"title": f"Chapter {i+1}", "content": str(content)})
|
|
@@ -364,13 +347,12 @@ def generate_novel(premise):
|
|
| 364 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 365 |
|
| 366 |
# ==========================================
|
| 367 |
-
# Debug UI
|
| 368 |
# ==========================================
|
| 369 |
with gr.Blocks(title="Backend Service") as demo:
|
| 370 |
gr.Markdown("## 🔒 LongStory Backend API")
|
| 371 |
premise_in = gr.Textbox(label="Input Premise")
|
| 372 |
|
| 373 |
-
# 状态管理
|
| 374 |
story_state = gr.State([])
|
| 375 |
page_state = gr.State(0)
|
| 376 |
|
|
@@ -379,27 +361,19 @@ with gr.Blocks(title="Backend Service") as demo:
|
|
| 379 |
log_box = gr.Textbox(label="Logs", lines=10)
|
| 380 |
outline_box = gr.JSON(label="Outline", visible=False)
|
| 381 |
plan_box = gr.JSON(label="Plan", visible=False)
|
| 382 |
-
# Personas 仍然是 HTML
|
| 383 |
persona_box = gr.HTML(label="Personas Card")
|
| 384 |
|
| 385 |
with gr.Column(scale=2):
|
| 386 |
gr.Markdown("### 📖 故事预览 (E-Reader Mode)")
|
| 387 |
-
# 阅读器显示区域
|
| 388 |
story_display = gr.HTML(label="Story Reader", min_height=600)
|
| 389 |
-
|
| 390 |
-
# 翻页控制
|
| 391 |
with gr.Row():
|
| 392 |
prev_btn = gr.Button("← 上一章")
|
| 393 |
next_btn = gr.Button("下一章 →")
|
| 394 |
|
| 395 |
-
# API 输出组件 (Hidden JSON to store story data)
|
| 396 |
story_json_connector = gr.JSON(visible=False, label="Story Data Connector")
|
| 397 |
|
| 398 |
btn = gr.Button("Run Generation", variant="primary")
|
| 399 |
|
| 400 |
-
# 1. 运行生成
|
| 401 |
-
# 注意:outputs 的顺序必须和 yield 一致
|
| 402 |
-
# [log, outline, plan, personas, story_json]
|
| 403 |
btn.click(
|
| 404 |
fn=generate_novel,
|
| 405 |
inputs=premise_in,
|
|
@@ -407,18 +381,15 @@ with gr.Blocks(title="Backend Service") as demo:
|
|
| 407 |
api_name="generate_novel"
|
| 408 |
)
|
| 409 |
|
| 410 |
-
# 2. 监听数据变化,更新阅读器
|
| 411 |
def update_reader(story_data, page):
|
| 412 |
return render_book_page(story_data, page)
|
| 413 |
|
| 414 |
-
# 当后端返回新的故事数据时,重置页码并渲染第一页
|
| 415 |
story_json_connector.change(
|
| 416 |
fn=lambda x: (x, 0, render_book_page(x, 0)),
|
| 417 |
inputs=[story_json_connector],
|
| 418 |
outputs=[story_state, page_state, story_display]
|
| 419 |
)
|
| 420 |
|
| 421 |
-
# 3. 翻页逻辑
|
| 422 |
def go_prev(story, page):
|
| 423 |
new_page = max(0, page - 1)
|
| 424 |
return new_page, render_book_page(story, new_page)
|
|
|
|
| 8 |
import gradio as gr
|
| 9 |
from huggingface_hub import InferenceClient
|
| 10 |
|
| 11 |
+
# 假设这些是你上传的 storywriter 库
|
| 12 |
from storywriter import (
|
| 13 |
OutlineAgent,
|
| 14 |
PlanningAgent,
|
|
|
|
| 25 |
class ImageGenerator:
|
| 26 |
def __init__(self, token=None):
|
| 27 |
self.token = token
|
| 28 |
+
self.model_id = "cagliostrolab/animagine-xl-3.1"
|
| 29 |
self.client = InferenceClient(model=self.model_id, token=token)
|
| 30 |
|
| 31 |
def _translate_prompt(self, text):
|
|
|
|
| 76 |
time.sleep(2)
|
| 77 |
|
| 78 |
# ==========================================
|
| 79 |
+
# UI 渲染辅助函数 (人物卡片)
|
| 80 |
# ==========================================
|
| 81 |
def render_persona_html(personas_data, image_map=None, generation_started=False):
|
| 82 |
if not personas_data: return ""
|
|
|
|
| 86 |
html = """
|
| 87 |
<style>
|
| 88 |
.persona-container { display: flex; flex-wrap: wrap; gap: 20px; justify-content: center; font-family: 'Noto Sans SC', sans-serif; }
|
| 89 |
+
.persona-card { width: 300px; background: #fff; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.08); overflow: hidden; border: 1px solid #f3f4f6; transition: transform 0.2s, box-shadow 0.2s; display: flex; flex-direction: column; }
|
| 90 |
.persona-card:hover { transform: translateY(-4px); box-shadow: 0 12px 20px rgba(0,0,0,0.12); }
|
| 91 |
+
.card-img-wrapper { width: 100%; height: 360px; background: #f9fafb; display: flex; align-items: center; justify-content: center; overflow: hidden; border-bottom: 1px solid #eee; }
|
| 92 |
.card-img { width: 100%; height: 100%; object-fit: cover; transition: transform 0.5s ease; }
|
| 93 |
.card-img:hover { transform: scale(1.03); }
|
| 94 |
.card-placeholder { color: #9ca3af; font-size: 0.9rem; font-style: italic; text-align: center; padding: 20px; }
|
| 95 |
+
.card-content { padding: 15px; flex-grow: 1; display: flex; flex-direction: column; }
|
| 96 |
.card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
|
| 97 |
+
.card-name { font-size: 1.3rem; font-weight: 800; color: #111827; }
|
| 98 |
+
.card-age { font-size: 0.8rem; color: #6b7280; background: #f3f4f6; padding: 2px 8px; border-radius: 12px; }
|
| 99 |
+
.card-role-badge { align-self: flex-start; display: inline-block; padding: 3px 8px; border-radius: 6px; background: #e0e7ff; color: #4f46e5; font-size: 0.75rem; font-weight: 600; margin-bottom: 10px; }
|
| 100 |
+
.card-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 12px; }
|
| 101 |
+
.card-tag { font-size: 0.7rem; background: #f3f4f6; color: #4b5563; padding: 2px 6px; border-radius: 99px; border: 1px solid #e5e7eb; }
|
| 102 |
+
.card-section { margin-bottom: 6px; font-size: 0.85rem; color: #374151; line-height: 1.5; }
|
| 103 |
.label { font-weight: 700; color: #1f2937; margin-right: 4px; }
|
| 104 |
</style>
|
| 105 |
<div class='persona-container'>
|
| 106 |
"""
|
| 107 |
+
|
| 108 |
MAX_IMAGES = 3
|
| 109 |
for idx, p in enumerate(personas_list):
|
| 110 |
name = p.get("name", "Unknown")
|
|
|
|
| 115 |
tags_html = "".join([f"<span class='card-tag'>#{t}</span>" for t in archetypes[:4]])
|
| 116 |
|
| 117 |
img_src = image_map.get(name, "") if image_map else ""
|
| 118 |
+
placeholder_text = "No Image" if idx >= MAX_IMAGES else ("Generating Art..." if generation_started else "Waiting...")
|
| 119 |
img_html = f"<div class='card-img-wrapper'><img src='{img_src}' class='card-img' alt='{name}'></div>" if img_src else f"<div class='card-img-wrapper'><div class='card-placeholder'>{placeholder_text}</div></div>"
|
| 120 |
|
| 121 |
html += f"""
|
| 122 |
<div class="persona-card">{img_html}<div class="card-content">
|
| 123 |
<div class="card-header"><div class="card-name">{name}</div><div class="card-age">{age} {gender}</div></div>
|
| 124 |
<div class="card-role-badge">{role}</div><div class="card-tags">{tags_html}</div>
|
| 125 |
+
<div class="card-section"><span class="label">外貌:</span>{appearance[:40]}...</div>
|
| 126 |
</div></div>"""
|
| 127 |
return html + "</div>"
|
| 128 |
|
| 129 |
+
# ==========================================
|
| 130 |
+
# UI 渲染辅助函数 (电子书)
|
| 131 |
+
# ==========================================
|
| 132 |
def render_book_page(story_data, page_index):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
if not story_data or not isinstance(story_data, list) or len(story_data) == 0:
|
| 134 |
return "<div style='text-align:center; padding: 50px; color: #999;'><i>等待故事生成...</i></div>"
|
| 135 |
|
|
|
|
| 136 |
page_index = max(0, min(page_index, len(story_data) - 1))
|
| 137 |
chapter = story_data[page_index]
|
|
|
|
| 138 |
title = chapter.get("title", f"Chapter {page_index + 1}")
|
| 139 |
content = chapter.get("content", "")
|
| 140 |
|
|
|
|
| 141 |
paragraphs = content.split('\n')
|
| 142 |
content_html = "".join([f"<p>{p.strip()}</p>" for p in paragraphs if p.strip()])
|
| 143 |
|
| 144 |
html = f"""
|
| 145 |
<style>
|
| 146 |
.book-wrapper {{
|
| 147 |
+
background-color: #fdf6e3; padding: 60px 80px; border-radius: 8px;
|
| 148 |
+
box-shadow: 0 10px 30px rgba(0,0,0,0.1); font-family: 'Noto Serif SC', serif;
|
| 149 |
+
color: #2c3e50; min-height: 600px; max-width: 800px; margin: 0 auto; position: relative;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
}}
|
| 151 |
.book-wrapper::before {{
|
| 152 |
content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 4px;
|
|
|
|
| 159 |
.chapter-content p {{
|
| 160 |
font-size: 1.15em; line-height: 1.8; margin-bottom: 1.2em; text-align: justify; text-indent: 2em;
|
| 161 |
}}
|
| 162 |
+
.page-number {{ text-align: center; margin-top: 40px; font-size: 0.9em; color: #888; }}
|
|
|
|
|
|
|
| 163 |
</style>
|
| 164 |
<div class="book-wrapper">
|
| 165 |
<div class="chapter-title">{title}</div>
|
|
|
|
| 170 |
return html
|
| 171 |
|
| 172 |
# ==========================================
|
| 173 |
+
# 核心生成逻辑
|
| 174 |
# ==========================================
|
| 175 |
def generate_novel(premise):
|
| 176 |
msg = "🚀 [Backend] Process initialized...\n"
|
|
|
|
| 180 |
current_outline = None
|
| 181 |
current_plan = None
|
| 182 |
current_personas = None
|
| 183 |
+
current_story = None # 将存储结构化数据
|
| 184 |
persona_images_map = {}
|
| 185 |
|
|
|
|
| 186 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 187 |
|
| 188 |
if not premise or not premise.strip():
|
|
|
|
| 194 |
hf_token = os.environ.get("HF_TOKEN")
|
| 195 |
img_gen = ImageGenerator(token=hf_token)
|
| 196 |
|
| 197 |
+
# --- Phase 1: Outline & Art ---
|
| 198 |
msg = f"📝 [1/5] Generating outline & initial profiles...\n"
|
| 199 |
print(msg.strip())
|
| 200 |
current_log += msg
|
|
|
|
| 221 |
current_log += msg
|
| 222 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 223 |
|
| 224 |
+
# 生成图片 (Phase 1)
|
| 225 |
if hf_token and isinstance(personas_raw_data, dict):
|
|
|
|
|
|
|
|
|
|
| 226 |
p_list = personas_raw_data.get("personas", [])
|
| 227 |
if isinstance(p_list, list):
|
| 228 |
for i, p in enumerate(p_list[:3]):
|
|
|
|
| 243 |
print(msg.strip())
|
| 244 |
current_log += msg
|
| 245 |
elif not hf_token:
|
| 246 |
+
msg = "⚠️ [Art] HF_TOKEN missing. Skipping Art.\n"
|
| 247 |
print(msg.strip())
|
| 248 |
current_log += msg
|
| 249 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
|
|
|
| 256 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 257 |
return
|
| 258 |
|
| 259 |
+
# --- Phase 2: Plan ---
|
| 260 |
msg = "📅 [2/5] Splitting events into sub-events...\n"
|
| 261 |
print(msg.strip())
|
| 262 |
current_log += msg
|
|
|
|
| 283 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 284 |
return
|
| 285 |
|
| 286 |
+
# --- Phase 3: Persona Refinement ---
|
| 287 |
+
msg = "👥 [3/5] Refining Personas (Text Only)...\n"
|
| 288 |
print(msg.strip())
|
| 289 |
current_log += msg
|
| 290 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
|
|
|
| 311 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 312 |
return
|
| 313 |
|
| 314 |
+
# --- Phase 4: Writing (结构化 JSON 输出) ---
|
| 315 |
msg = "✍️ [4/5] Writing chapters (Stream starting)...\n"
|
| 316 |
print(msg.strip())
|
| 317 |
current_log += msg
|
| 318 |
+
current_story = [{"title": "系统消息", "content": "正在撰写正文,请稍候... (Writing in progress)"}]
|
|
|
|
| 319 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 320 |
|
| 321 |
try:
|
| 322 |
writer = WritingAgent()
|
| 323 |
outputs = writer.write_from_subevents_json(events_json=current_outline, subevents_json=current_plan, personas=personas_data if 'personas_data' in locals() else {}, max_turns=500)
|
| 324 |
|
|
|
|
| 325 |
structured_story = []
|
| 326 |
if isinstance(outputs, dict):
|
| 327 |
for title, content in outputs.items():
|
| 328 |
+
structured_story.append({"title": str(title), "content": str(content)})
|
| 329 |
elif isinstance(outputs, list):
|
| 330 |
for i, content in enumerate(outputs):
|
| 331 |
structured_story.append({"title": f"Chapter {i+1}", "content": str(content)})
|
|
|
|
| 347 |
yield current_log, current_outline, current_plan, current_personas, current_story
|
| 348 |
|
| 349 |
# ==========================================
|
| 350 |
+
# Debug UI
|
| 351 |
# ==========================================
|
| 352 |
with gr.Blocks(title="Backend Service") as demo:
|
| 353 |
gr.Markdown("## 🔒 LongStory Backend API")
|
| 354 |
premise_in = gr.Textbox(label="Input Premise")
|
| 355 |
|
|
|
|
| 356 |
story_state = gr.State([])
|
| 357 |
page_state = gr.State(0)
|
| 358 |
|
|
|
|
| 361 |
log_box = gr.Textbox(label="Logs", lines=10)
|
| 362 |
outline_box = gr.JSON(label="Outline", visible=False)
|
| 363 |
plan_box = gr.JSON(label="Plan", visible=False)
|
|
|
|
| 364 |
persona_box = gr.HTML(label="Personas Card")
|
| 365 |
|
| 366 |
with gr.Column(scale=2):
|
| 367 |
gr.Markdown("### 📖 故事预览 (E-Reader Mode)")
|
|
|
|
| 368 |
story_display = gr.HTML(label="Story Reader", min_height=600)
|
|
|
|
|
|
|
| 369 |
with gr.Row():
|
| 370 |
prev_btn = gr.Button("← 上一章")
|
| 371 |
next_btn = gr.Button("下一章 →")
|
| 372 |
|
|
|
|
| 373 |
story_json_connector = gr.JSON(visible=False, label="Story Data Connector")
|
| 374 |
|
| 375 |
btn = gr.Button("Run Generation", variant="primary")
|
| 376 |
|
|
|
|
|
|
|
|
|
|
| 377 |
btn.click(
|
| 378 |
fn=generate_novel,
|
| 379 |
inputs=premise_in,
|
|
|
|
| 381 |
api_name="generate_novel"
|
| 382 |
)
|
| 383 |
|
|
|
|
| 384 |
def update_reader(story_data, page):
|
| 385 |
return render_book_page(story_data, page)
|
| 386 |
|
|
|
|
| 387 |
story_json_connector.change(
|
| 388 |
fn=lambda x: (x, 0, render_book_page(x, 0)),
|
| 389 |
inputs=[story_json_connector],
|
| 390 |
outputs=[story_state, page_state, story_display]
|
| 391 |
)
|
| 392 |
|
|
|
|
| 393 |
def go_prev(story, page):
|
| 394 |
new_page = max(0, page - 1)
|
| 395 |
return new_page, render_book_page(story, new_page)
|