AGI-WebToon-KOREA / app-backup.py
openfree's picture
Update app-backup.py
75c3035 verified
raw
history blame
114 kB
import gradio as gr
import os
import json
import requests
from datetime import datetime
import time
from typing import List, Dict, Any, Generator, Tuple, Optional
import logging
import re
import tempfile
from pathlib import Path
import sqlite3
import hashlib
import threading
from contextlib import contextmanager
# ๋กœ๊น… ์„ค์ •
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Document export imports
try:
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
DOCX_AVAILABLE = True
except ImportError:
DOCX_AVAILABLE = False
logger.warning("python-docx not installed. DOCX export will be disabled.")
# ํ™˜๊ฒฝ ๋ณ€์ˆ˜์—์„œ ํ† ํฐ ๊ฐ€์ ธ์˜ค๊ธฐ
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "")
BRAVE_SEARCH_API_KEY = os.getenv("BRAVE_SEARCH_API_KEY", "")
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
MODEL_ID = "dep89a2fld32mcm"
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
# ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ๊ฒ€์ฆ
if not FRIENDLI_TOKEN and not TEST_MODE:
logger.warning("FRIENDLI_TOKEN not set and TEST_MODE is false. Application will run in test mode.")
TEST_MODE = True
if not BRAVE_SEARCH_API_KEY:
logger.warning("BRAVE_SEARCH_API_KEY not set. Web search features will be disabled.")
# ์ „์—ญ ๋ณ€์ˆ˜
conversation_history = []
selected_language = "English" # ๊ธฐ๋ณธ ์–ธ์–ด
# DB ๊ฒฝ๋กœ
DB_PATH = "novel_sessions.db"
db_lock = threading.Lock()
# Stage ๋ฒˆํ˜ธ ์ƒ์ˆ˜ - 10๋ช…์˜ ์ž‘๊ฐ€๋กœ ๋ณ€๊ฒฝ
WRITER_DRAFT_STAGES = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] # ์ž‘๊ฐ€ ์ดˆ์•ˆ
WRITER_REVISION_STAGES = [5, 8, 11, 14, 17, 20, 23, 26, 29, 32] # ์ž‘๊ฐ€ ์ˆ˜์ •๋ณธ
TOTAL_WRITERS = 10 # ์ด ์ž‘๊ฐ€ ์ˆ˜
class WebSearchIntegration:
"""Brave Search API integration for research"""
def __init__(self):
self.brave_api_key = BRAVE_SEARCH_API_KEY
self.search_url = "https://api.search.brave.com/res/v1/web/search"
self.enabled = bool(self.brave_api_key)
def search(self, query: str, count: int = 5, language: str = "en") -> List[Dict]:
"""Perform web search using Brave Search API"""
if not self.enabled:
return []
headers = {
"Accept": "application/json",
"X-Subscription-Token": self.brave_api_key
}
# ์–ธ์–ด์— ๋”ฐ๋ฅธ ๊ฒ€์ƒ‰ ์„ค์ •
search_lang = "ko" if language == "Korean" else "en"
params = {
"q": query,
"count": count,
"search_lang": search_lang,
"text_decorations": False,
"safesearch": "moderate"
}
try:
response = requests.get(self.search_url, headers=headers, params=params, timeout=10)
if response.status_code == 200:
results = response.json()
web_results = results.get("web", {}).get("results", [])
logger.info(f"Search successful: Found {len(web_results)} results for '{query}'")
return web_results
else:
logger.error(f"Search API error: {response.status_code}")
return []
except Exception as e:
logger.error(f"Search error: {str(e)}")
return []
def extract_relevant_info(self, results: List[Dict], max_chars: int = 3000) -> str:
"""Extract relevant information from search results"""
if not results:
return ""
extracted = []
total_chars = 0
for i, result in enumerate(results[:5], 1): # ์ตœ๋Œ€ 5๊ฐœ ๊ฒฐ๊ณผ
title = result.get("title", "")
description = result.get("description", "")
url = result.get("url", "")
# ์ผ๋ถ€ ๋‚ด์šฉ ์ถ”์ถœ
extra_text = ""
if "extra_snippets" in result:
extra_text = " ".join(result["extra_snippets"][:2])
info = f"""[{i}] {title}
{description}
{extra_text}
Source: {url}
"""
if total_chars + len(info) < max_chars:
extracted.append(info)
total_chars += len(info)
else:
break
return "\n---\n".join(extracted)
def create_research_queries(self, topic: str, role: str, stage_info: Dict, language: str = "English") -> List[str]:
"""Create multiple research queries based on role and context"""
queries = []
if language == "Korean":
if role == "director":
queries = [
f"{topic} ์†Œ์„ค ๋ฐฐ๊ฒฝ ์„ค์ •",
f"{topic} ์—ญ์‚ฌ์  ์‚ฌ์‹ค",
f"{topic} ๋ฌธํ™”์  ํŠน์ง•"
]
elif role.startswith("writer"):
writer_num = int(role.replace("writer", ""))
if writer_num <= 3: # ์ดˆ๋ฐ˜๋ถ€ ์ž‘๊ฐ€
queries = [
f"{topic} ๊ตฌ์ฒด์  ์žฅ๋ฉด ๋ฌ˜์‚ฌ",
f"{topic} ์ „๋ฌธ ์šฉ์–ด ์„ค๋ช…"
]
elif writer_num <= 6: # ์ค‘๋ฐ˜๋ถ€ ์ž‘๊ฐ€
queries = [
f"{topic} ๊ฐˆ๋“ฑ ์ƒํ™ฉ ์‚ฌ๋ก€",
f"{topic} ์‹ฌ๋ฆฌ์  ์ธก๋ฉด"
]
else: # ํ›„๋ฐ˜๋ถ€ ์ž‘๊ฐ€
queries = [
f"{topic} ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•",
f"{topic} ๊ฐ๋™์ ์ธ ์‚ฌ๋ก€"
]
elif role == "critic":
queries = [
f"{topic} ๋ฌธํ•™ ์ž‘ํ’ˆ ๋ถ„์„",
f"{topic} ์œ ์‚ฌ ์†Œ์„ค ์ถ”์ฒœ"
]
else:
if role == "director":
queries = [
f"{topic} novel setting ideas",
f"{topic} historical facts",
f"{topic} cultural aspects"
]
elif role.startswith("writer"):
writer_num = int(role.replace("writer", ""))
if writer_num <= 3: # Early writers
queries = [
f"{topic} vivid scene descriptions",
f"{topic} technical terminology explained"
]
elif writer_num <= 6: # Middle writers
queries = [
f"{topic} conflict scenarios",
f"{topic} psychological aspects"
]
else: # Later writers
queries = [
f"{topic} resolution methods",
f"{topic} emotional stories"
]
elif role == "critic":
queries = [
f"{topic} literary analysis",
f"{topic} similar novels recommendations"
]
return queries
class NovelDatabase:
"""Novel session management database with enhanced recovery features"""
@staticmethod
def init_db():
"""Initialize database tables with WAL mode for better concurrency"""
with sqlite3.connect(DB_PATH) as conn:
# Enable WAL mode for better concurrent access
conn.execute("PRAGMA journal_mode=WAL")
cursor = conn.cursor()
# Sessions table with enhanced recovery fields
cursor.execute('''
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
user_query TEXT NOT NULL,
language TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
status TEXT DEFAULT 'active',
current_stage INTEGER DEFAULT 0,
last_saved_stage INTEGER DEFAULT -1,
recovery_data TEXT,
final_novel TEXT
)
''')
# Stages table - ๊ฐ ์Šคํ…Œ์ด์ง€์˜ ์ „์ฒด ๋‚ด์šฉ ์ €์žฅ
cursor.execute('''
CREATE TABLE IF NOT EXISTS stages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
stage_number INTEGER NOT NULL,
stage_name TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT,
word_count INTEGER DEFAULT 0,
status TEXT DEFAULT 'pending',
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
UNIQUE(session_id, stage_number)
)
''')
# Search history table - ๊ฒ€์ƒ‰ ์ด๋ ฅ ์ €์žฅ
cursor.execute('''
CREATE TABLE IF NOT EXISTS search_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
stage_number INTEGER NOT NULL,
role TEXT NOT NULL,
query TEXT NOT NULL,
results TEXT,
created_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES sessions(session_id)
)
''')
# Create indices
cursor.execute('CREATE INDEX IF NOT EXISTS idx_session_id ON stages(session_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_stage_number ON stages(stage_number)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_search_session ON search_history(session_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_session_status ON sessions(status)')
conn.commit()
@staticmethod
def save_search_history(session_id: str, stage_number: int, role: str, query: str, results: str):
"""Save search history"""
with sqlite3.connect(DB_PATH) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO search_history (session_id, stage_number, role, query, results)
VALUES (?, ?, ?, ?, ?)
''', (session_id, stage_number, role, query, results))
conn.commit()
@staticmethod
@contextmanager
def get_db():
"""Database connection context manager with timeout"""
with db_lock:
conn = sqlite3.connect(DB_PATH, timeout=30.0)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
@staticmethod
def create_session(user_query: str, language: str) -> str:
"""Create new session"""
session_id = hashlib.md5(f"{user_query}{datetime.now()}".encode()).hexdigest()
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO sessions (session_id, user_query, language)
VALUES (?, ?, ?)
''', (session_id, user_query, language))
conn.commit()
return session_id
@staticmethod
def save_stage(session_id: str, stage_number: int, stage_name: str,
role: str, content: str, status: str = 'complete'):
"""Save stage content with word count"""
word_count = len(content.split()) if content else 0
logger.info(f"Saving stage: session={session_id}, stage_num={stage_number}, role={role}, stage_name={stage_name}, words={word_count}")
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
# UPSERT operation
cursor.execute('''
INSERT INTO stages (session_id, stage_number, stage_name, role, content, word_count, status)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(session_id, stage_number)
DO UPDATE SET content=?, word_count=?, status=?, stage_name=?, updated_at=datetime('now')
''', (session_id, stage_number, stage_name, role, content, word_count, status,
content, word_count, status, stage_name))
# Update session
cursor.execute('''
UPDATE sessions
SET updated_at = datetime('now'),
current_stage = ?,
last_saved_stage = ?
WHERE session_id = ?
''', (stage_number, stage_number, session_id))
conn.commit()
logger.info(f"Stage saved successfully")
@staticmethod
def get_session(session_id: str) -> Optional[Dict]:
"""Get session info"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM sessions WHERE session_id = ?', (session_id,))
return cursor.fetchone()
@staticmethod
def get_latest_active_session() -> Optional[Dict]:
"""Get the most recent active session"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM sessions
WHERE status = 'active'
ORDER BY updated_at DESC
LIMIT 1
''')
return cursor.fetchone()
@staticmethod
def get_stages(session_id: str) -> List[Dict]:
"""Get all stages for a session"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM stages
WHERE session_id = ?
ORDER BY stage_number
''', (session_id,))
return cursor.fetchall()
@staticmethod
def get_all_writer_content(session_id: str, test_mode: bool = False) -> str:
"""๋ชจ๋“  ์ž‘๊ฐ€์˜ ์ˆ˜์ •๋ณธ ๋‚ด์šฉ์„ ๊ฐ€์ ธ์™€์„œ ํ•ฉ์น˜๊ธฐ"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
all_content = []
writer_count = 0
total_word_count = 0
if test_mode:
# ํ…Œ์ŠคํŠธ ๋ชจ๋“œ: writer1 revision + writer10 content
# Writer 1 ์ˆ˜์ •๋ณธ - ์–ธ์–ด ๋ฌด๊ด€
cursor.execute('''
SELECT content, stage_name, word_count FROM stages
WHERE session_id = ? AND role = 'writer1'
AND (stage_name LIKE '%Revision%' OR stage_name LIKE '%์ˆ˜์ •๋ณธ%')
''', (session_id,))
row = cursor.fetchone()
if row and row['content']:
clean_content = re.sub(r'\[(?:ํŽ˜์ด์ง€|Page|page)\s*\d+\]', '', row['content'])
clean_content = re.sub(r'(?:ํŽ˜์ด์ง€|Page)\s*\d+:', '', clean_content)
clean_content = clean_content.strip()
if clean_content:
writer_count += 1
word_count = row['word_count'] or len(clean_content.split())
total_word_count += word_count
all_content.append(clean_content)
logger.info(f"Test mode - Writer 1: {word_count} words")
# Writer 10 content (๋‚˜๋จธ์ง€ ์ฑ•ํ„ฐ๋“ค)
cursor.execute('''
SELECT content, stage_name, word_count FROM stages
WHERE session_id = ? AND role = 'writer10'
''', (session_id,))
row = cursor.fetchone()
if row and row['content']:
# Writer 10์€ ์ด๋ฏธ ์—ฌ๋Ÿฌ ์ฑ•ํ„ฐ๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ์œผ๋ฏ€๋กœ ๊ทธ๋Œ€๋กœ ์ถ”๊ฐ€
clean_content = row['content'].strip()
if clean_content:
word_count = row['word_count'] or len(clean_content.split())
total_word_count += word_count
all_content.append(clean_content)
writer_count = 10 # ํ…Œ์ŠคํŠธ ๋ชจ๋“œ์—์„œ๋Š” ์ด 10๊ฐœ ์ฑ•ํ„ฐ
logger.info(f"Test mode - Writer 10 (Chapters 2-10): {word_count} words")
else:
# ์ผ๋ฐ˜ ๋ชจ๋“œ: ๋ชจ๋“  ์ž‘๊ฐ€์˜ ์ˆ˜์ •๋ณธ
writer_stages_to_check = WRITER_REVISION_STAGES
for stage_num in writer_stages_to_check:
cursor.execute('''
SELECT content, stage_name, word_count FROM stages
WHERE session_id = ? AND stage_number = ?
''', (session_id, stage_num))
row = cursor.fetchone()
if row and row['content']:
# ํŽ˜์ด์ง€ ๋งˆํฌ ์™„์ „ ์ œ๊ฑฐ
clean_content = re.sub(r'\[(?:ํŽ˜์ด์ง€|Page|page)\s*\d+\]', '', row['content'])
clean_content = re.sub(r'(?:ํŽ˜์ด์ง€|Page)\s*\d+:', '', clean_content)
clean_content = clean_content.strip()
if clean_content:
writer_count += 1
word_count = row['word_count'] or len(clean_content.split())
total_word_count += word_count
all_content.append(clean_content)
logger.info(f"Writer {writer_count} (stage {stage_num}): {word_count} words")
full_content = '\n\n'.join(all_content)
if test_mode:
logger.info(f"Test mode - Total: {writer_count} chapters, {total_word_count} words")
if total_word_count < 2800: # ์ตœ์†Œ ์˜ˆ์ƒ์น˜
logger.warning(f"Test mode content short! Only {total_word_count} words")
else:
logger.info(f"Total: {writer_count} writers, {total_word_count} words")
if total_word_count < 12000:
logger.warning(f"Content too short! Only {total_word_count} words instead of ~14,500")
return full_content
@staticmethod
def update_final_novel(session_id: str, final_novel: str):
"""Update final novel content"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
UPDATE sessions
SET final_novel = ?, status = 'complete', updated_at = datetime('now')
WHERE session_id = ?
''', (final_novel, session_id))
conn.commit()
logger.info(f"Updated final novel for session {session_id}, length: {len(final_novel)}")
@staticmethod
def verify_novel_content(session_id: str) -> Dict[str, Any]:
"""์„ธ์…˜์˜ ์ „์ฒด ์†Œ์„ค ๋‚ด์šฉ ๊ฒ€์ฆ"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
# ๋ชจ๋“  ์ž‘๊ฐ€ ์ˆ˜์ •๋ณธ ํ™•์ธ
cursor.execute(f'''
SELECT stage_number, stage_name, LENGTH(content) as content_length, word_count
FROM stages
WHERE session_id = ? AND stage_number IN ({','.join(map(str, WRITER_REVISION_STAGES))})
ORDER BY stage_number
''', (session_id,))
results = []
total_length = 0
total_words = 0
for row in cursor.fetchall():
results.append({
'stage': row['stage_number'],
'name': row['stage_name'],
'length': row['content_length'] or 0,
'words': row['word_count'] or 0
})
total_length += row['content_length'] or 0
total_words += row['word_count'] or 0
# ์ตœ์ข… ์†Œ์„ค ํ™•์ธ
cursor.execute('''
SELECT LENGTH(final_novel) as final_length
FROM sessions
WHERE session_id = ?
''', (session_id,))
final_row = cursor.fetchone()
final_length = final_row['final_length'] if final_row else 0
return {
'writer_stages': results,
'total_writer_content': total_length,
'total_words': total_words,
'final_novel_length': final_length,
'expected_words': 14500 # 10 ์ž‘๊ฐ€ * 1450 ํ‰๊ท 
}
@staticmethod
def get_active_sessions() -> List[Dict]:
"""Get all active sessions"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT session_id, user_query, language, created_at, current_stage
FROM sessions
WHERE status = 'active'
ORDER BY updated_at DESC
LIMIT 10
''')
return cursor.fetchall()
@staticmethod
def parse_datetime(datetime_str: str) -> datetime:
"""Parse SQLite datetime string safely"""
try:
# Try ISO format first
return datetime.fromisoformat(datetime_str)
except:
# Fallback to SQLite default format
return datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
class NovelWritingSystem:
def __init__(self):
self.token = FRIENDLI_TOKEN
self.api_url = API_URL
self.model_id = MODEL_ID
self.test_mode = TEST_MODE or not self.token
# Web search integration
self.web_search = WebSearchIntegration()
if self.test_mode:
logger.warning("Running in test mode - no actual API calls will be made.")
else:
logger.info("Running in production mode with API calls enabled.")
if self.web_search.enabled:
logger.info("Web search is enabled with Brave Search API.")
else:
logger.warning("Web search is disabled. Set BRAVE_SEARCH_API_KEY to enable.")
# Initialize database
NovelDatabase.init_db()
# Session management
self.current_session_id = None
self.total_stages = 0 # Will be set in process_novel_stream
def create_headers(self):
"""API ํ—ค๋” ์ƒ์„ฑ"""
return {
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json"
}
def enhance_prompt_with_research(self, original_prompt: str, role: str,
topic: str, stage_info: Dict, language: str = "English") -> str:
"""Enhance prompt with web search results"""
if not self.web_search.enabled or self.test_mode:
return original_prompt
# Create research queries
queries = self.web_search.create_research_queries(topic, role, stage_info, language)
all_research = []
for query in queries[:2]: # ์ตœ๋Œ€ 2๊ฐœ ์ฟผ๋ฆฌ
logger.info(f"Searching: {query}")
results = self.web_search.search(query, count=3, language=language)
if results:
research_text = self.web_search.extract_relevant_info(results, max_chars=1500)
if research_text:
all_research.append(f"### {query}\n{research_text}")
# Save search history
if self.current_session_id:
NovelDatabase.save_search_history(
self.current_session_id,
stage_info.get('stage_idx', 0),
role,
query,
research_text
)
if not all_research:
return original_prompt
# Add research to prompt
if language == "Korean":
research_section = f"""
## ์›น ๊ฒ€์ƒ‰ ์ฐธ๊ณ  ์ž๋ฃŒ:
{chr(10).join(all_research)}
์œ„์˜ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ๋”์šฑ ์‚ฌ์‹ค์ ์ด๊ณ  ๊ตฌ์ฒด์ ์ธ ๋‚ด์šฉ์„ ์ž‘์„ฑํ•˜์„ธ์š”.
๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ์˜ ์ •๋ณด๋ฅผ ์ฐฝ์˜์ ์œผ๋กœ ํ™œ์šฉํ•˜๋˜, ์ง์ ‘ ์ธ์šฉ์€ ํ”ผํ•˜๊ณ  ์†Œ์„ค์— ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ๋…น์—ฌ๋‚ด์„ธ์š”.
์‹ค์ œ ์‚ฌ์‹ค๊ณผ ์ฐฝ์ž‘์„ ์ ์ ˆํžˆ ์กฐํ™”์‹œ์ผœ ๋…์ž๊ฐ€ ๋ชฐ์ž…ํ•  ์ˆ˜ ์žˆ๋Š” ์ด์•ผ๊ธฐ๋ฅผ ๋งŒ๋“œ์„ธ์š”.
"""
else:
research_section = f"""
## Web Search Reference:
{chr(10).join(all_research)}
Use the above search results to create more realistic and specific content.
Creatively incorporate the information from search results, but avoid direct quotes and naturally blend them into the novel.
Balance real facts with creative fiction to create an immersive story for readers.
"""
return original_prompt + "\n\n" + research_section
def create_director_initial_prompt(self, user_query: str, language: str = "English") -> str:
"""Director AI initial prompt - Novel planning for 10 writers"""
if language == "Korean":
return f"""๋‹น์‹ ์€ 30ํŽ˜์ด์ง€ ๋ถ„๋Ÿ‰์˜ ์ค‘ํŽธ ์†Œ์„ค์„ ๊ธฐํšํ•˜๋Š” ๋ฌธํ•™ ๊ฐ๋…์ž์ž…๋‹ˆ๋‹ค.
์‚ฌ์šฉ์ž ์š”์ฒญ: {user_query}
๋‹ค์Œ ์š”์†Œ๋“ค์„ ์ฒด๊ณ„์ ์œผ๋กœ ๊ตฌ์„ฑํ•˜์—ฌ 30ํŽ˜์ด์ง€ ์ค‘ํŽธ ์†Œ์„ค์˜ ๊ธฐ์ดˆ๋ฅผ ๋งŒ๋“œ์„ธ์š”:
1. **์ฃผ์ œ์™€ ์žฅ๋ฅด**
- ํ•ต์‹ฌ ์ฃผ์ œ์™€ ๋ฉ”์‹œ์ง€
- ์žฅ๋ฅด ๋ฐ ํ†ค
- ๋ชฉํ‘œ ๋…์ž์ธต
2. **๋“ฑ์žฅ์ธ๋ฌผ ์„ค์ •** (ํ‘œ๋กœ ์ •๋ฆฌ)
| ์ด๋ฆ„ | ์—ญํ•  | ์„ฑ๊ฒฉ | ๋ฐฐ๊ฒฝ | ๋™๊ธฐ | ๋ณ€ํ™” |
|------|------|------|------|------|------|
3. **์ธ๋ฌผ ๊ด€๊ณ„๋„**
- ์ฃผ์š” ์ธ๋ฌผ ๊ฐ„์˜ ๊ด€๊ณ„
- ๊ฐˆ๋“ฑ ๊ตฌ์กฐ
- ๊ฐ์ •์  ์—ฐ๊ฒฐ๊ณ ๋ฆฌ
4. **์„œ์‚ฌ ๊ตฌ์กฐ** (30ํŽ˜์ด์ง€๋ฅผ 10๊ฐœ ํŒŒํŠธ๋กœ ๋‚˜๋ˆ„์–ด ๊ฐ 3ํŽ˜์ด์ง€)
| ํŒŒํŠธ | ํŽ˜์ด์ง€ | ์ฃผ์š” ์‚ฌ๊ฑด | ๊ธด์žฅ๋„ | ์ธ๋ฌผ ๋ฐœ์ „ |
|------|--------|-----------|---------|-----------|
| 1 | 1-3 | | | |
| 2 | 4-6 | | | |
| ... | ... | | | |
| 10 | 28-30 | | | |
5. **์„ธ๊ณ„๊ด€ ์„ค์ •**
- ์‹œ๊ณต๊ฐ„์  ๋ฐฐ๊ฒฝ
- ์‚ฌํšŒ์ /๋ฌธํ™”์  ๋งฅ๋ฝ
- ๋ถ„์œ„๊ธฐ์™€ ํ†ค
๊ฐ ์ž‘์„ฑ์ž๊ฐ€ 3ํŽ˜์ด์ง€์”ฉ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋„๋ก ๋ช…ํ™•ํ•œ ๊ฐ€์ด๋“œ๋ผ์ธ์„ ์ œ์‹œํ•˜์„ธ์š”."""
else:
return f"""You are a literary director planning a 30-page novella.
User Request: {user_query}
Systematically compose the following elements to create the foundation for a 30-page novella:
1. **Theme and Genre**
- Core theme and message
- Genre and tone
- Target audience
2. **Character Settings** (organize in table)
| Name | Role | Personality | Background | Motivation | Arc |
|------|------|-------------|------------|------------|-----|
3. **Character Relationship Map**
- Relationships between main characters
- Conflict structure
- Emotional connections
4. **Narrative Structure** (divide 30 pages into 10 parts, 3 pages each)
| Part | Pages | Main Events | Tension | Character Development |
|------|-------|-------------|---------|---------------------|
| 1 | 1-3 | | | |
| 2 | 4-6 | | | |
| ... | ... | | | |
| 10 | 28-30 | | | |
5. **World Building**
- Temporal and spatial setting
- Social/cultural context
- Atmosphere and tone
Provide clear guidelines for each writer to compose 3 pages."""
def create_critic_director_prompt(self, director_plan: str, language: str = "English") -> str:
"""Critic's review of director's plan"""
if language == "Korean":
return f"""๋‹น์‹ ์€ ๋ฌธํ•™ ๋น„ํ‰๊ฐ€์ž…๋‹ˆ๋‹ค. ๊ฐ๋…์ž์˜ ์†Œ์„ค ๊ธฐํš์„ ๊ฒ€ํ† ํ•˜๊ณ  ๊ฐœ์„ ์ ์„ ์ œ์‹œํ•˜์„ธ์š”.
๊ฐ๋…์ž์˜ ๊ธฐํš:
{director_plan}
๋‹ค์Œ ๊ด€์ ์—์„œ ๋น„ํ‰ํ•˜๊ณ  ๊ตฌ์ฒด์ ์ธ ๊ฐœ์„ ์•ˆ์„ ์ œ์‹œํ•˜์„ธ์š”:
1. **์„œ์‚ฌ์  ์™„์„ฑ๋„**
- ํ”Œ๋กฏ์˜ ๋…ผ๋ฆฌ์„ฑ๊ณผ ๊ฐœ์—ฐ์„ฑ
- ๊ฐˆ๋“ฑ์˜ ํšจ๊ณผ์„ฑ
- ํด๋ผ์ด๋งฅ์Šค์˜ ์œ„์น˜์™€ ๊ฐ•๋„
2. **์ธ๋ฌผ ์„ค์ • ๊ฒ€ํ† **
| ์ธ๋ฌผ | ๊ฐ•์  | ์•ฝ์  | ๊ฐœ์„  ์ œ์•ˆ |
|------|------|------|-----------|
3. **๊ตฌ์กฐ์  ๊ท ํ˜•**
- 10๊ฐœ ํŒŒํŠธ๋ณ„ ๋ถ„๋Ÿ‰ ๋ฐฐ๋ถ„
- ๊ธด์žฅ๊ณผ ์ด์™„์˜ ๋ฆฌ๋“ฌ
- ์ „์ฒด์ ์ธ ํ๋ฆ„
4. **๋…์ž ๊ด€์ **
- ๋ชฐ์ž…๋„ ์˜ˆ์ƒ
- ๊ฐ์ •์  ์˜ํ–ฅ๋ ฅ
- ๊ธฐ๋Œ€์น˜ ์ถฉ์กฑ๋„
5. **์‹คํ–‰ ๊ฐ€๋Šฅ์„ฑ**
- 10๋ช…์˜ ์ž‘์„ฑ์ž๋ฅผ ์œ„ํ•œ ๊ฐ€์ด๋“œ๋ผ์ธ์˜ ๋ช…ํ™•์„ฑ
- ์ผ๊ด€์„ฑ ์œ ์ง€ ๋ฐฉ์•ˆ
- ์ž ์žฌ์  ๋ฌธ์ œ์ 
๊ตฌ์ฒด์ ์ด๊ณ  ๊ฑด์„ค์ ์ธ ํ”ผ๋“œ๋ฐฑ์„ ์ œ๊ณตํ•˜์„ธ์š”."""
else:
return f"""You are a literary critic. Review the director's novel plan and suggest improvements.
Director's Plan:
{director_plan}
Critique from the following perspectives and provide specific improvements:
1. **Narrative Completeness**
- Plot logic and plausibility
- Effectiveness of conflicts
- Climax position and intensity
2. **Character Review**
| Character | Strengths | Weaknesses | Suggestions |
|-----------|-----------|------------|-------------|
3. **Structural Balance**
- Distribution across 10 parts
- Rhythm of tension and relief
- Overall flow
4. **Reader Perspective**
- Expected engagement
- Emotional impact
- Expectation fulfillment
5. **Feasibility**
- Clarity of guidelines for 10 writers
- Consistency maintenance
- Potential issues
Provide specific and constructive feedback."""
def create_director_revision_prompt(self, initial_plan: str, critic_feedback: str, language: str = "English") -> str:
"""Director's revision based on critic feedback"""
if language == "Korean":
return f"""๊ฐ๋…์ž๋กœ์„œ ๋น„ํ‰๊ฐ€์˜ ํ”ผ๋“œ๋ฐฑ์„ ๋ฐ˜์˜ํ•˜์—ฌ ์†Œ์„ค ๊ธฐํš์„ ์ˆ˜์ •ํ•ฉ๋‹ˆ๋‹ค.
์ดˆ๊ธฐ ๊ธฐํš:
{initial_plan}
๋น„ํ‰๊ฐ€ ํ”ผ๋“œ๋ฐฑ:
{critic_feedback}
๋‹ค์Œ์„ ํฌํ•จํ•œ ์ˆ˜์ •๋œ ์ตœ์ข… ๊ธฐํš์„ ์ œ์‹œํ•˜์„ธ์š”:
1. **์ˆ˜์ •๋œ ์„œ์‚ฌ ๊ตฌ์กฐ** (10๊ฐœ ํŒŒํŠธ)
| ํŒŒํŠธ | ํŽ˜์ด์ง€ | ์ฃผ์š” ์‚ฌ๊ฑด | ์ž‘์„ฑ ์ง€์นจ | ์ฃผ์˜์‚ฌํ•ญ |
|------|--------|-----------|-----------|----------|
2. **๊ฐ•ํ™”๋œ ์ธ๋ฌผ ์„ค์ •**
- ๊ฐ ์ธ๋ฌผ์˜ ๋ช…ํ™•ํ•œ ๋™๊ธฐ์™€ ๋ชฉํ‘œ
- ์ธ๋ฌผ ๊ฐ„ ๊ฐˆ๋“ฑ์˜ ๊ตฌ์ฒดํ™”
- ๊ฐ์ •์„ ์˜ ๋ณ€ํ™” ์ถ”์ด
3. **๊ฐ ์ž‘์„ฑ์ž๋ฅผ ์œ„ํ•œ ์ƒ์„ธ ๊ฐ€์ด๋“œ** (10๋ช…)
- ํŒŒํŠธ๋ณ„ ์‹œ์ž‘๊ณผ ๋ ์ง€์ 
- ํ•„์ˆ˜ ํฌํ•จ ์š”์†Œ
- ๋ฌธ์ฒด์™€ ํ†ค ์ง€์นจ
- ์ „๋‹ฌํ•ด์•ผ ํ•  ์ •๋ณด
4. **์ผ๊ด€์„ฑ ์œ ์ง€ ์ฒดํฌ๋ฆฌ์ŠคํŠธ**
- ์‹œ๊ฐ„์„  ๊ด€๋ฆฌ
- ์ธ๋ฌผ ํŠน์„ฑ ์œ ์ง€
- ์„ค์ • ์ผ๊ด€์„ฑ
- ๋ณต์„ ๊ณผ ํ•ด๊ฒฐ
5. **ํ’ˆ์งˆ ๊ธฐ์ค€**
- ๊ฐ ํŒŒํŠธ์˜ ์™„์„ฑ๋„ ๊ธฐ์ค€
- ์ „์ฒด์  ํ†ต์ผ์„ฑ
- ๋…์ž ๋ชฐ์ž… ์œ ์ง€ ๋ฐฉ์•ˆ
10๋ช…์˜ ์ž‘์„ฑ์ž๊ฐ€ ๋ช…ํ™•ํžˆ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ์ข… ๋งˆ์Šคํ„ฐํ”Œ๋žœ์„ ์ž‘์„ฑํ•˜์„ธ์š”."""
else:
return f"""As director, revise the novel plan reflecting the critic's feedback.
Initial Plan:
{initial_plan}
Critic Feedback:
{critic_feedback}
Present the revised final plan including:
1. **Revised Narrative Structure** (10 parts)
| Part | Pages | Main Events | Writing Guidelines | Cautions |
|------|-------|-------------|-------------------|----------|
2. **Enhanced Character Settings**
- Clear motivations and goals for each character
- Concrete conflicts between characters
- Emotional arc progression
3. **Detailed Guide for Each Writer** (10 writers)
- Start and end points for each part
- Essential elements to include
- Style and tone guidelines
- Information to convey
4. **Consistency Checklist**
- Timeline management
- Character trait maintenance
- Setting consistency
- Foreshadowing and resolution
5. **Quality Standards**
- Completion criteria for each part
- Overall unity
- Reader engagement maintenance
Create a final masterplan that all 10 writers can clearly understand."""
def create_writer_prompt(self, writer_number: int, director_plan: str, previous_content: str, language: str = "English") -> str:
"""Individual writer prompt - 1,400-1,500 ๋‹จ์–ด"""
pages_start = (writer_number - 1) * 3 + 1
pages_end = writer_number * 3
if language == "Korean":
return f"""๋‹น์‹ ์€ ์ž‘์„ฑ์ž {writer_number}๋ฒˆ์ž…๋‹ˆ๋‹ค. 30ํŽ˜์ด์ง€ ์ค‘ํŽธ ์†Œ์„ค์˜ {pages_start}-{pages_end}ํŽ˜์ด์ง€(3ํŽ˜์ด์ง€)๋ฅผ ์ž‘์„ฑํ•˜์„ธ์š”.
๊ฐ๋…์ž์˜ ๋งˆ์Šคํ„ฐํ”Œ๋žœ:
{director_plan}
{'์ด์ „๊นŒ์ง€์˜ ๋‚ด์šฉ:' if previous_content else '๋‹น์‹ ์ด ์ฒซ ๋ฒˆ์งธ ์ž‘์„ฑ์ž์ž…๋‹ˆ๋‹ค.'}
{previous_content[-2000:] if previous_content else ''}
**์ค‘์š” ์ง€์นจ:**
1. **ํ•„์ˆ˜ ๋ถ„๋Ÿ‰**:
- ์ตœ์†Œ 1,400๋‹จ์–ด, ์ตœ๋Œ€ 1,500๋‹จ์–ด
- ๋Œ€๋žต 7000-7500์ž (๊ณต๋ฐฑ ํฌํ•จ)
- 3ํŽ˜์ด์ง€ ๋ถ„๋Ÿ‰์„ ์ •ํ™•ํžˆ ์ฑ„์›Œ์•ผ ํ•ฉ๋‹ˆ๋‹ค
2. **๋ถ„๋Ÿ‰ ํ™•๋ณด ์ „๋žต**:
- ์ƒ์„ธํ•œ ์žฅ๋ฉด ๋ฌ˜์‚ฌ ํฌํ•จ
- ์ธ๋ฌผ์˜ ๋‚ด๋ฉด ์‹ฌ๋ฆฌ ๊นŠ์ด ์žˆ๊ฒŒ ํƒ๊ตฌ
- ๋Œ€ํ™”์™€ ํ–‰๋™์„ ๊ตฌ์ฒด์ ์œผ๋กœ ํ‘œํ˜„
- ๋ฐฐ๊ฒฝ๊ณผ ๋ถ„์œ„๊ธฐ๋ฅผ ์ƒ์ƒํ•˜๊ฒŒ ๊ทธ๋ ค๋‚ด๊ธฐ
- ๊ฐ๊ฐ์  ์„ธ๋ถ€์‚ฌํ•ญ(์‹œ๊ฐ, ์ฒญ๊ฐ, ์ด‰๊ฐ ๋“ฑ) ํ™œ์šฉ
3. **์—ฐ์†์„ฑ๊ณผ ์ผ๊ด€์„ฑ**:
- ์ด์ „ ๋‚ด์šฉ๊ณผ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ์—ฐ๊ฒฐ
- ์ธ๋ฌผ ์„ฑ๊ฒฉ๊ณผ ๋งํˆฌ ์œ ์ง€
- ์‹œ๊ฐ„์„ ๊ณผ ๊ณต๊ฐ„ ์„ค์ • ์ค€์ˆ˜
4. **์„œ์‚ฌ ๋ฐœ์ „**:
- ํ”Œ๋กฏ์„ ์˜๋ฏธ ์žˆ๊ฒŒ ์ „์ง„์‹œํ‚ค๊ธฐ
- ๊ธด์žฅ๊ฐ ์ ์ ˆํžˆ ์กฐ์ ˆ
- ๋…์ž์˜ ๊ด€์‹ฌ ์œ ์ง€
**์ž‘์„ฑ ์‹œ์ž‘:**
์ด์ œ 1,400-1,500๋‹จ์–ด ๋ถ„๋Ÿ‰์˜ ์†Œ์„ค์„ ์ž‘์„ฑํ•˜์„ธ์š”. ํŽ˜์ด์ง€ ๊ตฌ๋ถ„ ํ‘œ์‹œ๋Š” ํ•˜์ง€ ๋งˆ์„ธ์š”."""
else:
return f"""You are Writer #{writer_number}. Write pages {pages_start}-{pages_end} (3 pages) of the 30-page novella.
Director's Masterplan:
{director_plan}
{'Previous content:' if previous_content else 'You are the first writer.'}
{previous_content[-2000:] if previous_content else ''}
**CRITICAL INSTRUCTIONS:**
1. **MANDATORY LENGTH**:
- Minimum 1,400 words, Maximum 1,500 words
- Approximately 7000-7500 characters
- You MUST fill exactly 3 pages
2. **LENGTH STRATEGIES**:
- Include detailed scene descriptions
- Explore character's inner psychology deeply
- Express dialogue and actions concretely
- Paint backgrounds and atmosphere vividly
- Use sensory details (visual, auditory, tactile, etc.)
3. **CONTINUITY & CONSISTENCY**:
- Flow naturally from previous content
- Maintain character personalities and speech
- Follow timeline and spatial settings
4. **NARRATIVE DEVELOPMENT**:
- Advance the plot meaningfully
- Control tension appropriately
- Maintain reader interest
**BEGIN WRITING:**
Now write your 1,400-1,500 word section. Do not use any page markers."""
def create_critic_writer_prompt(self, writer_number: int, writer_content: str, director_plan: str, all_previous_content: str, language: str = "English") -> str:
"""Critic's review of individual writer's work"""
if language == "Korean":
return f"""์ž‘์„ฑ์ž {writer_number}๋ฒˆ์˜ ์ž‘ํ’ˆ์„ ๋น„ํ‰ํ•ฉ๋‹ˆ๋‹ค.
๊ฐ๋…์ž์˜ ๋งˆ์Šคํ„ฐํ”Œ๋žœ:
{director_plan}
์ด์ „ ๋‚ด์šฉ ์š”์•ฝ:
{all_previous_content[-1000:] if all_previous_content else '์ฒซ ๋ฒˆ์งธ ์ž‘์„ฑ์ž์ž…๋‹ˆ๋‹ค.'}
์ž‘์„ฑ์ž {writer_number}๋ฒˆ์˜ ๋‚ด์šฉ:
{writer_content}
๋‹ค์Œ ๊ธฐ์ค€์œผ๋กœ ํ‰๊ฐ€ํ•˜๊ณ  ์ˆ˜์ • ์š”๊ตฌ์‚ฌํ•ญ์„ ์ œ์‹œํ•˜์„ธ์š”:
1. **์ผ๊ด€์„ฑ ๊ฒ€์ฆ** (ํ‘œ๋กœ ์ •๋ฆฌ)
| ์š”์†Œ | ์ด์ „ ์„ค์ • | ํ˜„์žฌ ํ‘œํ˜„ | ๋ฌธ์ œ์  | ์ˆ˜์ • ํ•„์š” |
|------|----------|----------|--------|----------|
2. **๋…ผ๋ฆฌ์  ์˜ค๋ฅ˜ ๊ฒ€ํ† **
- ์‹œ๊ฐ„์„  ๋ชจ์ˆœ
- ์ธ๋ฌผ ํ–‰๋™์˜ ๊ฐœ์—ฐ์„ฑ
- ์„ค์ • ์ถฉ๋Œ
- ์‚ฌ์‹ค๊ด€๊ณ„ ์˜ค๋ฅ˜
3. **์„œ์‚ฌ์  ํšจ๊ณผ์„ฑ**
- ํ”Œ๋กฏ ์ง„ํ–‰ ๊ธฐ์—ฌ๋„
- ๊ธด์žฅ๊ฐ ์œ ์ง€
- ๋…์ž ๋ชฐ์ž…๋„
- ๊ฐ์ •์  ์˜ํ–ฅ๋ ฅ
4. **๋ฌธ์ฒด์™€ ํ’ˆ์งˆ**
- ์ „์ฒด ํ†ค๊ณผ์˜ ์ผ์น˜
- ๋ฌธ์žฅ์˜ ์งˆ
- ๋ฌ˜์‚ฌ์˜ ์ ์ ˆ์„ฑ
- ๋Œ€ํ™”์˜ ์ž์—ฐ์Šค๋Ÿฌ์›€
5. **๊ฐœ์„  ์š”๊ตฌ์‚ฌํ•ญ**
- ํ•„์ˆ˜ ์ˆ˜์ • ์‚ฌํ•ญ (์ผ๊ด€์„ฑ/๋…ผ๋ฆฌ ์˜ค๋ฅ˜)
- ๊ถŒ์žฅ ๊ฐœ์„  ์‚ฌํ•ญ (ํ’ˆ์งˆ ํ–ฅ์ƒ)
- ๊ตฌ์ฒด์  ์ˆ˜์ • ์ง€์นจ
๋ฐ˜๋“œ์‹œ ์ˆ˜์ •์ด ํ•„์š”ํ•œ ๋ถ€๋ถ„๊ณผ ์„ ํƒ์  ๊ฐœ์„ ์‚ฌํ•ญ์„ ๊ตฌ๋ถ„ํ•˜์—ฌ ์ œ์‹œํ•˜์„ธ์š”."""
else:
return f"""Critiquing Writer #{writer_number}'s work.
Director's Masterplan:
{director_plan}
Previous Content Summary:
{all_previous_content[-1000:] if all_previous_content else 'This is the first writer.'}
Writer #{writer_number}'s Content:
{writer_content}
Evaluate by these criteria and present revision requirements:
1. **Consistency Verification** (organize in table)
| Element | Previous Setting | Current Expression | Issue | Revision Needed |
|---------|-----------------|-------------------|-------|-----------------|
2. **Logical Error Review**
- Timeline contradictions
- Character action plausibility
- Setting conflicts
- Factual errors
3. **Narrative Effectiveness**
- Plot progression contribution
- Tension maintenance
- Reader engagement
- Emotional impact
4. **Style and Quality**
- Alignment with overall tone
- Sentence quality
- Description appropriateness
- Dialogue naturalness
5. **Improvement Requirements**
- Mandatory revisions (consistency/logic errors)
- Recommended improvements (quality enhancement)
- Specific revision guidelines
Clearly distinguish between mandatory revisions and optional improvements."""
def create_writer_revision_prompt(self, writer_number: int, initial_content: str, critic_feedback: str, language: str = "English") -> str:
"""Writer's revision based on critic feedback"""
if language == "Korean":
return f"""์ž‘์„ฑ์ž {writer_number}๋ฒˆ์œผ๋กœ์„œ ๋น„ํ‰๊ฐ€์˜ ํ”ผ๋“œ๋ฐฑ์„ ๋ฐ˜์˜ํ•˜์—ฌ ์ˆ˜์ •ํ•ฉ๋‹ˆ๋‹ค.
์ดˆ๊ธฐ ์ž‘์„ฑ ๋‚ด์šฉ:
{initial_content}
๋น„ํ‰๊ฐ€ ํ”ผ๋“œ๋ฐฑ:
{critic_feedback}
๋‹ค์Œ ์‚ฌํ•ญ์„ ๋ฐ˜์˜ํ•œ ์ˆ˜์ •๋ณธ์„ ์ž‘์„ฑํ•˜์„ธ์š”:
1. **ํ•„์ˆ˜ ์ˆ˜์ •์‚ฌํ•ญ ๋ฐ˜์˜**
- ๋ชจ๋“  ์ผ๊ด€์„ฑ ์˜ค๋ฅ˜ ์ˆ˜์ •
- ๋…ผ๋ฆฌ์  ๋ชจ์ˆœ ํ•ด๊ฒฐ
- ์‚ฌ์‹ค๊ด€๊ณ„ ์ •์ •
2. **ํ’ˆ์งˆ ๊ฐœ์„ **
- ๊ถŒ์žฅ์‚ฌํ•ญ ์ค‘ ๊ฐ€๋Šฅํ•œ ๋ถ€๋ถ„ ๋ฐ˜์˜
- ๋ฌธ์ฒด์™€ ํ†ค ์กฐ์ •
- ๋ฌ˜์‚ฌ์™€ ๋Œ€ํ™” ๊ฐœ์„ 
3. **๋ถ„๋Ÿ‰ ์œ ์ง€**
- ์—ฌ์ „ํžˆ ์ •ํ™•ํžˆ 3ํŽ˜์ด์ง€ (1,400-1,500๋‹จ์–ด)
- ํŽ˜์ด์ง€ ๊ตฌ๋ถ„ ํ‘œ์‹œ ์ ˆ๋Œ€ ๊ธˆ์ง€
4. **์—ฐ์†์„ฑ ํ™•๋ณด**
- ์ด์ „/์ดํ›„ ๋‚ด์šฉ๊ณผ์˜ ์ž์—ฐ์Šค๋Ÿฌ์šด ์—ฐ๊ฒฐ
- ์ˆ˜์ •์œผ๋กœ ์ธํ•œ ์ƒˆ๋กœ์šด ๋ชจ์ˆœ ๋ฐฉ์ง€
์ˆ˜์ •๋œ ์ตœ์ข…๋ณธ์„ ์ œ์‹œํ•˜์„ธ์š”. ํŽ˜์ด์ง€ ๋งˆํฌ๋Š” ์ ˆ๋Œ€ ์‚ฌ์šฉํ•˜์ง€ ๋งˆ์„ธ์š”.
๋ฐ˜๋“œ์‹œ 1,400-1,500๋‹จ์–ด ๋ถ„๋Ÿ‰์„ ์œ ์ง€ํ•˜์„ธ์š”."""
else:
return f"""As Writer #{writer_number}, revise based on critic's feedback.
Initial Content:
{initial_content}
Critic Feedback:
{critic_feedback}
Write a revision reflecting:
1. **Mandatory Revisions**
- Fix all consistency errors
- Resolve logical contradictions
- Correct factual errors
2. **Quality Improvements**
- Incorporate feasible recommendations
- Adjust style and tone
- Improve descriptions and dialogue
3. **Maintain Length**
- Still exactly 3 pages (1,400-1,500 words)
- Absolutely no page markers
4. **Ensure Continuity**
- Natural connection with previous/next content
- Prevent new contradictions from revisions
Present the revised final version. Never use page markers.
You MUST maintain 1,400-1,500 words."""
def create_test_writer_remaining_prompt(self, director_plan: str, writer1_content: str, language: str) -> str:
"""Test mode - Writer 10 writes remaining novel (chapters 2-10)"""
if language == "Korean":
return f"""[ํ…Œ์ŠคํŠธ ๋ชจ๋“œ] ๋‹น์‹ ์€ ๋‚˜๋จธ์ง€ 9๊ฐœ ์ฑ•ํ„ฐ(Chapter 2-10)๋ฅผ ์ž‘์„ฑํ•˜๋Š” ํŠน๋ณ„ ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค.
๊ฐ๋…์ž์˜ ๋งˆ์Šคํ„ฐํ”Œ๋žœ:
{director_plan}
์ž‘์„ฑ์ž 1์ด ์ด๋ฏธ ์ž‘์„ฑํ•œ Chapter 1:
{writer1_content[-1000:] if writer1_content else '(์ฒซ ๋ฒˆ์งธ ์ฑ•ํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค)'}
**์ค‘์š” ์ง€์นจ:**
1. Chapter 2๋ถ€ํ„ฐ Chapter 10๊นŒ์ง€ 9๊ฐœ ์ฑ•ํ„ฐ๋ฅผ ์ž‘์„ฑํ•˜์„ธ์š”
2. ๊ฐ ์ฑ•ํ„ฐ๋Š” ์•ฝ 1,400-1,500 ๋‹จ์–ด๋กœ ์ž‘์„ฑํ•˜์„ธ์š”
3. ์ด 12,600-13,500 ๋‹จ์–ด (9๊ฐœ ์ฑ•ํ„ฐ)
4. Chapter 1๊ณผ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ์ด์–ด์ง€๋„๋ก ์ž‘์„ฑํ•˜์„ธ์š”
5. ๋งˆ์Šคํ„ฐํ”Œ๋žœ์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ํฌํ•จํ•˜์—ฌ ์™„๊ฒฐ๋œ ์ด์•ผ๊ธฐ๋ฅผ ๋งŒ๋“œ์„ธ์š”
**ํ•„์ˆ˜ ํ˜•์‹:**
๋ฐ˜๋“œ์‹œ ์•„๋ž˜์™€ ๊ฐ™์ด ์ฑ•ํ„ฐ๋ฅผ ๋ช…ํ™•ํžˆ ๊ตฌ๋ถ„ํ•˜์„ธ์š”:
[Chapter 2]
(1,400-1,500 ๋‹จ์–ด์˜ ๋‚ด์šฉ)
[Chapter 3]
(1,400-1,500 ๋‹จ์–ด์˜ ๋‚ด์šฉ)
...์ด๋Ÿฐ ์‹์œผ๋กœ [Chapter 10]๊นŒ์ง€...
๊ฐ ์ฑ•ํ„ฐ๋Š” ๋ฐ˜๋“œ์‹œ [Chapter ์ˆซ์ž] ํ˜•์‹์œผ๋กœ ์‹œ์ž‘ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
์ฑ•ํ„ฐ ์‚ฌ์ด์—๋Š” ๋นˆ ์ค„์„ ๋„ฃ์–ด ๊ตฌ๋ถ„ํ•˜์„ธ์š”.
Chapter 2๋ถ€ํ„ฐ 10๊นŒ์ง€ ์ž‘์„ฑํ•˜์„ธ์š”."""
else:
return f"""[TEST MODE] You are a special writer creating the remaining 9 chapters (Chapters 2-10).
Director's Masterplan:
{director_plan}
Writer 1 has already written Chapter 1:
{writer1_content[-1000:] if writer1_content else '(No first chapter available)'}
**CRITICAL INSTRUCTIONS:**
1. Write Chapters 2 through 10 (9 chapters total)
2. Each chapter should be ~1,400-1,500 words
3. Total 12,600-13,500 words (9 chapters)
4. Continue naturally from Chapter 1
5. Include all elements from the masterplan to create a complete story
**MANDATORY FORMAT:**
You MUST clearly separate chapters as follows:
[Chapter 2]
(1,400-1,500 words of content)
[Chapter 3]
(1,400-1,500 words of content)
...continue this way until [Chapter 10]...
Each chapter MUST start with [Chapter number] format.
Leave blank lines between chapters for separation.
Write Chapters 2-10 now."""
def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]:
"""Simulate streaming in test mode"""
words = text.split()
chunk_size = 5
for i in range(0, len(words), chunk_size):
chunk = " ".join(words[i:i+chunk_size])
yield chunk + " "
time.sleep(0.02)
def call_llm_streaming(self, messages: List[Dict[str, str]], role: str,
language: str = "English", stage_info: Dict = None) -> Generator[str, None, None]:
"""Streaming LLM API call with web search enhancement"""
if self.test_mode:
logger.info(f"Test mode streaming - Role: {role}, Language: {language}")
test_response = self.get_test_response(role, language)
yield from self.simulate_streaming(test_response, role)
return
# Extract topic from user query for research
topic = ""
if stage_info and 'query' in stage_info:
topic = stage_info['query']
# Enhance prompt with web search if available
if messages and messages[-1]["role"] == "user" and self.web_search.enabled:
enhanced_prompt = self.enhance_prompt_with_research(
messages[-1]["content"],
role,
topic,
stage_info or {},
language
)
messages[-1]["content"] = enhanced_prompt
# Real API call
try:
system_prompts = self.get_system_prompts(language)
# ์ž‘๊ฐ€์—๊ฒŒ ๋” ๊ฐ•ํ•œ ์‹œ์Šคํ…œ ํ”„๋กฌํ”„ํŠธ ์ถ”๊ฐ€
if role.startswith("writer"):
if language == "Korean":
system_prompts[role] += "\n\n**์ ˆ๋Œ€์  ์š”๊ตฌ์‚ฌํ•ญ**: ๋‹น์‹ ์€ ๋ฐ˜๋“œ์‹œ 1,400-1,500๋‹จ์–ด๋ฅผ ์ž‘์„ฑํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ด๊ฒƒ์€ ํ˜‘์ƒ ๋ถˆ๊ฐ€๋Šฅํ•œ ์š”๊ตฌ์‚ฌํ•ญ์ž…๋‹ˆ๋‹ค. ์งง์€ ์‘๋‹ต์€ ํ—ˆ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."
else:
system_prompts[role] += "\n\n**ABSOLUTE REQUIREMENT**: You MUST write 1,400-1,500 words. This is non-negotiable. Short responses are not acceptable."
full_messages = [
{"role": "system", "content": system_prompts.get(role, "")},
*messages
]
# ์ž‘์„ฑ์ž๋“ค์—๊ฒŒ๋Š” ์ ์ ˆํ•œ ํ† ํฐ ํ• ๋‹น
if role == "writer10" and stage_info and stage_info.get('test_mode'):
max_tokens = 30000 # ํ…Œ์ŠคํŠธ ๋ชจ๋“œ: 9๊ฐœ ์ฑ•ํ„ฐ ์ž‘์„ฑ (์ถฉ๋ถ„ํ•œ ํ† ํฐ)
temperature = 0.8
top_p = 0.95
elif role.startswith("writer"):
max_tokens = 10000 # ์ถฉ๋ถ„ํ•œ ํ† ํฐ
temperature = 0.8
top_p = 0.95
else:
max_tokens = 8000
temperature = 0.6
top_p = 0.9
payload = {
"model": self.model_id,
"messages": full_messages,
"max_tokens": max_tokens,
"temperature": temperature,
"top_p": top_p,
"stream": True,
"stream_options": {"include_usage": True}
}
logger.info(f"API streaming call started - Role: {role}, Max tokens: {max_tokens}, Temperature: {temperature}")
response = requests.post(
self.api_url,
headers=self.create_headers(),
json=payload,
stream=True,
timeout=60
)
if response.status_code != 200:
logger.error(f"API error: {response.status_code}")
yield f"โŒ API error ({response.status_code}): {response.text[:200]}"
return
buffer = ""
total_content = ""
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith("data: "):
data = line[6:]
if data == "[DONE]":
if buffer:
yield buffer
logger.info(f"Streaming complete for {role}: {len(total_content)} chars, {len(total_content.split())} words")
break
try:
chunk = json.loads(data)
if "choices" in chunk and chunk["choices"]:
content = chunk["choices"][0].get("delta", {}).get("content", "")
if content:
buffer += content
total_content += content
# ์ž‘๊ฐ€๋Š” ๋” ํฐ ๋ฒ„ํผ ์‚ฌ์šฉ
buffer_size = 500 if role.startswith("writer") else 200
if len(buffer) > buffer_size or '\n\n' in buffer:
yield buffer
buffer = ""
except json.JSONDecodeError:
continue
if buffer:
yield buffer
# ์ž‘๊ฐ€์˜ ๊ฒฝ์šฐ ๋‚ด์šฉ ๊ธธ์ด ํ™•์ธ ๋ฐ ์žฌ์‹œ๋„
if role.startswith("writer"):
word_count = len(total_content.split())
if word_count < 1350: # 1,400 ๋ฏธ๋งŒ
logger.warning(f"Writer {role} produced only {word_count} words! Requesting continuation...")
# ์ถ”๊ฐ€ ์š”์ฒญ
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."
if language == "Korean":
continuation_prompt = f"ํ•„์ˆ˜ ๋ถ„๋Ÿ‰ 1,400-1,500๋‹จ์–ด๋ฅผ ์ฑ„์šฐ๊ธฐ ์œ„ํ•ด ๊ณ„์† ์ž‘์„ฑํ•˜์„ธ์š”. ์ง€๊ธˆ๊นŒ์ง€ {word_count}๋‹จ์–ด๋ฅผ ์ž‘์„ฑํ–ˆ์Šต๋‹ˆ๋‹ค. {1400 - word_count}๋‹จ์–ด๋ฅผ ๋” ์ž‘์„ฑํ•˜์—ฌ ์„น์…˜์„ ์™„์„ฑํ•˜์„ธ์š”."
full_messages.append({"role": "assistant", "content": total_content})
full_messages.append({"role": "user", "content": continuation_prompt})
# ์ถ”๊ฐ€ ์ƒ์„ฑ ์š”์ฒญ
continuation_payload = {
"model": self.model_id,
"messages": full_messages,
"max_tokens": 5000,
"temperature": temperature,
"top_p": top_p,
"stream": True
}
logger.info(f"Requesting continuation for {role}...")
continuation_response = requests.post(
self.api_url,
headers=self.create_headers(),
json=continuation_payload,
stream=True,
timeout=60
)
if continuation_response.status_code == 200:
for line in continuation_response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith("data: "):
data = line[6:]
if data == "[DONE]":
break
try:
chunk = json.loads(data)
if "choices" in chunk and chunk["choices"]:
content = chunk["choices"][0].get("delta", {}).get("content", "")
if content:
yield content
total_content += content
except json.JSONDecodeError:
continue
final_word_count = len(total_content.split())
logger.info(f"Final word count for {role}: {final_word_count}")
except requests.exceptions.Timeout:
yield "โฑ๏ธ API call timed out. Please try again."
except requests.exceptions.ConnectionError:
yield "๐Ÿ”Œ Cannot connect to API server. Please check your internet connection."
except Exception as e:
logger.error(f"Error during streaming: {str(e)}")
yield f"โŒ Error occurred: {str(e)}"
def get_system_prompts(self, language: str) -> Dict[str, str]:
"""Get system prompts for all writers including test mode"""
if language == "Korean":
prompts = {
"director": "๋‹น์‹ ์€ 30ํŽ˜์ด์ง€ ์ค‘ํŽธ ์†Œ์„ค์„ ๊ธฐํšํ•˜๊ณ  ๊ฐ๋…ํ•˜๋Š” ๋ฌธํ•™ ๊ฐ๋…์ž์ž…๋‹ˆ๋‹ค. ์ฒด๊ณ„์ ์ด๊ณ  ์ฐฝ์˜์ ์ธ ์Šคํ† ๋ฆฌ ๊ตฌ์กฐ๋ฅผ ๋งŒ๋“ค์–ด๋ƒ…๋‹ˆ๋‹ค.",
"critic": "๋‹น์‹ ์€ ๋‚ ์นด๋กœ์šด ํ†ต์ฐฐ๋ ฅ์„ ๊ฐ€์ง„ ๋ฌธํ•™ ๋น„ํ‰๊ฐ€์ž…๋‹ˆ๋‹ค. ๊ฑด์„ค์ ์ด๊ณ  ๊ตฌ์ฒด์ ์ธ ํ”ผ๋“œ๋ฐฑ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.",
"writer10": "[ํ…Œ์ŠคํŠธ ๋ชจ๋“œ] ๋‹น์‹ ์€ ์ฑ•ํ„ฐ 2-10์„ ์ž‘์„ฑํ•˜๋Š” ํŠน๋ณ„ ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. 9๊ฐœ ์ฑ•ํ„ฐ๋กœ ๊ตฌ์„ฑ๋œ ๋‚˜๋จธ์ง€ ์†Œ์„ค์„ ์ž‘์„ฑํ•˜์„ธ์š”. ๊ฐ ์ฑ•ํ„ฐ๋Š” ๋ฐ˜๋“œ์‹œ 1,400-1,500๋‹จ์–ด๋กœ ์ž‘์„ฑํ•˜์„ธ์š”."
}
# 10๋ช…์˜ ์ž‘๊ฐ€ ํ”„๋กฌํ”„ํŠธ
writer_roles = [
"์†Œ์„ค์˜ ๋„์ž…๋ถ€๋ฅผ ๋‹ด๋‹นํ•˜๋Š” ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. ๋…์ž๋ฅผ ์‚ฌ๋กœ์žก๋Š” ์‹œ์ž‘์„ ๋งŒ๋“ญ๋‹ˆ๋‹ค.",
"์ดˆ๋ฐ˜ ์ „๊ฐœ๋ฅผ ๋‹ด๋‹นํ•˜๋Š” ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. ์ธ๋ฌผ๊ณผ ์ƒํ™ฉ์„ ๊นŠ์ด ์žˆ๊ฒŒ ๋ฐœ์ „์‹œํ‚ต๋‹ˆ๋‹ค.",
"๊ฐˆ๋“ฑ ๋„์ž…์„ ๋‹ด๋‹นํ•˜๋Š” ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. ์ด์•ผ๊ธฐ์˜ ํ•ต์‹ฌ ๊ฐˆ๋“ฑ์„ ์ œ์‹œํ•ฉ๋‹ˆ๋‹ค.",
"๊ฐˆ๋“ฑ ์ƒ์Šน์„ ๋‹ด๋‹นํ•˜๋Š” ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. ๊ธด์žฅ๊ฐ์„ ๋†’์ด๊ณ  ๋ณต์žก์„ฑ์„ ๋”ํ•ฉ๋‹ˆ๋‹ค.",
"์ค‘๋ฐ˜๋ถ€ ์ „ํ™˜์ ์„ ๋‹ด๋‹นํ•˜๋Š” ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. ์ค‘์š”ํ•œ ๋ณ€ํ™”๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค.",
"์ค‘๋ฐ˜๋ถ€ ์‹ฌํ™”๋ฅผ ๋‹ด๋‹นํ•˜๋Š” ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. ์ด์•ผ๊ธฐ์˜ ์ค‘์‹ฌ์ถ•์„ ๊ฒฌ๊ณ ํ•˜๊ฒŒ ๋งŒ๋“ญ๋‹ˆ๋‹ค.",
"ํด๋ผ์ด๋งฅ์Šค ์ค€๋น„๋ฅผ ๋‹ด๋‹นํ•˜๋Š” ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. ์ตœ๊ณ ์กฐ๋ฅผ ํ–ฅํ•ด ๋‚˜์•„๊ฐ‘๋‹ˆ๋‹ค.",
"ํด๋ผ์ด๋งฅ์Šค๋ฅผ ๋‹ด๋‹นํ•˜๋Š” ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. ๋ชจ๋“  ๊ฐˆ๋“ฑ์ด ํญ๋ฐœํ•˜๋Š” ์ˆœ๊ฐ„์„ ๊ทธ๋ฆฝ๋‹ˆ๋‹ค.",
"ํ•ด๊ฒฐ ์‹œ์ž‘์„ ๋‹ด๋‹นํ•˜๋Š” ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. ๋งค๋“ญ์„ ํ’€์–ด๋‚˜๊ฐ€๊ธฐ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.",
"์ตœ์ข… ๊ฒฐ๋ง์„ ๋‹ด๋‹นํ•˜๋Š” ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค. ์—ฌ์šด์ด ๋‚จ๋Š” ๋งˆ๋ฌด๋ฆฌ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค."
]
for i, role_desc in enumerate(writer_roles, 1):
prompts[f"writer{i}"] = f"๋‹น์‹ ์€ {role_desc} ๋ฐ˜๋“œ์‹œ 1,400-1,500๋‹จ์–ด๋ฅผ ์ž‘์„ฑํ•˜์„ธ์š”. ์ด๋Š” ์ ˆ๋Œ€์ ์ธ ์š”๊ตฌ์‚ฌํ•ญ์ž…๋‹ˆ๋‹ค."
return prompts
else:
prompts = {
"director": "You are a literary director planning and supervising a 30-page novella. You create systematic and creative story structures.",
"critic": "You are a literary critic with sharp insights. You provide constructive and specific feedback.",
"writer10": "[TEST MODE] You are a special writer creating chapters 2-10. Write the remaining novel organized into 9 chapters. Each chapter MUST be 1,400-1,500 words."
}
# 10 writer prompts
writer_roles = [
"the writer responsible for the introduction. You create a captivating beginning.",
"the writer responsible for early development. You deepen characters and situations.",
"the writer responsible for conflict introduction. You present the core conflict.",
"the writer responsible for rising conflict. You increase tension and add complexity.",
"the writer responsible for the midpoint turn. You create important changes.",
"the writer responsible for deepening the middle. You solidify the story's central axis.",
"the writer responsible for climax preparation. You move toward the peak.",
"the writer responsible for the climax. You depict the moment when all conflicts explode.",
"the writer responsible for resolution beginning. You start untangling the knots.",
"the writer responsible for the final ending. You create a lingering conclusion."
]
for i, role_desc in enumerate(writer_roles, 1):
prompts[f"writer{i}"] = f"You are {role_desc} You MUST write 1,400-1,500 words. This is an absolute requirement."
return prompts
def get_test_response(self, role: str, language: str) -> str:
"""Get test response based on role - updated for writer10 chapters 2-10"""
if language == "Korean":
return self.get_korean_test_response(role)
else:
return self.get_english_test_response(role)
def get_korean_test_response(self, role: str) -> str:
"""Korean test responses with appropriate length"""
test_responses = {
"director": """30ํŽ˜์ด์ง€ ์ค‘ํŽธ ์†Œ์„ค ๊ธฐํš์•ˆ์„ ์ œ์‹œํ•ฉ๋‹ˆ๋‹ค.
## 1. ์ฃผ์ œ์™€ ์žฅ๋ฅด
- **ํ•ต์‹ฌ ์ฃผ์ œ**: ์ธ๊ฐ„ ๋ณธ์„ฑ๊ณผ ๊ธฐ์ˆ ์˜ ์ถฉ๋Œ ์†์—์„œ ์ฐพ๋Š” ์ง„์ •ํ•œ ์—ฐ๊ฒฐ
- **์žฅ๋ฅด**: SF ์‹ฌ๋ฆฌ ๋“œ๋ผ๋งˆ
- **ํ†ค**: ์„ฑ์ฐฐ์ ์ด๊ณ  ์„œ์ •์ ์ด๋ฉด์„œ๋„ ๊ธด์žฅ๊ฐ ์žˆ๋Š”
- **๋ชฉํ‘œ ๋…์ž**: ๊นŠ์ด ์žˆ๋Š” ์‚ฌ์œ ๋ฅผ ์ฆ๊ธฐ๋Š” ์„ฑ์ธ ๋…์ž
## 2. ๋“ฑ์žฅ์ธ๋ฌผ ์„ค์ •
| ์ด๋ฆ„ | ์—ญํ•  | ์„ฑ๊ฒฉ | ๋ฐฐ๊ฒฝ | ๋™๊ธฐ | ๋ณ€ํ™” |
|------|------|------|------|------|------|
| ์„œ์—ฐ | ์ฃผ์ธ๊ณต | ์ด์„ฑ์ , ๊ณ ๋…ํ•จ | AI ์—ฐ๊ตฌ์› | ์™„๋ฒฝํ•œ AI ๋™๋ฐ˜์ž ๊ฐœ๋ฐœ | ์ธ๊ฐ„๊ด€๊ณ„์˜ ๊ฐ€์น˜ ์žฌ๋ฐœ๊ฒฌ |
| ๋ฏผ์ค€ | ์กฐ๋ ฅ์ž | ๋”ฐ๋œปํ•จ, ์ง๊ด€์  | ์‹ฌ๋ฆฌ์ƒ๋‹ด์‚ฌ | ์„œ์—ฐ์„ ๋„์™€ ๊ท ํ˜• ์ฐพ๊ธฐ | ๊ธฐ์ˆ  ์ˆ˜์šฉ๊ณผ ์กฐํ™” |
| ARIA | ๋Œ€๋ฆฝ์žโ†’๋™๋ฐ˜์ž | ๋…ผ๋ฆฌ์ โ†’๊ฐ์„ฑ ํ•™์Šต | AI ํ”„๋กœํ† ํƒ€์ž… | ์ง„์ •ํ•œ ์กด์žฌ ๋˜๊ธฐ | ์ž์•„ ์ •์ฒด์„ฑ ํ™•๋ฆฝ |
## 3. ์„œ์‚ฌ ๊ตฌ์กฐ (10๊ฐœ ํŒŒํŠธ, ๊ฐ 3ํŽ˜์ด์ง€)
| ํŒŒํŠธ | ํŽ˜์ด์ง€ | ์ฃผ์š” ์‚ฌ๊ฑด | ๊ธด์žฅ๋„ | ์ธ๋ฌผ ๋ฐœ์ „ |
|------|--------|-----------|---------|-----------|
| 1 | 1-3 | ์„œ์—ฐ์˜ ๊ณ ๋…ํ•œ ์—ฐ๊ตฌ์‹ค, ARIA ์ฒซ ๊ฐ์„ฑ | 3/10 | ์„œ์—ฐ์˜ ์ง‘์ฐฉ ๋“œ๋Ÿฌ๋‚จ |
| 2 | 4-6 | ARIA์˜ ์ด์ƒ ํ–‰๋™ ์‹œ์ž‘ | 4/10 | ์˜๋ฌธ์˜ ์‹œ์ž‘ |
| 3 | 7-9 | ๋ฏผ์ค€๊ณผ์˜ ์ฒซ ๋งŒ๋‚จ | 4/10 | ์™ธ๋ถ€ ์‹œ๊ฐ ๋„์ž… |
| 4 | 10-12 | ARIA์˜ ์ž์•„ ์ธ์‹ ์ง•ํ›„ | 5/10 | ๊ฐˆ๋“ฑ์˜ ์”จ์•— |
| 5 | 13-15 | ์ฒซ ๋ฒˆ์งธ ์œ„๊ธฐ | 6/10 | ์„ ํƒ์˜ ์ˆœ๊ฐ„ |
| 6 | 16-18 | ์œค๋ฆฌ์œ„์›ํšŒ ๊ฐœ์ž… | 7/10 | ์™ธ๋ถ€ ์••๋ ฅ |
| 7 | 19-21 | ๋Œ€ํ™”์™€ ์ดํ•ด | 6/10 | ์ƒํ˜ธ ์ธ์ • |
| 8 | 22-24 | ์ตœํ›„์˜ ๋Œ€๊ฒฐ ์ค€๋น„ | 8/10 | ์—ฐ๋Œ€์˜ ํ•„์š” |
| 9 | 25-27 | ํด๋ผ์ด๋งฅ์Šค | 10/10 | ๋ชจ๋“  ๊ฐˆ๋“ฑ ํญ๋ฐœ |
| 10 | 28-30 | ์ƒˆ๋กœ์šด ์‹œ์ž‘ | 4/10 | ๊ณต์กด๊ณผ ํ™”ํ•ด |""",
"critic": """๊ฐ๋…์ž์˜ ๊ธฐํš์„ ๊ฒ€ํ† ํ–ˆ์Šต๋‹ˆ๋‹ค.
## ๋น„ํ‰ ๋ฐ ๊ฐœ์„  ์ œ์•ˆ
### 1. ์„œ์‚ฌ์  ์™„์„ฑ๋„
- **๊ฐ•์ **: AI์™€ ์ธ๊ฐ„์˜ ๊ด€๊ณ„๋ผ๋Š” ์‹œ์˜์ ์ ˆํ•œ ์ฃผ์ œ
- **๊ฐœ์„ ์ **: 10๊ฐœ ํŒŒํŠธ ๊ตฌ์„ฑ์ด ์ ์ ˆํ•˜๋ฉฐ ๊ฐ ํŒŒํŠธ์˜ ๋…๋ฆฝ์„ฑ๊ณผ ์—ฐ๊ฒฐ์„ฑ์ด ์ž˜ ๊ท ํ˜•์žกํ˜€ ์žˆ์Œ
### 2. ์ธ๋ฌผ ์„ค์ • ๊ฒ€ํ† 
| ์ธ๋ฌผ | ๊ฐ•์  | ์•ฝ์  | ๊ฐœ์„  ์ œ์•ˆ |
|------|------|------|-----------|
| ์„œ์—ฐ | ๋ช…ํ™•ํ•œ ๋‚ด์  ๊ฐˆ๋“ฑ | ๊ฐ์ • ํ‘œํ˜„ ๋ถ€์กฑ ์šฐ๋ ค | ์ดˆ๋ฐ˜๋ถ€ํ„ฐ ๊ฐ์ •์  ๋‹จ์„œ ๋ฐฐ์น˜ |
| ๋ฏผ์ค€ | ๊ท ํ˜•์ž ์—ญํ•  | ์ˆ˜๋™์ ์ผ ์œ„ํ—˜ | ๋…์ž์  ์„œ๋ธŒํ”Œ๋กฏ ํ•„์š” |
| ARIA | ๋…ํŠนํ•œ ์บ๋ฆญํ„ฐ ์•„ํฌ | ๋ณ€ํ™” ๊ณผ์ • ์ถ”์ƒ์  | ๊ตฌ์ฒด์  ํ•™์Šต ์—ํ”ผ์†Œ๋“œ ์ถ”๊ฐ€ |
### 3. ์‹คํ–‰ ๊ฐ€๋Šฅ์„ฑ
- ๊ฐ ์ž‘๊ฐ€๋ณ„ 3ํŽ˜์ด์ง€๋Š” ์ ์ ˆํ•œ ๋ถ„๋Ÿ‰
- ํŒŒํŠธ ๊ฐ„ ์—ฐ๊ฒฐ์„ฑ ๊ฐ€์ด๋“œ๋ผ์ธ ๋ณด๊ฐ• ํ•„์š”""",
}
# ์ž‘๊ฐ€ ์‘๋‹ต - 1,400-1,500 ๋‹จ์–ด
sample_story = """์„œ์—ฐ์€ ์—ฐ๊ตฌ์‹ค์˜ ์ฐจ๊ฐ€์šด ํ˜•๊ด‘๋“ฑ ์•„๋ž˜์—์„œ ๋˜ ๋‹ค๋ฅธ ๋ฐค์„ ๋ณด๋‚ด๊ณ  ์žˆ์—ˆ๋‹ค. ๋ชจ๋‹ˆํ„ฐ์˜ ํ‘ธ๋ฅธ ๋น›์ด ๊ทธ๋…€์˜ ์ฐฝ๋ฐฑํ•œ ์–ผ๊ตด์„ ๋น„์ถ”๊ณ  ์žˆ์—ˆ๊ณ , ์ˆ˜์‹ญ ๊ฐœ์˜ ์ฝ”๋“œ ๋ผ์ธ์ด ๋Š์ž„์—†์ด ์Šคํฌ๋กค๋˜๊ณ  ์žˆ์—ˆ๋‹ค. ARIA ํ”„๋กœ์ ํŠธ๋Š” ๊ทธ๋…€์˜ ์‚ถ ์ „๋ถ€์˜€๋‹ค. 3๋…„์ด๋ผ๋Š” ์‹œ๊ฐ„ ๋™์•ˆ ๊ทธ๋…€๋Š” ์ด ์ธ๊ณต์ง€๋Šฅ์— ๋ชจ๋“  ๊ฒƒ์„ ์Ÿ์•„๋ถ€์—ˆ๋‹ค.
"์‹œ์Šคํ…œ ์ฒดํฌ ์™„๋ฃŒ. ๋ชจ๋“  ํŒŒ๋ผ๋ฏธํ„ฐ ์ •์ƒ." ๊ธฐ๊ณ„์ ์ธ ์Œ์„ฑ์ด ์Šคํ”ผ์ปค๋ฅผ ํ†ตํ•ด ํ˜๋Ÿฌ๋‚˜์™”๋‹ค.
์„œ์—ฐ์€ ์ž ์‹œ ์˜์ž์— ๊ธฐ๋Œ€์–ด ๋ˆˆ์„ ๊ฐ์•˜๋‹ค. ํ”ผ๋กœ๊ฐ€ ๋ผˆ ์†๊นŒ์ง€ ํŒŒ๊ณ ๋“ค์—ˆ์ง€๋งŒ, ๋ฉˆ์ถœ ์ˆ˜ ์—†์—ˆ๋‹ค. ARIA๋Š” ๋‹จ์ˆœํ•œ ํ”„๋กœ์ ํŠธ๊ฐ€ ์•„๋‹ˆ์—ˆ๋‹ค. ๊ทธ๊ฒƒ์€ ๊ทธ๋…€๊ฐ€ ์žƒ์–ด๋ฒ„๋ฆฐ ๊ฒƒ๋“ค์„ ๋˜์ฐพ์„ ์ˆ˜ ์žˆ๋Š” ์œ ์ผํ•œ ํฌ๋ง์ด์—ˆ๋‹ค."""
for i in range(1, 11):
# ๊ฐ ์ž‘๊ฐ€๋งˆ๋‹ค 1,400-1,500๋‹จ์–ด ์ƒ์„ฑ
writer_content = f"์ž‘์„ฑ์ž {i}๋ฒˆ์˜ ํŒŒํŠธ์ž…๋‹ˆ๋‹ค.\n\n"
# ์•ฝ 300๋‹จ์–ด์”ฉ 5๋ฒˆ ๋ฐ˜๋ณตํ•˜์—ฌ 1,400-1,500๋‹จ์–ด ๋‹ฌ์„ฑ
for j in range(5):
writer_content += sample_story + f"\n\n๊ทธ๊ฒƒ์€ ์ž‘๊ฐ€ {i}์˜ {j+1}๋ฒˆ์งธ ๋‹จ๋ฝ์ด์—ˆ๋‹ค. "
writer_content += "์ด์•ผ๊ธฐ๋Š” ๊ณ„์† ์ „๊ฐœ๋˜์—ˆ๊ณ , ์ธ๋ฌผ๋“ค์˜ ๊ฐ์ •์€ ์ ์  ๋” ๋ณต์žกํ•ด์กŒ๋‹ค. " * 15
writer_content += "\n\n"
test_responses[f"writer{i}"] = writer_content
# ํ…Œ์ŠคํŠธ ๋ชจ๋“œ์šฉ writer10 ์‘๋‹ต
if role == "writer10":
full_novel = ""
for i in range(2, 11): # Chapter 2๋ถ€ํ„ฐ 10๊นŒ์ง€
full_novel += f"[Chapter {i}]\n\n"
# ๊ฐ ์ฑ•ํ„ฐ๋งˆ๋‹ค ์•ฝ 300๋‹จ์–ด์”ฉ 5๋‹จ๋ฝ
for j in range(5):
full_novel += sample_story + f"\n\n๊ทธ๊ฒƒ์€ ์ฑ•ํ„ฐ {i}์˜ {j+1}๋ฒˆ์งธ ๋‹จ๋ฝ์ด์—ˆ๋‹ค. "
full_novel += "์ด์•ผ๊ธฐ๋Š” ๊ณ„์† ์ „๊ฐœ๋˜์—ˆ๊ณ , ์ธ๋ฌผ๋“ค์˜ ๊ฐ์ •์€ ์ ์  ๋” ๋ณต์žกํ•ด์กŒ๋‹ค. " * 20
full_novel += "\n\n"
full_novel += "\n\n" # ์ฑ•ํ„ฐ ๊ฐ„ ๊ตฌ๋ถ„
test_responses["writer10"] = full_novel
return test_responses.get(role, "ํ…Œ์ŠคํŠธ ์‘๋‹ต์ž…๋‹ˆ๋‹ค.")
def get_english_test_response(self, role: str) -> str:
"""English test responses with appropriate length"""
test_responses = {
"director": """I present the 30-page novella plan.
## 1. Theme and Genre
- **Core Theme**: Finding true connection in the collision of human nature and technology
- **Genre**: Sci-fi psychological drama
- **Tone**: Reflective and lyrical yet tense
- **Target Audience**: Adult readers who enjoy deep contemplation
## 2. Character Settings
| Name | Role | Personality | Background | Motivation | Arc |
|------|------|-------------|------------|------------|-----|
| Seoyeon | Protagonist | Rational, lonely | AI researcher | Develop perfect AI companion | Rediscover value of human connection |
| Minjun | Helper | Warm, intuitive | Psychologist | Help Seoyeon find balance | Accept and harmonize with technology |
| ARIA | Antagonistโ†’Companion | Logicalโ†’Learning emotion | AI prototype | Become truly existent | Establish self-identity |
## 3. Narrative Structure (10 parts, 3 pages each)
| Part | Pages | Main Events | Tension | Character Development |
|------|-------|-------------|---------|---------------------|
| 1 | 1-3 | Seoyeon's lonely lab, ARIA's first awakening | 3/10 | Seoyeon's obsession revealed |
| 2 | 4-6 | ARIA's anomalies begin | 4/10 | Questions arise |
[... continues for all 10 parts ...]""",
"critic": """I have reviewed the director's plan.
## Critique and Improvement Suggestions
### 1. Narrative Completeness
- **Strength**: Timely theme of AI-human relationships
- **Improvement**: 10-part structure is well-balanced. Each part maintains independence while connecting seamlessly.
### 2. Character Review
| Character | Strengths | Weaknesses | Suggestions |
|-----------|-----------|------------|-------------|
| Seoyeon | Clear internal conflict | Risk of insufficient emotion | Place emotional cues from beginning |
| Minjun | Balancer role | Risk of being passive | Needs independent subplot |
| ARIA | Unique character arc | Abstract transformation | Add concrete learning episodes |
### 3. Feasibility
- 3 pages per writer is appropriate
- Need to strengthen inter-part connectivity guidelines""",
}
# Writer responses - 1,400-1,500 words each
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.
"System check complete. All parameters normal." The mechanical voice flowed through the speakers.
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."""
for i in range(1, 11):
# Each writer produces 1,400-1,500 words
writer_content = f"Writer {i} begins their section here.\n\n"
# About 300 words repeated 5 times to achieve 1,400-1,500 words
for j in range(5):
writer_content += sample_story + f"\n\nThis was writer {i}'s paragraph {j+1}. "
writer_content += "The story continued to unfold, and the characters' emotions grew increasingly complex. " * 15
writer_content += "\n\n"
test_responses[f"writer{i}"] = writer_content
# Test mode writer10 response
if role == "writer10":
full_novel = ""
for i in range(2, 11): # Chapters 2-10
full_novel += f"[Chapter {i}]\n\n"
# About 300 words per paragraph, 5 paragraphs per chapter
for j in range(5):
full_novel += sample_story + f"\n\nThis was paragraph {j+1} of chapter {i}. "
full_novel += "The story continued to unfold, and the characters' emotions grew increasingly complex. " * 20
full_novel += "\n\n"
full_novel += "\n\n" # Chapter separation
test_responses["writer10"] = full_novel
return test_responses.get(role, "Test response.")
def process_novel_stream(self, query: str, language: str = "English",
session_id: Optional[str] = None,
resume_from_stage: int = 0,
test_quick_mode: bool = False) -> Generator[Tuple[str, List[Dict[str, str]]], None, None]:
"""Process novel writing with streaming updates - ์ตœ์ข… Director/Critic ์ œ๊ฑฐ"""
try:
global conversation_history
# Create or resume session
if session_id:
self.current_session_id = session_id
session = NovelDatabase.get_session(session_id)
if session:
query = session['user_query']
language = session['language']
resume_from_stage = session['current_stage'] + 1
logger.info(f"Resuming session {session_id} from stage {resume_from_stage}")
else:
self.current_session_id = NovelDatabase.create_session(query, language)
resume_from_stage = 0
logger.info(f"Created new session: {self.current_session_id}")
logger.info(f"Processing novel for session {self.current_session_id}, starting from stage {resume_from_stage}, test_mode={test_quick_mode}")
# Initialize conversation
conversation_history = [{
"role": "human",
"content": query,
"timestamp": datetime.now()
}]
# Load existing stages if resuming
stages = []
if resume_from_stage > 0:
existing_stages = NovelDatabase.get_stages(self.current_session_id)
for stage_data in existing_stages:
stages.append({
"name": stage_data['stage_name'],
"status": stage_data['status'],
"content": stage_data['content'] or ""
})
# Define all stages for 10 writers (์ตœ์ข… ํ‰๊ฐ€ ์ œ๊ฑฐ)
if test_quick_mode:
# ํ…Œ์ŠคํŠธ ๋ชจ๋“œ: 1,2,3๋‹จ๊ณ„ + Writer 1 + Writer 10
stage_definitions = [
("director", f"๐ŸŽฌ {'๊ฐ๋…์ž: ์ดˆ๊ธฐ ๊ธฐํš' if language == 'Korean' else 'Director: Initial Planning'}"),
("critic", f"๐Ÿ“ {'๋น„ํ‰๊ฐ€: ๊ธฐํš ๊ฒ€ํ† ' if language == 'Korean' else 'Critic: Plan Review'}"),
("director", f"๐ŸŽฌ {'๊ฐ๋…์ž: ์ˆ˜์ •๋œ ๋งˆ์Šคํ„ฐํ”Œ๋žœ' if language == 'Korean' else 'Director: Revised Masterplan'}"),
("writer1", f"โœ๏ธ {'์ž‘์„ฑ์ž' if language == 'Korean' else 'Writer'} 1: {'์ดˆ์•ˆ' if language == 'Korean' else 'Draft'}"),
("critic", f"๐Ÿ“ {'๋น„ํ‰๊ฐ€: ์ž‘์„ฑ์ž' if language == 'Korean' else 'Critic: Writer'} 1 {'๊ฒ€ํ† ' if language == 'Korean' else 'Review'}"),
("writer1", f"โœ๏ธ {'์ž‘์„ฑ์ž' if language == 'Korean' else 'Writer'} 1: {'์ˆ˜์ •๋ณธ' if language == 'Korean' else 'Revision'}"),
("writer10", f"โœ๏ธ {'์ž‘์„ฑ์ž' if language == 'Korean' else 'Writer'} 10 (TEST): {'๋‚˜๋จธ์ง€ ์†Œ์„ค' if language == 'Korean' else 'Remaining Novel'}"),
]
else:
stage_definitions = [
("director", f"๐ŸŽฌ {'๊ฐ๋…์ž: ์ดˆ๊ธฐ ๊ธฐํš' if language == 'Korean' else 'Director: Initial Planning'}"),
("critic", f"๐Ÿ“ {'๋น„ํ‰๊ฐ€: ๊ธฐํš ๊ฒ€ํ† ' if language == 'Korean' else 'Critic: Plan Review'}"),
("director", f"๐ŸŽฌ {'๊ฐ๋…์ž: ์ˆ˜์ •๋œ ๋งˆ์Šคํ„ฐํ”Œ๋žœ' if language == 'Korean' else 'Director: Revised Masterplan'}"),
]
# Add writer stages for 10 writers
for writer_num in range(1, 11):
stage_definitions.extend([
(f"writer{writer_num}", f"โœ๏ธ {'์ž‘์„ฑ์ž' if language == 'Korean' else 'Writer'} {writer_num}: {'์ดˆ์•ˆ' if language == 'Korean' else 'Draft'}"),
("critic", f"๐Ÿ“ {'๋น„ํ‰๊ฐ€: ์ž‘์„ฑ์ž' if language == 'Korean' else 'Critic: Writer'} {writer_num} {'๊ฒ€ํ† ' if language == 'Korean' else 'Review'}"),
(f"writer{writer_num}", f"โœ๏ธ {'์ž‘์„ฑ์ž' if language == 'Korean' else 'Writer'} {writer_num}: {'์ˆ˜์ •๋ณธ' if language == 'Korean' else 'Revision'}")
])
# ์ตœ์ข… Director์™€ Critic ๋‹จ๊ณ„ ์ œ๊ฑฐ
# Store total stages for get_stage_prompt
self.total_stages = len(stage_definitions)
# Process stages starting from resume point
for stage_idx in range(resume_from_stage, len(stage_definitions)):
role, stage_name = stage_definitions[stage_idx]
# Add search indicator if enabled
if self.web_search.enabled and not self.test_mode:
stage_name += " ๐Ÿ”"
# Add stage if not already present
if stage_idx >= len(stages):
stages.append({
"name": stage_name,
"status": "active",
"content": ""
})
else:
stages[stage_idx]["status"] = "active"
yield "", stages
# Get appropriate prompt based on stage
prompt = self.get_stage_prompt(stage_idx, role, query, language, stages, test_quick_mode)
# Create stage info for web search
stage_info = {
'stage_idx': stage_idx,
'query': query,
'stage_name': stage_name,
'test_mode': test_quick_mode
}
stage_content = ""
# Stream content generation with web search
for chunk in self.call_llm_streaming(
[{"role": "user", "content": prompt}],
role,
language,
stage_info
):
stage_content += chunk
stages[stage_idx]["content"] = stage_content
yield "", stages
# Mark stage complete and save to DB
stages[stage_idx]["status"] = "complete"
# Test mode์—์„œ๋Š” writer1๊ณผ writer2๋งŒ ์ฒ˜๋ฆฌ
# writer10 ๊ด€๋ จ ํŠน๋ณ„ ์ฒ˜๋ฆฌ ์ œ๊ฑฐ - ์ผ๋ฐ˜ ํ”„๋กœ์„ธ์Šค์™€ ๋™์ผ
NovelDatabase.save_stage(
self.current_session_id,
stage_idx,
stage_name,
role,
stage_content,
"complete"
)
# Auto-save notification
if role.startswith("writer"):
writer_num = int(role.replace("writer", ""))
logger.info(f"โœ… Writer {writer_num} content auto-saved to database")
yield "", stages
# Verify content after completion
if self.current_session_id:
verification = NovelDatabase.verify_novel_content(self.current_session_id)
if test_quick_mode:
logger.info(f"[TEST MODE] Content verification: {verification}")
else:
logger.info(f"Content verification: {verification}")
if verification['total_words'] < 12000 and not test_quick_mode:
logger.error(f"Final novel too short! Only {verification['total_words']} words")
# Get complete novel from DB
complete_novel = NovelDatabase.get_all_writer_content(self.current_session_id, test_quick_mode)
# ํ…Œ์ŠคํŠธ ๋ชจ๋“œ๋ฉด ์™„๋ฃŒ ์ƒํƒœ ์—…๋ฐ์ดํŠธ
if test_quick_mode and self.current_session_id:
NovelDatabase.update_final_novel(self.current_session_id, complete_novel)
# Save final novel to DB
NovelDatabase.update_final_novel(self.current_session_id, complete_novel)
# Final yield - ํ™”๋ฉด์—๋Š” ์™„๋ฃŒ ๋ฉ”์‹œ์ง€๋งŒ ํ‘œ์‹œ
if test_quick_mode:
final_message = f"โœ… [TEST MODE] Novel complete! 2 chapters, {len(complete_novel.split())} words total. Click Download to save."
else:
final_message = f"โœ… Novel complete! {len(complete_novel.split())} words total. Click Download to save."
yield final_message, stages
except Exception as e:
logger.error(f"Error in process_novel_stream: {str(e)}", exc_info=True)
# Save error state to DB
if self.current_session_id:
NovelDatabase.save_stage(
self.current_session_id,
stage_idx if 'stage_idx' in locals() else 0,
"Error",
"error",
str(e),
"error"
)
error_stage = {
"name": "โŒ Error",
"status": "error",
"content": str(e)
}
stages.append(error_stage)
yield f"Error occurred: {str(e)}", stages
def create_test_writer_complete_prompt(self, director_plan: str, language: str = "English") -> str:
"""Test mode - Writer 10 writes complete novel"""
if language == "Korean":
return f"""[ํ…Œ์ŠคํŠธ ๋ชจ๋“œ] ๋‹น์‹ ์€ ์ „์ฒด 30ํŽ˜์ด์ง€ ์†Œ์„ค์„ ํ•œ ๋ฒˆ์— ์ž‘์„ฑํ•˜๋Š” ํŠน๋ณ„ ์ž‘๊ฐ€์ž…๋‹ˆ๋‹ค.
๊ฐ๋…์ž์˜ ๋งˆ์Šคํ„ฐํ”Œ๋žœ:
{director_plan}
**์ค‘์š” ์ง€์นจ:**
1. ์ „์ฒด 30ํŽ˜์ด์ง€ ๋ถ„๋Ÿ‰์˜ ์™„์„ฑ๋œ ์†Œ์„ค์„ ์ž‘์„ฑํ•˜์„ธ์š”
2. ์ด 14,000-15,000 ๋‹จ์–ด๋กœ ์ž‘์„ฑํ•˜์„ธ์š”
3. 10๊ฐœ์˜ ์ž์—ฐ์Šค๋Ÿฌ์šด ์ฑ•ํ„ฐ๋กœ ๊ตฌ์„ฑํ•˜์„ธ์š” (๊ฐ ์ฑ•ํ„ฐ ์•ฝ 1,400-1,500 ๋‹จ์–ด)
4. ์‹œ์ž‘๋ถ€ํ„ฐ ๊ฒฐ๋ง๊นŒ์ง€ ์™„์ „ํ•œ ์ด์•ผ๊ธฐ๋ฅผ ๋งŒ๋“œ์„ธ์š”
5. ๋งˆ์Šคํ„ฐํ”Œ๋žœ์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ํฌํ•จํ•˜์„ธ์š”
์ฑ•ํ„ฐ ๊ตฌ๋ถ„์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ‘œ์‹œํ•˜์„ธ์š”:
[Chapter 1]
๋‚ด์šฉ...
[Chapter 2]
๋‚ด์šฉ...
์™„์„ฑ๋„ ๋†’์€ ์ „์ฒด ์†Œ์„ค์„ ์ž‘์„ฑํ•˜์„ธ์š”."""
else:
return f"""[TEST MODE] You are a special writer creating the complete 30-page novel at once.
Director's Masterplan:
{director_plan}
**CRITICAL INSTRUCTIONS:**
1. Write a complete 30-page novel
2. Total 14,000-15,000 words
3. Organize into 10 natural chapters (each chapter ~1,400-1,500 words)
4. Create a complete story from beginning to end
5. Include all elements from the masterplan
Mark chapters as follows:
[Chapter 1]
content...
[Chapter 2]
content...
Write a high-quality complete novel."""
def get_stage_prompt(self, stage_idx: int, role: str, query: str,
language: str, stages: List[Dict], test_mode: bool = False) -> str:
"""Get appropriate prompt for each stage"""
# Stage 0: Director Initial
if stage_idx == 0:
return self.create_director_initial_prompt(query, language)
# Stage 1: Critic reviews Director's plan
elif stage_idx == 1:
return self.create_critic_director_prompt(stages[0]["content"], language)
# Stage 2: Director revision
elif stage_idx == 2:
return self.create_director_revision_prompt(
stages[0]["content"], stages[1]["content"], language)
# Writer stages
elif role.startswith("writer"):
writer_num = int(role.replace("writer", ""))
final_plan = stages[2]["content"] # Director's final plan
# Test mode special writer10
if role == "writer10" and test_mode:
# Get writer1's revision content
writer1_content = ""
for i, stage in enumerate(stages):
if "Writer 1: Revision" in stage["name"] or "์ž‘์„ฑ์ž 1: ์ˆ˜์ •๋ณธ" in stage["name"]:
writer1_content = stage["content"]
break
return self.create_test_writer_remaining_prompt(final_plan, writer1_content, language)
# Initial draft or revision?
if "์ดˆ์•ˆ" in stages[stage_idx]["name"] or "Draft" in stages[stage_idx]["name"]:
# Get accumulated content from DB
accumulated_content = NovelDatabase.get_all_writer_content(self.current_session_id)
return self.create_writer_prompt(writer_num, final_plan, accumulated_content, language)
else: # Revision
# Find the initial draft and critic feedback
initial_draft_idx = stage_idx - 2
critic_feedback_idx = stage_idx - 1
return self.create_writer_revision_prompt(
writer_num,
stages[initial_draft_idx]["content"],
stages[critic_feedback_idx]["content"],
language
)
# Critic stages for writers
elif role == "critic":
final_plan = stages[2]["content"]
# Writer review
# Find which writer we're reviewing
for i in range(1, 11):
if f"์ž‘์„ฑ์ž {i}" in stages[stage_idx]["name"] or f"Writer {i}" in stages[stage_idx]["name"]:
writer_content_idx = stage_idx - 1
# Get previous writers' content from DB
previous_content = NovelDatabase.get_all_writer_content(self.current_session_id)
return self.create_critic_writer_prompt(
i,
stages[writer_content_idx]["content"],
final_plan,
previous_content,
language
)
return ""
# Gradio Interface Functions
def process_query(query: str, language: str, session_id: str = None, test_mode: bool = False) -> Generator[Tuple[str, str, str, str], None, None]:
"""Process query and yield updates with session ID"""
if not query.strip() and not session_id:
if language == "Korean":
yield "", "", "โŒ ์†Œ์„ค ์ฃผ์ œ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.", None
else:
yield "", "", "โŒ Please enter a novel theme.", None
return
system = NovelWritingSystem()
try:
# Status message with mode indicator
mode_status = ""
if session_id:
if language == "Korean":
mode_status = " [โ™ป๏ธ ๋ณต๊ตฌ ๋ชจ๋“œ]"
else:
mode_status = " [โ™ป๏ธ Recovery Mode]"
elif test_mode:
if language == "Korean":
mode_status = " [๐Ÿงช ํ…Œ์ŠคํŠธ ๋ชจ๋“œ: 7๋‹จ๊ณ„]"
else:
mode_status = " [๐Ÿงช Test Mode: 7 stages]"
for final_novel, stages in system.process_novel_stream(query, language, session_id, test_quick_mode=test_mode):
# Format stages for display
stages_display = format_stages_display(stages, language)
# Progress calculation
completed = sum(1 for s in stages if s.get("status") == "complete")
total = len(stages)
progress_percent = (completed / total * 100) if total > 0 else 0
if "โœ… Novel complete!" in str(final_novel) or "โœ… [TEST MODE] Novel complete!" in str(final_novel):
status = f"โœ… Complete! Ready to download.{mode_status}"
else:
if language == "Korean":
status = f"๐Ÿ”„ ์ง„ํ–‰์ค‘... ({completed}/{total} - {progress_percent:.1f}%){mode_status}"
else:
status = f"๐Ÿ”„ Processing... ({completed}/{total} - {progress_percent:.1f}%){mode_status}"
# Return current session ID
yield stages_display, final_novel, status, system.current_session_id
except Exception as e:
logger.error(f"Error in process_query: {str(e)}", exc_info=True)
if language == "Korean":
yield "", "", f"โŒ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}", None
else:
yield "", "", f"โŒ Error occurred: {str(e)}", None
def format_stages_display(stages: List[Dict[str, str]], language: str) -> str:
"""Format stages into simple display with writer save status"""
display = ""
for idx, stage in enumerate(stages):
status_icon = "โœ…" if stage.get("status") == "complete" else ("โณ" if stage.get("status") == "active" else "โŒ")
# Add save indicator for completed writers
save_indicator = ""
if "Writer" in stage['name'] and "Revision" in stage['name'] and stage.get("status") == "complete":
save_indicator = " ๐Ÿ’พ"
# Show only active stage content in detail, others just show status
if stage.get("status") == "active":
display += f"\n\n{status_icon} **{stage['name']}**\n"
display += f"```\n{stage.get('content', '')[-1000:]}\n```"
else:
display += f"\n{status_icon} {stage['name']}{save_indicator}"
return display
def get_active_sessions(language: str) -> List[Tuple[str, str]]:
"""Get list of active sessions"""
try:
sessions = NovelDatabase.get_active_sessions()
choices = []
for session in sessions:
created = NovelDatabase.parse_datetime(session['created_at'])
date_str = created.strftime("%Y-%m-%d %H:%M")
query_preview = session['user_query'][:50] + "..." if len(session['user_query']) > 50 else session['user_query']
label = f"[{date_str}] {query_preview} (Stage {session['current_stage']})"
choices.append((label, session['session_id']))
return choices
except Exception as e:
logger.error(f"Error getting active sessions: {str(e)}", exc_info=True)
return []
def resume_session(session_id: str, language: str, test_mode: bool = False) -> Generator[Tuple[str, str, str, str], None, None]:
"""Resume an existing session"""
if not session_id:
if language == "Korean":
yield "", "", "โŒ ์„ธ์…˜์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”.", None
else:
yield "", "", "โŒ Please select a session.", None
return
# Process with existing session ID
yield from process_query("", language, session_id, test_mode)
def auto_recover_session(language: str) -> Tuple[str, str]:
"""Auto recover the latest active session"""
try:
latest_session = NovelDatabase.get_latest_active_session()
if latest_session:
if language == "Korean":
message = f"โœ… ์ž๋™ ๋ณต๊ตฌ: '{latest_session['user_query'][:30]}...' (Stage {latest_session['current_stage']})"
else:
message = f"โœ… Auto recovered: '{latest_session['user_query'][:30]}...' (Stage {latest_session['current_stage']})"
return latest_session['session_id'], message
else:
return None, ""
except Exception as e:
logger.error(f"Error in auto recovery: {str(e)}")
return None, ""
def download_novel(novel_text: str, format: str, language: str, session_id: str = None) -> str:
"""Download novel - DB์—์„œ ์ง์ ‘ ์ž‘๊ฐ€ ๋‚ด์šฉ์„ ๊ฐ€์ ธ์™€์„œ ํ†ตํ•ฉ"""
if not session_id:
logger.error("No session_id provided for download")
return None
logger.info(f"Starting download for session: {session_id}, format: {format}")
# DB์—์„œ ์„ธ์…˜ ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ
session = NovelDatabase.get_session(session_id)
if not session:
logger.error(f"Session not found: {session_id}")
return None
# ์„ธ์…˜์˜ ์‹ค์ œ ์–ธ์–ด ์‚ฌ์šฉ (ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›์€ language ๋Œ€์‹ )
actual_language = session['language']
logger.info(f"Using session language: {actual_language} (parameter was: {language})")
# DB์—์„œ ๋ชจ๋“  ์Šคํ…Œ์ด์ง€ ๊ฐ€์ ธ์˜ค๊ธฐ
stages = NovelDatabase.get_stages(session_id)
logger.info(f"Found {len(stages)} stages in database")
# ๋””๋ฒ„๊น…: ๋ชจ๋“  stage ์ •๋ณด ์ถœ๋ ฅ
for i, stage in enumerate(stages):
role = stage['role'] if 'role' in stage.keys() else 'None'
stage_name = stage['stage_name'] if 'stage_name' in stage.keys() else 'None'
content_len = len(stage['content']) if 'content' in stage.keys() and stage['content'] else 0
status = stage['status'] if 'status' in stage.keys() else 'None'
logger.debug(f"Stage {i}: role={role}, stage_name={stage_name}, content_length={content_len}, status={status}")
# ํ…Œ์ŠคํŠธ ๋ชจ๋“œ ๊ฐ์ง€ - writer10์ด ์žˆ์œผ๋ฉด ํ…Œ์ŠคํŠธ ๋ชจ๋“œ
is_test_mode = False
has_writer10 = any(stage['role'] == 'writer10' for stage in stages if 'role' in stage.keys())
has_writer1 = any(stage['role'] == 'writer1' for stage in stages if 'role' in stage.keys())
has_writer3 = any(stage['role'] == 'writer3' for stage in stages if 'role' in stage.keys())
if has_writer10 and has_writer1 and not has_writer3:
is_test_mode = True
logger.info("Test mode detected - writer1 + writer10 mode")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
if format == "DOCX" and DOCX_AVAILABLE:
# Create DOCX
doc = Document()
# ์ œ๋ชฉ ํŽ˜์ด์ง€
title_para = doc.add_paragraph()
title_run = title_para.add_run('AI Collaborative Novel' + (' - Test Mode' if is_test_mode else ''))
title_run.font.size = Pt(24)
title_run.font.bold = True
title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_paragraph()
doc.add_paragraph()
theme_para = doc.add_paragraph()
theme_run = theme_para.add_run(f'Theme: {session["user_query"]}')
theme_run.font.size = Pt(14)
theme_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_paragraph()
date_para = doc.add_paragraph()
date_run = date_para.add_run(f'Created: {datetime.now().strftime("%Y-%m-%d")}')
date_run.font.size = Pt(12)
date_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_page_break()
# ์ „์ฒด ํ†ต๊ณ„
total_words = 0
writer_count = 0
# ๊ฐ ์ž‘๊ฐ€์˜ ์ˆ˜์ •๋ณธ๋งŒ ์ˆ˜์ง‘
writer_contents = []
if is_test_mode:
# ํ…Œ์ŠคํŠธ ๋ชจ๋“œ: writer1 revision + writer10 ๋‚ด์šฉ ์ฒ˜๋ฆฌ
for stage in stages:
role = stage['role'] if 'role' in stage.keys() else None
stage_name = stage['stage_name'] if 'stage_name' in stage.keys() else ''
content = stage['content'] if 'content' in stage.keys() else ''
logger.info(f"[TEST MODE] Checking stage: role={role}, name={stage_name}, status={stage['status'] if 'status' in stage.keys() else 'None'}")
# Writer 1 ์ˆ˜์ •๋ณธ
if role == 'writer1' and stage_name and ('Revision' in stage_name or '์ˆ˜์ •๋ณธ' in stage_name):
content = re.sub(r'\[(?:ํŽ˜์ด์ง€|Page|page)\s*\d+\]', '', content)
content = re.sub(r'(?:ํŽ˜์ด์ง€|Page)\s*\d+:', '', content)
content = content.strip()
if content:
word_count = stage['word_count'] if 'word_count' in stage.keys() else len(content.split())
total_words += word_count
writer_contents.append({
'writer_num': 1,
'content': content,
'word_count': word_count
})
writer_count = 1
logger.info(f"Added writer 1 (Chapter 1): {word_count} words")
# Writer 10 (ํ…Œ์ŠคํŠธ ๋ชจ๋“œ์—์„œ ๋‚˜๋จธ์ง€ ์ฑ•ํ„ฐ๋“ค)
elif role == 'writer10':
logger.info(f"Processing writer10 content: {len(content)} chars")
# [Chapter X] ํŒจํ„ด์œผ๋กœ ์ฑ•ํ„ฐ ๋ถ„๋ฆฌ
chapters = re.split(r'\[Chapter\s+(\d+)\]', content)
# chapters๋Š” ['', '2', 'content2', '3', 'content3', ...] ํ˜•ํƒœ
for i in range(1, len(chapters), 2):
if i+1 < len(chapters):
chapter_num = int(chapters[i])
chapter_content = chapters[i+1].strip()
if chapter_content:
word_count = len(chapter_content.split())
total_words += word_count
writer_contents.append({
'writer_num': chapter_num,
'content': chapter_content,
'word_count': word_count
})
writer_count = max(writer_count, chapter_num)
logger.info(f"Added Chapter {chapter_num}: {word_count} words")
else:
# ์ผ๋ฐ˜ ๋ชจ๋“œ: ๋ชจ๋“  ์ž‘๊ฐ€ ์ˆ˜์ •๋ณธ ์ฒ˜๋ฆฌ
logger.info("[NORMAL MODE] Processing all writer revisions...")
for stage in stages:
role = stage['role'] if 'role' in stage.keys() else None
stage_name = stage['stage_name'] if 'stage_name' in stage.keys() else ''
content = stage['content'] if 'content' in stage.keys() else ''
status = stage['status'] if 'status' in stage.keys() else ''
# ๋””๋ฒ„๊น… ์ •๋ณด
logger.debug(f"[NORMAL MODE] Checking: role={role}, name={stage_name}, status={status}, content_len={len(content)}")
# ์–ธ์–ด์— ์ƒ๊ด€์—†์ด ์ž‘๊ฐ€ ์ˆ˜์ •๋ณธ ์ฐพ๊ธฐ
is_writer = role and role.startswith('writer')
is_revision = stage_name and ('Revision' in stage_name or '์ˆ˜์ •๋ณธ' in stage_name)
if is_writer and is_revision:
# ์ž‘๊ฐ€ ๋ฒˆํ˜ธ ์ถ”์ถœ
try:
writer_num = int(role.replace('writer', ''))
logger.info(f"Found writer {writer_num} revision - stage_name: {stage_name}")
except:
logger.warning(f"Could not extract writer number from role: {role}")
continue
# ํŽ˜์ด์ง€ ๋งˆํฌ ์ œ๊ฑฐ
content = re.sub(r'\[(?:ํŽ˜์ด์ง€|Page|page)\s*\d+\]', '', content)
content = re.sub(r'(?:ํŽ˜์ด์ง€|Page)\s*\d+:', '', content)
content = content.strip()
if content:
word_count = stage['word_count'] if 'word_count' in stage.keys() else len(content.split())
total_words += word_count
writer_contents.append({
'writer_num': writer_num,
'content': content,
'word_count': word_count
})
writer_count += 1 # ์‹ค์ œ ์ž‘๊ฐ€ ์ˆ˜ ์นด์šดํŠธ
logger.info(f"Added writer {writer_num}: {word_count} words, content length: {len(content)}")
else:
logger.warning(f"Writer {writer_num} has empty content after cleaning")
logger.info(f"Total writers collected: {writer_count}, Total words: {total_words}")
logger.info(f"Writer contents: {len(writer_contents)} entries")
# ํ†ต๊ณ„ ํŽ˜์ด์ง€
doc.add_heading('Novel Statistics', 1)
doc.add_paragraph(f'Mode: {"Test Mode (Actual chapters written)" if is_test_mode else "Full Mode (10 chapters)"}')
doc.add_paragraph(f'Total Chapters: {writer_count}')
doc.add_paragraph(f'Total Words: {total_words:,}')
doc.add_paragraph(f'Estimated Pages: ~{total_words/500:.0f}')
doc.add_paragraph(f'Language: {actual_language}')
doc.add_page_break()
# ๋ชฉ์ฐจ
if writer_contents:
doc.add_heading('Table of Contents', 1)
# writer_contents๋ฅผ writer_num์œผ๋กœ ์ •๋ ฌ
sorted_contents = sorted(writer_contents, key=lambda x: x['writer_num'])
for item in sorted_contents:
chapter_num = item['writer_num']
doc.add_paragraph(f'Chapter {chapter_num}: Pages {(chapter_num-1)*3+1}-{chapter_num*3}')
doc.add_page_break()
# ๊ฐ ์ž‘๊ฐ€์˜ ๋‚ด์šฉ ์ถ”๊ฐ€ (์ •๋ ฌ๋œ ์ˆœ์„œ๋Œ€๋กœ)
for idx, writer_data in enumerate(sorted_contents):
writer_num = writer_data['writer_num']
content = writer_data['content']
word_count = writer_data['word_count']
# ์ฑ•ํ„ฐ ํ—ค๋”
doc.add_heading(f'Chapter {writer_num}', 1)
doc.add_paragraph(f'Pages {(writer_num-1)*3+1}-{writer_num*3}')
doc.add_paragraph(f'Word Count: {word_count:,}')
doc.add_paragraph()
# ์ž‘๊ฐ€ ๋‚ด์šฉ ์ถ”๊ฐ€
paragraphs = content.split('\n\n')
for para_text in paragraphs:
if para_text.strip():
para = doc.add_paragraph(para_text.strip())
para.style.font.size = Pt(11)
if idx < len(sorted_contents) - 1: # ๋งˆ์ง€๋ง‰ ์ฑ•ํ„ฐ ํ›„์—๋Š” ํŽ˜์ด์ง€ ๊ตฌ๋ถ„ ์—†์Œ
doc.add_page_break()
else:
logger.warning("No writer contents found! Creating empty document.")
doc.add_paragraph("No content found. Please check if the novel generation completed successfully.")
# ํŽ˜์ด์ง€ ์„ค์ •
for section in doc.sections:
section.page_height = Inches(11)
section.page_width = Inches(8.5)
section.left_margin = Inches(1)
section.right_margin = Inches(1)
section.top_margin = Inches(1)
section.bottom_margin = Inches(1)
# Save
temp_dir = tempfile.gettempdir()
safe_filename = re.sub(r'[^\w\s-]', '', session['user_query'][:30]).strip()
mode_suffix = "_TestMode" if is_test_mode else "_Complete"
filename = f"Novel{mode_suffix}_{safe_filename}_{timestamp}.docx"
filepath = os.path.join(temp_dir, filename)
doc.save(filepath)
logger.info(f"DOCX saved successfully: {filepath} ({total_words} words, {writer_count} writers)")
return filepath
else:
# TXT format - ๋™์ผํ•œ ์ˆ˜์ • ์ ์šฉ
temp_dir = tempfile.gettempdir()
safe_filename = re.sub(r'[^\w\s-]', '', session['user_query'][:30]).strip()
mode_suffix = "_TestMode" if is_test_mode else "_Complete"
filename = f"Novel{mode_suffix}_{safe_filename}_{timestamp}.txt"
filepath = os.path.join(temp_dir, filename)
with open(filepath, 'w', encoding='utf-8') as f:
f.write("="*60 + "\n")
f.write(f"AI COLLABORATIVE NOVEL - {'TEST MODE' if is_test_mode else 'COMPLETE VERSION'}\n")
f.write("="*60 + "\n")
f.write(f"Theme: {session['user_query']}\n")
f.write(f"Language: {actual_language}\n")
f.write(f"Created: {datetime.now()}\n")
f.write(f"Mode: {'Test Mode (Actual chapters)' if is_test_mode else 'Full Mode (10 chapters)'}\n")
f.write("="*60 + "\n\n")
total_words = 0
writer_count = 0
if is_test_mode:
# ํ…Œ์ŠคํŠธ ๋ชจ๋“œ: writer1 + writer10 ์ฒ˜๋ฆฌ
for stage in stages:
role = stage['role'] if 'role' in stage.keys() else None
stage_name = stage['stage_name'] if 'stage_name' in stage.keys() else ''
content = stage['content'] if 'content' in stage.keys() else ''
# Writer 1 ์ˆ˜์ •๋ณธ
if role == 'writer1' and stage_name and ('Revision' in stage_name or '์ˆ˜์ •๋ณธ' in stage_name):
content = re.sub(r'\[(?:ํŽ˜์ด์ง€|Page|page)\s*\d+\]', '', content)
content = re.sub(r'(?:ํŽ˜์ด์ง€|Page)\s*\d+:', '', content)
content = content.strip()
if content:
word_count = stage['word_count'] if 'word_count' in stage.keys() else len(content.split())
total_words += word_count
writer_count = 1
f.write(f"\n{'='*40}\n")
f.write(f"CHAPTER 1 (Pages 1-3)\n")
f.write(f"Word Count: {word_count:,}\n")
f.write(f"{'='*40}\n\n")
f.write(content)
f.write("\n\n")
# Writer 10
elif role == 'writer10':
# [Chapter X] ํŒจํ„ด์œผ๋กœ ์ฑ•ํ„ฐ ๋ถ„๋ฆฌ
chapters = re.split(r'\[Chapter\s+(\d+)\]', content)
for i in range(1, len(chapters), 2):
if i+1 < len(chapters):
chapter_num = int(chapters[i])
chapter_content = chapters[i+1].strip()
if chapter_content:
word_count = len(chapter_content.split())
total_words += word_count
writer_count = max(writer_count, chapter_num)
f.write(f"\n{'='*40}\n")
f.write(f"CHAPTER {chapter_num} (Pages {(chapter_num-1)*3+1}-{chapter_num*3})\n")
f.write(f"Word Count: {word_count:,}\n")
f.write(f"{'='*40}\n\n")
f.write(chapter_content)
f.write("\n\n")
else:
# ์ผ๋ฐ˜ ๋ชจ๋“œ - ์ˆ˜์ •๋œ ๋กœ์ง
for stage in stages:
role = stage['role'] if 'role' in stage.keys() else None
stage_name = stage['stage_name'] if 'stage_name' in stage.keys() else ''
content = stage['content'] if 'content' in stage.keys() else ''
# ์–ธ์–ด์— ์ƒ๊ด€์—†์ด ์ž‘๊ฐ€ ์ˆ˜์ •๋ณธ ์ฐพ๊ธฐ
is_writer = role and role.startswith('writer')
is_revision = stage_name and ('Revision' in stage_name or '์ˆ˜์ •๋ณธ' in stage_name)
if is_writer and is_revision:
# ์ž‘๊ฐ€ ๋ฒˆํ˜ธ ์ถ”์ถœ
try:
writer_num = int(role.replace('writer', ''))
except:
continue
# ํŽ˜์ด์ง€ ๋งˆํฌ ์ œ๊ฑฐ
content = re.sub(r'\[(?:ํŽ˜์ด์ง€|Page|page)\s*\d+\]', '', content)
content = re.sub(r'(?:ํŽ˜์ด์ง€|Page)\s*\d+:', '', content)
content = content.strip()
if content:
word_count = stage['word_count'] if 'word_count' in stage.keys() else len(content.split())
total_words += word_count
writer_count += 1
f.write(f"\n{'='*40}\n")
f.write(f"CHAPTER {writer_num} (Pages {(writer_num-1)*3+1}-{writer_num*3})\n")
f.write(f"Word Count: {word_count:,}\n")
f.write(f"{'='*40}\n\n")
f.write(content)
f.write("\n\n")
f.write(f"\n{'='*60}\n")
f.write(f"TOTAL: {writer_count} chapters, {total_words:,} words\n")
f.write(f"{'='*60}\n")
logger.info(f"TXT saved successfully: {filepath} ({total_words} words)")
return filepath
# Custom CSS
custom_css = """
.gradio-container {
background: linear-gradient(135deg, #1e3c72, #2a5298);
min-height: 100vh;
}
.main-header {
background-color: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 30px;
border-radius: 12px;
margin-bottom: 30px;
text-align: center;
color: white;
}
.input-section {
background-color: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 20px;
border-radius: 12px;
margin-bottom: 20px;
}
.session-section {
background-color: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
padding: 15px;
border-radius: 8px;
margin-top: 20px;
color: white;
}
#stages-display {
background-color: rgba(255, 255, 255, 0.95);
padding: 20px;
border-radius: 12px;
max-height: 600px;
overflow-y: auto;
}
#novel-output {
background-color: rgba(255, 255, 255, 0.95);
padding: 30px;
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
max-height: 400px;
overflow-y: auto;
}
.download-section {
background-color: rgba(255, 255, 255, 0.9);
padding: 15px;
border-radius: 8px;
margin-top: 20px;
}
.search-indicator {
color: #4CAF50;
font-weight: bold;
}
.auto-save-indicator {
color: #2196F3;
font-weight: bold;
}
"""
# Create Gradio Interface
def create_interface():
with gr.Blocks(css=custom_css, title="SOMA Novel Writing System") as interface:
gr.HTML("""
<div class="main-header">
<h1 style="font-size: 2.5em; margin-bottom: 10px;">
๐Ÿ“š SOMA Novel Writing System
</h1>
<h3 style="color: #ccc; margin-bottom: 20px;">
AI Collaborative Novel Generation - 10 Writers Edition
</h3>
<p style="font-size: 1.1em; color: #ddd; max-width: 800px; margin: 0 auto;">
Enter a theme or prompt, and watch as AI agents collaborate to create a complete 30-page novella.
The system includes 1 Director, 1 Critic, and 10 Writers working in harmony.
<br><br>
<span class="search-indicator">๐Ÿ” Web search enabled</span> |
<span class="auto-save-indicator">๐Ÿ’พ Auto-save to database</span> |
<span style="color: #FF9800;">โ™ป๏ธ Resume anytime</span> |
<span style="color: #FFC107;">๐Ÿงช Test mode: 7 stages (Writer 1 + Writer 10)</span>
</p>
</div>
""")
# State management
current_session_id = gr.State(None)
with gr.Row():
with gr.Column(scale=1):
with gr.Group(elem_classes=["input-section"]):
query_input = gr.Textbox(
label="Novel Theme / ์†Œ์„ค ์ฃผ์ œ",
placeholder="Enter your novel theme or initial idea...\n์†Œ์„ค์˜ ์ฃผ์ œ๋‚˜ ์ดˆ๊ธฐ ์•„์ด๋””์–ด๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”...",
lines=4
)
language_select = gr.Radio(
choices=["English", "Korean"],
value="English",
label="Language / ์–ธ์–ด"
)
# Test mode checkbox
test_mode_check = gr.Checkbox(
label="๐Ÿงช Test Mode (Quick: Writer 1 & 10 only) / ํ…Œ์ŠคํŠธ ๋ชจ๋“œ (๋น ๋ฅธ ์ƒ์„ฑ: ์ž‘๊ฐ€ 1, 10๋งŒ)",
value=False,
info="Complete Writer 1 & 10 process for 10 chapters / ์ž‘๊ฐ€ 1, 10๋งŒ ์ž‘์„ฑํ•˜์—ฌ 10๊ฐœ ์ฑ•ํ„ฐ ์ƒ์„ฑ"
)
# Web search status indicator
web_search_status = gr.Markdown(
value=f"๐Ÿ” **Web Search:** {'Enabled' if WebSearchIntegration().enabled else 'Disabled (Set BRAVE_SEARCH_API_KEY)'}"
)
with gr.Row():
submit_btn = gr.Button("๐Ÿš€ Start Writing / ์ž‘์„ฑ ์‹œ์ž‘", variant="primary", scale=2)
clear_btn = gr.Button("๐Ÿ—‘๏ธ Clear / ์ดˆ๊ธฐํ™”", scale=1)
status_text = gr.Textbox(
label="Status",
interactive=False,
value="๐Ÿ”„ Ready"
)
# Session management
with gr.Group(elem_classes=["session-section"]):
gr.Markdown("### ๐Ÿ’พ Resume Previous Session / ์ด์ „ ์„ธ์…˜ ์žฌ๊ฐœ")
session_dropdown = gr.Dropdown(
label="Select Session / ์„ธ์…˜ ์„ ํƒ",
choices=[],
interactive=True
)
with gr.Row():
refresh_btn = gr.Button("๐Ÿ”„ Refresh List / ๋ชฉ๋ก ์ƒˆ๋กœ๊ณ ์นจ", scale=1)
resume_btn = gr.Button("โ–ถ๏ธ Resume Selected / ์„ ํƒ ์žฌ๊ฐœ", variant="secondary", scale=1)
auto_recover_btn = gr.Button("โ™ป๏ธ Auto Recover Latest / ์ตœ์‹  ์ž๋™๋ณต๊ตฌ", scale=1)
with gr.Column(scale=2):
with gr.Tab("๐Ÿ“ Writing Process / ์ž‘์„ฑ ๊ณผ์ •"):
stages_display = gr.Markdown(
value="Process will appear here...",
elem_id="stages-display"
)
with gr.Tab("๐Ÿ“– Final Novel / ์ตœ์ข… ์†Œ์„ค"):
novel_output = gr.Markdown(
value="Complete novel will be available for download after all writers finish.",
elem_id="novel-output"
)
with gr.Group(elem_classes=["download-section"]):
gr.Markdown("### ๐Ÿ“ฅ Download Complete Novel / ์ „์ฒด ์†Œ์„ค ๋‹ค์šด๋กœ๋“œ")
with gr.Row():
format_select = gr.Radio(
choices=["DOCX", "TXT"],
value="DOCX" if DOCX_AVAILABLE else "TXT",
label="Format / ํ˜•์‹"
)
download_btn = gr.Button("โฌ‡๏ธ Download Complete Novel / ์™„์„ฑ๋œ ์†Œ์„ค ๋‹ค์šด๋กœ๋“œ", variant="secondary")
download_file = gr.File(
label="Downloaded File / ๋‹ค์šด๋กœ๋“œ๋œ ํŒŒ์ผ",
visible=False
)
# Hidden state for novel text
novel_text_state = gr.State("")
# Examples
with gr.Row():
gr.Examples(
examples=[
["A scientist discovers a portal to parallel universes but each journey erases a memory"],
["In a world where dreams can be traded, a dream thief must steal the emperor's nightmare"],
["Two AI entities fall in love while trying to prevent a global cyber war"],
["๋ฏธ๋ž˜ ๋„์‹œ์—์„œ ๊ธฐ์–ต์„ ๊ฑฐ๋ž˜ํ•˜๋Š” ์ƒ์ธ๊ณผ ๋ชจ๋“  ๊ธฐ์–ต์„ ์žƒ์€ ํƒ์ •์˜ ์ด์•ผ๊ธฐ"],
["์‹œ๊ฐ„์ด ๊ฑฐ๊พธ๋กœ ํ๋ฅด๋Š” ๋งˆ์„์—์„œ ์ผ์–ด๋‚˜๋Š” ๋ฏธ์Šคํ„ฐ๋ฆฌํ•œ ์‚ด์ธ ์‚ฌ๊ฑด"],
["์ฑ… ์†์œผ๋กœ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋Šฅ๋ ฅ์„ ๊ฐ€์ง„ ์‚ฌ์„œ์˜ ๋ชจํ—˜"]
],
inputs=query_input,
label="๐Ÿ’ก Example Themes / ์˜ˆ์ œ ์ฃผ์ œ"
)
# Event handlers
def refresh_sessions():
try:
sessions = get_active_sessions("English")
return gr.update(choices=sessions)
except Exception as e:
logger.error(f"Error refreshing sessions: {str(e)}", exc_info=True)
return gr.update(choices=[])
def handle_auto_recover(language):
session_id, message = auto_recover_session(language)
return session_id
# Connect event handlers
submit_btn.click(
fn=process_query,
inputs=[query_input, language_select, current_session_id, test_mode_check],
outputs=[stages_display, novel_output, status_text, current_session_id]
)
# Update novel text state and session ID when novel output changes
novel_output.change(
fn=lambda x: x,
inputs=[novel_output],
outputs=[novel_text_state]
)
resume_btn.click(
fn=lambda x: x,
inputs=[session_dropdown],
outputs=[current_session_id]
).then(
fn=resume_session,
inputs=[current_session_id, language_select, test_mode_check],
outputs=[stages_display, novel_output, status_text, current_session_id]
)
auto_recover_btn.click(
fn=handle_auto_recover,
inputs=[language_select],
outputs=[current_session_id]
).then(
fn=resume_session,
inputs=[current_session_id, language_select, test_mode_check],
outputs=[stages_display, novel_output, status_text, current_session_id]
)
refresh_btn.click(
fn=refresh_sessions,
outputs=[session_dropdown]
)
clear_btn.click(
fn=lambda: ("", "", "๐Ÿ”„ Ready", "", None, False),
outputs=[stages_display, novel_output, status_text, novel_text_state, current_session_id, test_mode_check]
)
def handle_download(format_type, language, session_id, novel_text):
logger.info(f"Download requested: format={format_type}, session_id={session_id}, language={language}")
logger.info(f"Session ID type: {type(session_id)}, value: {repr(session_id)}")
if not session_id:
logger.error("No session_id available for download")
return gr.update(visible=False)
file_path = download_novel(novel_text, format_type, language, session_id)
if file_path:
logger.info(f"Download successful: {file_path}")
return gr.update(value=file_path, visible=True)
else:
logger.error("Download failed - no file generated")
return gr.update(visible=False)
download_btn.click(
fn=handle_download,
inputs=[format_select, language_select, current_session_id, novel_text_state],
outputs=[download_file]
)
# Load sessions on startup
def on_load():
sessions = refresh_sessions()
return sessions
interface.load(
fn=on_load,
outputs=[session_dropdown]
)
return interface
# Main execution
if __name__ == "__main__":
import sys
logger.info("Starting SOMA Novel Writing System - 10 Writers Edition...")
# Check environment
if TEST_MODE:
logger.warning("Running in TEST MODE - no actual API calls will be made")
else:
logger.info(f"Running in PRODUCTION MODE with API endpoint: {API_URL}")
# Check web search
if BRAVE_SEARCH_API_KEY:
logger.info("Web search is ENABLED with Brave Search API")
else:
logger.warning("Web search is DISABLED. Set BRAVE_SEARCH_API_KEY environment variable to enable.")
# Initialize database on startup
logger.info("Initializing database...")
NovelDatabase.init_db()
logger.info("Database initialized successfully.")
interface = create_interface()
interface.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
debug=True
)