openfree commited on
Commit
2a4f761
Β·
verified Β·
1 Parent(s): da9c53d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +2334 -0
app.py ADDED
@@ -0,0 +1,2334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )