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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import json
|
4 |
+
import requests
|
5 |
+
from datetime import datetime
|
6 |
+
import time
|
7 |
+
from typing import List, Dict, Any, Generator, Tuple, Optional
|
8 |
+
import logging
|
9 |
+
import re
|
10 |
+
import tempfile
|
11 |
+
from pathlib import Path
|
12 |
+
import sqlite3
|
13 |
+
import hashlib
|
14 |
+
import threading
|
15 |
+
from contextlib import contextmanager
|
16 |
+
|
17 |
+
# λ‘κΉ
μ€μ
|
18 |
+
logging.basicConfig(level=logging.INFO)
|
19 |
+
logger = logging.getLogger(__name__)
|
20 |
+
|
21 |
+
# Document export imports
|
22 |
+
try:
|
23 |
+
from docx import Document
|
24 |
+
from docx.shared import Inches, Pt, RGBColor
|
25 |
+
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
26 |
+
from docx.enum.style import WD_STYLE_TYPE
|
27 |
+
DOCX_AVAILABLE = True
|
28 |
+
except ImportError:
|
29 |
+
DOCX_AVAILABLE = False
|
30 |
+
logger.warning("python-docx not installed. DOCX export will be disabled.")
|
31 |
+
|
32 |
+
# νκ²½ λ³μμμ ν ν° κ°μ Έμ€κΈ°
|
33 |
+
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "")
|
34 |
+
BRAVE_SEARCH_API_KEY = os.getenv("BRAVE_SEARCH_API_KEY", "")
|
35 |
+
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
|
36 |
+
MODEL_ID = "dep89a2fld32mcm"
|
37 |
+
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
|
38 |
+
|
39 |
+
# νκ²½ λ³μ κ²μ¦
|
40 |
+
if not FRIENDLI_TOKEN and not TEST_MODE:
|
41 |
+
logger.warning("FRIENDLI_TOKEN not set and TEST_MODE is false. Application will run in test mode.")
|
42 |
+
TEST_MODE = True
|
43 |
+
|
44 |
+
if not BRAVE_SEARCH_API_KEY:
|
45 |
+
logger.warning("BRAVE_SEARCH_API_KEY not set. Web search features will be disabled.")
|
46 |
+
|
47 |
+
# μ μ λ³μ
|
48 |
+
conversation_history = []
|
49 |
+
selected_language = "English" # κΈ°λ³Έ μΈμ΄
|
50 |
+
|
51 |
+
# DB κ²½λ‘
|
52 |
+
DB_PATH = "novel_sessions.db"
|
53 |
+
db_lock = threading.Lock()
|
54 |
+
|
55 |
+
# Stage λ²νΈ μμ - 10λͺ
μ μκ°λ‘ λ³κ²½
|
56 |
+
WRITER_DRAFT_STAGES = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] # μκ° μ΄μ
|
57 |
+
WRITER_REVISION_STAGES = [5, 8, 11, 14, 17, 20, 23, 26, 29, 32] # μκ° μμ λ³Έ
|
58 |
+
TOTAL_WRITERS = 10 # μ΄ μκ° μ
|
59 |
+
|
60 |
+
class WebSearchIntegration:
|
61 |
+
"""Brave Search API integration for research"""
|
62 |
+
|
63 |
+
def __init__(self):
|
64 |
+
self.brave_api_key = BRAVE_SEARCH_API_KEY
|
65 |
+
self.search_url = "https://api.search.brave.com/res/v1/web/search"
|
66 |
+
self.enabled = bool(self.brave_api_key)
|
67 |
+
|
68 |
+
def search(self, query: str, count: int = 5, language: str = "en") -> List[Dict]:
|
69 |
+
"""Perform web search using Brave Search API"""
|
70 |
+
if not self.enabled:
|
71 |
+
return []
|
72 |
+
|
73 |
+
headers = {
|
74 |
+
"Accept": "application/json",
|
75 |
+
"X-Subscription-Token": self.brave_api_key
|
76 |
+
}
|
77 |
+
|
78 |
+
# μΈμ΄μ λ°λ₯Έ κ²μ μ€μ
|
79 |
+
search_lang = "ko" if language == "Korean" else "en"
|
80 |
+
|
81 |
+
params = {
|
82 |
+
"q": query,
|
83 |
+
"count": count,
|
84 |
+
"search_lang": search_lang,
|
85 |
+
"text_decorations": False,
|
86 |
+
"safesearch": "moderate"
|
87 |
+
}
|
88 |
+
|
89 |
+
try:
|
90 |
+
response = requests.get(self.search_url, headers=headers, params=params, timeout=10)
|
91 |
+
if response.status_code == 200:
|
92 |
+
results = response.json()
|
93 |
+
web_results = results.get("web", {}).get("results", [])
|
94 |
+
logger.info(f"Search successful: Found {len(web_results)} results for '{query}'")
|
95 |
+
return web_results
|
96 |
+
else:
|
97 |
+
logger.error(f"Search API error: {response.status_code}")
|
98 |
+
return []
|
99 |
+
except Exception as e:
|
100 |
+
logger.error(f"Search error: {str(e)}")
|
101 |
+
return []
|
102 |
+
|
103 |
+
def extract_relevant_info(self, results: List[Dict], max_chars: int = 3000) -> str:
|
104 |
+
"""Extract relevant information from search results"""
|
105 |
+
if not results:
|
106 |
+
return ""
|
107 |
+
|
108 |
+
extracted = []
|
109 |
+
total_chars = 0
|
110 |
+
|
111 |
+
for i, result in enumerate(results[:5], 1): # μ΅λ 5κ° κ²°κ³Ό
|
112 |
+
title = result.get("title", "")
|
113 |
+
description = result.get("description", "")
|
114 |
+
url = result.get("url", "")
|
115 |
+
|
116 |
+
# μΌλΆ λ΄μ© μΆμΆ
|
117 |
+
extra_text = ""
|
118 |
+
if "extra_snippets" in result:
|
119 |
+
extra_text = " ".join(result["extra_snippets"][:2])
|
120 |
+
|
121 |
+
info = f"""[{i}] {title}
|
122 |
+
{description}
|
123 |
+
{extra_text}
|
124 |
+
Source: {url}
|
125 |
+
"""
|
126 |
+
|
127 |
+
if total_chars + len(info) < max_chars:
|
128 |
+
extracted.append(info)
|
129 |
+
total_chars += len(info)
|
130 |
+
else:
|
131 |
+
break
|
132 |
+
|
133 |
+
return "\n---\n".join(extracted)
|
134 |
+
|
135 |
+
def create_research_queries(self, topic: str, role: str, stage_info: Dict, language: str = "English") -> List[str]:
|
136 |
+
"""Create multiple research queries based on role and context"""
|
137 |
+
queries = []
|
138 |
+
|
139 |
+
if language == "Korean":
|
140 |
+
if role == "director":
|
141 |
+
queries = [
|
142 |
+
f"{topic} μμ€ λ°°κ²½ μ€μ ",
|
143 |
+
f"{topic} μμ¬μ μ¬μ€",
|
144 |
+
f"{topic} λ¬Ένμ νΉμ§"
|
145 |
+
]
|
146 |
+
elif role.startswith("writer"):
|
147 |
+
writer_num = int(role.replace("writer", ""))
|
148 |
+
if writer_num <= 3: # μ΄λ°λΆ μκ°
|
149 |
+
queries = [
|
150 |
+
f"{topic} ꡬ체μ μ₯λ©΄ λ¬μ¬",
|
151 |
+
f"{topic} μ λ¬Έ μ©μ΄ μ€λͺ
"
|
152 |
+
]
|
153 |
+
elif writer_num <= 6: # μ€λ°λΆ μκ°
|
154 |
+
queries = [
|
155 |
+
f"{topic} κ°λ± μν© μ¬λ‘",
|
156 |
+
f"{topic} μ¬λ¦¬μ μΈ‘λ©΄"
|
157 |
+
]
|
158 |
+
else: # νλ°λΆ μκ°
|
159 |
+
queries = [
|
160 |
+
f"{topic} ν΄κ²° λ°©λ²",
|
161 |
+
f"{topic} κ°λμ μΈ μ¬λ‘"
|
162 |
+
]
|
163 |
+
elif role == "critic":
|
164 |
+
queries = [
|
165 |
+
f"{topic} λ¬Έν μν λΆμ",
|
166 |
+
f"{topic} μ μ¬ μμ€ μΆμ²"
|
167 |
+
]
|
168 |
+
else:
|
169 |
+
if role == "director":
|
170 |
+
queries = [
|
171 |
+
f"{topic} novel setting ideas",
|
172 |
+
f"{topic} historical facts",
|
173 |
+
f"{topic} cultural aspects"
|
174 |
+
]
|
175 |
+
elif role.startswith("writer"):
|
176 |
+
writer_num = int(role.replace("writer", ""))
|
177 |
+
if writer_num <= 3: # Early writers
|
178 |
+
queries = [
|
179 |
+
f"{topic} vivid scene descriptions",
|
180 |
+
f"{topic} technical terminology explained"
|
181 |
+
]
|
182 |
+
elif writer_num <= 6: # Middle writers
|
183 |
+
queries = [
|
184 |
+
f"{topic} conflict scenarios",
|
185 |
+
f"{topic} psychological aspects"
|
186 |
+
]
|
187 |
+
else: # Later writers
|
188 |
+
queries = [
|
189 |
+
f"{topic} resolution methods",
|
190 |
+
f"{topic} emotional stories"
|
191 |
+
]
|
192 |
+
elif role == "critic":
|
193 |
+
queries = [
|
194 |
+
f"{topic} literary analysis",
|
195 |
+
f"{topic} similar novels recommendations"
|
196 |
+
]
|
197 |
+
|
198 |
+
return queries
|
199 |
+
|
200 |
+
class NovelDatabase:
|
201 |
+
"""Novel session management database with enhanced recovery features"""
|
202 |
+
|
203 |
+
@staticmethod
|
204 |
+
def init_db():
|
205 |
+
"""Initialize database tables with WAL mode for better concurrency"""
|
206 |
+
with sqlite3.connect(DB_PATH) as conn:
|
207 |
+
# Enable WAL mode for better concurrent access
|
208 |
+
conn.execute("PRAGMA journal_mode=WAL")
|
209 |
+
|
210 |
+
cursor = conn.cursor()
|
211 |
+
|
212 |
+
# Sessions table with enhanced recovery fields
|
213 |
+
cursor.execute('''
|
214 |
+
CREATE TABLE IF NOT EXISTS sessions (
|
215 |
+
session_id TEXT PRIMARY KEY,
|
216 |
+
user_query TEXT NOT NULL,
|
217 |
+
language TEXT NOT NULL,
|
218 |
+
created_at TEXT DEFAULT (datetime('now')),
|
219 |
+
updated_at TEXT DEFAULT (datetime('now')),
|
220 |
+
status TEXT DEFAULT 'active',
|
221 |
+
current_stage INTEGER DEFAULT 0,
|
222 |
+
last_saved_stage INTEGER DEFAULT -1,
|
223 |
+
recovery_data TEXT,
|
224 |
+
final_novel TEXT
|
225 |
+
)
|
226 |
+
''')
|
227 |
+
|
228 |
+
# Stages table - κ° μ€ν
μ΄μ§μ μ 체 λ΄μ© μ μ₯
|
229 |
+
cursor.execute('''
|
230 |
+
CREATE TABLE IF NOT EXISTS stages (
|
231 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
232 |
+
session_id TEXT NOT NULL,
|
233 |
+
stage_number INTEGER NOT NULL,
|
234 |
+
stage_name TEXT NOT NULL,
|
235 |
+
role TEXT NOT NULL,
|
236 |
+
content TEXT,
|
237 |
+
word_count INTEGER DEFAULT 0,
|
238 |
+
status TEXT DEFAULT 'pending',
|
239 |
+
created_at TEXT DEFAULT (datetime('now')),
|
240 |
+
updated_at TEXT DEFAULT (datetime('now')),
|
241 |
+
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
242 |
+
UNIQUE(session_id, stage_number)
|
243 |
+
)
|
244 |
+
''')
|
245 |
+
|
246 |
+
# Search history table - κ²μ μ΄λ ₯ μ μ₯
|
247 |
+
cursor.execute('''
|
248 |
+
CREATE TABLE IF NOT EXISTS search_history (
|
249 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
250 |
+
session_id TEXT NOT NULL,
|
251 |
+
stage_number INTEGER NOT NULL,
|
252 |
+
role TEXT NOT NULL,
|
253 |
+
query TEXT NOT NULL,
|
254 |
+
results TEXT,
|
255 |
+
created_at TEXT DEFAULT (datetime('now')),
|
256 |
+
FOREIGN KEY (session_id) REFERENCES sessions(session_id)
|
257 |
+
)
|
258 |
+
''')
|
259 |
+
|
260 |
+
# Create indices
|
261 |
+
cursor.execute('CREATE INDEX IF NOT EXISTS idx_session_id ON stages(session_id)')
|
262 |
+
cursor.execute('CREATE INDEX IF NOT EXISTS idx_stage_number ON stages(stage_number)')
|
263 |
+
cursor.execute('CREATE INDEX IF NOT EXISTS idx_search_session ON search_history(session_id)')
|
264 |
+
cursor.execute('CREATE INDEX IF NOT EXISTS idx_session_status ON sessions(status)')
|
265 |
+
|
266 |
+
conn.commit()
|
267 |
+
|
268 |
+
@staticmethod
|
269 |
+
def save_search_history(session_id: str, stage_number: int, role: str, query: str, results: str):
|
270 |
+
"""Save search history"""
|
271 |
+
with sqlite3.connect(DB_PATH) as conn:
|
272 |
+
cursor = conn.cursor()
|
273 |
+
cursor.execute('''
|
274 |
+
INSERT INTO search_history (session_id, stage_number, role, query, results)
|
275 |
+
VALUES (?, ?, ?, ?, ?)
|
276 |
+
''', (session_id, stage_number, role, query, results))
|
277 |
+
conn.commit()
|
278 |
+
|
279 |
+
@staticmethod
|
280 |
+
@contextmanager
|
281 |
+
def get_db():
|
282 |
+
"""Database connection context manager with timeout"""
|
283 |
+
with db_lock:
|
284 |
+
conn = sqlite3.connect(DB_PATH, timeout=30.0)
|
285 |
+
conn.row_factory = sqlite3.Row
|
286 |
+
try:
|
287 |
+
yield conn
|
288 |
+
finally:
|
289 |
+
conn.close()
|
290 |
+
|
291 |
+
@staticmethod
|
292 |
+
def create_session(user_query: str, language: str) -> str:
|
293 |
+
"""Create new session"""
|
294 |
+
session_id = hashlib.md5(f"{user_query}{datetime.now()}".encode()).hexdigest()
|
295 |
+
|
296 |
+
with NovelDatabase.get_db() as conn:
|
297 |
+
cursor = conn.cursor()
|
298 |
+
cursor.execute('''
|
299 |
+
INSERT INTO sessions (session_id, user_query, language)
|
300 |
+
VALUES (?, ?, ?)
|
301 |
+
''', (session_id, user_query, language))
|
302 |
+
conn.commit()
|
303 |
+
|
304 |
+
return session_id
|
305 |
+
|
306 |
+
@staticmethod
|
307 |
+
def save_stage(session_id: str, stage_number: int, stage_name: str,
|
308 |
+
role: str, content: str, status: str = 'complete'):
|
309 |
+
"""Save stage content with word count"""
|
310 |
+
word_count = len(content.split()) if content else 0
|
311 |
+
|
312 |
+
with NovelDatabase.get_db() as conn:
|
313 |
+
cursor = conn.cursor()
|
314 |
+
|
315 |
+
# UPSERT operation
|
316 |
+
cursor.execute('''
|
317 |
+
INSERT INTO stages (session_id, stage_number, stage_name, role, content, word_count, status)
|
318 |
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
319 |
+
ON CONFLICT(session_id, stage_number)
|
320 |
+
DO UPDATE SET content=?, word_count=?, status=?, stage_name=?, updated_at=datetime('now')
|
321 |
+
''', (session_id, stage_number, stage_name, role, content, word_count, status,
|
322 |
+
content, word_count, status, stage_name))
|
323 |
+
|
324 |
+
# Update session
|
325 |
+
cursor.execute('''
|
326 |
+
UPDATE sessions
|
327 |
+
SET updated_at = datetime('now'),
|
328 |
+
current_stage = ?,
|
329 |
+
last_saved_stage = ?
|
330 |
+
WHERE session_id = ?
|
331 |
+
''', (stage_number, stage_number, session_id))
|
332 |
+
|
333 |
+
conn.commit()
|
334 |
+
logger.info(f"Saved stage {stage_number} for session {session_id}, content length: {len(content)}, words: {word_count}")
|
335 |
+
|
336 |
+
@staticmethod
|
337 |
+
def get_session(session_id: str) -> Optional[Dict]:
|
338 |
+
"""Get session info"""
|
339 |
+
with NovelDatabase.get_db() as conn:
|
340 |
+
cursor = conn.cursor()
|
341 |
+
cursor.execute('SELECT * FROM sessions WHERE session_id = ?', (session_id,))
|
342 |
+
return cursor.fetchone()
|
343 |
+
|
344 |
+
@staticmethod
|
345 |
+
def get_latest_active_session() -> Optional[Dict]:
|
346 |
+
"""Get the most recent active session"""
|
347 |
+
with NovelDatabase.get_db() as conn:
|
348 |
+
cursor = conn.cursor()
|
349 |
+
cursor.execute('''
|
350 |
+
SELECT * FROM sessions
|
351 |
+
WHERE status = 'active'
|
352 |
+
ORDER BY updated_at DESC
|
353 |
+
LIMIT 1
|
354 |
+
''')
|
355 |
+
return cursor.fetchone()
|
356 |
+
|
357 |
+
@staticmethod
|
358 |
+
def get_stages(session_id: str) -> List[Dict]:
|
359 |
+
"""Get all stages for a session"""
|
360 |
+
with NovelDatabase.get_db() as conn:
|
361 |
+
cursor = conn.cursor()
|
362 |
+
cursor.execute('''
|
363 |
+
SELECT * FROM stages
|
364 |
+
WHERE session_id = ?
|
365 |
+
ORDER BY stage_number
|
366 |
+
''', (session_id,))
|
367 |
+
return cursor.fetchall()
|
368 |
+
|
369 |
+
@staticmethod
|
370 |
+
def get_all_writer_content(session_id: str) -> str:
|
371 |
+
"""λͺ¨λ μκ°μ μμ λ³Έ λ΄μ©μ κ°μ Έμμ ν©μΉκΈ° - 10λͺ
μκ°"""
|
372 |
+
with NovelDatabase.get_db() as conn:
|
373 |
+
cursor = conn.cursor()
|
374 |
+
|
375 |
+
all_content = []
|
376 |
+
writer_count = 0
|
377 |
+
total_word_count = 0
|
378 |
+
|
379 |
+
for stage_num in WRITER_REVISION_STAGES:
|
380 |
+
cursor.execute('''
|
381 |
+
SELECT content, stage_name, word_count FROM stages
|
382 |
+
WHERE session_id = ? AND stage_number = ?
|
383 |
+
''', (session_id, stage_num))
|
384 |
+
|
385 |
+
row = cursor.fetchone()
|
386 |
+
if row and row['content']:
|
387 |
+
# νμ΄μ§ λ§ν¬ μμ μ κ±°
|
388 |
+
clean_content = re.sub(r'\[(?:νμ΄μ§|Page|page)\s*\d+\]', '', row['content'])
|
389 |
+
clean_content = re.sub(r'(?:νμ΄μ§|Page)\s*\d+:', '', clean_content)
|
390 |
+
clean_content = clean_content.strip()
|
391 |
+
|
392 |
+
if clean_content:
|
393 |
+
writer_count += 1
|
394 |
+
word_count = row['word_count'] or len(clean_content.split())
|
395 |
+
total_word_count += word_count
|
396 |
+
all_content.append(clean_content)
|
397 |
+
logger.info(f"Writer {writer_count} (stage {stage_num}): {word_count} words")
|
398 |
+
|
399 |
+
full_content = '\n\n'.join(all_content)
|
400 |
+
logger.info(f"Total: {writer_count} writers, {total_word_count} words")
|
401 |
+
|
402 |
+
# 10λͺ
μκ° * 1,450 νκ· = 14,500 λ¨μ΄ λͺ©ν
|
403 |
+
if total_word_count < 12000:
|
404 |
+
logger.warning(f"Content too short! Only {total_word_count} words instead of ~14,500")
|
405 |
+
|
406 |
+
return full_content
|
407 |
+
|
408 |
+
@staticmethod
|
409 |
+
def update_final_novel(session_id: str, final_novel: str):
|
410 |
+
"""Update final novel content"""
|
411 |
+
with NovelDatabase.get_db() as conn:
|
412 |
+
cursor = conn.cursor()
|
413 |
+
cursor.execute('''
|
414 |
+
UPDATE sessions
|
415 |
+
SET final_novel = ?, status = 'complete', updated_at = datetime('now')
|
416 |
+
WHERE session_id = ?
|
417 |
+
''', (final_novel, session_id))
|
418 |
+
conn.commit()
|
419 |
+
logger.info(f"Updated final novel for session {session_id}, length: {len(final_novel)}")
|
420 |
+
|
421 |
+
@staticmethod
|
422 |
+
def get_active_sessions() -> List[Dict]:
|
423 |
+
"""Get all active sessions"""
|
424 |
+
with NovelDatabase.get_db() as conn:
|
425 |
+
cursor = conn.cursor()
|
426 |
+
cursor.execute('''
|
427 |
+
SELECT session_id, user_query, language, created_at, current_stage
|
428 |
+
FROM sessions
|
429 |
+
WHERE status = 'active'
|
430 |
+
ORDER BY updated_at DESC
|
431 |
+
LIMIT 10
|
432 |
+
''')
|
433 |
+
return cursor.fetchall()
|
434 |
+
|
435 |
+
@staticmethod
|
436 |
+
def parse_datetime(datetime_str: str) -> datetime:
|
437 |
+
"""Parse SQLite datetime string safely"""
|
438 |
+
try:
|
439 |
+
# Try ISO format first
|
440 |
+
return datetime.fromisoformat(datetime_str)
|
441 |
+
except:
|
442 |
+
# Fallback to SQLite default format
|
443 |
+
return datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
|
444 |
+
|
445 |
+
class NovelWritingSystem:
|
446 |
+
def __init__(self):
|
447 |
+
self.token = FRIENDLI_TOKEN
|
448 |
+
self.api_url = API_URL
|
449 |
+
self.model_id = MODEL_ID
|
450 |
+
self.test_mode = TEST_MODE or not self.token
|
451 |
+
|
452 |
+
# Web search integration
|
453 |
+
self.web_search = WebSearchIntegration()
|
454 |
+
|
455 |
+
if self.test_mode:
|
456 |
+
logger.warning("Running in test mode - no actual API calls will be made.")
|
457 |
+
else:
|
458 |
+
logger.info("Running in production mode with API calls enabled.")
|
459 |
+
|
460 |
+
if self.web_search.enabled:
|
461 |
+
logger.info("Web search is enabled with Brave Search API.")
|
462 |
+
else:
|
463 |
+
logger.warning("Web search is disabled. Set BRAVE_SEARCH_API_KEY to enable.")
|
464 |
+
|
465 |
+
# Initialize database
|
466 |
+
NovelDatabase.init_db()
|
467 |
+
|
468 |
+
# Session management
|
469 |
+
self.current_session_id = None
|
470 |
+
self.total_stages = 0 # Will be set in process_novel_stream
|
471 |
+
|
472 |
+
def create_headers(self):
|
473 |
+
"""API ν€λ μμ±"""
|
474 |
+
return {
|
475 |
+
"Authorization": f"Bearer {self.token}",
|
476 |
+
"Content-Type": "application/json"
|
477 |
+
}
|
478 |
+
|
479 |
+
def enhance_prompt_with_research(self, original_prompt: str, role: str,
|
480 |
+
topic: str, stage_info: Dict, language: str = "English") -> str:
|
481 |
+
"""Enhance prompt with web search results"""
|
482 |
+
if not self.web_search.enabled or self.test_mode:
|
483 |
+
return original_prompt
|
484 |
+
|
485 |
+
# Create research queries
|
486 |
+
queries = self.web_search.create_research_queries(topic, role, stage_info, language)
|
487 |
+
|
488 |
+
all_research = []
|
489 |
+
for query in queries[:2]: # μ΅λ 2κ° μΏΌλ¦¬
|
490 |
+
logger.info(f"Searching: {query}")
|
491 |
+
results = self.web_search.search(query, count=3, language=language)
|
492 |
+
if results:
|
493 |
+
research_text = self.web_search.extract_relevant_info(results, max_chars=1500)
|
494 |
+
if research_text:
|
495 |
+
all_research.append(f"### {query}\n{research_text}")
|
496 |
+
|
497 |
+
# Save search history
|
498 |
+
if self.current_session_id:
|
499 |
+
NovelDatabase.save_search_history(
|
500 |
+
self.current_session_id,
|
501 |
+
stage_info.get('stage_idx', 0),
|
502 |
+
role,
|
503 |
+
query,
|
504 |
+
research_text
|
505 |
+
)
|
506 |
+
|
507 |
+
if not all_research:
|
508 |
+
return original_prompt
|
509 |
+
|
510 |
+
# Add research to prompt
|
511 |
+
if language == "Korean":
|
512 |
+
research_section = f"""
|
513 |
+
## μΉ κ²μ μ°Έκ³ μλ£:
|
514 |
+
{chr(10).join(all_research)}
|
515 |
+
|
516 |
+
μμ κ²μ κ²°κ³Όλ₯Ό μ°Έκ³ νμ¬ λμ± μ¬μ€μ μ΄κ³ ꡬ체μ μΈ λ΄μ©μ μμ±νμΈμ.
|
517 |
+
κ²μ κ²°κ³Όμ μ 보λ₯Ό μ°½μμ μΌλ‘ νμ©νλ, μ§μ μΈμ©μ νΌνκ³ μμ€μ μμ°μ€λ½κ² λ
Ήμ¬λ΄μΈμ.
|
518 |
+
μ€μ μ¬μ€κ³Ό μ°½μμ μ μ ν μ‘°νμμΌ λ
μκ° λͺ°μ
ν μ μλ μ΄μΌκΈ°λ₯Ό λ§λμΈμ.
|
519 |
+
"""
|
520 |
+
else:
|
521 |
+
research_section = f"""
|
522 |
+
## Web Search Reference:
|
523 |
+
{chr(10).join(all_research)}
|
524 |
+
|
525 |
+
Use the above search results to create more realistic and specific content.
|
526 |
+
Creatively incorporate the information from search results, but avoid direct quotes and naturally blend them into the novel.
|
527 |
+
Balance real facts with creative fiction to create an immersive story for readers.
|
528 |
+
"""
|
529 |
+
|
530 |
+
return original_prompt + "\n\n" + research_section
|
531 |
+
|
532 |
+
def create_director_initial_prompt(self, user_query: str, language: str = "English") -> str:
|
533 |
+
"""Director AI initial prompt - Novel planning for 10 writers"""
|
534 |
+
if language == "Korean":
|
535 |
+
return f"""λΉμ μ 30νμ΄μ§ λΆλμ μ€νΈ μμ€μ κΈ°ννλ λ¬Έν κ°λ
μμ
λλ€.
|
536 |
+
|
537 |
+
μ¬μ©μ μμ²: {user_query}
|
538 |
+
|
539 |
+
λ€μ μμλ€μ 체κ³μ μΌλ‘ ꡬμ±νμ¬ 30νμ΄μ§ μ€νΈ μμ€μ κΈ°μ΄λ₯Ό λ§λμΈμ:
|
540 |
+
|
541 |
+
1. **μ£Όμ μ μ₯λ₯΄**
|
542 |
+
- ν΅μ¬ μ£Όμ μ λ©μμ§
|
543 |
+
- μ₯λ₯΄ λ° ν€
|
544 |
+
- λͺ©ν λ
μμΈ΅
|
545 |
+
|
546 |
+
2. **λ±μ₯μΈλ¬Ό μ€μ ** (νλ‘ μ 리)
|
547 |
+
| μ΄λ¦ | μν | μ±κ²© | λ°°κ²½ | λκΈ° | λ³ν |
|
548 |
+
|------|------|------|------|------|------|
|
549 |
+
|
550 |
+
3. **μΈλ¬Ό κ΄κ³λ**
|
551 |
+
- μ£Όμ μΈλ¬Ό κ°μ κ΄κ³
|
552 |
+
- κ°λ± ꡬ쑰
|
553 |
+
- κ°μ μ μ°κ²°κ³ 리
|
554 |
+
|
555 |
+
4. **μμ¬ κ΅¬μ‘°** (30νμ΄μ§λ₯Ό 10κ° ννΈλ‘ λλμ΄ κ° 3νμ΄μ§)
|
556 |
+
| ννΈ | νμ΄μ§ | μ£Όμ μ¬κ±΄ | κΈ΄μ₯λ | μΈλ¬Ό λ°μ |
|
557 |
+
|------|--------|-----------|---------|-----------|
|
558 |
+
| 1 | 1-3 | | | |
|
559 |
+
| 2 | 4-6 | | | |
|
560 |
+
| ... | ... | | | |
|
561 |
+
| 10 | 28-30 | | | |
|
562 |
+
|
563 |
+
5. **μΈκ³κ΄ μ€μ **
|
564 |
+
- μ곡κ°μ λ°°κ²½
|
565 |
+
- μ¬νμ /λ¬Ένμ λ§₯λ½
|
566 |
+
- λΆμκΈ°μ ν€
|
567 |
+
|
568 |
+
κ° μμ±μκ° 3νμ΄μ§μ© μμ±ν μ μλλ‘ λͺ
νν κ°μ΄λλΌμΈμ μ μνμΈμ."""
|
569 |
+
else:
|
570 |
+
return f"""You are a literary director planning a 30-page novella.
|
571 |
+
|
572 |
+
User Request: {user_query}
|
573 |
+
|
574 |
+
Systematically compose the following elements to create the foundation for a 30-page novella:
|
575 |
+
|
576 |
+
1. **Theme and Genre**
|
577 |
+
- Core theme and message
|
578 |
+
- Genre and tone
|
579 |
+
- Target audience
|
580 |
+
|
581 |
+
2. **Character Settings** (organize in table)
|
582 |
+
| Name | Role | Personality | Background | Motivation | Arc |
|
583 |
+
|------|------|-------------|------------|------------|-----|
|
584 |
+
|
585 |
+
3. **Character Relationship Map**
|
586 |
+
- Relationships between main characters
|
587 |
+
- Conflict structure
|
588 |
+
- Emotional connections
|
589 |
+
|
590 |
+
4. **Narrative Structure** (divide 30 pages into 10 parts, 3 pages each)
|
591 |
+
| Part | Pages | Main Events | Tension | Character Development |
|
592 |
+
|------|-------|-------------|---------|---------------------|
|
593 |
+
| 1 | 1-3 | | | |
|
594 |
+
| 2 | 4-6 | | | |
|
595 |
+
| ... | ... | | | |
|
596 |
+
| 10 | 28-30 | | | |
|
597 |
+
|
598 |
+
5. **World Building**
|
599 |
+
- Temporal and spatial setting
|
600 |
+
- Social/cultural context
|
601 |
+
- Atmosphere and tone
|
602 |
+
|
603 |
+
Provide clear guidelines for each writer to compose 3 pages."""
|
604 |
+
|
605 |
+
def create_critic_director_prompt(self, director_plan: str, language: str = "English") -> str:
|
606 |
+
"""Critic's review of director's plan"""
|
607 |
+
if language == "Korean":
|
608 |
+
return f"""λΉμ μ λ¬Έν λΉνκ°μ
λλ€. κ°λ
μμ μμ€ κΈ°νμ κ²ν νκ³ κ°μ μ μ μ μνμΈμ.
|
609 |
+
|
610 |
+
κ°λ
μμ κΈ°ν:
|
611 |
+
{director_plan}
|
612 |
+
|
613 |
+
λ€μ κ΄μ μμ λΉννκ³ κ΅¬μ²΄μ μΈ κ°μ μμ μ μνμΈμ:
|
614 |
+
|
615 |
+
1. **μμ¬μ μμ±λ**
|
616 |
+
- νλ‘―μ λ
Όλ¦¬μ±κ³Ό κ°μ°μ±
|
617 |
+
- κ°λ±μ ν¨κ³Όμ±
|
618 |
+
- ν΄λΌμ΄λ§₯μ€μ μμΉμ κ°λ
|
619 |
+
|
620 |
+
2. **μΈλ¬Ό μ€μ κ²ν **
|
621 |
+
| μΈλ¬Ό | κ°μ | μ½μ | κ°μ μ μ |
|
622 |
+
|------|------|------|-----------|
|
623 |
+
|
624 |
+
3. **ꡬ쑰μ κ· ν**
|
625 |
+
- 10κ° ννΈλ³ λΆλ λ°°λΆ
|
626 |
+
- κΈ΄μ₯κ³Ό μ΄μμ 리λ¬
|
627 |
+
- μ 체μ μΈ νλ¦
|
628 |
+
|
629 |
+
4. **λ
μ κ΄μ **
|
630 |
+
- λͺ°μ
λ μμ
|
631 |
+
- κ°μ μ μν₯λ ₯
|
632 |
+
- κΈ°λμΉ μΆ©μ‘±λ
|
633 |
+
|
634 |
+
5. **μ€ν κ°λ₯μ±**
|
635 |
+
- 10λͺ
μ μμ±μλ₯Ό μν κ°μ΄λλΌμΈμ λͺ
νμ±
|
636 |
+
- μΌκ΄μ± μ μ§ λ°©μ
|
637 |
+
- μ μ¬μ λ¬Έμ μ
|
638 |
+
|
639 |
+
ꡬ체μ μ΄κ³ 건μ€μ μΈ νΌλλ°±μ μ 곡νμΈμ."""
|
640 |
+
else:
|
641 |
+
return f"""You are a literary critic. Review the director's novel plan and suggest improvements.
|
642 |
+
|
643 |
+
Director's Plan:
|
644 |
+
{director_plan}
|
645 |
+
|
646 |
+
Critique from the following perspectives and provide specific improvements:
|
647 |
+
|
648 |
+
1. **Narrative Completeness**
|
649 |
+
- Plot logic and plausibility
|
650 |
+
- Effectiveness of conflicts
|
651 |
+
- Climax position and intensity
|
652 |
+
|
653 |
+
2. **Character Review**
|
654 |
+
| Character | Strengths | Weaknesses | Suggestions |
|
655 |
+
|-----------|-----------|------------|-------------|
|
656 |
+
|
657 |
+
3. **Structural Balance**
|
658 |
+
- Distribution across 10 parts
|
659 |
+
- Rhythm of tension and relief
|
660 |
+
- Overall flow
|
661 |
+
|
662 |
+
4. **Reader Perspective**
|
663 |
+
- Expected engagement
|
664 |
+
- Emotional impact
|
665 |
+
- Expectation fulfillment
|
666 |
+
|
667 |
+
5. **Feasibility**
|
668 |
+
- Clarity of guidelines for 10 writers
|
669 |
+
- Consistency maintenance
|
670 |
+
- Potential issues
|
671 |
+
|
672 |
+
Provide specific and constructive feedback."""
|
673 |
+
|
674 |
+
def create_director_revision_prompt(self, initial_plan: str, critic_feedback: str, language: str = "English") -> str:
|
675 |
+
"""Director's revision based on critic feedback"""
|
676 |
+
if language == "Korean":
|
677 |
+
return f"""κ°λ
μλ‘μ λΉνκ°μ νΌλλ°±μ λ°μνμ¬ μμ€ κΈ°νμ μμ ν©λλ€.
|
678 |
+
|
679 |
+
μ΄κΈ° κΈ°ν:
|
680 |
+
{initial_plan}
|
681 |
+
|
682 |
+
λΉνκ° νΌλλ°±:
|
683 |
+
{critic_feedback}
|
684 |
+
|
685 |
+
λ€μμ ν¬ν¨ν μμ λ μ΅μ’
κΈ°νμ μ μνμΈμ:
|
686 |
+
|
687 |
+
1. **μμ λ μμ¬ κ΅¬μ‘°** (10κ° ννΈ)
|
688 |
+
| ννΈ | νμ΄μ§ | μ£Όμ μ¬κ±΄ | μμ± μ§μΉ¨ | μ£Όμμ¬ν |
|
689 |
+
|------|--------|-----------|-----------|----------|
|
690 |
+
|
691 |
+
2. **κ°νλ μΈλ¬Ό μ€μ **
|
692 |
+
- κ° μΈλ¬Όμ λͺ
νν λκΈ°μ λͺ©ν
|
693 |
+
- μΈλ¬Ό κ° κ°λ±μ ꡬ체ν
|
694 |
+
- κ°μ μ μ λ³ν μΆμ΄
|
695 |
+
|
696 |
+
3. **κ° μμ±μλ₯Ό μν μμΈ κ°μ΄λ** (10λͺ
)
|
697 |
+
- ννΈλ³ μμκ³Ό λ μ§μ
|
698 |
+
- νμ ν¬ν¨ μμ
|
699 |
+
- 문체μ ν€ μ§μΉ¨
|
700 |
+
- μ λ¬ν΄μΌ ν μ 보
|
701 |
+
|
702 |
+
4. **μΌκ΄μ± μ μ§ μ²΄ν¬λ¦¬μ€νΈ**
|
703 |
+
- μκ°μ κ΄λ¦¬
|
704 |
+
- μΈλ¬Ό νΉμ± μ μ§
|
705 |
+
- μ€μ μΌκ΄μ±
|
706 |
+
- 볡μ κ³Ό ν΄κ²°
|
707 |
+
|
708 |
+
5. **νμ§ κΈ°μ€**
|
709 |
+
- κ° ννΈμ μμ±λ κΈ°μ€
|
710 |
+
- μ 체μ ν΅μΌμ±
|
711 |
+
- λ
μ λͺ°μ
μ μ§ λ°©μ
|
712 |
+
|
713 |
+
10λͺ
μ μμ±μκ° λͺ
νν μ΄ν΄ν μ μλ μ΅μ’
λ§μ€ν°νλμ μμ±νμΈμ."""
|
714 |
+
else:
|
715 |
+
return f"""As director, revise the novel plan reflecting the critic's feedback.
|
716 |
+
|
717 |
+
Initial Plan:
|
718 |
+
{initial_plan}
|
719 |
+
|
720 |
+
Critic Feedback:
|
721 |
+
{critic_feedback}
|
722 |
+
|
723 |
+
Present the revised final plan including:
|
724 |
+
|
725 |
+
1. **Revised Narrative Structure** (10 parts)
|
726 |
+
| Part | Pages | Main Events | Writing Guidelines | Cautions |
|
727 |
+
|------|-------|-------------|-------------------|----------|
|
728 |
+
|
729 |
+
2. **Enhanced Character Settings**
|
730 |
+
- Clear motivations and goals for each character
|
731 |
+
- Concrete conflicts between characters
|
732 |
+
- Emotional arc progression
|
733 |
+
|
734 |
+
3. **Detailed Guide for Each Writer** (10 writers)
|
735 |
+
- Start and end points for each part
|
736 |
+
- Essential elements to include
|
737 |
+
- Style and tone guidelines
|
738 |
+
- Information to convey
|
739 |
+
|
740 |
+
4. **Consistency Checklist**
|
741 |
+
- Timeline management
|
742 |
+
- Character trait maintenance
|
743 |
+
- Setting consistency
|
744 |
+
- Foreshadowing and resolution
|
745 |
+
|
746 |
+
5. **Quality Standards**
|
747 |
+
- Completion criteria for each part
|
748 |
+
- Overall unity
|
749 |
+
- Reader engagement maintenance
|
750 |
+
|
751 |
+
Create a final masterplan that all 10 writers can clearly understand."""
|
752 |
+
|
753 |
+
def create_writer_prompt(self, writer_number: int, director_plan: str, previous_content: str, language: str = "English") -> str:
|
754 |
+
"""Individual writer prompt - 1,400-1,500 λ¨μ΄"""
|
755 |
+
pages_start = (writer_number - 1) * 3 + 1
|
756 |
+
pages_end = writer_number * 3
|
757 |
+
|
758 |
+
if language == "Korean":
|
759 |
+
return f"""λΉμ μ μμ±μ {writer_number}λ²μ
λλ€. 30νμ΄μ§ μ€νΈ μμ€μ {pages_start}-{pages_end}νμ΄μ§(3νμ΄μ§)λ₯Ό μμ±νμΈμ.
|
760 |
+
|
761 |
+
κ°λ
μμ λ§μ€ν°νλ:
|
762 |
+
{director_plan}
|
763 |
+
|
764 |
+
{'μ΄μ κΉμ§μ λ΄μ©:' if previous_content else 'λΉμ μ΄ μ²« λ²μ§Έ μμ±μμ
λλ€.'}
|
765 |
+
{previous_content[-2000:] if previous_content else ''}
|
766 |
+
|
767 |
+
**μ€μ μ§μΉ¨:**
|
768 |
+
|
769 |
+
1. **νμ λΆλ**:
|
770 |
+
- μ΅μ 1,400λ¨μ΄, μ΅λ 1,500λ¨μ΄
|
771 |
+
- λλ΅ 7000-7500μ (곡백 ν¬ν¨)
|
772 |
+
- 3νμ΄μ§ λΆλμ μ νν μ±μμΌ ν©λλ€
|
773 |
+
|
774 |
+
2. **λΆλ ν보 μ λ΅**:
|
775 |
+
- μμΈν μ₯λ©΄ λ¬μ¬ ν¬ν¨
|
776 |
+
- μΈλ¬Όμ λ΄λ©΄ μ¬λ¦¬ κΉμ΄ μκ² νꡬ
|
777 |
+
- λνμ νλμ ꡬ체μ μΌλ‘ νν
|
778 |
+
- λ°°κ²½κ³Ό λΆμκΈ°λ₯Ό μμνκ² κ·Έλ €λ΄κΈ°
|
779 |
+
- κ°κ°μ μΈλΆμ¬ν(μκ°, μ²κ°, μ΄κ° λ±) νμ©
|
780 |
+
|
781 |
+
3. **μ°μμ±κ³Ό μΌκ΄μ±**:
|
782 |
+
- μ΄μ λ΄μ©κ³Ό μμ°μ€λ½κ² μ°κ²°
|
783 |
+
- μΈλ¬Ό μ±κ²©κ³Ό λ§ν¬ μ μ§
|
784 |
+
- μκ°μ κ³Ό κ³΅κ° μ€μ μ€μ
|
785 |
+
|
786 |
+
4. **μμ¬ λ°μ **:
|
787 |
+
- νλ‘―μ μλ―Έ μκ² μ μ§μν€κΈ°
|
788 |
+
- κΈ΄μ₯κ° μ μ ν μ‘°μ
|
789 |
+
- λ
μμ κ΄μ¬ μ μ§
|
790 |
+
|
791 |
+
**μμ± μμ:**
|
792 |
+
μ΄μ 1,400-1,500λ¨μ΄ λΆλμ μμ€μ μμ±νμΈμ. νμ΄μ§ κ΅¬λΆ νμλ νμ§ λ§μΈμ."""
|
793 |
+
else:
|
794 |
+
return f"""You are Writer #{writer_number}. Write pages {pages_start}-{pages_end} (3 pages) of the 30-page novella.
|
795 |
+
|
796 |
+
Director's Masterplan:
|
797 |
+
{director_plan}
|
798 |
+
|
799 |
+
{'Previous content:' if previous_content else 'You are the first writer.'}
|
800 |
+
{previous_content[-2000:] if previous_content else ''}
|
801 |
+
|
802 |
+
**CRITICAL INSTRUCTIONS:**
|
803 |
+
|
804 |
+
1. **MANDATORY LENGTH**:
|
805 |
+
- Minimum 1,400 words, Maximum 1,500 words
|
806 |
+
- Approximately 7000-7500 characters
|
807 |
+
- You MUST fill exactly 3 pages
|
808 |
+
|
809 |
+
2. **LENGTH STRATEGIES**:
|
810 |
+
- Include detailed scene descriptions
|
811 |
+
- Explore character's inner psychology deeply
|
812 |
+
- Express dialogue and actions concretely
|
813 |
+
- Paint backgrounds and atmosphere vividly
|
814 |
+
- Use sensory details (visual, auditory, tactile, etc.)
|
815 |
+
|
816 |
+
3. **CONTINUITY & CONSISTENCY**:
|
817 |
+
- Flow naturally from previous content
|
818 |
+
- Maintain character personalities and speech
|
819 |
+
- Follow timeline and spatial settings
|
820 |
+
|
821 |
+
4. **NARRATIVE DEVELOPMENT**:
|
822 |
+
- Advance the plot meaningfully
|
823 |
+
- Control tension appropriately
|
824 |
+
- Maintain reader interest
|
825 |
+
|
826 |
+
**BEGIN WRITING:**
|
827 |
+
Now write your 1,400-1,500 word section. Do not use any page markers."""
|
828 |
+
|
829 |
+
def create_critic_writer_prompt(self, writer_number: int, writer_content: str, director_plan: str, all_previous_content: str, language: str = "English") -> str:
|
830 |
+
"""Critic's review of individual writer's work"""
|
831 |
+
if language == "Korean":
|
832 |
+
return f"""μμ±μ {writer_number}λ²μ μνμ λΉνν©λλ€.
|
833 |
+
|
834 |
+
κ°λ
μμ λ§μ€ν°νλ:
|
835 |
+
{director_plan}
|
836 |
+
|
837 |
+
μ΄μ λ΄μ© μμ½:
|
838 |
+
{all_previous_content[-1000:] if all_previous_content else '첫 λ²μ§Έ μμ±μμ
λλ€.'}
|
839 |
+
|
840 |
+
μμ±μ {writer_number}λ²μ λ΄μ©:
|
841 |
+
{writer_content}
|
842 |
+
|
843 |
+
λ€μ κΈ°μ€μΌλ‘ νκ°νκ³ μμ μꡬμ¬νμ μ μνμΈμ:
|
844 |
+
|
845 |
+
1. **μΌκ΄μ± κ²μ¦** (νλ‘ μ 리)
|
846 |
+
| μμ | μ΄μ μ€μ | νμ¬ νν | λ¬Έμ μ | μμ νμ |
|
847 |
+
|------|----------|----------|--------|----------|
|
848 |
+
|
849 |
+
2. **λ
Όλ¦¬μ μ€λ₯ κ²ν **
|
850 |
+
- μκ°μ λͺ¨μ
|
851 |
+
- μΈλ¬Ό νλμ κ°μ°μ±
|
852 |
+
- μ€μ μΆ©λ
|
853 |
+
- μ¬μ€κ΄κ³ μ€λ₯
|
854 |
+
|
855 |
+
3. **μμ¬μ ν¨κ³Όμ±**
|
856 |
+
- νλ‘― μ§ν κΈ°μ¬λ
|
857 |
+
- κΈ΄μ₯κ° μ μ§
|
858 |
+
- λ
μ λͺ°μ
λ
|
859 |
+
- κ°μ μ μν₯λ ₯
|
860 |
+
|
861 |
+
4. **문체μ νμ§**
|
862 |
+
- μ 체 ν€κ³Όμ μΌμΉ
|
863 |
+
- λ¬Έμ₯μ μ§
|
864 |
+
- λ¬μ¬μ μ μ μ±
|
865 |
+
- λνμ μμ°μ€λ¬μ
|
866 |
+
|
867 |
+
5. **κ°μ μꡬμ¬ν**
|
868 |
+
- νμ μμ μ¬ν (μΌκ΄μ±/λ
Όλ¦¬ μ€λ₯)
|
869 |
+
- κΆμ₯ κ°μ μ¬ν (νμ§ ν₯μ)
|
870 |
+
- ꡬ체μ μμ μ§μΉ¨
|
871 |
+
|
872 |
+
λ°λμ μμ μ΄ νμν λΆλΆκ³Ό μ νμ κ°μ μ¬νμ ꡬλΆνμ¬ μ μνμΈμ."""
|
873 |
+
else:
|
874 |
+
return f"""Critiquing Writer #{writer_number}'s work.
|
875 |
+
|
876 |
+
Director's Masterplan:
|
877 |
+
{director_plan}
|
878 |
+
|
879 |
+
Previous Content Summary:
|
880 |
+
{all_previous_content[-1000:] if all_previous_content else 'This is the first writer.'}
|
881 |
+
|
882 |
+
Writer #{writer_number}'s Content:
|
883 |
+
{writer_content}
|
884 |
+
|
885 |
+
Evaluate by these criteria and present revision requirements:
|
886 |
+
|
887 |
+
1. **Consistency Verification** (organize in table)
|
888 |
+
| Element | Previous Setting | Current Expression | Issue | Revision Needed |
|
889 |
+
|---------|-----------------|-------------------|-------|-----------------|
|
890 |
+
|
891 |
+
2. **Logical Error Review**
|
892 |
+
- Timeline contradictions
|
893 |
+
- Character action plausibility
|
894 |
+
- Setting conflicts
|
895 |
+
- Factual errors
|
896 |
+
|
897 |
+
3. **Narrative Effectiveness**
|
898 |
+
- Plot progression contribution
|
899 |
+
- Tension maintenance
|
900 |
+
- Reader engagement
|
901 |
+
- Emotional impact
|
902 |
+
|
903 |
+
4. **Style and Quality**
|
904 |
+
- Alignment with overall tone
|
905 |
+
- Sentence quality
|
906 |
+
- Description appropriateness
|
907 |
+
- Dialogue naturalness
|
908 |
+
|
909 |
+
5. **Improvement Requirements**
|
910 |
+
- Mandatory revisions (consistency/logic errors)
|
911 |
+
- Recommended improvements (quality enhancement)
|
912 |
+
- Specific revision guidelines
|
913 |
+
|
914 |
+
Clearly distinguish between mandatory revisions and optional improvements."""
|
915 |
+
|
916 |
+
def create_writer_revision_prompt(self, writer_number: int, initial_content: str, critic_feedback: str, language: str = "English") -> str:
|
917 |
+
"""Writer's revision based on critic feedback"""
|
918 |
+
if language == "Korean":
|
919 |
+
return f"""μμ±μ {writer_number}λ²μΌλ‘μ λΉνκ°μ νΌλλ°±μ λ°μνμ¬ μμ ν©λλ€.
|
920 |
+
|
921 |
+
μ΄κΈ° μμ± λ΄μ©:
|
922 |
+
{initial_content}
|
923 |
+
|
924 |
+
λΉνκ° νΌλλ°±:
|
925 |
+
{critic_feedback}
|
926 |
+
|
927 |
+
λ€μ μ¬νμ λ°μν μμ λ³Έμ μμ±νμΈμ:
|
928 |
+
|
929 |
+
1. **νμ μμ μ¬ν λ°μ**
|
930 |
+
- λͺ¨λ μΌκ΄μ± μ€λ₯ μμ
|
931 |
+
- λ
Όλ¦¬μ λͺ¨μ ν΄κ²°
|
932 |
+
- μ¬μ€κ΄κ³ μ μ
|
933 |
+
|
934 |
+
2. **νμ§ κ°μ **
|
935 |
+
- κΆμ₯μ¬ν μ€ κ°λ₯ν λΆλΆ λ°μ
|
936 |
+
- 문체μ ν€ μ‘°μ
|
937 |
+
- λ¬μ¬μ λν κ°μ
|
938 |
+
|
939 |
+
3. **λΆλ μ μ§**
|
940 |
+
- μ¬μ ν μ νν 3νμ΄μ§ (1,400-1,500λ¨μ΄)
|
941 |
+
- νμ΄μ§ κ΅¬λΆ νμ μ λ κΈμ§
|
942 |
+
|
943 |
+
4. **μ°μμ± ν보**
|
944 |
+
- μ΄μ /μ΄ν λ΄μ©κ³Όμ μμ°μ€λ¬μ΄ μ°κ²°
|
945 |
+
- μμ μΌλ‘ μΈν μλ‘μ΄ λͺ¨μ λ°©μ§
|
946 |
+
|
947 |
+
μμ λ μ΅μ’
λ³Έμ μ μνμΈμ. νμ΄μ§ λ§ν¬λ μ λ μ¬μ©νμ§ λ§μΈμ.
|
948 |
+
λ°λμ 1,400-1,500λ¨μ΄ λΆλμ μ μ§νμΈμ."""
|
949 |
+
else:
|
950 |
+
return f"""As Writer #{writer_number}, revise based on critic's feedback.
|
951 |
+
|
952 |
+
Initial Content:
|
953 |
+
{initial_content}
|
954 |
+
|
955 |
+
Critic Feedback:
|
956 |
+
{critic_feedback}
|
957 |
+
|
958 |
+
Write a revision reflecting:
|
959 |
+
|
960 |
+
1. **Mandatory Revisions**
|
961 |
+
- Fix all consistency errors
|
962 |
+
- Resolve logical contradictions
|
963 |
+
- Correct factual errors
|
964 |
+
|
965 |
+
2. **Quality Improvements**
|
966 |
+
- Incorporate feasible recommendations
|
967 |
+
- Adjust style and tone
|
968 |
+
- Improve descriptions and dialogue
|
969 |
+
|
970 |
+
3. **Maintain Length**
|
971 |
+
- Still exactly 3 pages (1,400-1,500 words)
|
972 |
+
- Absolutely no page markers
|
973 |
+
|
974 |
+
4. **Ensure Continuity**
|
975 |
+
- Natural connection with previous/next content
|
976 |
+
- Prevent new contradictions from revisions
|
977 |
+
|
978 |
+
Present the revised final version. Never use page markers.
|
979 |
+
You MUST maintain 1,400-1,500 words."""
|
980 |
+
|
981 |
+
def create_test_writer_complete_prompt(self, director_plan: str, language: str = "English") -> str:
|
982 |
+
"""Test mode - Writer 10 writes complete novel"""
|
983 |
+
if language == "Korean":
|
984 |
+
return f"""[ν
μ€νΈ λͺ¨λ] λΉμ μ μ 체 30νμ΄μ§ μμ€μ ν λ²μ μμ±νλ νΉλ³ μκ°μ
λλ€.
|
985 |
+
|
986 |
+
κ°λ
μμ λ§μ€ν°νλ:
|
987 |
+
{director_plan}
|
988 |
+
|
989 |
+
**μ€μ μ§μΉ¨:**
|
990 |
+
1. μ 체 30νμ΄μ§ λΆλμ μμ±λ μμ€μ μμ±νμΈμ
|
991 |
+
2. μ΄ 14,000-15,000 λ¨μ΄λ‘ μμ±νμΈμ
|
992 |
+
3. 10κ°μ μμ°μ€λ¬μ΄ μ±ν°λ‘ ꡬμ±νμΈμ (κ° μ±ν° μ½ 1,400-1,500 λ¨μ΄)
|
993 |
+
4. μμλΆν° κ²°λ§κΉμ§ μμ ν μ΄μΌκΈ°λ₯Ό λ§λμΈμ
|
994 |
+
5. λ§μ€ν°νλμ λͺ¨λ μμλ₯Ό ν¬ν¨νμΈμ
|
995 |
+
|
996 |
+
μ±ν° ꡬλΆμ λ€μκ³Ό κ°μ΄ νμνμΈμ:
|
997 |
+
[Chapter 1]
|
998 |
+
λ΄μ©...
|
999 |
+
|
1000 |
+
[Chapter 2]
|
1001 |
+
λ΄μ©...
|
1002 |
+
|
1003 |
+
μμ±λ λμ μ 체 μμ€μ μμ±νμΈμ."""
|
1004 |
+
else:
|
1005 |
+
return f"""[TEST MODE] You are a special writer creating the complete 30-page novel at once.
|
1006 |
+
|
1007 |
+
Director's Masterplan:
|
1008 |
+
{director_plan}
|
1009 |
+
|
1010 |
+
**CRITICAL INSTRUCTIONS:**
|
1011 |
+
1. Write a complete 30-page novel
|
1012 |
+
2. Total 14,000-15,000 words
|
1013 |
+
3. Organize into 10 natural chapters (each chapter ~1,400-1,500 words)
|
1014 |
+
4. Create a complete story from beginning to end
|
1015 |
+
5. Include all elements from the masterplan
|
1016 |
+
|
1017 |
+
Mark chapters as follows:
|
1018 |
+
[Chapter 1]
|
1019 |
+
content...
|
1020 |
+
|
1021 |
+
[Chapter 2]
|
1022 |
+
content...
|
1023 |
+
|
1024 |
+
Write a high-quality complete novel."""
|
1025 |
+
|
1026 |
+
def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]:
|
1027 |
+
"""Simulate streaming in test mode"""
|
1028 |
+
words = text.split()
|
1029 |
+
chunk_size = 5
|
1030 |
+
for i in range(0, len(words), chunk_size):
|
1031 |
+
chunk = " ".join(words[i:i+chunk_size])
|
1032 |
+
yield chunk + " "
|
1033 |
+
time.sleep(0.02)
|
1034 |
+
|
1035 |
+
def call_llm_streaming(self, messages: List[Dict[str, str]], role: str,
|
1036 |
+
language: str = "English", stage_info: Dict = None) -> Generator[str, None, None]:
|
1037 |
+
"""Streaming LLM API call with web search enhancement"""
|
1038 |
+
|
1039 |
+
if self.test_mode:
|
1040 |
+
logger.info(f"Test mode streaming - Role: {role}, Language: {language}")
|
1041 |
+
test_response = self.get_test_response(role, language)
|
1042 |
+
yield from self.simulate_streaming(test_response, role)
|
1043 |
+
return
|
1044 |
+
|
1045 |
+
# Extract topic from user query for research
|
1046 |
+
topic = ""
|
1047 |
+
if stage_info and 'query' in stage_info:
|
1048 |
+
topic = stage_info['query']
|
1049 |
+
|
1050 |
+
# Enhance prompt with web search if available
|
1051 |
+
if messages and messages[-1]["role"] == "user" and self.web_search.enabled:
|
1052 |
+
enhanced_prompt = self.enhance_prompt_with_research(
|
1053 |
+
messages[-1]["content"],
|
1054 |
+
role,
|
1055 |
+
topic,
|
1056 |
+
stage_info or {},
|
1057 |
+
language
|
1058 |
+
)
|
1059 |
+
messages[-1]["content"] = enhanced_prompt
|
1060 |
+
|
1061 |
+
# Real API call
|
1062 |
+
try:
|
1063 |
+
system_prompts = self.get_system_prompts(language)
|
1064 |
+
|
1065 |
+
# μκ°μκ² λ κ°ν μμ€ν
ν둬ννΈ μΆκ°
|
1066 |
+
if role.startswith("writer"):
|
1067 |
+
if language == "Korean":
|
1068 |
+
system_prompts[role] += "\n\n**μ λμ μꡬμ¬ν**: λΉμ μ λ°λμ 1,400-1,500λ¨μ΄λ₯Ό μμ±ν΄μΌ ν©λλ€. μ΄κ²μ νμ λΆκ°λ₯ν μꡬμ¬νμ
λλ€. μ§§μ μλ΅μ νμ©λμ§ μμ΅λλ€."
|
1069 |
+
else:
|
1070 |
+
system_prompts[role] += "\n\n**ABSOLUTE REQUIREMENT**: You MUST write 1,400-1,500 words. This is non-negotiable. Short responses are not acceptable."
|
1071 |
+
|
1072 |
+
full_messages = [
|
1073 |
+
{"role": "system", "content": system_prompts.get(role, "")},
|
1074 |
+
*messages
|
1075 |
+
]
|
1076 |
+
|
1077 |
+
# μμ±μλ€μκ²λ μ μ ν ν ν° ν λΉ
|
1078 |
+
if role == "writer10" and stage_info and stage_info.get('test_mode'):
|
1079 |
+
max_tokens = 20000 # ν
μ€νΈ λͺ¨λ: μ 체 μμ€ μμ±
|
1080 |
+
temperature = 0.8
|
1081 |
+
top_p = 0.95
|
1082 |
+
elif role.startswith("writer"):
|
1083 |
+
max_tokens = 10000 # μΆ©λΆν ν ν°
|
1084 |
+
temperature = 0.8
|
1085 |
+
top_p = 0.95
|
1086 |
+
else:
|
1087 |
+
max_tokens = 8000
|
1088 |
+
temperature = 0.6
|
1089 |
+
top_p = 0.9
|
1090 |
+
|
1091 |
+
payload = {
|
1092 |
+
"model": self.model_id,
|
1093 |
+
"messages": full_messages,
|
1094 |
+
"max_tokens": max_tokens,
|
1095 |
+
"temperature": temperature,
|
1096 |
+
"top_p": top_p,
|
1097 |
+
"stream": True,
|
1098 |
+
"stream_options": {"include_usage": True}
|
1099 |
+
}
|
1100 |
+
|
1101 |
+
logger.info(f"API streaming call started - Role: {role}, Max tokens: {max_tokens}, Temperature: {temperature}")
|
1102 |
+
|
1103 |
+
response = requests.post(
|
1104 |
+
self.api_url,
|
1105 |
+
headers=self.create_headers(),
|
1106 |
+
json=payload,
|
1107 |
+
stream=True,
|
1108 |
+
timeout=60
|
1109 |
+
)
|
1110 |
+
|
1111 |
+
if response.status_code != 200:
|
1112 |
+
logger.error(f"API error: {response.status_code}")
|
1113 |
+
yield f"β API error ({response.status_code}): {response.text[:200]}"
|
1114 |
+
return
|
1115 |
+
|
1116 |
+
buffer = ""
|
1117 |
+
total_content = ""
|
1118 |
+
|
1119 |
+
for line in response.iter_lines():
|
1120 |
+
if line:
|
1121 |
+
line = line.decode('utf-8')
|
1122 |
+
if line.startswith("data: "):
|
1123 |
+
data = line[6:]
|
1124 |
+
if data == "[DONE]":
|
1125 |
+
if buffer:
|
1126 |
+
yield buffer
|
1127 |
+
logger.info(f"Streaming complete for {role}: {len(total_content)} chars, {len(total_content.split())} words")
|
1128 |
+
break
|
1129 |
+
try:
|
1130 |
+
chunk = json.loads(data)
|
1131 |
+
if "choices" in chunk and chunk["choices"]:
|
1132 |
+
content = chunk["choices"][0].get("delta", {}).get("content", "")
|
1133 |
+
if content:
|
1134 |
+
buffer += content
|
1135 |
+
total_content += content
|
1136 |
+
|
1137 |
+
# μκ°λ λ ν° λ²νΌ μ¬μ©
|
1138 |
+
buffer_size = 500 if role.startswith("writer") else 200
|
1139 |
+
|
1140 |
+
if len(buffer) > buffer_size or '\n\n' in buffer:
|
1141 |
+
yield buffer
|
1142 |
+
buffer = ""
|
1143 |
+
except json.JSONDecodeError:
|
1144 |
+
continue
|
1145 |
+
|
1146 |
+
if buffer:
|
1147 |
+
yield buffer
|
1148 |
+
|
1149 |
+
# μκ°μ κ²½μ° λ΄μ© κΈΈμ΄ νμΈ λ° μ¬μλ
|
1150 |
+
if role.startswith("writer"):
|
1151 |
+
word_count = len(total_content.split())
|
1152 |
+
if word_count < 1350: # 1,400 λ―Έλ§
|
1153 |
+
logger.warning(f"Writer {role} produced only {word_count} words! Requesting continuation...")
|
1154 |
+
|
1155 |
+
# μΆκ° μμ²
|
1156 |
+
continuation_prompt = f"Continue writing to reach the required 1,400-1,500 words. You have written {word_count} words so far. Write {1400 - word_count} more words to complete your section."
|
1157 |
+
|
1158 |
+
if language == "Korean":
|
1159 |
+
continuation_prompt = f"νμ λΆλ 1,400-1,500λ¨μ΄λ₯Ό μ±μ°κΈ° μν΄ κ³μ μμ±νμΈμ. μ§κΈκΉμ§ {word_count}λ¨μ΄λ₯Ό μμ±νμ΅λλ€. {1400 - word_count}λ¨μ΄λ₯Ό λ μμ±νμ¬ μΉμ
μ μμ±νμΈμ."
|
1160 |
+
|
1161 |
+
full_messages.append({"role": "assistant", "content": total_content})
|
1162 |
+
full_messages.append({"role": "user", "content": continuation_prompt})
|
1163 |
+
|
1164 |
+
# μΆκ° μμ± μμ²
|
1165 |
+
continuation_payload = {
|
1166 |
+
"model": self.model_id,
|
1167 |
+
"messages": full_messages,
|
1168 |
+
"max_tokens": 5000,
|
1169 |
+
"temperature": temperature,
|
1170 |
+
"top_p": top_p,
|
1171 |
+
"stream": True
|
1172 |
+
}
|
1173 |
+
|
1174 |
+
logger.info(f"Requesting continuation for {role}...")
|
1175 |
+
|
1176 |
+
continuation_response = requests.post(
|
1177 |
+
self.api_url,
|
1178 |
+
headers=self.create_headers(),
|
1179 |
+
json=continuation_payload,
|
1180 |
+
stream=True,
|
1181 |
+
timeout=60
|
1182 |
+
)
|
1183 |
+
|
1184 |
+
if continuation_response.status_code == 200:
|
1185 |
+
for line in continuation_response.iter_lines():
|
1186 |
+
if line:
|
1187 |
+
line = line.decode('utf-8')
|
1188 |
+
if line.startswith("data: "):
|
1189 |
+
data = line[6:]
|
1190 |
+
if data == "[DONE]":
|
1191 |
+
break
|
1192 |
+
try:
|
1193 |
+
chunk = json.loads(data)
|
1194 |
+
if "choices" in chunk and chunk["choices"]:
|
1195 |
+
content = chunk["choices"][0].get("delta", {}).get("content", "")
|
1196 |
+
if content:
|
1197 |
+
yield content
|
1198 |
+
total_content += content
|
1199 |
+
except json.JSONDecodeError:
|
1200 |
+
continue
|
1201 |
+
|
1202 |
+
final_word_count = len(total_content.split())
|
1203 |
+
logger.info(f"Final word count for {role}: {final_word_count}")
|
1204 |
+
|
1205 |
+
except requests.exceptions.Timeout:
|
1206 |
+
yield "β±οΈ API call timed out. Please try again."
|
1207 |
+
except requests.exceptions.ConnectionError:
|
1208 |
+
yield "π Cannot connect to API server. Please check your internet connection."
|
1209 |
+
except Exception as e:
|
1210 |
+
logger.error(f"Error during streaming: {str(e)}")
|
1211 |
+
yield f"β Error occurred: {str(e)}"
|
1212 |
+
|
1213 |
+
def get_system_prompts(self, language: str) -> Dict[str, str]:
|
1214 |
+
"""Get system prompts for all 10 writers"""
|
1215 |
+
if language == "Korean":
|
1216 |
+
prompts = {
|
1217 |
+
"director": "λΉμ μ 30νμ΄μ§ μ€νΈ μμ€μ κΈ°ννκ³ κ°λ
νλ λ¬Έν κ°λ
μμ
λλ€. 체κ³μ μ΄κ³ μ°½μμ μΈ μ€ν 리 ꡬ쑰λ₯Ό λ§λ€μ΄λ
λλ€.",
|
1218 |
+
"critic": "λΉμ μ λ μΉ΄λ‘μ΄ ν΅μ°°λ ₯μ κ°μ§ λ¬Έν λΉνκ°μ
λλ€. 건μ€μ μ΄κ³ ꡬ체μ μΈ νΌλλ°±μ μ 곡ν©λλ€."
|
1219 |
+
}
|
1220 |
+
|
1221 |
+
# 10λͺ
μ μκ° ν둬ννΈ
|
1222 |
+
writer_roles = [
|
1223 |
+
"μμ€μ λμ
λΆλ₯Ό λ΄λΉνλ μκ°μ
λλ€. λ
μλ₯Ό μ¬λ‘μ‘λ μμμ λ§λλλ€.",
|
1224 |
+
"μ΄λ° μ κ°λ₯Ό λ΄λΉνλ μκ°μ
λλ€. μΈλ¬Όκ³Ό μν©μ κΉμ΄ μκ² λ°μ μν΅λλ€.",
|
1225 |
+
"κ°λ± λμ
μ λ΄λΉνλ μκ°μ
λλ€. μ΄μΌκΈ°μ ν΅μ¬ κ°λ±μ μ μν©λλ€.",
|
1226 |
+
"κ°λ± μμΉμ λ΄λΉνλ μκ°μ
λλ€. κΈ΄μ₯κ°μ λμ΄κ³ 볡μ‘μ±μ λν©λλ€.",
|
1227 |
+
"μ€λ°λΆ μ νμ μ λ΄λΉνλ μκ°μ
λλ€. μ€μν λ³νλ₯Ό λ§λλλ€.",
|
1228 |
+
"μ€λ°λΆ μ¬νλ₯Ό λ΄λΉνλ μκ°μ
λλ€. μ΄μΌκΈ°μ μ€μ¬μΆμ κ²¬κ³ νκ² λ§λλλ€.",
|
1229 |
+
"ν΄λΌμ΄λ§₯μ€ μ€λΉλ₯Ό λ΄λΉνλ μκ°μ
λλ€. μ΅κ³ μ‘°λ₯Ό ν₯ν΄ λμκ°λλ€.",
|
1230 |
+
"ν΄λΌμ΄λ§₯μ€λ₯Ό λ΄λΉνλ μκ°μ
λλ€. λͺ¨λ κ°λ±μ΄ νλ°νλ μκ°μ 그립λλ€.",
|
1231 |
+
"ν΄κ²° μμμ λ΄λΉνλ μκ°μ
λλ€. λ§€λμ νμ΄λκ°κΈ° μμν©λλ€.",
|
1232 |
+
"μ΅μ’
κ²°λ§μ λ΄λΉνλ μκ°μ
λλ€. μ¬μ΄μ΄ λ¨λ λ§λ¬΄λ¦¬λ₯Ό λ§λλλ€."
|
1233 |
+
]
|
1234 |
+
|
1235 |
+
for i, role_desc in enumerate(writer_roles, 1):
|
1236 |
+
prompts[f"writer{i}"] = f"λΉμ μ {role_desc} λ°λμ 1,400-1,500λ¨μ΄λ₯Ό μμ±νμΈμ. μ΄λ μ λμ μΈ μꡬμ¬νμ
λλ€."
|
1237 |
+
|
1238 |
+
return prompts
|
1239 |
+
else:
|
1240 |
+
prompts = {
|
1241 |
+
"director": "You are a literary director planning and supervising a 30-page novella. You create systematic and creative story structures.",
|
1242 |
+
"critic": "You are a literary critic with sharp insights. You provide constructive and specific feedback."
|
1243 |
+
}
|
1244 |
+
|
1245 |
+
# 10 writer prompts
|
1246 |
+
writer_roles = [
|
1247 |
+
"the writer responsible for the introduction. You create a captivating beginning.",
|
1248 |
+
"the writer responsible for early development. You deepen characters and situations.",
|
1249 |
+
"the writer responsible for conflict introduction. You present the core conflict.",
|
1250 |
+
"the writer responsible for rising conflict. You increase tension and add complexity.",
|
1251 |
+
"the writer responsible for the midpoint turn. You create important changes.",
|
1252 |
+
"the writer responsible for deepening the middle. You solidify the story's central axis.",
|
1253 |
+
"the writer responsible for climax preparation. You move toward the peak.",
|
1254 |
+
"the writer responsible for the climax. You depict the moment when all conflicts explode.",
|
1255 |
+
"the writer responsible for resolution beginning. You start untangling the knots.",
|
1256 |
+
"the writer responsible for the final ending. You create a lingering conclusion."
|
1257 |
+
]
|
1258 |
+
|
1259 |
+
for i, role_desc in enumerate(writer_roles, 1):
|
1260 |
+
prompts[f"writer{i}"] = f"You are {role_desc} You MUST write 1,400-1,500 words. This is an absolute requirement."
|
1261 |
+
|
1262 |
+
return prompts
|
1263 |
+
|
1264 |
+
def get_test_response(self, role: str, language: str) -> str:
|
1265 |
+
"""Get test response based on role"""
|
1266 |
+
if language == "Korean":
|
1267 |
+
return self.get_korean_test_response(role)
|
1268 |
+
else:
|
1269 |
+
return self.get_english_test_response(role)
|
1270 |
+
|
1271 |
+
def get_korean_test_response(self, role: str) -> str:
|
1272 |
+
"""Korean test responses with appropriate length"""
|
1273 |
+
test_responses = {
|
1274 |
+
"director": """30νμ΄μ§ μ€νΈ μμ€ κΈ°νμμ μ μν©λλ€.
|
1275 |
+
|
1276 |
+
## 1. μ£Όμ μ μ₯λ₯΄
|
1277 |
+
- **ν΅μ¬ μ£Όμ **: μΈκ° λ³Έμ±κ³Ό κΈ°μ μ μΆ©λ μμμ μ°Ύλ μ§μ ν μ°κ²°
|
1278 |
+
- **μ₯λ₯΄**: SF μ¬λ¦¬ λλΌλ§
|
1279 |
+
- **ν€**: μ±μ°°μ μ΄κ³ μμ μ μ΄λ©΄μλ κΈ΄μ₯κ° μλ
|
1280 |
+
- **λͺ©ν λ
μ**: κΉμ΄ μλ μ¬μ λ₯Ό μ¦κΈ°λ μ±μΈ λ
μ
|
1281 |
+
|
1282 |
+
## 2. λ±μ₯μΈλ¬Ό μ€μ
|
1283 |
+
|
1284 |
+
| μ΄λ¦ | μν | μ±κ²© | λ°°κ²½ | λκΈ° | λ³ν |
|
1285 |
+
|------|------|------|------|------|------|
|
1286 |
+
| μμ° | μ£ΌμΈκ³΅ | μ΄μ±μ , κ³ λ
ν¨ | AI μ°κ΅¬μ | μλ²½ν AI λλ°μ κ°λ° | μΈκ°κ΄κ³μ κ°μΉ μ¬λ°κ²¬ |
|
1287 |
+
| λ―Όμ€ | μ‘°λ ₯μ | λ°λ»ν¨, μ§κ΄μ | μ¬λ¦¬μλ΄μ¬ | μμ°μ λμ κ· ν μ°ΎκΈ° | κΈ°μ μμ©κ³Ό μ‘°ν |
|
1288 |
+
| ARIA | λ립μβλλ°μ | λ
Όλ¦¬μ βκ°μ± νμ΅ | AI νλ‘ν νμ
| μ§μ ν μ‘΄μ¬ λκΈ° | μμ μ μ²΄μ± ν립 |
|
1289 |
+
|
1290 |
+
## 3. μμ¬ κ΅¬μ‘° (10κ° ννΈ, κ° 3νμ΄μ§)
|
1291 |
+
|
1292 |
+
| ννΈ | νμ΄μ§ | μ£Όμ μ¬κ±΄ | κΈ΄μ₯λ | μΈλ¬Ό λ°μ |
|
1293 |
+
|------|--------|-----------|---------|-----------|
|
1294 |
+
| 1 | 1-3 | μμ°μ κ³ λ
ν μ°κ΅¬μ€, ARIA 첫 κ°μ± | 3/10 | μμ°μ μ§μ°© λλ¬λ¨ |
|
1295 |
+
| 2 | 4-6 | ARIAμ μ΄μ νλ μμ | 4/10 | μλ¬Έμ μμ |
|
1296 |
+
| 3 | 7-9 | λ―Όμ€κ³Όμ 첫 λ§λ¨ | 4/10 | μΈλΆ μκ° λμ
|
|
1297 |
+
| 4 | 10-12 | ARIAμ μμ μΈμ μ§ν | 5/10 | κ°λ±μ μ¨μ |
|
1298 |
+
| 5 | 13-15 | 첫 λ²μ§Έ μκΈ° | 6/10 | μ νμ μκ° |
|
1299 |
+
| 6 | 16-18 | μ€λ¦¬μμν κ°μ
| 7/10 | μΈλΆ μλ ₯ |
|
1300 |
+
| 7 | 19-21 | λνμ μ΄ν΄ | 6/10 | μνΈ μΈμ |
|
1301 |
+
| 8 | 22-24 | μ΅νμ λκ²° μ€λΉ | 8/10 | μ°λμ νμ |
|
1302 |
+
| 9 | 25-27 | ν΄λΌμ΄λ§₯μ€ | 10/10 | λͺ¨λ κ°λ± νλ° |
|
1303 |
+
| 10 | 28-30 | μλ‘μ΄ μμ | 4/10 | 곡쑴과 νν΄ |""",
|
1304 |
+
|
1305 |
+
"critic": """κ°λ
μμ κΈ°νμ κ²ν νμ΅λλ€.
|
1306 |
+
|
1307 |
+
## λΉν λ° κ°μ μ μ
|
1308 |
+
|
1309 |
+
### 1. μμ¬μ μμ±λ
|
1310 |
+
- **κ°μ **: AIμ μΈκ°μ κ΄κ³λΌλ μμμ μ ν μ£Όμ
|
1311 |
+
- **κ°μ μ **: 10κ° ννΈ κ΅¬μ±μ΄ μ μ νλ©° κ° ννΈμ λ
립μ±κ³Ό μ°κ²°μ±μ΄ μ κ· νμ‘ν μμ
|
1312 |
+
|
1313 |
+
### 2. μΈλ¬Ό μ€μ κ²ν
|
1314 |
+
|
1315 |
+
| μΈλ¬Ό | κ°μ | μ½μ | κ°μ μ μ |
|
1316 |
+
|------|------|------|-----------|
|
1317 |
+
| μμ° | λͺ
νν λ΄μ κ°λ± | κ°μ νν λΆμ‘± μ°λ € | μ΄λ°λΆν° κ°μ μ λ¨μ λ°°μΉ |
|
1318 |
+
| λ―Όμ€ | κ· νμ μν | μλμ μΌ μν | λ
μμ μλΈνλ‘― νμ |
|
1319 |
+
| ARIA | λ
νΉν μΊλ¦ν° μν¬ | λ³ν κ³Όμ μΆμμ | ꡬ체μ νμ΅ μνΌμλ μΆκ° |
|
1320 |
+
|
1321 |
+
### 3. μ€ν κ°λ₯μ±
|
1322 |
+
- κ° μκ°λ³ 3νμ΄μ§λ μ μ ν λΆλ
|
1323 |
+
- ννΈ κ° μ°κ²°μ± κ°μ΄λλΌμΈ λ³΄κ° νμ""",
|
1324 |
+
}
|
1325 |
+
|
1326 |
+
# μκ° μλ΅ - 1,400-1,500 λ¨μ΄
|
1327 |
+
sample_story = """μμ°μ μ°κ΅¬μ€μ μ°¨κ°μ΄ νκ΄λ± μλμμ λ λ€λ₯Έ λ°€μ 보λ΄κ³ μμλ€. λͺ¨λν°μ νΈλ₯Έ λΉμ΄ κ·Έλ
μ μ°½λ°±ν μΌκ΅΄μ λΉμΆκ³ μμκ³ , μμ κ°μ μ½λ λΌμΈμ΄ λμμμ΄ μ€ν¬λ‘€λκ³ μμλ€. ARIA νλ‘μ νΈλ κ·Έλ
μ μΆ μ λΆμλ€. 3λ
μ΄λΌλ μκ° λμ κ·Έλ
λ μ΄ μΈκ³΅μ§λ₯μ λͺ¨λ κ²μ μμλΆμλ€.
|
1328 |
+
|
1329 |
+
"μμ€ν
μ²΄ν¬ μλ£. λͺ¨λ νλΌλ―Έν° μ μ." κΈ°κ³μ μΈ μμ±μ΄ μ€νΌμ»€λ₯Ό ν΅ν΄ νλ¬λμλ€.
|
1330 |
+
|
1331 |
+
μμ°μ μ μ μμμ κΈ°λμ΄ λμ κ°μλ€. νΌλ‘κ° λΌ μκΉμ§ νκ³ λ€μμ§λ§, λ©μΆ μ μμλ€. ARIAλ λ¨μν νλ‘μ νΈκ° μλμλ€. κ·Έκ²μ κ·Έλ
κ° μμ΄λ²λ¦° κ²λ€μ λμ°Ύμ μ μλ μ μΌν ν¬λ§μ΄μλ€."""
|
1332 |
+
|
1333 |
+
for i in range(1, 11):
|
1334 |
+
# κ° μκ°λ§λ€ 1,400-1,500λ¨μ΄ μμ±
|
1335 |
+
writer_content = f"μμ±μ {i}λ²μ ννΈμ
λλ€.\n\n"
|
1336 |
+
# μ½ 300λ¨μ΄μ© 5λ² λ°λ³΅νμ¬ 1,400-1,500λ¨μ΄ λ¬μ±
|
1337 |
+
for j in range(5):
|
1338 |
+
writer_content += sample_story + f"\n\nκ·Έκ²μ μκ° {i}μ {j+1}λ²μ§Έ λ¨λ½μ΄μλ€. "
|
1339 |
+
writer_content += "μ΄μΌκΈ°λ κ³μ μ κ°λμκ³ , μΈλ¬Όλ€μ κ°μ μ μ μ λ 볡μ‘ν΄μ‘λ€. " * 15
|
1340 |
+
writer_content += "\n\n"
|
1341 |
+
|
1342 |
+
test_responses[f"writer{i}"] = writer_content
|
1343 |
+
|
1344 |
+
# ν
μ€νΈ λͺ¨λμ© writer10 μλ΅
|
1345 |
+
if role == "writer10":
|
1346 |
+
full_novel = ""
|
1347 |
+
for i in range(1, 11):
|
1348 |
+
full_novel += f"\n\n[Chapter {i}]\n\n"
|
1349 |
+
full_novel += sample_story + f"\n\nμ΄κ²μ μ±ν° {i}μ λ΄μ©μ
λλ€. "
|
1350 |
+
full_novel += "μ΄μΌκΈ°λ κ³μ μ κ°λμκ³ , μΈλ¬Όλ€μ κ°μ μ μ μ λ 볡μ‘ν΄μ‘λ€. " * 100
|
1351 |
+
full_novel += "\n\n"
|
1352 |
+
test_responses["writer10"] = full_novel
|
1353 |
+
|
1354 |
+
return test_responses.get(role, "ν
μ€νΈ μλ΅μ
λλ€.")
|
1355 |
+
|
1356 |
+
def get_english_test_response(self, role: str) -> str:
|
1357 |
+
"""English test responses with appropriate length"""
|
1358 |
+
test_responses = {
|
1359 |
+
"director": """I present the 30-page novella plan.
|
1360 |
+
|
1361 |
+
## 1. Theme and Genre
|
1362 |
+
- **Core Theme**: Finding true connection in the collision of human nature and technology
|
1363 |
+
- **Genre**: Sci-fi psychological drama
|
1364 |
+
- **Tone**: Reflective and lyrical yet tense
|
1365 |
+
- **Target Audience**: Adult readers who enjoy deep contemplation
|
1366 |
+
|
1367 |
+
## 2. Character Settings
|
1368 |
+
|
1369 |
+
| Name | Role | Personality | Background | Motivation | Arc |
|
1370 |
+
|------|------|-------------|------------|------------|-----|
|
1371 |
+
| Seoyeon | Protagonist | Rational, lonely | AI researcher | Develop perfect AI companion | Rediscover value of human connection |
|
1372 |
+
| Minjun | Helper | Warm, intuitive | Psychologist | Help Seoyeon find balance | Accept and harmonize with technology |
|
1373 |
+
| ARIA | AntagonistβCompanion | LogicalβLearning emotion | AI prototype | Become truly existent | Establish self-identity |
|
1374 |
+
|
1375 |
+
## 3. Narrative Structure (10 parts, 3 pages each)
|
1376 |
+
|
1377 |
+
| Part | Pages | Main Events | Tension | Character Development |
|
1378 |
+
|------|-------|-------------|---------|---------------------|
|
1379 |
+
| 1 | 1-3 | Seoyeon's lonely lab, ARIA's first awakening | 3/10 | Seoyeon's obsession revealed |
|
1380 |
+
| 2 | 4-6 | ARIA's anomalies begin | 4/10 | Questions arise |
|
1381 |
+
[... continues for all 10 parts ...]""",
|
1382 |
+
|
1383 |
+
"critic": """I have reviewed the director's plan.
|
1384 |
+
|
1385 |
+
## Critique and Improvement Suggestions
|
1386 |
+
|
1387 |
+
### 1. Narrative Completeness
|
1388 |
+
- **Strength**: Timely theme of AI-human relationships
|
1389 |
+
- **Improvement**: 10-part structure is well-balanced. Each part maintains independence while connecting seamlessly.
|
1390 |
+
|
1391 |
+
### 2. Character Review
|
1392 |
+
|
1393 |
+
| Character | Strengths | Weaknesses | Suggestions |
|
1394 |
+
|-----------|-----------|------------|-------------|
|
1395 |
+
| Seoyeon | Clear internal conflict | Risk of insufficient emotion | Place emotional cues from beginning |
|
1396 |
+
| Minjun | Balancer role | Risk of being passive | Needs independent subplot |
|
1397 |
+
| ARIA | Unique character arc | Abstract transformation | Add concrete learning episodes |
|
1398 |
+
|
1399 |
+
### 3. Feasibility
|
1400 |
+
- 3 pages per writer is appropriate
|
1401 |
+
- Need to strengthen inter-part connectivity guidelines""",
|
1402 |
+
}
|
1403 |
+
|
1404 |
+
# Writer responses - 1,400-1,500 words each
|
1405 |
+
sample_story = """Seoyeon spent another night under the cold fluorescent lights of her laboratory. The blue glow from the monitor illuminated her pale face, and dozens of lines of code scrolled endlessly. The ARIA project was her entire life. For three years, she had poured everything into this artificial intelligence.
|
1406 |
+
|
1407 |
+
"System check complete. All parameters normal." The mechanical voice flowed through the speakers.
|
1408 |
+
|
1409 |
+
Seoyeon leaned back in her chair and closed her eyes for a moment. Fatigue penetrated to her bones, but she couldn't stop. ARIA wasn't just a project. It was her only hope to reclaim what she had lost."""
|
1410 |
+
|
1411 |
+
for i in range(1, 11):
|
1412 |
+
# Each writer produces 1,400-1,500 words
|
1413 |
+
writer_content = f"Writer {i} begins their section here.\n\n"
|
1414 |
+
# About 300 words repeated 5 times to achieve 1,400-1,500 words
|
1415 |
+
for j in range(5):
|
1416 |
+
writer_content += sample_story + f"\n\nThis was writer {i}'s paragraph {j+1}. "
|
1417 |
+
writer_content += "The story continued to unfold, and the characters' emotions grew increasingly complex. " * 15
|
1418 |
+
writer_content += "\n\n"
|
1419 |
+
|
1420 |
+
test_responses[f"writer{i}"] = writer_content
|
1421 |
+
|
1422 |
+
# Test mode writer10 response
|
1423 |
+
if role == "writer10":
|
1424 |
+
full_novel = ""
|
1425 |
+
for i in range(1, 11):
|
1426 |
+
full_novel += f"\n\n[Chapter {i}]\n\n"
|
1427 |
+
full_novel += sample_story + f"\n\nThis was chapter {i} content. "
|
1428 |
+
full_novel += "The story continued to unfold, and the characters' emotions grew increasingly complex. " * 100
|
1429 |
+
full_novel += "\n\n"
|
1430 |
+
test_responses["writer10"] = full_novel
|
1431 |
+
|
1432 |
+
return test_responses.get(role, "Test response.")
|
1433 |
+
|
1434 |
+
def process_novel_stream(self, query: str, language: str = "English",
|
1435 |
+
session_id: Optional[str] = None,
|
1436 |
+
resume_from_stage: int = 0,
|
1437 |
+
test_quick_mode: bool = False) -> Generator[Tuple[str, List[Dict[str, str]]], None, None]:
|
1438 |
+
"""Process novel writing with streaming updates - μ΅μ’
Director/Critic μ κ±°"""
|
1439 |
+
try:
|
1440 |
+
global conversation_history
|
1441 |
+
|
1442 |
+
# Create or resume session
|
1443 |
+
if session_id:
|
1444 |
+
self.current_session_id = session_id
|
1445 |
+
session = NovelDatabase.get_session(session_id)
|
1446 |
+
if session:
|
1447 |
+
query = session['user_query']
|
1448 |
+
language = session['language']
|
1449 |
+
resume_from_stage = session['current_stage'] + 1
|
1450 |
+
else:
|
1451 |
+
self.current_session_id = NovelDatabase.create_session(query, language)
|
1452 |
+
resume_from_stage = 0
|
1453 |
+
|
1454 |
+
logger.info(f"Processing novel for session {self.current_session_id}, starting from stage {resume_from_stage}")
|
1455 |
+
|
1456 |
+
# Initialize conversation
|
1457 |
+
conversation_history = [{
|
1458 |
+
"role": "human",
|
1459 |
+
"content": query,
|
1460 |
+
"timestamp": datetime.now()
|
1461 |
+
}]
|
1462 |
+
|
1463 |
+
# Load existing stages if resuming
|
1464 |
+
stages = []
|
1465 |
+
if resume_from_stage > 0:
|
1466 |
+
existing_stages = NovelDatabase.get_stages(self.current_session_id)
|
1467 |
+
for stage_data in existing_stages:
|
1468 |
+
stages.append({
|
1469 |
+
"name": stage_data['stage_name'],
|
1470 |
+
"status": stage_data['status'],
|
1471 |
+
"content": stage_data['content'] or ""
|
1472 |
+
})
|
1473 |
+
|
1474 |
+
# Define all stages for 10 writers (μ΅μ’
νκ° μ κ±°)
|
1475 |
+
if test_quick_mode:
|
1476 |
+
# ν
μ€νΈ λͺ¨λ: 1,2λ¨κ³ + Writer 10λ§
|
1477 |
+
stage_definitions = [
|
1478 |
+
("director", f"π¬ {'κ°λ
μ: μ΄κΈ° κΈ°ν' if language == 'Korean' else 'Director: Initial Planning'}"),
|
1479 |
+
("critic", f"π {'λΉνκ°: κΈ°ν κ²ν ' if language == 'Korean' else 'Critic: Plan Review'}"),
|
1480 |
+
("director", f"π¬ {'κ°λ
μ: μμ λ λ§μ€ν°νλ' if language == 'Korean' else 'Director: Revised Masterplan'}"),
|
1481 |
+
("writer10", f"βοΈ {'μμ±μ' if language == 'Korean' else 'Writer'} 10 (TEST): {'μ 체 μμ€' if language == 'Korean' else 'Complete Novel'}"),
|
1482 |
+
]
|
1483 |
+
else:
|
1484 |
+
stage_definitions = [
|
1485 |
+
("director", f"π¬ {'κ°λ
μ: μ΄κΈ° κΈ°ν' if language == 'Korean' else 'Director: Initial Planning'}"),
|
1486 |
+
("critic", f"π {'λΉνκ°: κΈ°ν κ²ν ' if language == 'Korean' else 'Critic: Plan Review'}"),
|
1487 |
+
("director", f"π¬ {'κ°λ
μ: μμ λ λ§μ€ν°νλ' if language == 'Korean' else 'Director: Revised Masterplan'}"),
|
1488 |
+
]
|
1489 |
+
|
1490 |
+
# Add writer stages for 10 writers
|
1491 |
+
for writer_num in range(1, 11):
|
1492 |
+
stage_definitions.extend([
|
1493 |
+
(f"writer{writer_num}", f"βοΈ {'μμ±μ' if language == 'Korean' else 'Writer'} {writer_num}: {'μ΄μ' if language == 'Korean' else 'Draft'}"),
|
1494 |
+
("critic", f"π {'λΉνκ°: μμ±μ' if language == 'Korean' else 'Critic: Writer'} {writer_num} {'κ²ν ' if language == 'Korean' else 'Review'}"),
|
1495 |
+
(f"writer{writer_num}", f"βοΈ {'μμ±μ' if language == 'Korean' else 'Writer'} {writer_num}: {'μμ λ³Έ' if language == 'Korean' else 'Revision'}")
|
1496 |
+
])
|
1497 |
+
|
1498 |
+
# μ΅μ’
Directorμ Critic λ¨κ³ μ κ±°
|
1499 |
+
|
1500 |
+
# Store total stages for get_stage_prompt
|
1501 |
+
self.total_stages = len(stage_definitions)
|
1502 |
+
|
1503 |
+
# Process stages starting from resume point
|
1504 |
+
for stage_idx in range(resume_from_stage, len(stage_definitions)):
|
1505 |
+
role, stage_name = stage_definitions[stage_idx]
|
1506 |
+
|
1507 |
+
# Add search indicator if enabled
|
1508 |
+
if self.web_search.enabled and not self.test_mode:
|
1509 |
+
stage_name += " π"
|
1510 |
+
|
1511 |
+
# Add stage if not already present
|
1512 |
+
if stage_idx >= len(stages):
|
1513 |
+
stages.append({
|
1514 |
+
"name": stage_name,
|
1515 |
+
"status": "active",
|
1516 |
+
"content": ""
|
1517 |
+
})
|
1518 |
+
else:
|
1519 |
+
stages[stage_idx]["status"] = "active"
|
1520 |
+
|
1521 |
+
yield "", stages
|
1522 |
+
|
1523 |
+
# Get appropriate prompt based on stage
|
1524 |
+
prompt = self.get_stage_prompt(stage_idx, role, query, language, stages, test_quick_mode)
|
1525 |
+
|
1526 |
+
# Create stage info for web search
|
1527 |
+
stage_info = {
|
1528 |
+
'stage_idx': stage_idx,
|
1529 |
+
'query': query,
|
1530 |
+
'stage_name': stage_name,
|
1531 |
+
'test_mode': test_quick_mode
|
1532 |
+
}
|
1533 |
+
|
1534 |
+
stage_content = ""
|
1535 |
+
|
1536 |
+
# Stream content generation with web search
|
1537 |
+
for chunk in self.call_llm_streaming(
|
1538 |
+
[{"role": "user", "content": prompt}],
|
1539 |
+
role,
|
1540 |
+
language,
|
1541 |
+
stage_info
|
1542 |
+
):
|
1543 |
+
stage_content += chunk
|
1544 |
+
stages[stage_idx]["content"] = stage_content
|
1545 |
+
yield "", stages
|
1546 |
+
|
1547 |
+
# Mark stage complete and save to DB
|
1548 |
+
stages[stage_idx]["status"] = "complete"
|
1549 |
+
|
1550 |
+
# ν
μ€νΈ λͺ¨λμμ writer10 μ μ₯ μ νΉλ³ μ²λ¦¬
|
1551 |
+
if test_quick_mode and role == "writer10":
|
1552 |
+
# μ 체 λ΄μ©μ 10κ° μ±ν°λ‘ λΆν νμ¬ μ μ₯
|
1553 |
+
chapters = re.split(r'\[Chapter \d+\]', stage_content)
|
1554 |
+
chapters = [ch.strip() for ch in chapters if ch.strip()]
|
1555 |
+
|
1556 |
+
# κ° μ±ν°λ₯Ό κ°λ³ writerλ‘ μ μ₯
|
1557 |
+
for i, chapter_content in enumerate(chapters[:10], 1):
|
1558 |
+
writer_stage_num = (i-1) * 3 + 5 # 5, 8, 11, 14, 17, 20, 23, 26, 29, 32
|
1559 |
+
NovelDatabase.save_stage(
|
1560 |
+
self.current_session_id,
|
1561 |
+
writer_stage_num,
|
1562 |
+
f"Writer {i}: Revision",
|
1563 |
+
f"writer{i}",
|
1564 |
+
chapter_content,
|
1565 |
+
"complete"
|
1566 |
+
)
|
1567 |
+
logger.info(f"β
Test mode: Saved chapter {i} as writer {i}")
|
1568 |
+
else:
|
1569 |
+
NovelDatabase.save_stage(
|
1570 |
+
self.current_session_id,
|
1571 |
+
stage_idx,
|
1572 |
+
stage_name,
|
1573 |
+
role,
|
1574 |
+
stage_content,
|
1575 |
+
"complete"
|
1576 |
+
)
|
1577 |
+
|
1578 |
+
# Auto-save notification
|
1579 |
+
if role.startswith("writer"):
|
1580 |
+
writer_num = int(role.replace("writer", ""))
|
1581 |
+
logger.info(f"β
Writer {writer_num} content auto-saved to database")
|
1582 |
+
|
1583 |
+
yield "", stages
|
1584 |
+
|
1585 |
+
# Verify content after completion
|
1586 |
+
if self.current_session_id:
|
1587 |
+
verification = NovelDatabase.verify_novel_content(self.current_session_id)
|
1588 |
+
logger.info(f"Content verification: {verification}")
|
1589 |
+
|
1590 |
+
if verification['total_words'] < 12000:
|
1591 |
+
logger.error(f"Final novel too short! Only {verification['total_words']} words")
|
1592 |
+
|
1593 |
+
# Get complete novel from DB
|
1594 |
+
complete_novel = NovelDatabase.get_all_writer_content(self.current_session_id)
|
1595 |
+
|
1596 |
+
# ν
μ€νΈ λͺ¨λλ©΄ μλ£ μν μ
λ°μ΄νΈ
|
1597 |
+
if test_quick_mode and self.current_session_id:
|
1598 |
+
NovelDatabase.update_final_novel(self.current_session_id, complete_novel)
|
1599 |
+
|
1600 |
+
# Save final novel to DB
|
1601 |
+
NovelDatabase.update_final_novel(self.current_session_id, complete_novel)
|
1602 |
+
|
1603 |
+
# Final yield - νλ©΄μλ μλ£ λ©μμ§λ§ νμ
|
1604 |
+
if test_quick_mode:
|
1605 |
+
final_message = f"β
[TEST MODE] Novel complete! {len(complete_novel.split())} words total. Click Download to save."
|
1606 |
+
else:
|
1607 |
+
final_message = f"β
Novel complete! {len(complete_novel.split())} words total. Click Download to save."
|
1608 |
+
yield final_message, stages
|
1609 |
+
|
1610 |
+
except Exception as e:
|
1611 |
+
logger.error(f"Error in process_novel_stream: {str(e)}", exc_info=True)
|
1612 |
+
|
1613 |
+
# Save error state to DB
|
1614 |
+
if self.current_session_id:
|
1615 |
+
NovelDatabase.save_stage(
|
1616 |
+
self.current_session_id,
|
1617 |
+
stage_idx if 'stage_idx' in locals() else 0,
|
1618 |
+
"Error",
|
1619 |
+
"error",
|
1620 |
+
str(e),
|
1621 |
+
"error"
|
1622 |
+
)
|
1623 |
+
|
1624 |
+
error_stage = {
|
1625 |
+
"name": "β Error",
|
1626 |
+
"status": "error",
|
1627 |
+
"content": str(e)
|
1628 |
+
}
|
1629 |
+
stages.append(error_stage)
|
1630 |
+
yield f"Error occurred: {str(e)}", stages
|
1631 |
+
|
1632 |
+
def create_test_writer_complete_prompt(self, director_plan: str, language: str = "English") -> str:
|
1633 |
+
"""Test mode - Writer 10 writes complete novel"""
|
1634 |
+
if language == "Korean":
|
1635 |
+
return f"""[ν
μ€νΈ λͺ¨λ] λΉμ μ μ 체 30νμ΄μ§ μμ€μ ν λ²μ μμ±νλ νΉλ³ μκ°μ
λλ€.
|
1636 |
+
|
1637 |
+
κ°λ
μμ λ§μ€ν°νλ:
|
1638 |
+
{director_plan}
|
1639 |
+
|
1640 |
+
**μ€μ μ§μΉ¨:**
|
1641 |
+
1. μ 체 30νμ΄μ§ λΆλμ μμ±λ μμ€μ μμ±νμΈμ
|
1642 |
+
2. μ΄ 14,000-15,000 λ¨μ΄λ‘ μμ±νμΈμ
|
1643 |
+
3. 10κ°μ μμ°μ€λ¬μ΄ μ±ν°λ‘ ꡬμ±νμΈμ (κ° μ±ν° μ½ 1,400-1,500 λ¨μ΄)
|
1644 |
+
4. μμλΆν° κ²°λ§κΉμ§ μμ ν μ΄μΌκΈ°λ₯Ό λ§λμΈμ
|
1645 |
+
5. λ§μ€ν°νλμ λͺ¨λ μμλ₯Ό ν¬ν¨νμΈμ
|
1646 |
+
|
1647 |
+
μ±ν° ꡬλΆμ λ€μκ³Ό κ°μ΄ νμνμΈμ:
|
1648 |
+
[Chapter 1]
|
1649 |
+
λ΄μ©...
|
1650 |
+
|
1651 |
+
[Chapter 2]
|
1652 |
+
λ΄μ©...
|
1653 |
+
|
1654 |
+
μμ±λ λμ μ 체 μμ€μ μμ±νμΈμ."""
|
1655 |
+
else:
|
1656 |
+
return f"""[TEST MODE] You are a special writer creating the complete 30-page novel at once.
|
1657 |
+
|
1658 |
+
Director's Masterplan:
|
1659 |
+
{director_plan}
|
1660 |
+
|
1661 |
+
**CRITICAL INSTRUCTIONS:**
|
1662 |
+
1. Write a complete 30-page novel
|
1663 |
+
2. Total 14,000-15,000 words
|
1664 |
+
3. Organize into 10 natural chapters (each chapter ~1,400-1,500 words)
|
1665 |
+
4. Create a complete story from beginning to end
|
1666 |
+
5. Include all elements from the masterplan
|
1667 |
+
|
1668 |
+
Mark chapters as follows:
|
1669 |
+
[Chapter 1]
|
1670 |
+
content...
|
1671 |
+
|
1672 |
+
[Chapter 2]
|
1673 |
+
content...
|
1674 |
+
|
1675 |
+
Write a high-quality complete novel."""
|
1676 |
+
|
1677 |
+
def get_stage_prompt(self, stage_idx: int, role: str, query: str,
|
1678 |
+
language: str, stages: List[Dict], test_mode: bool = False) -> str:
|
1679 |
+
"""Get appropriate prompt for each stage"""
|
1680 |
+
# Stage 0: Director Initial
|
1681 |
+
if stage_idx == 0:
|
1682 |
+
return self.create_director_initial_prompt(query, language)
|
1683 |
+
|
1684 |
+
# Stage 1: Critic reviews Director's plan
|
1685 |
+
elif stage_idx == 1:
|
1686 |
+
return self.create_critic_director_prompt(stages[0]["content"], language)
|
1687 |
+
|
1688 |
+
# Stage 2: Director revision
|
1689 |
+
elif stage_idx == 2:
|
1690 |
+
return self.create_director_revision_prompt(
|
1691 |
+
stages[0]["content"], stages[1]["content"], language)
|
1692 |
+
|
1693 |
+
# Test mode - Writer 10 writes complete novel
|
1694 |
+
elif test_mode and role == "writer10":
|
1695 |
+
return self.create_test_writer_complete_prompt(stages[2]["content"], language)
|
1696 |
+
|
1697 |
+
# Writer stages
|
1698 |
+
elif role.startswith("writer"):
|
1699 |
+
writer_num = int(role.replace("writer", ""))
|
1700 |
+
final_plan = stages[2]["content"] # Director's final plan
|
1701 |
+
|
1702 |
+
# Initial draft or revision?
|
1703 |
+
if "μ΄μ" in stages[stage_idx]["name"] or "Draft" in stages[stage_idx]["name"]:
|
1704 |
+
# Get accumulated content from DB
|
1705 |
+
accumulated_content = NovelDatabase.get_all_writer_content(self.current_session_id)
|
1706 |
+
return self.create_writer_prompt(writer_num, final_plan, accumulated_content, language)
|
1707 |
+
else: # Revision
|
1708 |
+
# Find the initial draft and critic feedback
|
1709 |
+
initial_draft_idx = stage_idx - 2
|
1710 |
+
critic_feedback_idx = stage_idx - 1
|
1711 |
+
return self.create_writer_revision_prompt(
|
1712 |
+
writer_num,
|
1713 |
+
stages[initial_draft_idx]["content"],
|
1714 |
+
stages[critic_feedback_idx]["content"],
|
1715 |
+
language
|
1716 |
+
)
|
1717 |
+
|
1718 |
+
# Critic stages for writers
|
1719 |
+
elif role == "critic":
|
1720 |
+
final_plan = stages[2]["content"]
|
1721 |
+
|
1722 |
+
# Writer review
|
1723 |
+
# Find which writer we're reviewing
|
1724 |
+
for i in range(1, 11):
|
1725 |
+
if f"μμ±μ {i}" in stages[stage_idx]["name"] or f"Writer {i}" in stages[stage_idx]["name"]:
|
1726 |
+
writer_content_idx = stage_idx - 1
|
1727 |
+
# Get previous writers' content from DB
|
1728 |
+
previous_content = NovelDatabase.get_all_writer_content(self.current_session_id)
|
1729 |
+
return self.create_critic_writer_prompt(
|
1730 |
+
i,
|
1731 |
+
stages[writer_content_idx]["content"],
|
1732 |
+
final_plan,
|
1733 |
+
previous_content,
|
1734 |
+
language
|
1735 |
+
)
|
1736 |
+
|
1737 |
+
return ""
|
1738 |
+
|
1739 |
+
# Gradio Interface Functions
|
1740 |
+
def process_query(query: str, language: str, session_id: str = None, test_mode: bool = False) -> Generator[Tuple[str, str, str, str], None, None]:
|
1741 |
+
"""Process query and yield updates with recovery status"""
|
1742 |
+
if not query.strip() and not session_id:
|
1743 |
+
if language == "Korean":
|
1744 |
+
yield "", "", "β μμ€ μ£Όμ λ₯Ό μ
λ ₯ν΄μ£ΌμΈμ.", ""
|
1745 |
+
else:
|
1746 |
+
yield "", "", "β Please enter a novel theme.", ""
|
1747 |
+
return
|
1748 |
+
|
1749 |
+
system = NovelWritingSystem()
|
1750 |
+
|
1751 |
+
try:
|
1752 |
+
# Recovery status message
|
1753 |
+
recovery_status = ""
|
1754 |
+
if session_id:
|
1755 |
+
if language == "Korean":
|
1756 |
+
recovery_status = "β»οΈ μ΄μ μΈμ
μ 볡ꡬνμ¬ κ³μ μ§νν©λλ€..."
|
1757 |
+
else:
|
1758 |
+
recovery_status = "β»οΈ Recovering previous session and continuing..."
|
1759 |
+
elif test_mode:
|
1760 |
+
if language == "Korean":
|
1761 |
+
recovery_status = "π§ͺ ν
μ€νΈ λͺ¨λ: λΉ λ₯Έ μμ± (1,2λ¨κ³ + Writer 10λ§)"
|
1762 |
+
else:
|
1763 |
+
recovery_status = "π§ͺ Test Mode: Quick generation (Stages 1,2 + Writer 10 only)"
|
1764 |
+
|
1765 |
+
for final_novel, stages in system.process_novel_stream(query, language, session_id, test_quick_mode=test_mode):
|
1766 |
+
# Format stages for display
|
1767 |
+
stages_display = format_stages_display(stages, language)
|
1768 |
+
|
1769 |
+
# Progress calculation
|
1770 |
+
completed = sum(1 for s in stages if s.get("status") == "complete")
|
1771 |
+
total = len(stages)
|
1772 |
+
progress_percent = (completed / total * 100) if total > 0 else 0
|
1773 |
+
|
1774 |
+
if "β
Novel complete!" in str(final_novel):
|
1775 |
+
status = "β
Complete! Ready to download."
|
1776 |
+
else:
|
1777 |
+
if language == "Korean":
|
1778 |
+
status = f"π μ§νμ€... ({completed}/{total} - {progress_percent:.1f}%)"
|
1779 |
+
else:
|
1780 |
+
status = f"π Processing... ({completed}/{total} - {progress_percent:.1f}%)"
|
1781 |
+
|
1782 |
+
yield stages_display, final_novel, status, recovery_status
|
1783 |
+
|
1784 |
+
except Exception as e:
|
1785 |
+
logger.error(f"Error in process_query: {str(e)}", exc_info=True)
|
1786 |
+
if language == "Korean":
|
1787 |
+
yield "", "", f"β μ€λ₯ λ°μ: {str(e)}", ""
|
1788 |
+
else:
|
1789 |
+
yield "", "", f"β Error occurred: {str(e)}", ""
|
1790 |
+
|
1791 |
+
def format_stages_display(stages: List[Dict[str, str]], language: str) -> str:
|
1792 |
+
"""Format stages into simple display with writer save status"""
|
1793 |
+
display = ""
|
1794 |
+
|
1795 |
+
for idx, stage in enumerate(stages):
|
1796 |
+
status_icon = "β
" if stage.get("status") == "complete" else ("β³" if stage.get("status") == "active" else "β")
|
1797 |
+
|
1798 |
+
# Add save indicator for completed writers
|
1799 |
+
save_indicator = ""
|
1800 |
+
if "Writer" in stage['name'] and "Revision" in stage['name'] and stage.get("status") == "complete":
|
1801 |
+
save_indicator = " πΎ"
|
1802 |
+
|
1803 |
+
# Show only active stage content in detail, others just show status
|
1804 |
+
if stage.get("status") == "active":
|
1805 |
+
display += f"\n\n{status_icon} **{stage['name']}**\n"
|
1806 |
+
display += f"```\n{stage.get('content', '')[-1000:]}\n```"
|
1807 |
+
else:
|
1808 |
+
display += f"\n{status_icon} {stage['name']}{save_indicator}"
|
1809 |
+
|
1810 |
+
return display
|
1811 |
+
|
1812 |
+
def get_active_sessions(language: str) -> List[Tuple[str, str]]:
|
1813 |
+
"""Get list of active sessions"""
|
1814 |
+
try:
|
1815 |
+
sessions = NovelDatabase.get_active_sessions()
|
1816 |
+
|
1817 |
+
choices = []
|
1818 |
+
for session in sessions:
|
1819 |
+
created = NovelDatabase.parse_datetime(session['created_at'])
|
1820 |
+
date_str = created.strftime("%Y-%m-%d %H:%M")
|
1821 |
+
query_preview = session['user_query'][:50] + "..." if len(session['user_query']) > 50 else session['user_query']
|
1822 |
+
label = f"[{date_str}] {query_preview} (Stage {session['current_stage']})"
|
1823 |
+
choices.append((label, session['session_id']))
|
1824 |
+
|
1825 |
+
return choices
|
1826 |
+
except Exception as e:
|
1827 |
+
logger.error(f"Error getting active sessions: {str(e)}", exc_info=True)
|
1828 |
+
return []
|
1829 |
+
|
1830 |
+
def resume_session(session_id: str, language: str, test_mode: bool = False) -> Generator[Tuple[str, str, str], None, None]:
|
1831 |
+
"""Resume an existing session"""
|
1832 |
+
if not session_id:
|
1833 |
+
if language == "Korean":
|
1834 |
+
yield "", "", "β μΈμ
μ μ νν΄μ£ΌμΈμ."
|
1835 |
+
else:
|
1836 |
+
yield "", "", "β Please select a session."
|
1837 |
+
return
|
1838 |
+
|
1839 |
+
# Process with existing session ID
|
1840 |
+
yield from process_query("", language, session_id, test_mode)
|
1841 |
+
|
1842 |
+
def auto_recover_session(language: str) -> Tuple[str, str]:
|
1843 |
+
"""Auto recover the latest active session"""
|
1844 |
+
try:
|
1845 |
+
latest_session = NovelDatabase.get_latest_active_session()
|
1846 |
+
if latest_session:
|
1847 |
+
if language == "Korean":
|
1848 |
+
message = f"β
μλ 볡ꡬ: '{latest_session['user_query'][:30]}...' (Stage {latest_session['current_stage']})"
|
1849 |
+
else:
|
1850 |
+
message = f"β
Auto recovered: '{latest_session['user_query'][:30]}...' (Stage {latest_session['current_stage']})"
|
1851 |
+
return latest_session['session_id'], message
|
1852 |
+
else:
|
1853 |
+
return None, ""
|
1854 |
+
except Exception as e:
|
1855 |
+
logger.error(f"Error in auto recovery: {str(e)}")
|
1856 |
+
return None, ""
|
1857 |
+
|
1858 |
+
def download_novel(novel_text: str, format: str, language: str, session_id: str = None) -> str:
|
1859 |
+
"""Download novel - DBμμ μ§μ μκ° λ΄μ©μ κ°μ Έμμ ν΅ν©"""
|
1860 |
+
if not session_id:
|
1861 |
+
logger.error("No session_id provided for download")
|
1862 |
+
return None
|
1863 |
+
|
1864 |
+
# DBμμ μΈμ
μ 보 κ°μ Έμ€κΈ°
|
1865 |
+
session = NovelDatabase.get_session(session_id)
|
1866 |
+
if not session:
|
1867 |
+
logger.error(f"Session not found: {session_id}")
|
1868 |
+
return None
|
1869 |
+
|
1870 |
+
# DBμμ λͺ¨λ μ€ν
μ΄μ§ κ°μ Έμ€κΈ°
|
1871 |
+
stages = NovelDatabase.get_stages(session_id)
|
1872 |
+
|
1873 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
1874 |
+
|
1875 |
+
if format == "DOCX" and DOCX_AVAILABLE:
|
1876 |
+
# Create DOCX
|
1877 |
+
doc = Document()
|
1878 |
+
|
1879 |
+
# μ λͺ© νμ΄μ§
|
1880 |
+
title_para = doc.add_paragraph()
|
1881 |
+
title_run = title_para.add_run('AI Collaborative Novel')
|
1882 |
+
title_run.font.size = Pt(24)
|
1883 |
+
title_run.font.bold = True
|
1884 |
+
title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
1885 |
+
|
1886 |
+
doc.add_paragraph()
|
1887 |
+
doc.add_paragraph()
|
1888 |
+
|
1889 |
+
theme_para = doc.add_paragraph()
|
1890 |
+
theme_run = theme_para.add_run(f'Theme: {session["user_query"]}')
|
1891 |
+
theme_run.font.size = Pt(14)
|
1892 |
+
theme_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
1893 |
+
|
1894 |
+
doc.add_paragraph()
|
1895 |
+
|
1896 |
+
date_para = doc.add_paragraph()
|
1897 |
+
date_run = date_para.add_run(f'Created: {datetime.now().strftime("%Y-%m-%d")}')
|
1898 |
+
date_run.font.size = Pt(12)
|
1899 |
+
date_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
1900 |
+
|
1901 |
+
doc.add_page_break()
|
1902 |
+
|
1903 |
+
# μ 체 ν΅κ³
|
1904 |
+
total_words = 0
|
1905 |
+
writer_count = 0
|
1906 |
+
|
1907 |
+
# κ° μκ°μ μμ λ³Έλ§ μμ§
|
1908 |
+
writer_contents = []
|
1909 |
+
for stage in stages:
|
1910 |
+
if stage['role'].startswith('writer') and 'Revision' in stage['stage_name']:
|
1911 |
+
writer_count += 1
|
1912 |
+
content = stage['content'] or ""
|
1913 |
+
# νμ΄μ§ λ§ν¬ μ κ±°
|
1914 |
+
content = re.sub(r'\[(?:νμ΄μ§|Page|page)\s*\d+\]', '', content)
|
1915 |
+
content = re.sub(r'(?:νμ΄μ§|Page)\s*\d+:', '', content)
|
1916 |
+
content = content.strip()
|
1917 |
+
|
1918 |
+
if content:
|
1919 |
+
word_count = stage['word_count'] or len(content.split())
|
1920 |
+
total_words += word_count
|
1921 |
+
writer_contents.append({
|
1922 |
+
'writer_num': writer_count,
|
1923 |
+
'content': content,
|
1924 |
+
'word_count': word_count
|
1925 |
+
})
|
1926 |
+
|
1927 |
+
# ν΅κ³ νμ΄μ§
|
1928 |
+
doc.add_heading('Novel Statistics', 1)
|
1929 |
+
doc.add_paragraph(f'Total Writers: {writer_count}')
|
1930 |
+
doc.add_paragraph(f'Total Words: {total_words:,}')
|
1931 |
+
doc.add_paragraph(f'Estimated Pages: ~{total_words/500:.0f}')
|
1932 |
+
doc.add_paragraph(f'Language: {session["language"]}')
|
1933 |
+
doc.add_page_break()
|
1934 |
+
|
1935 |
+
# λͺ©μ°¨
|
1936 |
+
doc.add_heading('Table of Contents', 1)
|
1937 |
+
for i in range(1, writer_count + 1):
|
1938 |
+
doc.add_paragraph(f'Chapter {i}: Pages {(i-1)*3+1}-{i*3}')
|
1939 |
+
doc.add_page_break()
|
1940 |
+
|
1941 |
+
# κ° μκ°μ λ΄μ© μΆκ°
|
1942 |
+
for writer_data in writer_contents:
|
1943 |
+
writer_num = writer_data['writer_num']
|
1944 |
+
content = writer_data['content']
|
1945 |
+
word_count = writer_data['word_count']
|
1946 |
+
|
1947 |
+
# μ±ν° ν€λ
|
1948 |
+
doc.add_heading(f'Chapter {writer_num}', 1)
|
1949 |
+
doc.add_paragraph(f'Pages {(writer_num-1)*3+1}-{writer_num*3}')
|
1950 |
+
doc.add_paragraph(f'Word Count: {word_count:,}')
|
1951 |
+
doc.add_paragraph()
|
1952 |
+
|
1953 |
+
# μκ° λ΄μ© μΆκ°
|
1954 |
+
paragraphs = content.split('\n\n')
|
1955 |
+
for para_text in paragraphs:
|
1956 |
+
if para_text.strip():
|
1957 |
+
para = doc.add_paragraph(para_text.strip())
|
1958 |
+
para.style.font.size = Pt(11)
|
1959 |
+
|
1960 |
+
if writer_num < writer_count: # λ§μ§λ§ μκ° νμλ νμ΄μ§ κ΅¬λΆ μμ
|
1961 |
+
doc.add_page_break()
|
1962 |
+
|
1963 |
+
# νμ΄μ§ μ€μ
|
1964 |
+
for section in doc.sections:
|
1965 |
+
section.page_height = Inches(11)
|
1966 |
+
section.page_width = Inches(8.5)
|
1967 |
+
section.left_margin = Inches(1)
|
1968 |
+
section.right_margin = Inches(1)
|
1969 |
+
section.top_margin = Inches(1)
|
1970 |
+
section.bottom_margin = Inches(1)
|
1971 |
+
|
1972 |
+
# Save
|
1973 |
+
temp_dir = tempfile.gettempdir()
|
1974 |
+
safe_filename = re.sub(r'[^\w\s-]', '', session['user_query'][:30]).strip()
|
1975 |
+
filename = f"Novel_Complete_{safe_filename}_{timestamp}.docx"
|
1976 |
+
filepath = os.path.join(temp_dir, filename)
|
1977 |
+
doc.save(filepath)
|
1978 |
+
|
1979 |
+
logger.info(f"DOCX saved successfully: {filepath} ({total_words} words)")
|
1980 |
+
return filepath
|
1981 |
+
else:
|
1982 |
+
# TXT format
|
1983 |
+
temp_dir = tempfile.gettempdir()
|
1984 |
+
safe_filename = re.sub(r'[^\w\s-]', '', session['user_query'][:30]).strip()
|
1985 |
+
filename = f"Novel_Complete_{safe_filename}_{timestamp}.txt"
|
1986 |
+
filepath = os.path.join(temp_dir, filename)
|
1987 |
+
|
1988 |
+
with open(filepath, 'w', encoding='utf-8') as f:
|
1989 |
+
f.write("="*60 + "\n")
|
1990 |
+
f.write("AI COLLABORATIVE NOVEL - COMPLETE VERSION\n")
|
1991 |
+
f.write("="*60 + "\n")
|
1992 |
+
f.write(f"Theme: {session['user_query']}\n")
|
1993 |
+
f.write(f"Language: {session['language']}\n")
|
1994 |
+
f.write(f"Created: {datetime.now()}\n")
|
1995 |
+
f.write("="*60 + "\n\n")
|
1996 |
+
|
1997 |
+
total_words = 0
|
1998 |
+
writer_count = 0
|
1999 |
+
|
2000 |
+
# κ° μκ°μ μμ λ³Έλ§ μΆλ ₯
|
2001 |
+
for stage in stages:
|
2002 |
+
if stage['role'].startswith('writer') and 'Revision' in stage['stage_name']:
|
2003 |
+
writer_count += 1
|
2004 |
+
content = stage['content'] or ""
|
2005 |
+
# νμ΄μ§ λ§ν¬ μ κ±°
|
2006 |
+
content = re.sub(r'\[(?:νμ΄μ§|Page|page)\s*\d+\]', '', content)
|
2007 |
+
content = re.sub(r'(?:νμ΄μ§|Page)\s*\d+:', '', content)
|
2008 |
+
content = content.strip()
|
2009 |
+
|
2010 |
+
if content:
|
2011 |
+
word_count = stage['word_count'] or len(content.split())
|
2012 |
+
total_words += word_count
|
2013 |
+
|
2014 |
+
f.write(f"\n{'='*40}\n")
|
2015 |
+
f.write(f"CHAPTER {writer_count} (Pages {(writer_count-1)*3+1}-{writer_count*3})\n")
|
2016 |
+
f.write(f"Word Count: {word_count:,}\n")
|
2017 |
+
f.write(f"{'='*40}\n\n")
|
2018 |
+
f.write(content)
|
2019 |
+
f.write("\n\n")
|
2020 |
+
|
2021 |
+
f.write(f"\n{'='*60}\n")
|
2022 |
+
f.write(f"TOTAL: {writer_count} writers, {total_words:,} words\n")
|
2023 |
+
f.write(f"{'='*60}\n")
|
2024 |
+
|
2025 |
+
logger.info(f"TXT saved successfully: {filepath} ({total_words} words)")
|
2026 |
+
return filepath
|
2027 |
+
|
2028 |
+
# Custom CSS
|
2029 |
+
custom_css = """
|
2030 |
+
.gradio-container {
|
2031 |
+
background: linear-gradient(135deg, #1e3c72, #2a5298);
|
2032 |
+
min-height: 100vh;
|
2033 |
+
}
|
2034 |
+
|
2035 |
+
.main-header {
|
2036 |
+
background-color: rgba(255, 255, 255, 0.1);
|
2037 |
+
backdrop-filter: blur(10px);
|
2038 |
+
padding: 30px;
|
2039 |
+
border-radius: 12px;
|
2040 |
+
margin-bottom: 30px;
|
2041 |
+
text-align: center;
|
2042 |
+
color: white;
|
2043 |
+
}
|
2044 |
+
|
2045 |
+
.input-section {
|
2046 |
+
background-color: rgba(255, 255, 255, 0.1);
|
2047 |
+
backdrop-filter: blur(10px);
|
2048 |
+
padding: 20px;
|
2049 |
+
border-radius: 12px;
|
2050 |
+
margin-bottom: 20px;
|
2051 |
+
}
|
2052 |
+
|
2053 |
+
.session-section {
|
2054 |
+
background-color: rgba(255, 255, 255, 0.1);
|
2055 |
+
backdrop-filter: blur(10px);
|
2056 |
+
padding: 15px;
|
2057 |
+
border-radius: 8px;
|
2058 |
+
margin-top: 20px;
|
2059 |
+
color: white;
|
2060 |
+
}
|
2061 |
+
|
2062 |
+
#stages-display {
|
2063 |
+
background-color: rgba(255, 255, 255, 0.95);
|
2064 |
+
padding: 20px;
|
2065 |
+
border-radius: 12px;
|
2066 |
+
max-height: 600px;
|
2067 |
+
overflow-y: auto;
|
2068 |
+
}
|
2069 |
+
|
2070 |
+
#novel-output {
|
2071 |
+
background-color: rgba(255, 255, 255, 0.95);
|
2072 |
+
padding: 30px;
|
2073 |
+
border-radius: 12px;
|
2074 |
+
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
|
2075 |
+
max-height: 400px;
|
2076 |
+
overflow-y: auto;
|
2077 |
+
}
|
2078 |
+
|
2079 |
+
.download-section {
|
2080 |
+
background-color: rgba(255, 255, 255, 0.9);
|
2081 |
+
padding: 15px;
|
2082 |
+
border-radius: 8px;
|
2083 |
+
margin-top: 20px;
|
2084 |
+
}
|
2085 |
+
|
2086 |
+
.search-indicator {
|
2087 |
+
color: #4CAF50;
|
2088 |
+
font-weight: bold;
|
2089 |
+
}
|
2090 |
+
|
2091 |
+
.auto-save-indicator {
|
2092 |
+
color: #2196F3;
|
2093 |
+
font-weight: bold;
|
2094 |
+
}
|
2095 |
+
"""
|
2096 |
+
|
2097 |
+
# Create Gradio Interface
|
2098 |
+
def create_interface():
|
2099 |
+
with gr.Blocks(css=custom_css, title="SOMA Novel Writing System") as interface:
|
2100 |
+
gr.HTML("""
|
2101 |
+
<div class="main-header">
|
2102 |
+
<h1 style="font-size: 2.5em; margin-bottom: 10px;">
|
2103 |
+
π SOMA Novel Writing System
|
2104 |
+
</h1>
|
2105 |
+
<h3 style="color: #ccc; margin-bottom: 20px;">
|
2106 |
+
AI Collaborative Novel Generation - 10 Writers Edition
|
2107 |
+
</h3>
|
2108 |
+
<p style="font-size: 1.1em; color: #ddd; max-width: 800px; margin: 0 auto;">
|
2109 |
+
Enter a theme or prompt, and watch as AI agents collaborate to create a complete 30-page novella.
|
2110 |
+
The system includes 1 Director, 1 Critic, and 10 Writers working in harmony.
|
2111 |
+
<br><br>
|
2112 |
+
<span class="search-indicator">π Web search enabled</span> |
|
2113 |
+
<span class="auto-save-indicator">πΎ Auto-save to database</span> |
|
2114 |
+
<span style="color: #FF9800;">β»οΈ Resume anytime</span> |
|
2115 |
+
<span style="color: #FFC107;">π§ͺ Test mode available</span>
|
2116 |
+
</p>
|
2117 |
+
</div>
|
2118 |
+
""")
|
2119 |
+
|
2120 |
+
# State management
|
2121 |
+
current_session_id = gr.State(None)
|
2122 |
+
|
2123 |
+
with gr.Row():
|
2124 |
+
with gr.Column(scale=1):
|
2125 |
+
with gr.Group(elem_classes=["input-section"]):
|
2126 |
+
query_input = gr.Textbox(
|
2127 |
+
label="Novel Theme / μμ€ μ£Όμ ",
|
2128 |
+
placeholder="Enter your novel theme or initial idea...\nμμ€μ μ£Όμ λ μ΄κΈ° μμ΄λμ΄λ₯Ό μ
λ ₯νμΈμ...",
|
2129 |
+
lines=4
|
2130 |
+
)
|
2131 |
+
|
2132 |
+
language_select = gr.Radio(
|
2133 |
+
choices=["English", "Korean"],
|
2134 |
+
value="English",
|
2135 |
+
label="Language / μΈμ΄"
|
2136 |
+
)
|
2137 |
+
|
2138 |
+
# Test mode checkbox
|
2139 |
+
test_mode_check = gr.Checkbox(
|
2140 |
+
label="π§ͺ Test Mode (Quick: 1,2 + Writer 10 only) / ν
μ€νΈ λͺ¨λ (λΉ λ₯Έ μμ±)",
|
2141 |
+
value=False,
|
2142 |
+
info="Skip writers 1-9, only Writer 10 creates the complete novel / μκ° 1-9λ₯Ό 건λλ°κ³ μκ° 10μ΄ μ 체 μμ€ μμ±"
|
2143 |
+
)
|
2144 |
+
|
2145 |
+
# Web search status indicator
|
2146 |
+
web_search_status = gr.Markdown(
|
2147 |
+
value=f"π **Web Search:** {'Enabled' if WebSearchIntegration().enabled else 'Disabled (Set BRAVE_SEARCH_API_KEY)'}"
|
2148 |
+
)
|
2149 |
+
|
2150 |
+
with gr.Row():
|
2151 |
+
submit_btn = gr.Button("π Start Writing / μμ± μμ", variant="primary", scale=2)
|
2152 |
+
clear_btn = gr.Button("ποΈ Clear / μ΄κΈ°ν", scale=1)
|
2153 |
+
|
2154 |
+
status_text = gr.Textbox(
|
2155 |
+
label="Status",
|
2156 |
+
interactive=False,
|
2157 |
+
value="π Ready"
|
2158 |
+
)
|
2159 |
+
|
2160 |
+
# Session management
|
2161 |
+
with gr.Group(elem_classes=["session-section"]):
|
2162 |
+
gr.Markdown("### πΎ Resume Previous Session / μ΄μ μΈμ
μ¬κ°")
|
2163 |
+
session_dropdown = gr.Dropdown(
|
2164 |
+
label="Select Session / μΈμ
μ ν",
|
2165 |
+
choices=[],
|
2166 |
+
interactive=True
|
2167 |
+
)
|
2168 |
+
with gr.Row():
|
2169 |
+
refresh_btn = gr.Button("π Refresh List / λͺ©λ‘ μλ‘κ³ μΉ¨", scale=1)
|
2170 |
+
resume_btn = gr.Button("βΆοΈ Resume Selected / μ ν μ¬κ°", variant="secondary", scale=1)
|
2171 |
+
auto_recover_btn = gr.Button("β»οΈ Auto Recover Latest / μ΅μ μλ볡ꡬ", scale=1)
|
2172 |
+
|
2173 |
+
with gr.Column(scale=2):
|
2174 |
+
with gr.Tab("π Writing Process / μμ± κ³Όμ "):
|
2175 |
+
stages_display = gr.Markdown(
|
2176 |
+
value="Process will appear here...",
|
2177 |
+
elem_id="stages-display"
|
2178 |
+
)
|
2179 |
+
|
2180 |
+
with gr.Tab("π Final Novel / μ΅μ’
μμ€"):
|
2181 |
+
novel_output = gr.Markdown(
|
2182 |
+
value="Complete novel will be available for download after all writers finish.",
|
2183 |
+
elem_id="novel-output"
|
2184 |
+
)
|
2185 |
+
|
2186 |
+
with gr.Group(elem_classes=["download-section"]):
|
2187 |
+
gr.Markdown("### π₯ Download Complete Novel / μ 체 μμ€ λ€μ΄λ‘λ")
|
2188 |
+
with gr.Row():
|
2189 |
+
format_select = gr.Radio(
|
2190 |
+
choices=["DOCX", "TXT"],
|
2191 |
+
value="DOCX" if DOCX_AVAILABLE else "TXT",
|
2192 |
+
label="Format / νμ"
|
2193 |
+
)
|
2194 |
+
download_btn = gr.Button("β¬οΈ Download Complete Novel / μμ±λ μμ€ λ€μ΄λ‘λ", variant="secondary")
|
2195 |
+
|
2196 |
+
download_file = gr.File(
|
2197 |
+
label="Downloaded File / λ€μ΄λ‘λλ νμΌ",
|
2198 |
+
visible=False
|
2199 |
+
)
|
2200 |
+
|
2201 |
+
# Hidden state for novel text
|
2202 |
+
novel_text_state = gr.State("")
|
2203 |
+
|
2204 |
+
# Examples
|
2205 |
+
with gr.Row():
|
2206 |
+
gr.Examples(
|
2207 |
+
examples=[
|
2208 |
+
["A scientist discovers a portal to parallel universes but each journey erases a memory"],
|
2209 |
+
["In a world where dreams can be traded, a dream thief must steal the emperor's nightmare"],
|
2210 |
+
["Two AI entities fall in love while trying to prevent a global cyber war"],
|
2211 |
+
["λ―Έλ λμμμ κΈ°μ΅μ κ±°λνλ μμΈκ³Ό λͺ¨λ κΈ°μ΅μ μμ νμ μ μ΄μΌκΈ°"],
|
2212 |
+
["μκ°μ΄ κ±°κΎΈλ‘ νλ₯΄λ λ§μμμ μΌμ΄λλ λ―Έμ€ν°λ¦¬ν μ΄μΈ μ¬κ±΄"],
|
2213 |
+
["μ±
μμΌλ‘ λ€μ΄κ° μ μλ λ₯λ ₯μ κ°μ§ μ¬μμ λͺ¨ν"]
|
2214 |
+
],
|
2215 |
+
inputs=query_input,
|
2216 |
+
label="π‘ Example Themes / μμ μ£Όμ "
|
2217 |
+
)
|
2218 |
+
|
2219 |
+
# Event handlers
|
2220 |
+
def refresh_sessions():
|
2221 |
+
try:
|
2222 |
+
sessions = get_active_sessions("English")
|
2223 |
+
return gr.update(choices=sessions)
|
2224 |
+
except Exception as e:
|
2225 |
+
logger.error(f"Error refreshing sessions: {str(e)}", exc_info=True)
|
2226 |
+
return gr.update(choices=[])
|
2227 |
+
|
2228 |
+
def handle_auto_recover(language):
|
2229 |
+
session_id, message = auto_recover_session(language)
|
2230 |
+
return session_id
|
2231 |
+
|
2232 |
+
# Connect event handlers
|
2233 |
+
submit_btn.click(
|
2234 |
+
fn=process_query,
|
2235 |
+
inputs=[query_input, language_select, current_session_id, test_mode_check],
|
2236 |
+
outputs=[stages_display, novel_output, status_text]
|
2237 |
+
)
|
2238 |
+
|
2239 |
+
# Update novel text state and session ID when novel output changes
|
2240 |
+
novel_output.change(
|
2241 |
+
fn=lambda x: x,
|
2242 |
+
inputs=[novel_output],
|
2243 |
+
outputs=[novel_text_state]
|
2244 |
+
)
|
2245 |
+
|
2246 |
+
resume_btn.click(
|
2247 |
+
fn=lambda x: x,
|
2248 |
+
inputs=[session_dropdown],
|
2249 |
+
outputs=[current_session_id]
|
2250 |
+
).then(
|
2251 |
+
fn=resume_session,
|
2252 |
+
inputs=[current_session_id, language_select, test_mode_check],
|
2253 |
+
outputs=[stages_display, novel_output, status_text]
|
2254 |
+
)
|
2255 |
+
|
2256 |
+
auto_recover_btn.click(
|
2257 |
+
fn=handle_auto_recover,
|
2258 |
+
inputs=[language_select],
|
2259 |
+
outputs=[current_session_id]
|
2260 |
+
).then(
|
2261 |
+
fn=resume_session,
|
2262 |
+
inputs=[current_session_id, language_select, test_mode_check],
|
2263 |
+
outputs=[stages_display, novel_output, status_text]
|
2264 |
+
)
|
2265 |
+
|
2266 |
+
refresh_btn.click(
|
2267 |
+
fn=refresh_sessions,
|
2268 |
+
outputs=[session_dropdown]
|
2269 |
+
)
|
2270 |
+
|
2271 |
+
clear_btn.click(
|
2272 |
+
fn=lambda: ("", "", "π Ready", "", None, False),
|
2273 |
+
outputs=[stages_display, novel_output, status_text, novel_text_state, current_session_id, test_mode_check]
|
2274 |
+
)
|
2275 |
+
|
2276 |
+
def handle_download(format_type, language, session_id, novel_text):
|
2277 |
+
if not session_id:
|
2278 |
+
return gr.update(visible=False)
|
2279 |
+
|
2280 |
+
file_path = download_novel(novel_text, format_type, language, session_id)
|
2281 |
+
if file_path:
|
2282 |
+
return gr.update(value=file_path, visible=True)
|
2283 |
+
else:
|
2284 |
+
return gr.update(visible=False)
|
2285 |
+
|
2286 |
+
download_btn.click(
|
2287 |
+
fn=handle_download,
|
2288 |
+
inputs=[format_select, language_select, current_session_id, novel_text_state],
|
2289 |
+
outputs=[download_file]
|
2290 |
+
)
|
2291 |
+
|
2292 |
+
# Load sessions on startup
|
2293 |
+
def on_load():
|
2294 |
+
sessions = refresh_sessions()
|
2295 |
+
return sessions
|
2296 |
+
|
2297 |
+
interface.load(
|
2298 |
+
fn=on_load,
|
2299 |
+
outputs=[session_dropdown]
|
2300 |
+
)
|
2301 |
+
|
2302 |
+
return interface
|
2303 |
+
|
2304 |
+
# Main execution
|
2305 |
+
if __name__ == "__main__":
|
2306 |
+
import sys
|
2307 |
+
|
2308 |
+
logger.info("Starting SOMA Novel Writing System - 10 Writers Edition...")
|
2309 |
+
|
2310 |
+
# Check environment
|
2311 |
+
if TEST_MODE:
|
2312 |
+
logger.warning("Running in TEST MODE - no actual API calls will be made")
|
2313 |
+
else:
|
2314 |
+
logger.info(f"Running in PRODUCTION MODE with API endpoint: {API_URL}")
|
2315 |
+
|
2316 |
+
# Check web search
|
2317 |
+
if BRAVE_SEARCH_API_KEY:
|
2318 |
+
logger.info("Web search is ENABLED with Brave Search API")
|
2319 |
+
else:
|
2320 |
+
logger.warning("Web search is DISABLED. Set BRAVE_SEARCH_API_KEY environment variable to enable.")
|
2321 |
+
|
2322 |
+
# Initialize database on startup
|
2323 |
+
logger.info("Initializing database...")
|
2324 |
+
NovelDatabase.init_db()
|
2325 |
+
logger.info("Database initialized successfully.")
|
2326 |
+
|
2327 |
+
interface = create_interface()
|
2328 |
+
|
2329 |
+
interface.launch(
|
2330 |
+
server_name="0.0.0.0",
|
2331 |
+
server_port=7860,
|
2332 |
+
share=False,
|
2333 |
+
debug=True
|
2334 |
+
)
|