Spaces:
Running
Running
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""" | |
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() | |
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() | |
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() | |
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 | |
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") | |
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() | |
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() | |
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() | |
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 | |
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)}") | |
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 ํ๊ท | |
} | |
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() | |
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์์ ์ง์ ์๊ฐ ๋ด์ฉ์ ๊ฐ์ ธ์์ ํตํฉ""" | |
def extract_chapter_title(content: str, chapter_num: int, language: str) -> str: | |
"""์ฑํฐ ๋ด์ฉ์์ ์ ๋ชฉ ์ถ์ถ""" | |
# ๋ด์ฉ์ ์ค ๋จ์๋ก ๋ถ๋ฆฌ | |
lines = content.strip().split('\n') | |
# ์ฒซ ๋ฒ์งธ ์๋ฏธ์๋ ๋ฌธ์ฅ ์ฐพ๊ธฐ (๋น ์ค ์ ์ธ) | |
for line in lines[:5]: # ์ฒ์ 5์ค ๋ด์์ ์ฐพ๊ธฐ | |
line = line.strip() | |
if len(line) > 10: # 10์ ์ด์์ ์๋ฏธ์๋ ๋ฌธ์ฅ | |
# ๋ํ๋ฌธ์ด๋ฉด ์คํต (๋ฐ์ดํ๋ก ์์ํ๋ ๊ฒฝ์ฐ) | |
if line.startswith('"') or line.startswith("'") or line.startswith('"') or line.startswith('''): | |
continue | |
# ๋ง์นจํ, ๋๋ํ, ๋ฌผ์ํ๋ก ๋๋๋ ์ฒซ ๋ฌธ์ฅ๋ง ์ถ์ถ | |
import re | |
match = re.match(r'^[^.!?]+[.!?]', line) | |
if match: | |
title = match.group(0).strip() | |
else: | |
title = line | |
# ๋๋ฌด ๊ธธ๋ฉด ์๋ฅด๊ธฐ | |
if len(title) > 50: | |
title = title[:47] + "..." | |
return title | |
# ์ ์ ํ ์ ๋ชฉ์ ์ฐพ์ง ๋ชปํ ๊ฒฝ์ฐ ๊ธฐ๋ณธ ์ ๋ชฉ | |
if language == "Korean": | |
return f"์ {chapter_num}์ฅ" | |
else: | |
return f"Part {chapter_num}" | |
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() | |
if actual_language == 'Korean': | |
main_title = 'AI ํ์ ์์ค' + (' - ํ ์คํธ ๋ชจ๋' if is_test_mode else '') | |
else: | |
main_title = 'AI Collaborative Novel' + (' - Test Mode' if is_test_mode else '') | |
title_run = title_para.add_run(main_title) | |
title_run.font.size = Pt(20) # ์ ๊ตญํ์ ๋ง๊ฒ ํฌ๊ธฐ ์กฐ์ | |
title_run.font.bold = True | |
title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER | |
doc.add_paragraph() | |
doc.add_paragraph() | |
theme_para = doc.add_paragraph() | |
theme_label = '์ฃผ์ : ' if actual_language == 'Korean' else 'Theme: ' | |
theme_run = theme_para.add_run(f'{theme_label}{session["user_query"]}') | |
theme_run.font.size = Pt(12) # ํฌ๊ธฐ ์กฐ์ | |
theme_para.alignment = WD_ALIGN_PARAGRAPH.CENTER | |
doc.add_paragraph() | |
date_para = doc.add_paragraph() | |
date_label = '์์ฑ์ผ: ' if actual_language == 'Korean' else 'Created: ' | |
date_run = date_para.add_run(f'{date_label}{datetime.now().strftime("%Y-%m-%d")}') | |
date_run.font.size = Pt(10) # ํฌ๊ธฐ ์กฐ์ | |
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") | |
# ํต๊ณ ํ์ด์ง | |
stats_heading = '์์ค ํต๊ณ' if actual_language == 'Korean' else 'Novel Statistics' | |
doc.add_heading(stats_heading, 1) | |
if actual_language == 'Korean': | |
doc.add_paragraph(f'๋ชจ๋: {"ํ ์คํธ ๋ชจ๋ (์ค์ ์์ฑ๋ ์ฑํฐ)" if is_test_mode else "์ ์ฒด ๋ชจ๋ (10๊ฐ ์ฑํฐ)"}') | |
doc.add_paragraph(f'์ด ์ฑํฐ ์: {writer_count}') | |
doc.add_paragraph(f'์ด ๋จ์ด ์: {total_words:,}') | |
doc.add_paragraph(f'์์ ํ์ด์ง ์: ์ฝ {total_words/300:.0f}') # ํ๊ตญ์ด๋ ํ์ด์ง๋น 300๋จ์ด ๊ธฐ์ค | |
doc.add_paragraph(f'์ธ์ด: ํ๊ตญ์ด') | |
else: | |
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/250:.0f}') # ์์ด๋ ํ์ด์ง๋น 250๋จ์ด ๊ธฐ์ค | |
doc.add_paragraph(f'Language: English') | |
doc.add_page_break() | |
# ๋ชฉ์ฐจ | |
if writer_contents: | |
toc_heading = '๋ชฉ์ฐจ' if actual_language == 'Korean' else 'Table of Contents' | |
doc.add_heading(toc_heading, 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'] | |
content = item['content'] | |
# ์ฑํฐ ์ ๋ชฉ ์ถ์ถ - ์ฒซ ๋ฒ์งธ ์๋ฏธ์๋ ๋ฌธ์ฅ ๋๋ ๋จ๋ฝ | |
chapter_title = extract_chapter_title(content, chapter_num, actual_language) | |
# ๋ชฉ์ฐจ ํญ๋ชฉ ์ถ๊ฐ (ํ์ด์ง ๋ฒํธ ์์ด) | |
if actual_language == 'Korean': | |
toc_entry = f"์ {chapter_num}์ฅ: {chapter_title}" | |
else: | |
toc_entry = f"Chapter {chapter_num}: {chapter_title}" | |
doc.add_paragraph(toc_entry) | |
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'] | |
# ์ฑํฐ ํค๋ | |
chapter_header = f'์ {writer_num}์ฅ' if actual_language == 'Korean' else f'Chapter {writer_num}' | |
doc.add_heading(chapter_header, 1) | |
# ์ฑํฐ ์ ๋ชฉ ์ถ๊ฐ | |
chapter_title = extract_chapter_title(content, writer_num, actual_language) | |
title_para = doc.add_paragraph(chapter_title) | |
title_para.style.font.size = Pt(14) | |
title_para.style.font.bold = True | |
title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER | |
word_count_label = f'๋จ์ด ์: {word_count:,}' if actual_language == 'Korean' else f'Word Count: {word_count:,}' | |
doc.add_paragraph(word_count_label) | |
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(10.5) # ํ๊ตญ ์์ค ํ์ค ํฌ๊ธฐ | |
if idx < len(sorted_contents) - 1: # ๋ง์ง๋ง ์ฑํฐ ํ์๋ ํ์ด์ง ๊ตฌ๋ถ ์์ | |
doc.add_page_break() | |
else: | |
logger.warning("No writer contents found! Creating empty document.") | |
if actual_language == 'Korean': | |
doc.add_paragraph("๋ด์ฉ์ ์ฐพ์ ์ ์์ต๋๋ค. ์์ค ์์ฑ์ด ์ ์์ ์ผ๋ก ์๋ฃ๋์๋์ง ํ์ธํด์ฃผ์ธ์.") | |
else: | |
doc.add_paragraph("No content found. Please check if the novel generation completed successfully.") | |
# ํ์ด์ง ์ค์ - ํ๊ตญ ์ ๊ตญํ (152 ร 225mm) | |
for section in doc.sections: | |
section.page_width = Inches(5.98) # 152mm | |
section.page_height = Inches(8.86) # 225mm | |
section.left_margin = Inches(0.79) # 20mm | |
section.right_margin = Inches(0.79) # 20mm | |
section.top_margin = Inches(0.79) # 20mm | |
section.bottom_margin = Inches(0.79) # 20mm | |
# 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") | |
if actual_language == 'Korean': | |
f.write(f"AI ํ์ ์์ค - {'ํ ์คํธ ๋ชจ๋' if is_test_mode else '์์ฑ๋ณธ'}\n") | |
else: | |
f.write(f"AI COLLABORATIVE NOVEL - {'TEST MODE' if is_test_mode else 'COMPLETE VERSION'}\n") | |
f.write("="*60 + "\n") | |
if actual_language == 'Korean': | |
f.write(f"์ฃผ์ : {session['user_query']}\n") | |
f.write(f"์ธ์ด: ํ๊ตญ์ด\n") | |
f.write(f"์์ฑ์ผ: {datetime.now()}\n") | |
f.write(f"๋ชจ๋: {'ํ ์คํธ ๋ชจ๋ (์ค์ ์์ฑ๋ ์ฑํฐ)' if is_test_mode else '์ ์ฒด ๋ชจ๋ (10๊ฐ ์ฑํฐ)'}\n") | |
else: | |
f.write(f"Theme: {session['user_query']}\n") | |
f.write(f"Language: English\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") | |
chapter_label = f"์ 1์ฅ" if actual_language == 'Korean' else "CHAPTER 1" | |
f.write(f"{chapter_label}\n") | |
# ์ฑํฐ ์ ๋ชฉ ์ถ์ถ ๋ฐ ์ถ๋ ฅ | |
chapter_title = extract_chapter_title(content, 1, actual_language) | |
f.write(f"{chapter_title}\n") | |
word_count_label = f"๋จ์ด ์: {word_count:,}" if actual_language == 'Korean' else f"Word Count: {word_count:,}" | |
f.write(f"{word_count_label}\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") | |
chapter_label = f"์ {chapter_num}์ฅ" if actual_language == 'Korean' else f"CHAPTER {chapter_num}" | |
f.write(f"{chapter_label}\n") | |
# ์ฑํฐ ์ ๋ชฉ ์ถ์ถ ๋ฐ ์ถ๋ ฅ | |
chapter_title = extract_chapter_title(chapter_content, chapter_num, actual_language) | |
f.write(f"{chapter_title}\n") | |
word_count_label = f"๋จ์ด ์: {word_count:,}" if actual_language == 'Korean' else f"Word Count: {word_count:,}" | |
f.write(f"{word_count_label}\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") | |
chapter_label = f"์ {writer_num}์ฅ" if actual_language == 'Korean' else f"CHAPTER {writer_num}" | |
f.write(f"{chapter_label}\n") | |
# ์ฑํฐ ์ ๋ชฉ ์ถ์ถ ๋ฐ ์ถ๋ ฅ | |
chapter_title = extract_chapter_title(content, writer_num, actual_language) | |
f.write(f"{chapter_title}\n") | |
word_count_label = f"๋จ์ด ์: {word_count:,}" if actual_language == 'Korean' else f"Word Count: {word_count:,}" | |
f.write(f"{word_count_label}\n") | |
f.write(f"{'='*40}\n\n") | |
f.write(content) | |
f.write("\n\n") | |
f.write(f"\n{'='*60}\n") | |
if actual_language == 'Korean': | |
f.write(f"์ด๊ณ: {writer_count}๊ฐ ์ฑํฐ, {total_words:,} ๋จ์ด\n") | |
else: | |
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 | |
) |