AGI-WebToon-KOREA / app-backup.py
openfree's picture
Rename app.py to app-backup.py
da9c53d verified
raw
history blame
88.5 kB
import gradio as gr
import os
import json
import requests
from datetime import datetime
import time
from typing import List, Dict, Any, Generator, Tuple, Optional
import logging
import re
import tempfile
from pathlib import Path
import sqlite3
import hashlib
import threading
from contextlib import contextmanager
# λ‘œκΉ… μ„€μ •
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Document export imports
try:
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
DOCX_AVAILABLE = True
except ImportError:
DOCX_AVAILABLE = False
logger.warning("python-docx not installed. DOCX export will be disabled.")
# ν™˜κ²½ λ³€μˆ˜μ—μ„œ 토큰 κ°€μ Έμ˜€κΈ°
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "")
BRAVE_SEARCH_API_KEY = os.getenv("BRAVE_SEARCH_API_KEY", "")
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
MODEL_ID = "dep89a2fld32mcm"
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
# ν™˜κ²½ λ³€μˆ˜ 검증
if not FRIENDLI_TOKEN and not TEST_MODE:
logger.warning("FRIENDLI_TOKEN not set and TEST_MODE is false. Application will run in test mode.")
TEST_MODE = True
if not BRAVE_SEARCH_API_KEY:
logger.warning("BRAVE_SEARCH_API_KEY not set. Web search features will be disabled.")
# μ „μ—­ λ³€μˆ˜
conversation_history = []
selected_language = "English" # κΈ°λ³Έ μ–Έμ–΄
# DB 경둜
DB_PATH = "novel_sessions.db"
db_lock = threading.Lock()
# Stage 번호 μƒμˆ˜ - 10λͺ…μ˜ μž‘κ°€λ‘œ λ³€κ²½
WRITER_DRAFT_STAGES = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] # μž‘κ°€ μ΄ˆμ•ˆ
WRITER_REVISION_STAGES = [5, 8, 11, 14, 17, 20, 23, 26, 29, 32] # μž‘κ°€ μˆ˜μ •λ³Έ
TOTAL_WRITERS = 10 # 총 μž‘κ°€ 수
class WebSearchIntegration:
"""Brave Search API integration for research"""
def __init__(self):
self.brave_api_key = BRAVE_SEARCH_API_KEY
self.search_url = "https://api.search.brave.com/res/v1/web/search"
self.enabled = bool(self.brave_api_key)
def search(self, query: str, count: int = 5, language: str = "en") -> List[Dict]:
"""Perform web search using Brave Search API"""
if not self.enabled:
return []
headers = {
"Accept": "application/json",
"X-Subscription-Token": self.brave_api_key
}
# 언어에 λ”°λ₯Έ 검색 μ„€μ •
search_lang = "ko" if language == "Korean" else "en"
params = {
"q": query,
"count": count,
"search_lang": search_lang,
"text_decorations": False,
"safesearch": "moderate"
}
try:
response = requests.get(self.search_url, headers=headers, params=params, timeout=10)
if response.status_code == 200:
results = response.json()
web_results = results.get("web", {}).get("results", [])
logger.info(f"Search successful: Found {len(web_results)} results for '{query}'")
return web_results
else:
logger.error(f"Search API error: {response.status_code}")
return []
except Exception as e:
logger.error(f"Search error: {str(e)}")
return []
def extract_relevant_info(self, results: List[Dict], max_chars: int = 3000) -> str:
"""Extract relevant information from search results"""
if not results:
return ""
extracted = []
total_chars = 0
for i, result in enumerate(results[:5], 1): # μ΅œλŒ€ 5개 κ²°κ³Ό
title = result.get("title", "")
description = result.get("description", "")
url = result.get("url", "")
# 일뢀 λ‚΄μš© μΆ”μΆœ
extra_text = ""
if "extra_snippets" in result:
extra_text = " ".join(result["extra_snippets"][:2])
info = f"""[{i}] {title}
{description}
{extra_text}
Source: {url}
"""
if total_chars + len(info) < max_chars:
extracted.append(info)
total_chars += len(info)
else:
break
return "\n---\n".join(extracted)
def create_research_queries(self, topic: str, role: str, stage_info: Dict, language: str = "English") -> List[str]:
"""Create multiple research queries based on role and context"""
queries = []
if language == "Korean":
if role == "director":
queries = [
f"{topic} μ†Œμ„€ λ°°κ²½ μ„€μ •",
f"{topic} 역사적 사싀",
f"{topic} 문화적 νŠΉμ§•"
]
elif role.startswith("writer"):
writer_num = int(role.replace("writer", ""))
if writer_num <= 3: # μ΄ˆλ°˜λΆ€ μž‘κ°€
queries = [
f"{topic} ꡬ체적 μž₯λ©΄ λ¬˜μ‚¬",
f"{topic} μ „λ¬Έ μš©μ–΄ μ„€λͺ…"
]
elif writer_num <= 6: # μ€‘λ°˜λΆ€ μž‘κ°€
queries = [
f"{topic} κ°ˆλ“± 상황 사둀",
f"{topic} 심리적 μΈ‘λ©΄"
]
else: # ν›„λ°˜λΆ€ μž‘κ°€
queries = [
f"{topic} ν•΄κ²° 방법",
f"{topic} 감동적인 사둀"
]
elif role == "critic":
queries = [
f"{topic} λ¬Έν•™ μž‘ν’ˆ 뢄석",
f"{topic} μœ μ‚¬ μ†Œμ„€ μΆ”μ²œ"
]
else:
if role == "director":
queries = [
f"{topic} novel setting ideas",
f"{topic} historical facts",
f"{topic} cultural aspects"
]
elif role.startswith("writer"):
writer_num = int(role.replace("writer", ""))
if writer_num <= 3: # Early writers
queries = [
f"{topic} vivid scene descriptions",
f"{topic} technical terminology explained"
]
elif writer_num <= 6: # Middle writers
queries = [
f"{topic} conflict scenarios",
f"{topic} psychological aspects"
]
else: # Later writers
queries = [
f"{topic} resolution methods",
f"{topic} emotional stories"
]
elif role == "critic":
queries = [
f"{topic} literary analysis",
f"{topic} similar novels recommendations"
]
return queries
class NovelDatabase:
"""Novel session management database with enhanced recovery features"""
@staticmethod
def init_db():
"""Initialize database tables with WAL mode for better concurrency"""
with sqlite3.connect(DB_PATH) as conn:
# Enable WAL mode for better concurrent access
conn.execute("PRAGMA journal_mode=WAL")
cursor = conn.cursor()
# Sessions table with enhanced recovery fields
cursor.execute('''
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
user_query TEXT NOT NULL,
language TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
status TEXT DEFAULT 'active',
current_stage INTEGER DEFAULT 0,
last_saved_stage INTEGER DEFAULT -1,
recovery_data TEXT,
final_novel TEXT
)
''')
# Stages table - 각 μŠ€ν…Œμ΄μ§€μ˜ 전체 λ‚΄μš© μ €μž₯
cursor.execute('''
CREATE TABLE IF NOT EXISTS stages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
stage_number INTEGER NOT NULL,
stage_name TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT,
word_count INTEGER DEFAULT 0,
status TEXT DEFAULT 'pending',
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
UNIQUE(session_id, stage_number)
)
''')
# Search history table - 검색 이λ ₯ μ €μž₯
cursor.execute('''
CREATE TABLE IF NOT EXISTS search_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
stage_number INTEGER NOT NULL,
role TEXT NOT NULL,
query TEXT NOT NULL,
results TEXT,
created_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES sessions(session_id)
)
''')
# Create indices
cursor.execute('CREATE INDEX IF NOT EXISTS idx_session_id ON stages(session_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_stage_number ON stages(stage_number)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_search_session ON search_history(session_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_session_status ON sessions(status)')
conn.commit()
@staticmethod
def save_search_history(session_id: str, stage_number: int, role: str, query: str, results: str):
"""Save search history"""
with sqlite3.connect(DB_PATH) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO search_history (session_id, stage_number, role, query, results)
VALUES (?, ?, ?, ?, ?)
''', (session_id, stage_number, role, query, results))
conn.commit()
@staticmethod
@contextmanager
def get_db():
"""Database connection context manager with timeout"""
with db_lock:
conn = sqlite3.connect(DB_PATH, timeout=30.0)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
@staticmethod
def create_session(user_query: str, language: str) -> str:
"""Create new session"""
session_id = hashlib.md5(f"{user_query}{datetime.now()}".encode()).hexdigest()
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO sessions (session_id, user_query, language)
VALUES (?, ?, ?)
''', (session_id, user_query, language))
conn.commit()
return session_id
@staticmethod
def save_stage(session_id: str, stage_number: int, stage_name: str,
role: str, content: str, status: str = 'complete'):
"""Save stage content with word count"""
word_count = len(content.split()) if content else 0
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"Saved stage {stage_number} for session {session_id}, content length: {len(content)}, words: {word_count}")
@staticmethod
def get_session(session_id: str) -> Optional[Dict]:
"""Get session info"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM sessions WHERE session_id = ?', (session_id,))
return cursor.fetchone()
@staticmethod
def get_latest_active_session() -> Optional[Dict]:
"""Get the most recent active session"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM sessions
WHERE status = 'active'
ORDER BY updated_at DESC
LIMIT 1
''')
return cursor.fetchone()
@staticmethod
def get_stages(session_id: str) -> List[Dict]:
"""Get all stages for a session"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM stages
WHERE session_id = ?
ORDER BY stage_number
''', (session_id,))
return cursor.fetchall()
@staticmethod
def get_all_writer_content(session_id: str) -> str:
"""λͺ¨λ“  μž‘κ°€μ˜ μˆ˜μ •λ³Έ λ‚΄μš©μ„ κ°€μ Έμ™€μ„œ ν•©μΉ˜κΈ° - 10λͺ… μž‘κ°€"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
all_content = []
writer_count = 0
total_word_count = 0
for stage_num in WRITER_REVISION_STAGES:
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)
logger.info(f"Total: {writer_count} writers, {total_word_count} words")
# 10λͺ… μž‘κ°€ * 1,450 평균 = 14,500 단어 λͺ©ν‘œ
if total_word_count < 12000:
logger.warning(f"Content too short! Only {total_word_count} words instead of ~14,500")
return full_content
@staticmethod
def update_final_novel(session_id: str, final_novel: str):
"""Update final novel content"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
UPDATE sessions
SET final_novel = ?, status = 'complete', updated_at = datetime('now')
WHERE session_id = ?
''', (final_novel, session_id))
conn.commit()
logger.info(f"Updated final novel for session {session_id}, length: {len(final_novel)}")
@staticmethod
def get_active_sessions() -> List[Dict]:
"""Get all active sessions"""
with NovelDatabase.get_db() as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT session_id, user_query, language, created_at, current_stage
FROM sessions
WHERE status = 'active'
ORDER BY updated_at DESC
LIMIT 10
''')
return cursor.fetchall()
@staticmethod
def parse_datetime(datetime_str: str) -> datetime:
"""Parse SQLite datetime string safely"""
try:
# Try ISO format first
return datetime.fromisoformat(datetime_str)
except:
# Fallback to SQLite default format
return datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
class NovelWritingSystem:
def __init__(self):
self.token = FRIENDLI_TOKEN
self.api_url = API_URL
self.model_id = MODEL_ID
self.test_mode = TEST_MODE or not self.token
# Web search integration
self.web_search = WebSearchIntegration()
if self.test_mode:
logger.warning("Running in test mode - no actual API calls will be made.")
else:
logger.info("Running in production mode with API calls enabled.")
if self.web_search.enabled:
logger.info("Web search is enabled with Brave Search API.")
else:
logger.warning("Web search is disabled. Set BRAVE_SEARCH_API_KEY to enable.")
# Initialize database
NovelDatabase.init_db()
# Session management
self.current_session_id = None
self.total_stages = 0 # Will be set in process_novel_stream
def create_headers(self):
"""API 헀더 생성"""
return {
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json"
}
def enhance_prompt_with_research(self, original_prompt: str, role: str,
topic: str, stage_info: Dict, language: str = "English") -> str:
"""Enhance prompt with web search results"""
if not self.web_search.enabled or self.test_mode:
return original_prompt
# Create research queries
queries = self.web_search.create_research_queries(topic, role, stage_info, language)
all_research = []
for query in queries[:2]: # μ΅œλŒ€ 2개 쿼리
logger.info(f"Searching: {query}")
results = self.web_search.search(query, count=3, language=language)
if results:
research_text = self.web_search.extract_relevant_info(results, max_chars=1500)
if research_text:
all_research.append(f"### {query}\n{research_text}")
# Save search history
if self.current_session_id:
NovelDatabase.save_search_history(
self.current_session_id,
stage_info.get('stage_idx', 0),
role,
query,
research_text
)
if not all_research:
return original_prompt
# Add research to prompt
if language == "Korean":
research_section = f"""
## μ›Ή 검색 μ°Έκ³  자료:
{chr(10).join(all_research)}
μœ„μ˜ 검색 κ²°κ³Όλ₯Ό μ°Έκ³ ν•˜μ—¬ λ”μš± 사싀적이고 ꡬ체적인 λ‚΄μš©μ„ μž‘μ„±ν•˜μ„Έμš”.
검색 결과의 정보λ₯Ό 창의적으둜 ν™œμš©ν•˜λ˜, 직접 μΈμš©μ€ ν”Όν•˜κ³  μ†Œμ„€μ— μžμ—°μŠ€λŸ½κ²Œ λ…Ήμ—¬λ‚΄μ„Έμš”.
μ‹€μ œ 사싀과 μ°½μž‘μ„ 적절히 μ‘°ν™”μ‹œμΌœ λ…μžκ°€ λͺ°μž…ν•  수 μžˆλŠ” 이야기λ₯Ό λ§Œλ“œμ„Έμš”.
"""
else:
research_section = f"""
## Web Search Reference:
{chr(10).join(all_research)}
Use the above search results to create more realistic and specific content.
Creatively incorporate the information from search results, but avoid direct quotes and naturally blend them into the novel.
Balance real facts with creative fiction to create an immersive story for readers.
"""
return original_prompt + "\n\n" + research_section
def create_director_initial_prompt(self, user_query: str, language: str = "English") -> str:
"""Director AI initial prompt - Novel planning for 10 writers"""
if language == "Korean":
return f"""당신은 30νŽ˜μ΄μ§€ λΆ„λŸ‰μ˜ μ€‘νŽΈ μ†Œμ„€μ„ κΈ°νšν•˜λŠ” λ¬Έν•™ κ°λ…μžμž…λ‹ˆλ‹€.
μ‚¬μš©μž μš”μ²­: {user_query}
λ‹€μŒ μš”μ†Œλ“€μ„ μ²΄κ³„μ μœΌλ‘œ κ΅¬μ„±ν•˜μ—¬ 30νŽ˜μ΄μ§€ μ€‘νŽΈ μ†Œμ„€μ˜ 기초λ₯Ό λ§Œλ“œμ„Έμš”:
1. **μ£Όμ œμ™€ μž₯λ₯΄**
- 핡심 μ£Όμ œμ™€ λ©”μ‹œμ§€
- μž₯λ₯΄ 및 톀
- λͺ©ν‘œ λ…μžμΈ΅
2. **λ“±μž₯인물 μ„€μ •** (ν‘œλ‘œ 정리)
| 이름 | μ—­ν•  | 성격 | λ°°κ²½ | 동기 | λ³€ν™” |
|------|------|------|------|------|------|
3. **인물 관계도**
- μ£Όμš” 인물 κ°„μ˜ 관계
- κ°ˆλ“± ꡬ쑰
- 감정적 연결고리
4. **μ„œμ‚¬ ꡬ쑰** (30νŽ˜μ΄μ§€λ₯Ό 10개 파트둜 λ‚˜λˆ„μ–΄ 각 3νŽ˜μ΄μ§€)
| 파트 | νŽ˜μ΄μ§€ | μ£Όμš” 사건 | κΈ΄μž₯도 | 인물 λ°œμ „ |
|------|--------|-----------|---------|-----------|
| 1 | 1-3 | | | |
| 2 | 4-6 | | | |
| ... | ... | | | |
| 10 | 28-30 | | | |
5. **세계관 μ„€μ •**
- μ‹œκ³΅κ°„μ  λ°°κ²½
- μ‚¬νšŒμ /문화적 λ§₯락
- λΆ„μœ„κΈ°μ™€ 톀
각 μž‘μ„±μžκ°€ 3νŽ˜μ΄μ§€μ”© μž‘μ„±ν•  수 μžˆλ„λ‘ λͺ…ν™•ν•œ κ°€μ΄λ“œλΌμΈμ„ μ œμ‹œν•˜μ„Έμš”."""
else:
return f"""You are a literary director planning a 30-page novella.
User Request: {user_query}
Systematically compose the following elements to create the foundation for a 30-page novella:
1. **Theme and Genre**
- Core theme and message
- Genre and tone
- Target audience
2. **Character Settings** (organize in table)
| Name | Role | Personality | Background | Motivation | Arc |
|------|------|-------------|------------|------------|-----|
3. **Character Relationship Map**
- Relationships between main characters
- Conflict structure
- Emotional connections
4. **Narrative Structure** (divide 30 pages into 10 parts, 3 pages each)
| Part | Pages | Main Events | Tension | Character Development |
|------|-------|-------------|---------|---------------------|
| 1 | 1-3 | | | |
| 2 | 4-6 | | | |
| ... | ... | | | |
| 10 | 28-30 | | | |
5. **World Building**
- Temporal and spatial setting
- Social/cultural context
- Atmosphere and tone
Provide clear guidelines for each writer to compose 3 pages."""
def create_critic_director_prompt(self, director_plan: str, language: str = "English") -> str:
"""Critic's review of director's plan"""
if language == "Korean":
return f"""당신은 λ¬Έν•™ λΉ„ν‰κ°€μž…λ‹ˆλ‹€. κ°λ…μžμ˜ μ†Œμ„€ κΈ°νšμ„ κ²€ν† ν•˜κ³  κ°œμ„ μ μ„ μ œμ‹œν•˜μ„Έμš”.
κ°λ…μžμ˜ 기획:
{director_plan}
λ‹€μŒ κ΄€μ μ—μ„œ λΉ„ν‰ν•˜κ³  ꡬ체적인 κ°œμ„ μ•ˆμ„ μ œμ‹œν•˜μ„Έμš”:
1. **μ„œμ‚¬μ  완성도**
- ν”Œλ‘―μ˜ 논리성과 κ°œμ—°μ„±
- κ°ˆλ“±μ˜ νš¨κ³Όμ„±
- 클라이λ§₯슀의 μœ„μΉ˜μ™€ 강도
2. **인물 μ„€μ • κ²€ν† **
| 인물 | 강점 | 약점 | κ°œμ„  μ œμ•ˆ |
|------|------|------|-----------|
3. **ꡬ쑰적 κ· ν˜•**
- 10개 νŒŒνŠΈλ³„ λΆ„λŸ‰ λ°°λΆ„
- κΈ΄μž₯κ³Ό μ΄μ™„μ˜ 리듬
- 전체적인 흐름
4. **λ…μž 관점**
- λͺ°μž…도 μ˜ˆμƒ
- 감정적 영ν–₯λ ₯
- κΈ°λŒ€μΉ˜ 좩쑱도
5. **μ‹€ν–‰ κ°€λŠ₯μ„±**
- 10λͺ…μ˜ μž‘μ„±μžλ₯Ό μœ„ν•œ κ°€μ΄λ“œλΌμΈμ˜ λͺ…ν™•μ„±
- 일관성 μœ μ§€ λ°©μ•ˆ
- 잠재적 문제점
ꡬ체적이고 건섀적인 ν”Όλ“œλ°±μ„ μ œκ³΅ν•˜μ„Έμš”."""
else:
return f"""You are a literary critic. Review the director's novel plan and suggest improvements.
Director's Plan:
{director_plan}
Critique from the following perspectives and provide specific improvements:
1. **Narrative Completeness**
- Plot logic and plausibility
- Effectiveness of conflicts
- Climax position and intensity
2. **Character Review**
| Character | Strengths | Weaknesses | Suggestions |
|-----------|-----------|------------|-------------|
3. **Structural Balance**
- Distribution across 10 parts
- Rhythm of tension and relief
- Overall flow
4. **Reader Perspective**
- Expected engagement
- Emotional impact
- Expectation fulfillment
5. **Feasibility**
- Clarity of guidelines for 10 writers
- Consistency maintenance
- Potential issues
Provide specific and constructive feedback."""
def create_director_revision_prompt(self, initial_plan: str, critic_feedback: str, language: str = "English") -> str:
"""Director's revision based on critic feedback"""
if language == "Korean":
return f"""κ°λ…μžλ‘œμ„œ λΉ„ν‰κ°€μ˜ ν”Όλ“œλ°±μ„ λ°˜μ˜ν•˜μ—¬ μ†Œμ„€ κΈ°νšμ„ μˆ˜μ •ν•©λ‹ˆλ‹€.
초기 기획:
{initial_plan}
비평가 ν”Όλ“œλ°±:
{critic_feedback}
λ‹€μŒμ„ ν¬ν•¨ν•œ μˆ˜μ •λœ μ΅œμ’… κΈ°νšμ„ μ œμ‹œν•˜μ„Έμš”:
1. **μˆ˜μ •λœ μ„œμ‚¬ ꡬ쑰** (10개 파트)
| 파트 | νŽ˜μ΄μ§€ | μ£Όμš” 사건 | μž‘μ„± μ§€μΉ¨ | μ£Όμ˜μ‚¬ν•­ |
|------|--------|-----------|-----------|----------|
2. **κ°•ν™”λœ 인물 μ„€μ •**
- 각 인물의 λͺ…ν™•ν•œ 동기와 λͺ©ν‘œ
- 인물 κ°„ κ°ˆλ“±μ˜ ꡬ체화
- κ°μ •μ„ μ˜ λ³€ν™” 좔이
3. **각 μž‘μ„±μžλ₯Ό μœ„ν•œ 상세 κ°€μ΄λ“œ** (10λͺ…)
- νŒŒνŠΈλ³„ μ‹œμž‘κ³Ό 끝 지점
- ν•„μˆ˜ 포함 μš”μ†Œ
- 문체와 톀 μ§€μΉ¨
- 전달해야 ν•  정보
4. **일관성 μœ μ§€ 체크리슀트**
- μ‹œκ°„μ„  관리
- 인물 νŠΉμ„± μœ μ§€
- μ„€μ • 일관성
- 볡선과 ν•΄κ²°
5. **ν’ˆμ§ˆ κΈ°μ€€**
- 각 파트의 완성도 κΈ°μ€€
- 전체적 톡일성
- λ…μž λͺ°μž… μœ μ§€ λ°©μ•ˆ
10λͺ…μ˜ μž‘μ„±μžκ°€ λͺ…ν™•νžˆ 이해할 수 μžˆλŠ” μ΅œμ’… λ§ˆμŠ€ν„°ν”Œλžœμ„ μž‘μ„±ν•˜μ„Έμš”."""
else:
return f"""As director, revise the novel plan reflecting the critic's feedback.
Initial Plan:
{initial_plan}
Critic Feedback:
{critic_feedback}
Present the revised final plan including:
1. **Revised Narrative Structure** (10 parts)
| Part | Pages | Main Events | Writing Guidelines | Cautions |
|------|-------|-------------|-------------------|----------|
2. **Enhanced Character Settings**
- Clear motivations and goals for each character
- Concrete conflicts between characters
- Emotional arc progression
3. **Detailed Guide for Each Writer** (10 writers)
- Start and end points for each part
- Essential elements to include
- Style and tone guidelines
- Information to convey
4. **Consistency Checklist**
- Timeline management
- Character trait maintenance
- Setting consistency
- Foreshadowing and resolution
5. **Quality Standards**
- Completion criteria for each part
- Overall unity
- Reader engagement maintenance
Create a final masterplan that all 10 writers can clearly understand."""
def create_writer_prompt(self, writer_number: int, director_plan: str, previous_content: str, language: str = "English") -> str:
"""Individual writer prompt - 1,400-1,500 단어"""
pages_start = (writer_number - 1) * 3 + 1
pages_end = writer_number * 3
if language == "Korean":
return f"""당신은 μž‘μ„±μž {writer_number}λ²ˆμž…λ‹ˆλ‹€. 30νŽ˜μ΄μ§€ μ€‘νŽΈ μ†Œμ„€μ˜ {pages_start}-{pages_end}νŽ˜μ΄μ§€(3νŽ˜μ΄μ§€)λ₯Ό μž‘μ„±ν•˜μ„Έμš”.
κ°λ…μžμ˜ λ§ˆμŠ€ν„°ν”Œλžœ:
{director_plan}
{'μ΄μ „κΉŒμ§€μ˜ λ‚΄μš©:' if previous_content else '당신이 첫 번째 μž‘μ„±μžμž…λ‹ˆλ‹€.'}
{previous_content[-2000:] if previous_content else ''}
**μ€‘μš” μ§€μΉ¨:**
1. **ν•„μˆ˜ λΆ„λŸ‰**:
- μ΅œμ†Œ 1,400단어, μ΅œλŒ€ 1,500단어
- λŒ€λž΅ 7000-7500자 (곡백 포함)
- 3νŽ˜μ΄μ§€ λΆ„λŸ‰μ„ μ •ν™•νžˆ μ±„μ›Œμ•Ό ν•©λ‹ˆλ‹€
2. **λΆ„λŸ‰ 확보 μ „λž΅**:
- μƒμ„Έν•œ μž₯λ©΄ λ¬˜μ‚¬ 포함
- 인물의 λ‚΄λ©΄ 심리 깊이 있게 탐ꡬ
- λŒ€ν™”μ™€ 행동을 ꡬ체적으둜 ν‘œν˜„
- λ°°κ²½κ³Ό λΆ„μœ„κΈ°λ₯Ό μƒμƒν•˜κ²Œ κ·Έλ €λ‚΄κΈ°
- 감각적 세뢀사항(μ‹œκ°, 청각, 촉각 λ“±) ν™œμš©
3. **연속성과 일관성**:
- 이전 λ‚΄μš©κ³Ό μžμ—°μŠ€λŸ½κ²Œ μ—°κ²°
- 인물 성격과 말투 μœ μ§€
- μ‹œκ°„μ„ κ³Ό 곡간 μ„€μ • μ€€μˆ˜
4. **μ„œμ‚¬ λ°œμ „**:
- ν”Œλ‘―μ„ 의미 있게 μ „μ§„μ‹œν‚€κΈ°
- κΈ΄μž₯감 적절히 쑰절
- λ…μžμ˜ 관심 μœ μ§€
**μž‘μ„± μ‹œμž‘:**
이제 1,400-1,500단어 λΆ„λŸ‰μ˜ μ†Œμ„€μ„ μž‘μ„±ν•˜μ„Έμš”. νŽ˜μ΄μ§€ ꡬ뢄 ν‘œμ‹œλŠ” ν•˜μ§€ λ§ˆμ„Έμš”."""
else:
return f"""You are Writer #{writer_number}. Write pages {pages_start}-{pages_end} (3 pages) of the 30-page novella.
Director's Masterplan:
{director_plan}
{'Previous content:' if previous_content else 'You are the first writer.'}
{previous_content[-2000:] if previous_content else ''}
**CRITICAL INSTRUCTIONS:**
1. **MANDATORY LENGTH**:
- Minimum 1,400 words, Maximum 1,500 words
- Approximately 7000-7500 characters
- You MUST fill exactly 3 pages
2. **LENGTH STRATEGIES**:
- Include detailed scene descriptions
- Explore character's inner psychology deeply
- Express dialogue and actions concretely
- Paint backgrounds and atmosphere vividly
- Use sensory details (visual, auditory, tactile, etc.)
3. **CONTINUITY & CONSISTENCY**:
- Flow naturally from previous content
- Maintain character personalities and speech
- Follow timeline and spatial settings
4. **NARRATIVE DEVELOPMENT**:
- Advance the plot meaningfully
- Control tension appropriately
- Maintain reader interest
**BEGIN WRITING:**
Now write your 1,400-1,500 word section. Do not use any page markers."""
def create_critic_writer_prompt(self, writer_number: int, writer_content: str, director_plan: str, all_previous_content: str, language: str = "English") -> str:
"""Critic's review of individual writer's work"""
if language == "Korean":
return f"""μž‘μ„±μž {writer_number}번의 μž‘ν’ˆμ„ λΉ„ν‰ν•©λ‹ˆλ‹€.
κ°λ…μžμ˜ λ§ˆμŠ€ν„°ν”Œλžœ:
{director_plan}
이전 λ‚΄μš© μš”μ•½:
{all_previous_content[-1000:] if all_previous_content else '첫 번째 μž‘μ„±μžμž…λ‹ˆλ‹€.'}
μž‘μ„±μž {writer_number}번의 λ‚΄μš©:
{writer_content}
λ‹€μŒ κΈ°μ€€μœΌλ‘œ ν‰κ°€ν•˜κ³  μˆ˜μ • μš”κ΅¬μ‚¬ν•­μ„ μ œμ‹œν•˜μ„Έμš”:
1. **일관성 검증** (ν‘œλ‘œ 정리)
| μš”μ†Œ | 이전 μ„€μ • | ν˜„μž¬ ν‘œν˜„ | 문제점 | μˆ˜μ • ν•„μš” |
|------|----------|----------|--------|----------|
2. **논리적 였λ₯˜ κ²€ν† **
- μ‹œκ°„μ„  λͺ¨μˆœ
- 인물 ν–‰λ™μ˜ κ°œμ—°μ„±
- μ„€μ • 좩돌
- 사싀관계 였λ₯˜
3. **μ„œμ‚¬μ  νš¨κ³Όμ„±**
- ν”Œλ‘― μ§„ν–‰ 기여도
- κΈ΄μž₯감 μœ μ§€
- λ…μž λͺ°μž…도
- 감정적 영ν–₯λ ₯
4. **문체와 ν’ˆμ§ˆ**
- 전체 ν†€κ³Όμ˜ 일치
- λ¬Έμž₯의 질
- λ¬˜μ‚¬μ˜ μ μ ˆμ„±
- λŒ€ν™”μ˜ μžμ—°μŠ€λŸ¬μ›€
5. **κ°œμ„  μš”κ΅¬μ‚¬ν•­**
- ν•„μˆ˜ μˆ˜μ • 사항 (일관성/논리 였λ₯˜)
- ꢌμž₯ κ°œμ„  사항 (ν’ˆμ§ˆ ν–₯상)
- ꡬ체적 μˆ˜μ • μ§€μΉ¨
λ°˜λ“œμ‹œ μˆ˜μ •μ΄ ν•„μš”ν•œ λΆ€λΆ„κ³Ό 선택적 κ°œμ„ μ‚¬ν•­μ„ κ΅¬λΆ„ν•˜μ—¬ μ œμ‹œν•˜μ„Έμš”."""
else:
return f"""Critiquing Writer #{writer_number}'s work.
Director's Masterplan:
{director_plan}
Previous Content Summary:
{all_previous_content[-1000:] if all_previous_content else 'This is the first writer.'}
Writer #{writer_number}'s Content:
{writer_content}
Evaluate by these criteria and present revision requirements:
1. **Consistency Verification** (organize in table)
| Element | Previous Setting | Current Expression | Issue | Revision Needed |
|---------|-----------------|-------------------|-------|-----------------|
2. **Logical Error Review**
- Timeline contradictions
- Character action plausibility
- Setting conflicts
- Factual errors
3. **Narrative Effectiveness**
- Plot progression contribution
- Tension maintenance
- Reader engagement
- Emotional impact
4. **Style and Quality**
- Alignment with overall tone
- Sentence quality
- Description appropriateness
- Dialogue naturalness
5. **Improvement Requirements**
- Mandatory revisions (consistency/logic errors)
- Recommended improvements (quality enhancement)
- Specific revision guidelines
Clearly distinguish between mandatory revisions and optional improvements."""
def create_writer_revision_prompt(self, writer_number: int, initial_content: str, critic_feedback: str, language: str = "English") -> str:
"""Writer's revision based on critic feedback"""
if language == "Korean":
return f"""μž‘μ„±μž {writer_number}λ²ˆμœΌλ‘œμ„œ λΉ„ν‰κ°€μ˜ ν”Όλ“œλ°±μ„ λ°˜μ˜ν•˜μ—¬ μˆ˜μ •ν•©λ‹ˆλ‹€.
초기 μž‘μ„± λ‚΄μš©:
{initial_content}
비평가 ν”Όλ“œλ°±:
{critic_feedback}
λ‹€μŒ 사항을 λ°˜μ˜ν•œ μˆ˜μ •λ³Έμ„ μž‘μ„±ν•˜μ„Έμš”:
1. **ν•„μˆ˜ μˆ˜μ •μ‚¬ν•­ 반영**
- λͺ¨λ“  일관성 였λ₯˜ μˆ˜μ •
- 논리적 λͺ¨μˆœ ν•΄κ²°
- 사싀관계 μ •μ •
2. **ν’ˆμ§ˆ κ°œμ„ **
- ꢌμž₯사항 쀑 κ°€λŠ₯ν•œ λΆ€λΆ„ 반영
- 문체와 톀 μ‘°μ •
- λ¬˜μ‚¬μ™€ λŒ€ν™” κ°œμ„ 
3. **λΆ„λŸ‰ μœ μ§€**
- μ—¬μ „νžˆ μ •ν™•νžˆ 3νŽ˜μ΄μ§€ (1,400-1,500단어)
- νŽ˜μ΄μ§€ ꡬ뢄 ν‘œμ‹œ μ ˆλŒ€ κΈˆμ§€
4. **연속성 확보**
- 이전/이후 λ‚΄μš©κ³Όμ˜ μžμ—°μŠ€λŸ¬μš΄ μ—°κ²°
- μˆ˜μ •μœΌλ‘œ μΈν•œ μƒˆλ‘œμš΄ λͺ¨μˆœ λ°©μ§€
μˆ˜μ •λœ μ΅œμ’…λ³Έμ„ μ œμ‹œν•˜μ„Έμš”. νŽ˜μ΄μ§€ λ§ˆν¬λŠ” μ ˆλŒ€ μ‚¬μš©ν•˜μ§€ λ§ˆμ„Έμš”.
λ°˜λ“œμ‹œ 1,400-1,500단어 λΆ„λŸ‰μ„ μœ μ§€ν•˜μ„Έμš”."""
else:
return f"""As Writer #{writer_number}, revise based on critic's feedback.
Initial Content:
{initial_content}
Critic Feedback:
{critic_feedback}
Write a revision reflecting:
1. **Mandatory Revisions**
- Fix all consistency errors
- Resolve logical contradictions
- Correct factual errors
2. **Quality Improvements**
- Incorporate feasible recommendations
- Adjust style and tone
- Improve descriptions and dialogue
3. **Maintain Length**
- Still exactly 3 pages (1,400-1,500 words)
- Absolutely no page markers
4. **Ensure Continuity**
- Natural connection with previous/next content
- Prevent new contradictions from revisions
Present the revised final version. Never use page markers.
You MUST maintain 1,400-1,500 words."""
def 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.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 10 writers"""
if language == "Korean":
prompts = {
"director": "당신은 30νŽ˜μ΄μ§€ μ€‘νŽΈ μ†Œμ„€μ„ κΈ°νšν•˜κ³  κ°λ…ν•˜λŠ” λ¬Έν•™ κ°λ…μžμž…λ‹ˆλ‹€. 체계적이고 창의적인 μŠ€ν† λ¦¬ ꡬ쑰λ₯Ό λ§Œλ“€μ–΄λƒ…λ‹ˆλ‹€.",
"critic": "당신은 λ‚ μΉ΄λ‘œμš΄ 톡찰λ ₯을 κ°€μ§„ λ¬Έν•™ λΉ„ν‰κ°€μž…λ‹ˆλ‹€. 건섀적이고 ꡬ체적인 ν”Όλ“œλ°±μ„ μ œκ³΅ν•©λ‹ˆλ‹€."
}
# 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."
}
# 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"""
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
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
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) -> 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
else:
self.current_session_id = NovelDatabase.create_session(query, language)
resume_from_stage = 0
logger.info(f"Processing novel for session {self.current_session_id}, starting from stage {resume_from_stage}")
# 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 (μ΅œμ’… 평가 제거)
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)
# Create stage info for web search
stage_info = {
'stage_idx': stage_idx,
'query': query,
'stage_name': stage_name
}
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"
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)
logger.info(f"Content verification: {verification}")
if verification['total_words'] < 12000:
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)
# Save final novel to DB
NovelDatabase.update_final_novel(self.current_session_id, complete_novel)
# Final yield - ν™”λ©΄μ—λŠ” μ™„λ£Œ λ©”μ‹œμ§€λ§Œ ν‘œμ‹œ
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 get_stage_prompt(self, stage_idx: int, role: str, query: str,
language: str, stages: List[Dict]) -> 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
# 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) -> Generator[Tuple[str, str, str, str], None, None]:
"""Process query and yield updates with recovery status"""
if not query.strip() and not session_id:
if language == "Korean":
yield "", "", "❌ μ†Œμ„€ 주제λ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”.", ""
else:
yield "", "", "❌ Please enter a novel theme.", ""
return
system = NovelWritingSystem()
try:
# Recovery status message
recovery_status = ""
if session_id:
if language == "Korean":
recovery_status = "♻️ 이전 μ„Έμ…˜μ„ λ³΅κ΅¬ν•˜μ—¬ 계속 μ§„ν–‰ν•©λ‹ˆλ‹€..."
else:
recovery_status = "♻️ Recovering previous session and continuing..."
for final_novel, stages in system.process_novel_stream(query, language, session_id):
# 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):
status = "βœ… Complete! Ready to download."
else:
if language == "Korean":
status = f"πŸ”„ 진행쀑... ({completed}/{total} - {progress_percent:.1f}%)"
else:
status = f"πŸ”„ Processing... ({completed}/{total} - {progress_percent:.1f}%)"
yield stages_display, final_novel, status, recovery_status
except Exception as e:
logger.error(f"Error in process_query: {str(e)}", exc_info=True)
if language == "Korean":
yield "", "", f"❌ 였λ₯˜ λ°œμƒ: {str(e)}", ""
else:
yield "", "", f"❌ Error occurred: {str(e)}", ""
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) -> Generator[Tuple[str, str, str], None, None]:
"""Resume an existing session"""
if not session_id:
if language == "Korean":
yield "", "", "❌ μ„Έμ…˜μ„ μ„ νƒν•΄μ£Όμ„Έμš”."
else:
yield "", "", "❌ Please select a session."
return
# Process with existing session ID
yield from process_query("", language, session_id)
def auto_recover_session(language: str) -> Tuple[str, str]:
"""Auto recover the latest active session"""
try:
latest_session = NovelDatabase.get_latest_active_session()
if latest_session:
if language == "Korean":
message = f"βœ… μžλ™ 볡ꡬ: '{latest_session['user_query'][:30]}...' (Stage {latest_session['current_stage']})"
else:
message = f"βœ… Auto recovered: '{latest_session['user_query'][:30]}...' (Stage {latest_session['current_stage']})"
return latest_session['session_id'], message
else:
return None, ""
except Exception as e:
logger.error(f"Error in auto recovery: {str(e)}")
return None, ""
def download_novel(novel_text: str, format: str, language: str, session_id: str = None) -> str:
"""Download novel - DBμ—μ„œ 직접 μž‘κ°€ λ‚΄μš©μ„ κ°€μ Έμ™€μ„œ 톡합"""
if not session_id:
logger.error("No session_id provided for download")
return None
# DBμ—μ„œ μ„Έμ…˜ 정보 κ°€μ Έμ˜€κΈ°
session = NovelDatabase.get_session(session_id)
if not session:
logger.error(f"Session not found: {session_id}")
return None
# DBμ—μ„œ λͺ¨λ“  μŠ€ν…Œμ΄μ§€ κ°€μ Έμ˜€κΈ°
stages = NovelDatabase.get_stages(session_id)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
if format == "DOCX" and DOCX_AVAILABLE:
# Create DOCX
doc = Document()
# 제λͺ© νŽ˜μ΄μ§€
title_para = doc.add_paragraph()
title_run = title_para.add_run('AI Collaborative Novel')
title_run.font.size = Pt(24)
title_run.font.bold = True
title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_paragraph()
doc.add_paragraph()
theme_para = doc.add_paragraph()
theme_run = theme_para.add_run(f'Theme: {session["user_query"]}')
theme_run.font.size = Pt(14)
theme_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_paragraph()
date_para = doc.add_paragraph()
date_run = date_para.add_run(f'Created: {datetime.now().strftime("%Y-%m-%d")}')
date_run.font.size = Pt(12)
date_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_page_break()
# 전체 톡계
total_words = 0
writer_count = 0
# 각 μž‘κ°€μ˜ μˆ˜μ •λ³Έλ§Œ μˆ˜μ§‘
writer_contents = []
for stage in stages:
if stage['role'].startswith('writer') and 'Revision' in stage['stage_name']:
writer_count += 1
content = stage['content'] or ""
# νŽ˜μ΄μ§€ 마크 제거
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'] or len(content.split())
total_words += word_count
writer_contents.append({
'writer_num': writer_count,
'content': content,
'word_count': word_count
})
# 톡계 νŽ˜μ΄μ§€
doc.add_heading('Novel Statistics', 1)
doc.add_paragraph(f'Total Writers: {writer_count}')
doc.add_paragraph(f'Total Words: {total_words:,}')
doc.add_paragraph(f'Estimated Pages: ~{total_words/500:.0f}')
doc.add_paragraph(f'Language: {session["language"]}')
doc.add_page_break()
# λͺ©μ°¨
doc.add_heading('Table of Contents', 1)
for i in range(1, writer_count + 1):
doc.add_paragraph(f'Chapter {i}: Pages {(i-1)*3+1}-{i*3}')
doc.add_page_break()
# 각 μž‘κ°€μ˜ λ‚΄μš© μΆ”κ°€
for writer_data in writer_contents:
writer_num = writer_data['writer_num']
content = writer_data['content']
word_count = writer_data['word_count']
# 챕터 헀더
doc.add_heading(f'Chapter {writer_num}', 1)
doc.add_paragraph(f'Pages {(writer_num-1)*3+1}-{writer_num*3}')
doc.add_paragraph(f'Word Count: {word_count:,}')
doc.add_paragraph()
# μž‘κ°€ λ‚΄μš© μΆ”κ°€
paragraphs = content.split('\n\n')
for para_text in paragraphs:
if para_text.strip():
para = doc.add_paragraph(para_text.strip())
para.style.font.size = Pt(11)
if writer_num < writer_count: # λ§ˆμ§€λ§‰ μž‘κ°€ ν›„μ—λŠ” νŽ˜μ΄μ§€ ꡬ뢄 μ—†μŒ
doc.add_page_break()
# νŽ˜μ΄μ§€ μ„€μ •
for section in doc.sections:
section.page_height = Inches(11)
section.page_width = Inches(8.5)
section.left_margin = Inches(1)
section.right_margin = Inches(1)
section.top_margin = Inches(1)
section.bottom_margin = Inches(1)
# Save
temp_dir = tempfile.gettempdir()
safe_filename = re.sub(r'[^\w\s-]', '', session['user_query'][:30]).strip()
filename = f"Novel_Complete_{safe_filename}_{timestamp}.docx"
filepath = os.path.join(temp_dir, filename)
doc.save(filepath)
logger.info(f"DOCX saved successfully: {filepath} ({total_words} words)")
return filepath
else:
# TXT format
temp_dir = tempfile.gettempdir()
safe_filename = re.sub(r'[^\w\s-]', '', session['user_query'][:30]).strip()
filename = f"Novel_Complete_{safe_filename}_{timestamp}.txt"
filepath = os.path.join(temp_dir, filename)
with open(filepath, 'w', encoding='utf-8') as f:
f.write("="*60 + "\n")
f.write("AI COLLABORATIVE NOVEL - COMPLETE VERSION\n")
f.write("="*60 + "\n")
f.write(f"Theme: {session['user_query']}\n")
f.write(f"Language: {session['language']}\n")
f.write(f"Created: {datetime.now()}\n")
f.write("="*60 + "\n\n")
total_words = 0
writer_count = 0
# 각 μž‘κ°€μ˜ μˆ˜μ •λ³Έλ§Œ 좜λ ₯
for stage in stages:
if stage['role'].startswith('writer') and 'Revision' in stage['stage_name']:
writer_count += 1
content = stage['content'] or ""
# νŽ˜μ΄μ§€ 마크 제거
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'] or len(content.split())
total_words += word_count
f.write(f"\n{'='*40}\n")
f.write(f"CHAPTER {writer_count} (Pages {(writer_count-1)*3+1}-{writer_count*3})\n")
f.write(f"Word Count: {word_count:,}\n")
f.write(f"{'='*40}\n\n")
f.write(content)
f.write("\n\n")
f.write(f"\n{'='*60}\n")
f.write(f"TOTAL: {writer_count} writers, {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>
</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 / μ–Έμ–΄"
)
# 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],
outputs=[stages_display, novel_output, status_text]
)
# 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],
outputs=[stages_display, novel_output, status_text]
)
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],
outputs=[stages_display, novel_output, status_text]
)
refresh_btn.click(
fn=refresh_sessions,
outputs=[session_dropdown]
)
clear_btn.click(
fn=lambda: ("", "", "πŸ”„ Ready", "", None),
outputs=[stages_display, novel_output, status_text, novel_text_state, current_session_id]
)
def handle_download(format_type, language, session_id, novel_text):
if not session_id:
return gr.update(visible=False)
file_path = download_novel(novel_text, format_type, language, session_id)
if file_path:
return gr.update(value=file_path, visible=True)
else:
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
)