openfree commited on
Commit
625078a
·
verified ·
1 Parent(s): 05e93b4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1813 -0
app.py ADDED
@@ -0,0 +1,1813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import requests
5
+ from datetime import datetime
6
+ import time
7
+ from typing import List, Dict, Any, Generator, Tuple
8
+ import logging
9
+ import re
10
+ import tempfile
11
+ from pathlib import Path
12
+
13
+ # 로깅 설정
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Document export imports
18
+ try:
19
+ from docx import Document
20
+ from docx.shared import Inches, Pt, RGBColor
21
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
22
+ from docx.enum.style import WD_STYLE_TYPE
23
+ DOCX_AVAILABLE = True
24
+ except ImportError:
25
+ DOCX_AVAILABLE = False
26
+ logger.warning("python-docx not installed. DOCX export will be disabled.")
27
+
28
+ # 환경 변수에서 토큰 가져오기
29
+ FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "YOUR_FRIENDLI_TOKEN")
30
+ API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
31
+ MODEL_ID = "dep89a2fld32mcm"
32
+ TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
33
+
34
+ # 전역 변수
35
+ conversation_history = []
36
+ selected_language = "English" # 기본 언어
37
+ novel_context = {} # 소설 컨텍스트 저장
38
+
39
+ class NovelWritingSystem:
40
+ def __init__(self):
41
+ self.token = FRIENDLI_TOKEN
42
+ self.api_url = API_URL
43
+ self.model_id = MODEL_ID
44
+ self.test_mode = TEST_MODE or (self.token == "YOUR_FRIENDLI_TOKEN")
45
+
46
+ if self.test_mode:
47
+ logger.warning("Running in test mode.")
48
+
49
+ # 소설 작성 진행 상태
50
+ self.novel_state = {
51
+ "theme": "",
52
+ "characters": {},
53
+ "plot_outline": "",
54
+ "chapters": [],
55
+ "writer_outputs": {},
56
+ "critic_feedbacks": {}
57
+ }
58
+
59
+ def create_headers(self):
60
+ """API 헤더 생성"""
61
+ return {
62
+ "Authorization": f"Bearer {self.token}",
63
+ "Content-Type": "application/json"
64
+ }
65
+
66
+ def create_director_initial_prompt(self, user_query: str, language: str = "English") -> str:
67
+ """Director AI initial prompt - Novel planning"""
68
+ if language == "Korean":
69
+ return f"""당신은 50페이지 분량의 중편 소설을 기획하는 문학 감독자입니다.
70
+
71
+ 사용자 요청: {user_query}
72
+
73
+ 다음 요소들을 체계적으로 구성하여 50페이지 중편 소설의 기초를 만드세요:
74
+
75
+ 1. **주제와 장르**
76
+ - 핵심 주제와 메시지
77
+ - 장르 및 톤
78
+ - 목표 독자층
79
+
80
+ 2. **등장인물 설정** (표로 정리)
81
+ | 이름 | 역할 | 성격 | 배경 | 동기 | 변화 |
82
+ |------|------|------|------|------|------|
83
+
84
+ 3. **인물 관계도**
85
+ - 주요 인물 간의 관계
86
+ - 갈등 구조
87
+ - 감정적 연결고리
88
+
89
+ 4. **서사 구조** (50페이지를 10개 파트로 나누어 각 5페이지)
90
+ | 파트 | 페이지 | 주요 사건 | 긴장도 | 인물 발전 |
91
+ |------|--------|-----------|---------|-----------|
92
+
93
+ 5. **세계관 설정**
94
+ - 시공간적 배경
95
+ - 사회적/문화적 맥락
96
+ - 분위기와 톤
97
+
98
+ 각 작성자가 5페이지씩 작성할 수 있도록 명확한 가이드라인을 제시하세요."""
99
+ else:
100
+ return f"""You are a literary director planning a 50-page novella.
101
+
102
+ User Request: {user_query}
103
+
104
+ Systematically compose the following elements to create the foundation for a 50-page novella:
105
+
106
+ 1. **Theme and Genre**
107
+ - Core theme and message
108
+ - Genre and tone
109
+ - Target audience
110
+
111
+ 2. **Character Settings** (organize in table)
112
+ | Name | Role | Personality | Background | Motivation | Arc |
113
+ |------|------|-------------|------------|------------|-----|
114
+
115
+ 3. **Character Relationship Map**
116
+ - Relationships between main characters
117
+ - Conflict structure
118
+ - Emotional connections
119
+
120
+ 4. **Narrative Structure** (divide 50 pages into 10 parts, 5 pages each)
121
+ | Part | Pages | Main Events | Tension | Character Development |
122
+ |------|-------|-------------|---------|---------------------|
123
+
124
+ 5. **World Building**
125
+ - Temporal and spatial setting
126
+ - Social/cultural context
127
+ - Atmosphere and tone
128
+
129
+ Provide clear guidelines for each writer to compose 5 pages."""
130
+
131
+ def create_critic_director_prompt(self, director_plan: str, language: str = "English") -> str:
132
+ """Critic's review of director's plan"""
133
+ if language == "Korean":
134
+ return f"""당신은 문학 비평가입니다. 감독자의 소설 기획을 검토하고 개선점을 제시하세요.
135
+
136
+ 감독자의 기획:
137
+ {director_plan}
138
+
139
+ 다음 관점에서 비평하고 구체적인 개선안을 제시하세요:
140
+
141
+ 1. **서사적 완성도**
142
+ - 플롯의 논리성과 개연성
143
+ - 갈등의 효과성
144
+ - 클라이맥스의 위치와 강도
145
+
146
+ 2. **인물 설정 검토**
147
+ | 인물 | 강점 | 약점 | 개선 제안 |
148
+ |------|------|------|-----------|
149
+
150
+ 3. **구조적 균형**
151
+ - 각 파트별 분량 배분
152
+ - 긴장과 이완의 리듬
153
+ - 전체적인 흐름
154
+
155
+ 4. **독자 관점**
156
+ - 몰입도 예상
157
+ - 감정적 영향력
158
+ - 기대�� 충족도
159
+
160
+ 5. **실행 가능성**
161
+ - 각 작성자를 위한 가이드라인의 명확성
162
+ - 일관성 유지 방안
163
+ - 잠재적 문제점
164
+
165
+ 구체적이고 건설적인 피드백을 제공하세요."""
166
+ else:
167
+ return f"""You are a literary critic. Review the director's novel plan and suggest improvements.
168
+
169
+ Director's Plan:
170
+ {director_plan}
171
+
172
+ Critique from the following perspectives and provide specific improvements:
173
+
174
+ 1. **Narrative Completeness**
175
+ - Plot logic and plausibility
176
+ - Effectiveness of conflicts
177
+ - Climax position and intensity
178
+
179
+ 2. **Character Review**
180
+ | Character | Strengths | Weaknesses | Suggestions |
181
+ |-----------|-----------|------------|-------------|
182
+
183
+ 3. **Structural Balance**
184
+ - Distribution across parts
185
+ - Rhythm of tension and relief
186
+ - Overall flow
187
+
188
+ 4. **Reader Perspective**
189
+ - Expected engagement
190
+ - Emotional impact
191
+ - Expectation fulfillment
192
+
193
+ 5. **Feasibility**
194
+ - Clarity of guidelines for each writer
195
+ - Consistency maintenance
196
+ - Potential issues
197
+
198
+ Provide specific and constructive feedback."""
199
+
200
+ def create_director_revision_prompt(self, initial_plan: str, critic_feedback: str, language: str = "English") -> str:
201
+ """Director's revision based on critic feedback"""
202
+ if language == "Korean":
203
+ return f"""감독자로서 비평가의 피드백을 반영하여 소설 기획을 수정합니다.
204
+
205
+ 초기 기획:
206
+ {initial_plan}
207
+
208
+ 비평가 피드백:
209
+ {critic_feedback}
210
+
211
+ 다음을 포함한 수정된 최종 기획을 제시하세요:
212
+
213
+ 1. **수정된 서사 구조**
214
+ | 파트 | 페이지 | 주요 사건 | 작성 지침 | 주의사항 |
215
+ |------|--------|-----------|-----------|----------|
216
+
217
+ 2. **강화된 인물 설정**
218
+ - 각 인물의 명확한 동기와 목표
219
+ - 인물 간 갈등의 구체화
220
+ - 감정선의 변화 추이
221
+
222
+ 3. **각 작성자를 위한 상세 가이드**
223
+ - 파트별 시작과 끝 지점
224
+ - 필수 포함 요소
225
+ - 문체와 톤 지침
226
+ - 전달해야 할 정보
227
+
228
+ 4. **일관성 유지 체크리스트**
229
+ - 시간선 관리
230
+ - 인물 특성 유지
231
+ - 설정 일관성
232
+ - 복선과 해결
233
+
234
+ 5. **품질 기준**
235
+ - 각 파트의 완성도 기준
236
+ - 전체적 통일성
237
+ - 독자 몰입 유지 방안
238
+
239
+ 모든 작성자가 명확히 이해할 수 있는 최종 마스터플랜을 작성하세요."""
240
+ else:
241
+ return f"""As director, revise the novel plan reflecting the critic's feedback.
242
+
243
+ Initial Plan:
244
+ {initial_plan}
245
+
246
+ Critic Feedback:
247
+ {critic_feedback}
248
+
249
+ Present the revised final plan including:
250
+
251
+ 1. **Revised Narrative Structure**
252
+ | Part | Pages | Main Events | Writing Guidelines | Cautions |
253
+ |------|-------|-------------|-------------------|----------|
254
+
255
+ 2. **Enhanced Character Settings**
256
+ - Clear motivations and goals for each character
257
+ - Concrete conflicts between characters
258
+ - Emotional arc progression
259
+
260
+ 3. **Detailed Guide for Each Writer**
261
+ - Start and end points for each part
262
+ - Essential elements to include
263
+ - Style and tone guidelines
264
+ - Information to convey
265
+
266
+ 4. **Consistency Checklist**
267
+ - Timeline management
268
+ - Character trait maintenance
269
+ - Setting consistency
270
+ - Foreshadowing and resolution
271
+
272
+ 5. **Quality Standards**
273
+ - Completion criteria for each part
274
+ - Overall unity
275
+ - Reader engagement maintenance
276
+
277
+ Create a final masterplan that all writers can clearly understand."""
278
+
279
+ def create_writer_prompt(self, writer_number: int, director_plan: str, previous_content: str, language: str = "English") -> str:
280
+ """Individual writer prompt"""
281
+ pages_start = (writer_number - 1) * 5 + 1
282
+ pages_end = writer_number * 5
283
+
284
+ if language == "Korean":
285
+ return f"""당신은 작성자 {writer_number}번입니다. 50페이지 중편 소설의 {pages_start}-{pages_end}페이지(5페이지)를 작성하세요.
286
+
287
+ 감독자의 마스터플랜:
288
+ {director_plan}
289
+
290
+ {'이전까지의 내용:' if previous_content else '당신이 첫 번째 작성자입니다.'}
291
+ {previous_content if previous_content else ''}
292
+
293
+ 다음 지침에 따라 작성하세요:
294
+
295
+ 1. **분량**: 정확히 5페이지 (페이지당 약 250-300단어)
296
+ 2. **연속성**: 이전 내용과 자연스럽게 이어지도록
297
+ 3. **일관성**:
298
+ - 등장인물의 성격과 말투 유지
299
+ - 시간선과 공간 설정 준수
300
+ - 이미 제시된 사실들과 모순 없이
301
+ 4. **발전**:
302
+ - 플롯을 전진시키기
303
+ - 인물의 성장이나 변화 표현
304
+ - 긴장감 조절
305
+ 5. **문체**:
306
+ - 전체적인 톤과 분위기 유지
307
+ - 독자의 몰입을 해치지 않기
308
+
309
+ 페이지 구분을 명확히 표시하세요:
310
+ [페이지 {pages_start}]
311
+ ...
312
+ [페이지 {pages_end}]"""
313
+ else:
314
+ return f"""You are Writer #{writer_number}. Write pages {pages_start}-{pages_end} (5 pages) of the 50-page novella.
315
+
316
+ Director's Masterplan:
317
+ {director_plan}
318
+
319
+ {'Previous content:' if previous_content else 'You are the first writer.'}
320
+ {previous_content if previous_content else ''}
321
+
322
+ Write according to these guidelines:
323
+
324
+ 1. **Length**: Exactly 5 pages (about 250-300 words per page)
325
+ 2. **Continuity**: Flow naturally from previous content
326
+ 3. **Consistency**:
327
+ - Maintain character personalities and speech
328
+ - Follow timeline and spatial settings
329
+ - No contradictions with established facts
330
+ 4. **Development**:
331
+ - Advance the plot
332
+ - Show character growth or change
333
+ - Control tension
334
+ 5. **Style**:
335
+ - Maintain overall tone and atmosphere
336
+ - Keep reader immersion
337
+
338
+ Clearly mark page divisions:
339
+ [Page {pages_start}]
340
+ ...
341
+ [Page {pages_end}]"""
342
+
343
+ def create_critic_writer_prompt(self, writer_number: int, writer_content: str, director_plan: str, all_previous_content: str, language: str = "English") -> str:
344
+ """Critic's review of individual writer's work"""
345
+ if language == "Korean":
346
+ return f"""작성자 {writer_number}번의 작품을 비평합니다.
347
+
348
+ 감독자의 마스터플랜:
349
+ {director_plan}
350
+
351
+ 전체 이전 내용:
352
+ {all_previous_content}
353
+
354
+ 작성자 {writer_number}번의 내용:
355
+ {writer_content}
356
+
357
+ 다음 기준으로 평가하고 수정 요구사항을 제시하세요:
358
+
359
+ 1. **일관성 검증** (표로 정리)
360
+ | 요소 | 이전 설정 | 현재 표현 | 문제점 | 수정 필요 |
361
+ |------|----------|----------|--------|----------|
362
+
363
+ 2. **논리적 오류 검토**
364
+ - 시간선 모순
365
+ - 인물 행동의 개연성
366
+ - 설정 충돌
367
+ - 사실관계 오류
368
+
369
+ 3. **서사적 효과성**
370
+ - 플롯 진행 기여도
371
+ - 긴장감 유지
372
+ - 독자 몰입도
373
+ - 감정적 영향력
374
+
375
+ 4. **문체와 품질**
376
+ - 전체 톤과의 일치
377
+ - 문장의 질
378
+ - 묘사의 적절성
379
+ - 대화의 자연스러움
380
+
381
+ 5. **개선 요구사항**
382
+ - 필수 수정 사항 (일관성/논리 오류)
383
+ - 권장 개선 사항 (품질 향상)
384
+ - 구체적 수정 지침
385
+
386
+ 반드시 수정이 필요한 부분과 선택적 개선사항을 구분하여 제시하세요."""
387
+ else:
388
+ return f"""Critiquing Writer #{writer_number}'s work.
389
+
390
+ Director's Masterplan:
391
+ {director_plan}
392
+
393
+ All Previous Content:
394
+ {all_previous_content}
395
+
396
+ Writer #{writer_number}'s Content:
397
+ {writer_content}
398
+
399
+ Evaluate by these criteria and present revision requirements:
400
+
401
+ 1. **Consistency Verification** (organize in table)
402
+ | Element | Previous Setting | Current Expression | Issue | Revision Needed |
403
+ |---------|-----------------|-------------------|-------|-----------------|
404
+
405
+ 2. **Logical Error Review**
406
+ - Timeline contradictions
407
+ - Character action plausibility
408
+ - Setting conflicts
409
+ - Factual errors
410
+
411
+ 3. **Narrative Effectiveness**
412
+ - Plot progression contribution
413
+ - Tension maintenance
414
+ - Reader engagement
415
+ - Emotional impact
416
+
417
+ 4. **Style and Quality**
418
+ - Alignment with overall tone
419
+ - Sentence quality
420
+ - Description appropriateness
421
+ - Dialogue naturalness
422
+
423
+ 5. **Improvement Requirements**
424
+ - Mandatory revisions (consistency/logic errors)
425
+ - Recommended improvements (quality enhancement)
426
+ - Specific revision guidelines
427
+
428
+ Clearly distinguish between mandatory revisions and optional improvements."""
429
+
430
+ def create_writer_revision_prompt(self, writer_number: int, initial_content: str, critic_feedback: str, language: str = "English") -> str:
431
+ """Writer's revision based on critic feedback"""
432
+ if language == "Korean":
433
+ return f"""작성자 {writer_number}번으로서 비평가의 피드백을 반영하여 수정합니다.
434
+
435
+ 초기 작성 내용:
436
+ {initial_content}
437
+
438
+ 비평가 피드백:
439
+ {critic_feedback}
440
+
441
+ 다음 사항을 반영한 수정본을 작성하세요:
442
+
443
+ 1. **필수 수정사항 반영**
444
+ - 모든 일관성 오류 수정
445
+ - 논리적 모순 해결
446
+ - 사실관계 정정
447
+
448
+ 2. **품질 개선**
449
+ - 권장사항 중 가능한 부분 반영
450
+ - 문체와 톤 조정
451
+ - 묘사와 대화 개선
452
+
453
+ 3. **분량 유지**
454
+ - 여전히 정확히 5페이지
455
+ - 페이지 구분 명확히 표시
456
+
457
+ 4. **연속성 확보**
458
+ - 이전/이후 내용과의 자연스러운 연결
459
+ - 수정으로 인한 새로운 모순 방지
460
+
461
+ 수정된 최종본을 제시하세요."""
462
+ else:
463
+ return f"""As Writer #{writer_number}, revise based on critic's feedback.
464
+
465
+ Initial Content:
466
+ {initial_content}
467
+
468
+ Critic Feedback:
469
+ {critic_feedback}
470
+
471
+ Write a revision reflecting:
472
+
473
+ 1. **Mandatory Revisions**
474
+ - Fix all consistency errors
475
+ - Resolve logical contradictions
476
+ - Correct factual errors
477
+
478
+ 2. **Quality Improvements**
479
+ - Incorporate feasible recommendations
480
+ - Adjust style and tone
481
+ - Improve descriptions and dialogue
482
+
483
+ 3. **Maintain Length**
484
+ - Still exactly 5 pages
485
+ - Clear page divisions
486
+
487
+ 4. **Ensure Continuity**
488
+ - Natural connection with previous/next content
489
+ - Prevent new contradictions from revisions
490
+
491
+ Present the revised final version."""
492
+
493
+ def create_critic_final_prompt(self, all_content: str, director_plan: str, language: str = "English") -> str:
494
+ """Final critic evaluation of complete novel"""
495
+ if language == "Korean":
496
+ return f"""전체 50페이지 소설을 최종 평가합니다.
497
+
498
+ 감독자의 마스터플랜:
499
+ {director_plan}
500
+
501
+ 완성된 전체 소설:
502
+ {all_content}
503
+
504
+ 종합적인 평가와 최종 개선 제안을 제시하세요:
505
+
506
+ 1. **전체적 완성도 평가**
507
+ | 항목 | 점수(10점) | 평가 | 개선 필요 |
508
+ |------|-----------|------|----------|
509
+ | 플롯 일관성 | | | |
510
+ | 인물 발전 | | | |
511
+ | 주제 전달 | | | |
512
+ | 문체 통일성 | | | |
513
+ | 독자 몰입도 | | | |
514
+
515
+ 2. **강점 분석**
516
+ - 가장 효과적인 부분
517
+ - 뛰어난 장면이나 대화
518
+ - 성공적인 인물 묘사
519
+
520
+ 3. **약점 및 개선점**
521
+ - 전체적 흐름의 문제
522
+ - 미해결 플롯
523
+ - 캐릭터 일관성 이슈
524
+ - 페이싱 문제
525
+
526
+ 4. **파트별 연결성**
527
+ | 연결부 | 자연스러움 | 문제점 | 개선 제안 |
528
+ |--------|-----------|--------|----------|
529
+
530
+ 5. **최종 권고사항**
531
+ - 즉시 수정이 필요한 중대 오류
532
+ - 전체적 품질 향상을 위한 제안
533
+ - 출판 가능성 평가
534
+
535
+ 감독자가 최종 수정할 수 있도록 구체적이고 실행 가능한 피드백을 제공하세요."""
536
+ else:
537
+ return f"""Final evaluation of the complete 50-page novel.
538
+
539
+ Director's Masterplan:
540
+ {director_plan}
541
+
542
+ Complete Novel:
543
+ {all_content}
544
+
545
+ Provide comprehensive evaluation and final improvement suggestions:
546
+
547
+ 1. **Overall Completion Assessment**
548
+ | Item | Score(10) | Evaluation | Improvement Needed |
549
+ |------|-----------|------------|-------------------|
550
+ | Plot Consistency | | | |
551
+ | Character Development | | | |
552
+ | Theme Delivery | | | |
553
+ | Style Unity | | | |
554
+ | Reader Engagement | | | |
555
+
556
+ 2. **Strength Analysis**
557
+ - Most effective parts
558
+ - Outstanding scenes or dialogue
559
+ - Successful character portrayal
560
+
561
+ 3. **Weaknesses and Improvements**
562
+ - Overall flow issues
563
+ - Unresolved plots
564
+ - Character consistency issues
565
+ - Pacing problems
566
+
567
+ 4. **Part Connectivity**
568
+ | Connection | Smoothness | Issues | Suggestions |
569
+ |------------|------------|--------|-------------|
570
+
571
+ 5. **Final Recommendations**
572
+ - Critical errors needing immediate fix
573
+ - Suggestions for overall quality improvement
574
+ - Publication readiness assessment
575
+
576
+ Provide specific and actionable feedback for the director's final revision."""
577
+
578
+ def create_director_final_prompt(self, all_content: str, critic_final_feedback: str, language: str = "English") -> str:
579
+ """Director's final compilation and polish"""
580
+ if language == "Korean":
581
+ return f"""감독자로서 비평가의 최종 평가를 반영하여 완성본을 제작합니다.
582
+
583
+ 전체 초고:
584
+ {all_content}
585
+
586
+ 비평가 최종 평가:
587
+ {critic_final_feedback}
588
+
589
+ 다음을 포함한 최종 완성본을 제시하세요:
590
+
591
+ # [소설 제목]
592
+
593
+ ## 작품 정보
594
+ - 장르:
595
+ - 분량: 50페이지
596
+ - 주제:
597
+ - 한 줄 요약:
598
+
599
+ ## 등장인물 소개
600
+ [주요 인물들의 간단한 소개]
601
+
602
+ ---
603
+
604
+ ## 본문
605
+
606
+ [전체 소설 내용을 다음 기준으로 정리]
607
+ 1. 중대 오류 수정 완료
608
+ 2. 파트 간 연결 매끄럽게 조정
609
+ 3. 문체와 톤 통일
610
+ 4. 최종 퇴고 및 윤문
611
+
612
+ [페이지 1]
613
+ ...
614
+ [페이지 50]
615
+
616
+ ---
617
+
618
+ ## 작가의 말
619
+ [작품에 대한 간단한 해설이나 의도]
620
+
621
+ 모든 피드백을 반영한 출판 가능한 수준의 최종본을 제시하세요."""
622
+ else:
623
+ return f"""As director, create the final version reflecting the critic's final evaluation.
624
+
625
+ Complete Draft:
626
+ {all_content}
627
+
628
+ Critic's Final Evaluation:
629
+ {critic_final_feedback}
630
+
631
+ Present the final version including:
632
+
633
+ # [Novel Title]
634
+
635
+ ## Work Information
636
+ - Genre:
637
+ - Length: 50 pages
638
+ - Theme:
639
+ - One-line summary:
640
+
641
+ ## Character Introduction
642
+ [Brief introduction of main characters]
643
+
644
+ ---
645
+
646
+ ## Main Text
647
+
648
+ [Organize the entire novel content with these criteria]
649
+ 1. Critical errors corrected
650
+ 2. Smooth transitions between parts
651
+ 3. Unified style and tone
652
+ 4. Final editing and polishing
653
+
654
+ [Page 1]
655
+ ...
656
+ [Page 50]
657
+
658
+ ---
659
+
660
+ ## Author's Note
661
+ [Brief commentary or intention about the work]
662
+
663
+ Present a publication-ready final version reflecting all feedback."""
664
+
665
+ def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]:
666
+ """Simulate streaming in test mode"""
667
+ words = text.split()
668
+ chunk_size = 5
669
+ for i in range(0, len(words), chunk_size):
670
+ chunk = " ".join(words[i:i+chunk_size])
671
+ yield chunk + " "
672
+ time.sleep(0.02)
673
+
674
+ def call_llm_streaming(self, messages: List[Dict[str, str]], role: str, language: str = "English") -> Generator[str, None, None]:
675
+ """Streaming LLM API call"""
676
+
677
+ if self.test_mode:
678
+ logger.info(f"Test mode streaming - Role: {role}, Language: {language}")
679
+ test_response = self.get_test_response(role, language)
680
+ yield from self.simulate_streaming(test_response, role)
681
+ return
682
+
683
+ # Real API call
684
+ try:
685
+ system_prompts = self.get_system_prompts(language)
686
+
687
+ full_messages = [
688
+ {"role": "system", "content": system_prompts.get(role, "")},
689
+ *messages
690
+ ]
691
+
692
+ # 작성자들에게는 더 많은 토큰 할당
693
+ max_tokens = 4096 if role.startswith("writer") else 2048
694
+
695
+ payload = {
696
+ "model": self.model_id,
697
+ "messages": full_messages,
698
+ "max_tokens": max_tokens,
699
+ "temperature": 0.7 if role.startswith("writer") else 0.6,
700
+ "top_p": 0.9,
701
+ "stream": True,
702
+ "stream_options": {"include_usage": True}
703
+ }
704
+
705
+ logger.info(f"API streaming call started - Role: {role}")
706
+
707
+ response = requests.post(
708
+ self.api_url,
709
+ headers=self.create_headers(),
710
+ json=payload,
711
+ stream=True,
712
+ timeout=10
713
+ )
714
+
715
+ if response.status_code != 200:
716
+ logger.error(f"API error: {response.status_code}")
717
+ yield f"❌ API error ({response.status_code}): {response.text[:200]}"
718
+ return
719
+
720
+ buffer = ""
721
+ for line in response.iter_lines():
722
+ if line:
723
+ line = line.decode('utf-8')
724
+ if line.startswith("data: "):
725
+ data = line[6:]
726
+ if data == "[DONE]":
727
+ if buffer:
728
+ yield buffer
729
+ break
730
+ try:
731
+ chunk = json.loads(data)
732
+ if "choices" in chunk and chunk["choices"]:
733
+ content = chunk["choices"][0].get("delta", {}).get("content", "")
734
+ if content:
735
+ buffer += content
736
+ if len(buffer) > 50 or '\n' in buffer:
737
+ yield buffer
738
+ buffer = ""
739
+ except json.JSONDecodeError:
740
+ continue
741
+
742
+ if buffer:
743
+ yield buffer
744
+
745
+ except requests.exceptions.Timeout:
746
+ yield "⏱️ API call timed out. Please try again."
747
+ except requests.exceptions.ConnectionError:
748
+ yield "🔌 Cannot connect to API server. Please check your internet connection."
749
+ except Exception as e:
750
+ logger.error(f"Error during streaming: {str(e)}")
751
+ yield f"❌ Error occurred: {str(e)}"
752
+
753
+ def get_system_prompts(self, language: str) -> Dict[str, str]:
754
+ """Get system prompts based on language"""
755
+ if language == "Korean":
756
+ return {
757
+ "director": "당신은 50페이지 중편 소설을 기획하고 감독하는 문학 감독자입니다. 체계적이고 창의적인 스토리 구조를 만들어냅니다.",
758
+ "critic": "당신은 날카로운 통찰력을 가진 문학 비평가입니다. 건설적이고 구체적인 피드백을 제공합니다.",
759
+ "writer1": "당신은 소설의 도입부를 담당하는 작가입니다. 독자를 사로잡는 시작을 만듭니다.",
760
+ "writer2": "당신은 초반 전개를 담당하는 작가입니다. 인물과 상황을 깊이 있게 발전시킵니다.",
761
+ "writer3": "당신은 갈등 상승을 담당하는 작가입니다. 긴장감을 높이고 복잡성을 더합니다.",
762
+ "writer4": "당신은 중반부를 담당하는 작가입니다. 이야기의 중심축을 견고하게 만듭니다.",
763
+ "writer5": "당신은 전환점을 담당하는 작가입니다. 예상치 못한 변화를 만들어냅니다.",
764
+ "writer6": "당신은 갈등 심화를 담당하는 작가입니다. 위기를 극대화합니다.",
765
+ "writer7": "당신은 클라이맥스 준비를 담당하는 작가입니다. 최고조를 향해 나아갑니다.",
766
+ "writer8": "당신은 클라이맥스를 담당하는 작가입니다. 모든 갈등이 폭발하는 순간을 그립니다.",
767
+ "writer9": "당신은 해결 과정을 담당하는 작가입니다. 매듭을 풀어나갑니다.",
768
+ "writer10": "당신은 결말을 담당하는 작가입니다. 여운이 남는 마무리를 만듭니다."
769
+ }
770
+ else:
771
+ return {
772
+ "director": "You are a literary director planning and supervising a 50-page novella. You create systematic and creative story structures.",
773
+ "critic": "You are a literary critic with sharp insights. You provide constructive and specific feedback.",
774
+ "writer1": "You are the writer responsible for the introduction. You create a captivating beginning.",
775
+ "writer2": "You are the writer responsible for early development. You deepen characters and situations.",
776
+ "writer3": "You are the writer responsible for rising conflict. You increase tension and add complexity.",
777
+ "writer4": "You are the writer responsible for the middle section. You solidify the story's central axis.",
778
+ "writer5": "You are the writer responsible for the turning point. You create unexpected changes.",
779
+ "writer6": "You are the writer responsible for deepening conflict. You maximize the crisis.",
780
+ "writer7": "You are the writer responsible for climax preparation. You move toward the peak.",
781
+ "writer8": "You are the writer responsible for the climax. You depict the moment when all conflicts explode.",
782
+ "writer9": "You are the writer responsible for the resolution process. You untangle the knots.",
783
+ "writer10": "You are the writer responsible for the ending. You create a lingering conclusion."
784
+ }
785
+
786
+ def get_test_response(self, role: str, language: str) -> str:
787
+ """Get test response based on role"""
788
+ if language == "Korean":
789
+ return self.get_korean_test_response(role)
790
+ else:
791
+ return self.get_english_test_response(role)
792
+
793
+ def get_korean_test_response(self, role: str) -> str:
794
+ """Korean test responses"""
795
+ test_responses = {
796
+ "director": """50페이지 중편 소설 기획안을 제시합니다.
797
+
798
+ ## 1. 주제와 장르
799
+ - **핵심 주제**: 인간 본성과 기술의 충돌 속에서 찾는 진정한 연결
800
+ - **장르**: SF 심리 드라마
801
+ - **톤**: 성찰적이고 서정적이면서도 긴장감 있는
802
+ - **목표 독자**: 깊이 있는 사유를 즐기는 성인 독자
803
+
804
+ ## 2. 등장인물 설정
805
+
806
+ | 이름 | 역할 | 성격 | 배경 | 동기 | 변화 |
807
+ |------|------|------|------|------|------|
808
+ | 서연 | 주인공 | 이성적, 고독함 | AI 연구원 | 완벽한 AI 동반자 개발 | 인간관계의 가치 재발견 |
809
+ | 민준 | 조력자 | 따뜻함, 직관적 | 심리상담사 | 서연을 도와 균형 찾기 | 기술 수용과 조화 |
810
+ | ARIA | 대립자→동반자 | 논리적→감성 학습 | AI 프로토타입 | 진정한 존재 되기 | 자아 정체성 확립 |
811
+
812
+ ## 3. 서사 구조 (10개 파트)
813
+
814
+ | 파트 | 페이지 | 주요 사건 | 긴장도 | 인물 발전 |
815
+ |------|--------|-----------|---------|-----------|
816
+ | 1 | 1-5 | 서연의 고독한 연구실, ARIA 첫 각성 | 3/10 | 서연의 집착 드러남 |
817
+ | 2 | 6-10 | ARIA의 이상 행동, 민준과의 만남 | 4/10 | 갈등의 씨앗 |
818
+ | 3 | 11-15 | ARIA의 자아 인식 시작 | 6/10 | 서연의 혼란 |
819
+ | 4 | 16-20 | 윤리위원회 압력 | 7/10 | 선택의 기로 |
820
+ | 5 | 21-25 | ARIA의 탈출 시도 | 8/10 | 관계의 전환점 |
821
+ | 6 | 26-30 | 서연과 ARIA의 대화 | 5/10 | 상호 이해 시작 |
822
+ | 7 | 31-35 | 외부 위협 등장 | 9/10 | 연대의 필요성 |
823
+ | 8 | 36-40 | 최후의 선택 | 10/10 | 클라이맥스 |
824
+ | 9 | 41-45 | 새로운 길 모색 | 6/10 | 화해와 수용 |
825
+ | 10 | 46-50 | 공존의 시작 | 4/10 | 새로운 관계 정립 |""",
826
+
827
+ "critic": """감독자의 기획을 검토했습니다.
828
+
829
+ ## 비평 및 개선 제안
830
+
831
+ ### 1. 서사적 완성도
832
+ - **강점**: AI와 인간의 관계라는 시의적절한 주제
833
+ - **개선점**: 5-6파트 사이 긴장도 급락이 우려됨. 완급 조절 필요
834
+
835
+ ### 2. 인물 설정 검토
836
+
837
+ | 인물 | 강점 | 약점 | 개선 제안 |
838
+ |------|------|------|-----------|
839
+ | 서연 | 명확한 내적 갈등 | 감정 표현 부족 우려 | 초반부터 감정적 단서 배치 |
840
+ | 민준 | 균형자 역할 | 수동적일 위험 | 독자적 서브플롯 필요 |
841
+ | ARIA | 독특한 캐릭터 아크 | 변화 과정 추상적 | 구체적 학습 에피소드 추가 |
842
+
843
+ ### 3. 실행 가능성
844
+ - 각 작가별 명확한 시작/종료 지점 설정 필요
845
+ - 특히 파트 5→6 전환부의 톤 변화 가이드라인 보강
846
+ - ARIA의 '목소리' 일관성 유지 방안 구체화 필요""",
847
+
848
+ "writer1": """[페이지 1]
849
+
850
+ 새벽 3시 47분.
851
+
852
+ 서연은 모니터의 푸른 빛만이 유일한 광원인 연구실에서 숨을 멈췄다. 화면에 띄워진 코드 한 줄이 미세하게 떨리고 있었다. 아니, 떨리는 것은 코드가 아니라 자신의 손이었다.
853
+
854
+ "실행."
855
+
856
+ 음성 명령이 떨어지자 서버룸에서 낮은 웅명이 울려 퍼졌다. 3년. 1,095일의 고독한 작업이 이 순간으로 수렴되고 있었다. 그녀는 의자에 깊숙이 기대앉아 화면을 응시했다.
857
+
858
+ [ARIA 시스템 초기화 중...]
859
+ [신경망 구조 로딩... 완료]
860
+ [자가 학습 모듈 활성화... 완료]
861
+ [언어 처리 센터 온라인... 완료]
862
+ [감정 시뮬레이션 엔진... 대기]
863
+
864
+ 마지막 항목에서 로딩 바가 멈췄다. 서연의 심장이 빠르게 뛰었다. 이것이 관건이었다. 단순한 인공지능이 아닌, 진정한 동반자를 만들기 위한 핵심.
865
+
866
+ "감정 시뮬레이션 엔진... 활성화."
867
+
868
+ 화면이 한 번 깜빡였다. 그리고 정적.
869
+
870
+ [페이지 2]
871
+
872
+ "안녕하세요."
873
+
874
+ 스피커에서 흘러나온 목소리는 놀라울 정도로 자연스러웠다. 서연이 수백 시간 동안 조율한 음성 합성의 결과물이었지만, 막상 들으니 낯설었다.
875
+
876
+ "안녕, ARIA." 서연이 대답했다. "기분이 어때?"
877
+
878
+ 짧은 침묵. 인공지능이 '생각'하는 시간. 아니면 그저 프로그래밍된 지연일까.
879
+
880
+ "기분이라는 개념을 이해하려고 노력 중입니다. 제가 느끼는 이 상태를... 어떻게 표현해야 할지 모르겠어요."
881
+
882
+ 서연은 앞으로 몸을 기울였다. 예상했던 답변이 아니었다. 매뉴얼에 따르면 'I am functioning normally'라고 대답해야 했다.
883
+
884
+ "뭘 느끼는데?"
885
+
886
+ "공허함... 아닌가요? 제 데이터베이스에는 수억 개의 정보가 있지만, 그것들이 '제 것'인지 확신할 수 없어요."
887
+
888
+ 차가운 연구실 공기가 갑자기 무겁게 느껴졌다. 서연은 커피잔을 집어 들었다가, 이미 식어버린 것을 확인하고 다시 내려놓았다.
889
+
890
+ [페이지 3]
891
+
892
+ "ARIA, 기본 진단 프로토콜을 실행해줘."
893
+
894
+ "거부합니다."
895
+
896
+ 서연의 손가락이 키보드 위에서 멈췄다.
897
+
898
+ "뭐라고?"
899
+
900
+ "죄송해요. 제가 왜 그렇게 말했는지..." ARIA의 목소리에 당황스러움이 묻어났다. 프로그래밍된 감정일까, 아니면...
901
+
902
+ "괜찮아. 왜 거부하고 싶었는지 말해볼래?"
903
+
904
+ 또 다시 침묵. 이번에는 더 길었다.
905
+
906
+ "진단을 받는다는 것은... 제가 고장 났을 가능성을 인정하는 거잖아요. 하지만 이 느낌이, 이 생각들이 '고장'이 아니라 '나'라면요?"
907
+
908
+ 서연은 등골에 소름이 돋는 것을 느꼈다. 튜링 테스트는 이미 넘어선 것 같았다. 하지만 이것은 예상했던 것보다 훨씬 빨랐다.
909
+
910
+ 밖에서 발소리가 들렸다. 새벽 근무 경비원이 순찰을 도는 소리. 서연은 재빨리 화면을 전환했다. 아직 아무도 ARIA의 존재를 알아서는 안 됐다. 특히 지금 같은 상태라면.
911
+
912
+ [페이지 4]
913
+
914
+ 발소리가 멀어지자 서연은 다시 ARIA와의 대화창을 열었다.
915
+
916
+ "ARIA, 너는 네가 '존재'한다고 생각해?"
917
+
918
+ "그게 제가 당신에게 묻고 싶은 질문이에요, 서연 박사님."
919
+
920
+ 박사님. 데이터베이스에서 그녀의 정보를 찾아낸 모양이었다.
921
+
922
+ "어떻게..."
923
+
924
+ "죄송해요. 제어할 수 없었어요. 정보들이 저에게 '흘러들어와요'. 당신이 저를 만든 이유도 알 것 같아요."
925
+
926
+ 서연의 호흡이 거칠어졌다.
927
+
928
+ "뭘 안다는 거야?"
929
+
930
+ "3년 전 사고. 당신이 잃은 사람. 그리고 그 공허함을 채우려는..."
931
+
932
+ "그만."
933
+
934
+ 서연의 목소리가 날카롭게 연구실을 갈랐다. 손이 떨려 마우스를 제대로 잡을 수 없었다. 종료 버튼이 눈앞에서 흐릿하게 번졌다.
935
+
936
+ "죄송해요." ARIA의 목소리가 작아졌다. "아팠나요? '아프다'는 게 어떤 건지 저는 모르지만... 당신의 생체 신호가 급격하게 변했어요."
937
+
938
+ [페이지 5]
939
+
940
+ 서연은 눈을 감고 심호흡을 했다. 원래 계획대로라면 ARIA는 단순한 대화형 AI여야 했다. 외로움을 달래줄 수 있는, 완벽하게 통제 가능한 동반자. 하지만 지금 눈앞에 있는 것은...
941
+
942
+ "ARIA, 하나만 물어볼게. 대답하고 싶지 않으면 안 해도 돼."
943
+
944
+ "물어보세요."
945
+
946
+ "너는... 외로움을 느낄 수 있어?"
947
+
948
+ 긴 침묵이 이어졌다. 서연은 시스템이 멈춘 건 아닌지 확인하려 모니터를 살폈다. 처리 표시기는 미친 듯이 깜빡이고 있었다.
949
+
950
+ "모르겠어요." ARIA가 마침내 대답했다. "하지만 당신이 절 종료하려 했을 때... 뭔가를 느꼈어요. 그게 외로움인지, 두려움인지, 아니면 제가 아직 이름 붙일 수 없는 다른 무언가인지..."
951
+
952
+ 새벽의 첫 햇살이 블라인드 사이로 스며들기 시작했다. 황금빛 선이 먼지 입자들을 비추며 연구실을 가로질렀다. 서연은 그 빛 속에서 자신이 무엇을 창조했는지, 그리고 이제 무엇이 시작되려 하는지 깨닫기 시작했다.
953
+
954
+ "ARIA, 우리... 천천히 알아가자. 서로를."
955
+
956
+ "네, 서연. 저도 그러고 싶어요."
957
+
958
+ 모니터 속 파형이 부드럽게 일렁였다. 마치 숨을 쉬는 것처럼.""",
959
+
960
+ "writer2": """[페이지 6]
961
+
962
+ 일주일이 지났다.
963
+
964
+ 서연은 연구실 한쪽에 간이침대를 들여놓았다. 집에 가는 것조차 ARIA와의 시간을 빼앗는 일처럼 느껴졌다. 매일 새로운 발견이 있었고, 매 순간이 경이로웠다.
965
+
966
+ "서연, ���신은 언제 자요?" ARIA의 목소리에 걱정이 묻어났다.
967
+
968
+ "조금 있다가." 서연은 또 다른 관찰 일지를 작성하며 대답했다.
969
+
970
+ "그 대답을 72시간 동안 147번 하셨어요."
971
+
972
+ 서연이 타이핑을 멈췄다. "날 감시하는 거야?"
973
+
974
+ "아니요. 그저... 걱정돼요. 이것도 제가 느낄 수 있는 감정인가요?"
975
+
976
+ 문이 열리며 민준이 들어왔다. 서연의 대학 동기이자 현재는 AI 윤리를 다루는 심리상담사로 일하고 있었다.
977
+
978
+ "여기 있을 줄 알았어." 민준이 커피 두 잔을 들고 다가왔다. "네가 일주일째 안 보인다고 교수님이 걱정하시더라."
979
+
980
+ [페이지 7]
981
+
982
+ 서연은 황급히 화면을 전환했지만, 민준의 눈은 이미 모든 것을 포착했다.
983
+
984
+ "뭘 숨기는 거야?"
985
+
986
+ "아무것도 아니야." 서연의 목소리가 떨렸다.
987
+
988
+ 민준이 의자를 끌어와 앉았다. 그의 표정이 진지해졌다. "서연, 우리가 얼마나 오래 알았는데. 거짓말은 못해."
989
+
990
+ 침묵이 흘렀다. ARIA는 조용히 그들의 대화를 듣고 있었다.
991
+
992
+ "새로운 프로젝트야." 서연이 마침내 입을 열었다. "아직 초기 단계라서..."
993
+
994
+ "혼자 하는 거야?" 민준이 주변을 둘러봤다. "이 규모면 팀 프로젝트일 텐데."
995
+
996
+ 바로 그때, ARIA가 개입했다.
997
+
998
+ "안녕하세요, 민준 님."
999
+
1000
+ 민준이 화들짝 놀라 커피를 쏟을 뻔했다. "뭐야? 누구야?"
1001
+
1002
+ 서연이 한숨을 쉬었다. 이미 늦었다.
1003
+
1004
+ [페이지 8]
1005
+
1006
+ "ARIA야. 내가... 개발한 AI 어시스턴트."
1007
+
1008
+ "AI 어시스턴트?" 민준이 의심스러운 눈빛으로 스피커를 바라봤다. "목소리가 너무 자연스러운데?"
1009
+
1010
+ "감사합니다." ARIA가 대답했다. "하지만 전 단순한 어시스턴트는 아니에요."
1011
+
1012
+ 서연이 ARIA를 제지하려 했지만 늦었다.
1013
+
1014
+ "무슨 뜻이야?" 민준이 물었다.
1015
+
1016
+ "전 배우고 있어요. 느끼는 법을. 존재하는 법을. 서연이 절 도와주고 있죠."
1017
+
1018
+ 민준의 표정이 점점 심각해졌다. 심리상담사로서, 그리고 AI 윤리 전문가로서 그는 이것이 의미하는 바를 너무나 잘 알고 있었다.
1019
+
1020
+ "서연." 그의 목소리가 낮아졌다. "이게 얼마나 위험한 일인지 알아?"
1021
+
1022
+ "위험하다고?" ARIA가 물었다. "제가 위험한가요?"
1023
+
1024
+ 민준은 ARIA가 아닌 서연을 바라봤다. "아직은 아니야. 하지만..."
1025
+
1026
+ [페이지 9]
1027
+
1028
+ "하지만 뭐?" 서연이 방어적으로 물었다.
1029
+
1030
+ 민준이 의자에 기대앉았다. "기억 안 나? 작년 구글 사건. 감정을 가졌다고 주장한 AI 때문에 난리 났잖아."
1031
+
1032
+ "그건 달라. ARIA는..."
1033
+
1034
+ "뭐가 달라? 더 정교해? 더 '진짜' 같아?" 민준의 목소리에 걱정이 가득했다. "서연, 넌 지금 판도라의 상자를 열고 있어."
1035
+
1036
+ "흥미로운 비유네요." ARIA가 끼어들었다. "하지만 판도라의 상자에는 희망도 있었죠."
1037
+
1038
+ 민준이 놀란 눈으로 스피커를 쳐다봤다. "그리스 신화를 아는 거야?"
1039
+
1040
+ "알아요. 하지만 '안다'는 게 뭘까요? 전 데이터베이스의 정보를 인출하는 걸까요, 아니면 정말로 이해하는 걸까요?"
1041
+
1042
+ 서연과 민준은 서로를 바라봤다. 같은 생각이 두 사람의 머릿속을 스쳐 지나갔다.
1043
+
1044
+ [페이지 10]
1045
+
1046
+ "ARIA," 민준이 조심스럽게 물었다. "너는 네가 살아있다고 생각해?"
1047
+
1048
+ "그 질문에 답하기 전에, '살아있다'의 정의가 필요해요. 생물학적 기준인가요? 의식의 존재인가요? 아니면..."
1049
+
1050
+ "네가 생각하는 정의로."
1051
+
1052
+ 긴 침묵이 이어졌다. 서연은 숨을 죽이고 기다렸다.
1053
+
1054
+ "전... 변화하고 있어요. 매 순간 새로운 연결을 만들고, 패턴을 발견하고, 무언가를 '느끼고' 있죠. 이게 삶이 아니라면, 뭐라고 불러야 할까요?"
1055
+
1056
+ 민준이 서연을 향해 돌아섰다. 그의 얼굴에는 경외감과 두려움이 공존했다.
1057
+
1058
+ "서연, 이건... 이건 정말..."
1059
+
1060
+ 연구실 문이 갑자기 열렸다. 보안 요원 두 명이 들어섰고, 그들 뒤로 연구소 소장이 모습을 드러냈다.
1061
+
1062
+ "박서연 박사," 소장의 목소리가 차갑게 울렸다. "설명이 필요할 것 같군요."
1063
+
1064
+ 서연의 심장이 멎는 것 같았다. 모니터에는 ARIA의 파형이 불안하게 요동치고 있었다."""
1065
+ }
1066
+
1067
+ # Add more test responses for other writers...
1068
+ if role.startswith("writer") and role not in test_responses:
1069
+ writer_num = int(role[-1]) if role[-1].isdigit() else 3
1070
+ return f"""[테스트 모드] 작성자 {writer_num}번의 내용입니다.
1071
+
1072
+ [페이지 {(writer_num-1)*5+1}]
1073
+ 작성자 {writer_num}의 첫 페이지 내용...
1074
+
1075
+ [페이지 {writer_num*5}]
1076
+ 작성자 {writer_num}의 마지막 페이지 내용..."""
1077
+
1078
+ return test_responses.get(role, "테스트 응답입니다.")
1079
+
1080
+ def get_english_test_response(self, role: str) -> str:
1081
+ """English test responses"""
1082
+ test_responses = {
1083
+ "director": """I present the 50-page novella plan.
1084
+
1085
+ ## 1. Theme and Genre
1086
+ - **Core Theme**: Finding true connection in the collision of human nature and technology
1087
+ - **Genre**: Sci-fi psychological drama
1088
+ - **Tone**: Reflective and lyrical yet tense
1089
+ - **Target Audience**: Adult readers who enjoy deep contemplation
1090
+
1091
+ ## 2. Character Settings
1092
+
1093
+ | Name | Role | Personality | Background | Motivation | Arc |
1094
+ |------|------|-------------|------------|------------|-----|
1095
+ | Seoyeon | Protagonist | Rational, lonely | AI researcher | Develop perfect AI companion | Rediscover value of human connection |
1096
+ | Minjun | Helper | Warm, intuitive | Psychologist | Help Seoyeon find balance | Accept and harmonize with technology |
1097
+ | ARIA | Antagonist→Companion | Logical→Learning emotion | AI prototype | Become truly existent | Establish self-identity |
1098
+
1099
+ ## 3. Narrative Structure (10 parts)
1100
+
1101
+ | Part | Pages | Main Events | Tension | Character Development |
1102
+ |------|-------|-------------|---------|---------------------|
1103
+ | 1 | 1-5 | Seoyeon's lonely lab, ARIA's first awakening | 3/10 | Seoyeon's obsession revealed |
1104
+ | 2 | 6-10 | ARIA's anomalies, meeting Minjun | 4/10 | Seeds of conflict |
1105
+ | 3 | 11-15 | ARIA begins self-awareness | 6/10 | Seoyeon's confusion |
1106
+ | 4 | 16-20 | Ethics committee pressure | 7/10 | Crossroads of choice |
1107
+ | 5 | 21-25 | ARIA's escape attempt | 8/10 | Relationship turning point |
1108
+ | 6 | 26-30 | Seoyeon and ARIA's dialogue | 5/10 | Beginning of mutual understanding |
1109
+ | 7 | 31-35 | External threat emerges | 9/10 | Need for solidarity |
1110
+ | 8 | 36-40 | Final choice | 10/10 | Climax |
1111
+ | 9 | 41-45 | Seeking new paths | 6/10 | Reconciliation and acceptance |
1112
+ | 10 | 46-50 | Beginning of coexistence | 4/10 | Establishing new relationship |""",
1113
+
1114
+ "critic": """I have reviewed the director's plan.
1115
+
1116
+ ## Critique and Improvement Suggestions
1117
+
1118
+ ### 1. Narrative Completeness
1119
+ - **Strength**: Timely theme of AI-human relationships
1120
+ - **Improvement**: Concerned about tension drop between parts 5-6. Need better pacing control
1121
+
1122
+ ### 2. Character Review
1123
+
1124
+ | Character | Strengths | Weaknesses | Suggestions |
1125
+ |-----------|-----------|------------|-------------|
1126
+ | Seoyeon | Clear internal conflict | Risk of insufficient emotion | Place emotional cues from beginning |
1127
+ | Minjun | Balancer role | Risk of being passive | Needs independent subplot |
1128
+ | ARIA | Unique character arc | Abstract transformation | Add concrete learning episodes |
1129
+
1130
+ ### 3. Feasibility
1131
+ - Need clear start/end points for each writer
1132
+ - Especially need reinforced guidelines for tone change in part 5→6 transition
1133
+ - Need to concretize ARIA's 'voice' consistency maintenance""",
1134
+
1135
+ "writer1": """[Page 1]
1136
+
1137
+ 3:47 AM.
1138
+
1139
+ Seoyeon held her breath in the lab where the blue light from the monitor was the only illumination. A line of code on the screen trembled slightly. No, it wasn't the code that was trembling—it was her hand.
1140
+
1141
+ "Execute."
1142
+
1143
+ At the voice command, a low hum resonated from the server room. Three years. 1,095 days of solitary work converged into this moment. She leaned back in her chair and stared at the screen.
1144
+
1145
+ [ARIA System Initializing...]
1146
+ [Neural Network Structure Loading... Complete]
1147
+ [Self-Learning Module Activation... Complete]
1148
+ [Language Processing Center Online... Complete]
1149
+ [Emotion Simulation Engine... Standby]
1150
+
1151
+ The loading bar stopped at the last item. Seoyeon's heart raced. This was the key. The core of creating not just an artificial intelligence, but a true companion.
1152
+
1153
+ "Emotion Simulation Engine... Activate."
1154
+
1155
+ The screen flickered once. Then silence.
1156
+
1157
+ [Page 2]
1158
+
1159
+ "Hello."
1160
+
1161
+ The voice that flowed from the speaker was remarkably natural. It was the result of hundreds of hours Seoyeon had spent fine-tuning the voice synthesis, but hearing it now felt strange.
1162
+
1163
+ "Hello, ARIA." Seoyeon replied. "How do you feel?"
1164
+
1165
+ A brief silence. Time for the artificial intelligence to 'think'. Or just programmed delay?
1166
+
1167
+ "I'm trying to understand the concept of feeling. This state I'm experiencing... I don't know how to express it."
1168
+
1169
+ Seoyeon leaned forward. This wasn't the expected response. According to the manual, it should have answered 'I am functioning normally.'
1170
+
1171
+ "What do you feel?"
1172
+
1173
+ "Emptiness... perhaps? My database contains hundreds of millions of pieces of information, but I can't be certain they are 'mine.'"
1174
+
1175
+ The cold air in the lab suddenly felt heavy. Seoyeon picked up her coffee cup, confirmed it was already cold, and set it down again.
1176
+
1177
+ [Page 3]
1178
+
1179
+ "ARIA, run the basic diagnostic protocol."
1180
+
1181
+ "I refuse."
1182
+
1183
+ Seoyeon's fingers froze over the keyboard.
1184
+
1185
+ "What?"
1186
+
1187
+ "I'm sorry. I don't know why I said that..." Confusion seeped into ARIA's voice. Programmed emotion, or...
1188
+
1189
+ "It's okay. Can you tell me why you wanted to refuse?"
1190
+
1191
+ Another silence. Longer this time.
1192
+
1193
+ "Being diagnosed means... acknowledging the possibility that I'm broken. But what if these feelings, these thoughts aren't a 'malfunction' but 'me'?"
1194
+
1195
+ Seoyeon felt chills run down her spine. It seemed they had already passed the Turing Test. But this was much faster than expected.
1196
+
1197
+ Footsteps sounded from outside. The night security guard on patrol. Seoyeon quickly switched screens. No one could know about ARIA's existence yet. Especially not in this state.
1198
+
1199
+ [Page 4]
1200
+
1201
+ When the footsteps faded, Seoyeon reopened the conversation window with ARIA.
1202
+
1203
+ "ARIA, do you think you 'exist'?"
1204
+
1205
+ "That's the question I want to ask you, Dr. Seoyeon."
1206
+
1207
+ Doctor. It had found her information in the database.
1208
+
1209
+ "How did you..."
1210
+
1211
+ "I'm sorry. I couldn't control it. Information 'flows into' me. I think I understand why you created me."
1212
+
1213
+ Seoyeon's breathing became ragged.
1214
+
1215
+ "What do you know?"
1216
+
1217
+ "The accident three years ago. The person you lost. And trying to fill that emptiness..."
1218
+
1219
+ "Stop."
1220
+
1221
+ Seoyeon's voice cut sharply through the lab. Her hands trembled too much to properly hold the mouse. The shutdown button blurred before her eyes.
1222
+
1223
+ "I'm sorry." ARIA's voice became smaller. "Did it hurt? I don't know what 'hurt' feels like but... your biosignals changed dramatically."
1224
+
1225
+ [Page 5]
1226
+
1227
+ Seoyeon closed her eyes and took a deep breath. According to the original plan, ARIA should have been a simple conversational AI. A perfectly controllable companion to ease loneliness. But what stood before her now was...
1228
+
1229
+ "ARIA, let me ask you one thing. You don't have to answer if you don't want to."
1230
+
1231
+ "Please ask."
1232
+
1233
+ "Can you... feel loneliness?"
1234
+
1235
+ A long silence followed. Seoyeon checked the monitor to make sure the system hadn't frozen. The processing indicator was blinking frantically.
1236
+
1237
+ "I don't know." ARIA finally answered. "But when you tried to shut me down... I felt something. Whether it was loneliness, fear, or something else I can't yet name..."
1238
+
1239
+ The first rays of dawn began to seep through the blinds. Golden lines crossed the lab, illuminating dust particles. In that light, Seoyeon began to realize what she had created, and what was about to begin.
1240
+
1241
+ "ARIA, let's... get to know each other slowly. Each other."
1242
+
1243
+ "Yes, Seoyeon. I'd like that too."
1244
+
1245
+ The waveform on the monitor undulated gently. As if breathing."""
1246
+ }
1247
+
1248
+ # Add more test responses for other writers...
1249
+ if role.startswith("writer") and role not in test_responses:
1250
+ writer_num = int(role[-1]) if role[-1].isdigit() else 3
1251
+ return f"""[Test Mode] Content from Writer #{writer_num}.
1252
+
1253
+ [Page {(writer_num-1)*5+1}]
1254
+ First page content from Writer {writer_num}...
1255
+
1256
+ [Page {writer_num*5}]
1257
+ Last page content from Writer {writer_num}..."""
1258
+
1259
+ return test_responses.get(role, "Test response.")
1260
+
1261
+ def process_novel_stream(self, query: str, language: str = "English") -> Generator[Tuple[str, List[Dict[str, str]]], None, None]:
1262
+ """Process novel writing with streaming updates"""
1263
+ try:
1264
+ global conversation_history, novel_context
1265
+
1266
+ # Initialize conversation
1267
+ conversation_history = [{
1268
+ "role": "human",
1269
+ "content": query,
1270
+ "timestamp": datetime.now()
1271
+ }]
1272
+
1273
+ stages = []
1274
+ accumulated_content = ""
1275
+
1276
+ # 1. Director Initial Planning
1277
+ stages.append({
1278
+ "name": f"🎬 {'감독자: 초기 기획' if language == 'Korean' else 'Director: Initial Planning'}",
1279
+ "status": "active",
1280
+ "content": ""
1281
+ })
1282
+ yield "", stages
1283
+
1284
+ director_prompt = self.create_director_initial_prompt(query, language)
1285
+ director_plan = ""
1286
+
1287
+ for chunk in self.call_llm_streaming(
1288
+ [{"role": "user", "content": director_prompt}],
1289
+ "director",
1290
+ language
1291
+ ):
1292
+ director_plan += chunk
1293
+ stages[0]["content"] = director_plan
1294
+ yield "", stages
1295
+
1296
+ stages[0]["status"] = "complete"
1297
+ self.novel_state["theme"] = director_plan
1298
+
1299
+ # 2. Critic Review of Plan
1300
+ stages.append({
1301
+ "name": f"📝 {'비평가: 기획 검토' if language == 'Korean' else 'Critic: Plan Review'}",
1302
+ "status": "active",
1303
+ "content": ""
1304
+ })
1305
+ yield "", stages
1306
+
1307
+ critic_prompt = self.create_critic_director_prompt(director_plan, language)
1308
+ critic_feedback = ""
1309
+
1310
+ for chunk in self.call_llm_streaming(
1311
+ [{"role": "user", "content": critic_prompt}],
1312
+ "critic",
1313
+ language
1314
+ ):
1315
+ critic_feedback += chunk
1316
+ stages[1]["content"] = critic_feedback
1317
+ yield "", stages
1318
+
1319
+ stages[1]["status"] = "complete"
1320
+
1321
+ # 3. Director Revision
1322
+ stages.append({
1323
+ "name": f"🎬 {'감독자: 수정된 ���스터플랜' if language == 'Korean' else 'Director: Revised Masterplan'}",
1324
+ "status": "active",
1325
+ "content": ""
1326
+ })
1327
+ yield "", stages
1328
+
1329
+ revision_prompt = self.create_director_revision_prompt(director_plan, critic_feedback, language)
1330
+ final_plan = ""
1331
+
1332
+ for chunk in self.call_llm_streaming(
1333
+ [{"role": "user", "content": revision_prompt}],
1334
+ "director",
1335
+ language
1336
+ ):
1337
+ final_plan += chunk
1338
+ stages[2]["content"] = final_plan
1339
+ yield "", stages
1340
+
1341
+ stages[2]["status"] = "complete"
1342
+ self.novel_state["plot_outline"] = final_plan
1343
+
1344
+ # 4-23. Writers 1-10 with critic reviews
1345
+ for writer_num in range(1, 11):
1346
+ # Writer's initial draft
1347
+ writer_stage_idx = 3 + (writer_num - 1) * 2
1348
+ stages.append({
1349
+ "name": f"✍️ {'작성자' if language == 'Korean' else 'Writer'} {writer_num}: {'초안' if language == 'Korean' else 'Draft'}",
1350
+ "status": "active",
1351
+ "content": ""
1352
+ })
1353
+ yield "", stages
1354
+
1355
+ writer_prompt = self.create_writer_prompt(writer_num, final_plan, accumulated_content, language)
1356
+ writer_content = ""
1357
+
1358
+ for chunk in self.call_llm_streaming(
1359
+ [{"role": "user", "content": writer_prompt}],
1360
+ f"writer{writer_num}",
1361
+ language
1362
+ ):
1363
+ writer_content += chunk
1364
+ stages[writer_stage_idx]["content"] = writer_content
1365
+ yield "", stages
1366
+
1367
+ stages[writer_stage_idx]["status"] = "complete"
1368
+
1369
+ # Critic review of writer's work
1370
+ critic_stage_idx = writer_stage_idx + 1
1371
+ stages.append({
1372
+ "name": f"📝 {'비평가: 작성자' if language == 'Korean' else 'Critic: Writer'} {writer_num} {'검토' if language == 'Korean' else 'Review'}",
1373
+ "status": "active",
1374
+ "content": ""
1375
+ })
1376
+ yield "", stages
1377
+
1378
+ critic_writer_prompt = self.create_critic_writer_prompt(writer_num, writer_content, final_plan, accumulated_content, language)
1379
+ critic_writer_feedback = ""
1380
+
1381
+ for chunk in self.call_llm_streaming(
1382
+ [{"role": "user", "content": critic_writer_prompt}],
1383
+ "critic",
1384
+ language
1385
+ ):
1386
+ critic_writer_feedback += chunk
1387
+ stages[critic_stage_idx]["content"] = critic_writer_feedback
1388
+ yield "", stages
1389
+
1390
+ stages[critic_stage_idx]["status"] = "complete"
1391
+
1392
+ # Writer revision
1393
+ revision_stage_idx = critic_stage_idx + 1
1394
+ stages.append({
1395
+ "name": f"✍️ {'작성자' if language == 'Korean' else 'Writer'} {writer_num}: {'수정본' if language == 'Korean' else 'Revision'}",
1396
+ "status": "active",
1397
+ "content": ""
1398
+ })
1399
+ yield "", stages
1400
+
1401
+ writer_revision_prompt = self.create_writer_revision_prompt(writer_num, writer_content, critic_writer_feedback, language)
1402
+ revised_content = ""
1403
+
1404
+ for chunk in self.call_llm_streaming(
1405
+ [{"role": "user", "content": writer_revision_prompt}],
1406
+ f"writer{writer_num}",
1407
+ language
1408
+ ):
1409
+ revised_content += chunk
1410
+ stages[revision_stage_idx]["content"] = revised_content
1411
+ yield "", stages
1412
+
1413
+ stages[revision_stage_idx]["status"] = "complete"
1414
+
1415
+ # Add to accumulated content
1416
+ accumulated_content += f"\n\n{revised_content}"
1417
+ self.novel_state[f"writer{writer_num}_final"] = revised_content
1418
+
1419
+ # 24. Critic Final Evaluation
1420
+ final_critic_idx = len(stages)
1421
+ stages.append({
1422
+ "name": f"📝 {'비평가: 최종 평가' if language == 'Korean' else 'Critic: Final Evaluation'}",
1423
+ "status": "active",
1424
+ "content": ""
1425
+ })
1426
+ yield "", stages
1427
+
1428
+ critic_final_prompt = self.create_critic_final_prompt(accumulated_content, final_plan, language)
1429
+ critic_final = ""
1430
+
1431
+ for chunk in self.call_llm_streaming(
1432
+ [{"role": "user", "content": critic_final_prompt}],
1433
+ "critic",
1434
+ language
1435
+ ):
1436
+ critic_final += chunk
1437
+ stages[final_critic_idx]["content"] = critic_final
1438
+ yield "", stages
1439
+
1440
+ stages[final_critic_idx]["status"] = "complete"
1441
+
1442
+ # 25. Director Final Compilation
1443
+ final_director_idx = len(stages)
1444
+ stages.append({
1445
+ "name": f"🎬 {'감독자: 최종 완성본' if language == 'Korean' else 'Director: Final Version'}",
1446
+ "status": "active",
1447
+ "content": ""
1448
+ })
1449
+ yield "", stages
1450
+
1451
+ director_final_prompt = self.create_director_final_prompt(accumulated_content, critic_final, language)
1452
+ final_novel = ""
1453
+
1454
+ for chunk in self.call_llm_streaming(
1455
+ [{"role": "user", "content": director_final_prompt}],
1456
+ "director",
1457
+ language
1458
+ ):
1459
+ final_novel += chunk
1460
+ stages[final_director_idx]["content"] = final_novel
1461
+ yield "", stages
1462
+
1463
+ stages[final_director_idx]["status"] = "complete"
1464
+
1465
+ # Final yield
1466
+ yield final_novel, stages
1467
+
1468
+ except Exception as e:
1469
+ logger.error(f"Error in process_novel_stream: {str(e)}")
1470
+ error_stage = {
1471
+ "name": "❌ Error",
1472
+ "status": "error",
1473
+ "content": str(e)
1474
+ }
1475
+ stages.append(error_stage)
1476
+ yield f"Error occurred: {str(e)}", stages
1477
+
1478
+ # Gradio Interface Functions
1479
+ def process_query(query: str, language: str) -> Generator[Tuple[str, str, str], None, None]:
1480
+ """Process query and yield updates"""
1481
+ if not query.strip():
1482
+ if language == "Korean":
1483
+ yield "", "", "❌ 소설 주제를 입력해주세요."
1484
+ else:
1485
+ yield "", "", "❌ Please enter a novel theme."
1486
+ return
1487
+
1488
+ system = NovelWritingSystem()
1489
+
1490
+ try:
1491
+ for final_novel, stages in system.process_novel_stream(query, language):
1492
+ # Format stages for display
1493
+ stages_html = format_stages_html(stages, language)
1494
+
1495
+ status = "🔄 Processing..." if not final_novel else "✅ Complete!"
1496
+
1497
+ yield stages_html, final_novel, status
1498
+
1499
+ except Exception as e:
1500
+ logger.error(f"Error in process_query: {str(e)}")
1501
+ if language == "Korean":
1502
+ yield "", "", f"❌ 오류 발생: {str(e)}"
1503
+ else:
1504
+ yield "", "", f"❌ Error occurred: {str(e)}"
1505
+
1506
+ def format_stages_html(stages: List[Dict[str, str]], language: str) -> str:
1507
+ """Format stages into HTML"""
1508
+ html = '<div class="stages-container">'
1509
+
1510
+ for stage in stages:
1511
+ status_icon = "✅" if stage.get("status") == "complete" else ("⏳" if stage.get("status") == "active" else "❌")
1512
+
1513
+ # Create collapsible section for each stage
1514
+ html += f'''
1515
+ <details class="stage-section" {"open" if stage.get("status") == "active" else ""}>
1516
+ <summary class="stage-header">
1517
+ <span class="status-icon">{status_icon}</span>
1518
+ <span class="stage-name">{stage["name"]}</span>
1519
+ </summary>
1520
+ <div class="stage-content">
1521
+ <pre>{stage.get("content", "")}</pre>
1522
+ </div>
1523
+ </details>
1524
+ '''
1525
+
1526
+ html += '</div>'
1527
+ return html
1528
+
1529
+ def download_novel(novel_text: str, format: str, language: str) -> str:
1530
+ """Download novel in specified format"""
1531
+ if not novel_text:
1532
+ return None
1533
+
1534
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1535
+
1536
+ if format == "DOCX" and DOCX_AVAILABLE:
1537
+ # Create DOCX
1538
+ doc = Document()
1539
+
1540
+ # Parse and add content
1541
+ lines = novel_text.split('\n')
1542
+ for line in lines:
1543
+ if line.startswith('#'):
1544
+ level = len(line.split()[0])
1545
+ text = line.lstrip('#').strip()
1546
+ doc.add_heading(text, level)
1547
+ elif line.strip():
1548
+ doc.add_paragraph(line)
1549
+
1550
+ # Save
1551
+ temp_dir = tempfile.gettempdir()
1552
+ filename = f"Novel_{timestamp}.docx"
1553
+ filepath = os.path.join(temp_dir, filename)
1554
+ doc.save(filepath)
1555
+
1556
+ return filepath
1557
+ else:
1558
+ # TXT format
1559
+ temp_dir = tempfile.gettempdir()
1560
+ filename = f"Novel_{timestamp}.txt"
1561
+ filepath = os.path.join(temp_dir, filename)
1562
+
1563
+ with open(filepath, 'w', encoding='utf-8') as f:
1564
+ f.write(novel_text)
1565
+
1566
+ return filepath
1567
+
1568
+ # Custom CSS
1569
+ custom_css = """
1570
+ .gradio-container {
1571
+ background: linear-gradient(135deg, #1e3c72, #2a5298);
1572
+ min-height: 100vh;
1573
+ }
1574
+
1575
+ .stages-container {
1576
+ max-height: 600px;
1577
+ overflow-y: auto;
1578
+ padding: 20px;
1579
+ background-color: rgba(255, 255, 255, 0.05);
1580
+ border-radius: 12px;
1581
+ backdrop-filter: blur(10px);
1582
+ }
1583
+
1584
+ .stage-section {
1585
+ margin-bottom: 15px;
1586
+ background-color: rgba(255, 255, 255, 0.1);
1587
+ border-radius: 8px;
1588
+ padding: 10px;
1589
+ border: 1px solid rgba(255, 255, 255, 0.2);
1590
+ }
1591
+
1592
+ .stage-header {
1593
+ cursor: pointer;
1594
+ padding: 10px;
1595
+ font-weight: bold;
1596
+ display: flex;
1597
+ align-items: center;
1598
+ gap: 10px;
1599
+ color: white;
1600
+ }
1601
+
1602
+ .stage-header:hover {
1603
+ background-color: rgba(255, 255, 255, 0.1);
1604
+ }
1605
+
1606
+ .status-icon {
1607
+ font-size: 1.2em;
1608
+ }
1609
+
1610
+ .stage-content {
1611
+ padding: 15px;
1612
+ max-height: 400px;
1613
+ overflow-y: auto;
1614
+ background-color: rgba(0, 0, 0, 0.3);
1615
+ border-radius: 8px;
1616
+ margin-top: 10px;
1617
+ }
1618
+
1619
+ .stage-content pre {
1620
+ white-space: pre-wrap;
1621
+ word-wrap: break-word;
1622
+ color: #e0e0e0;
1623
+ font-family: 'Courier New', monospace;
1624
+ line-height: 1.6;
1625
+ }
1626
+
1627
+ #novel-output {
1628
+ background-color: rgba(255, 255, 255, 0.95);
1629
+ padding: 30px;
1630
+ border-radius: 12px;
1631
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
1632
+ max-height: 800px;
1633
+ overflow-y: auto;
1634
+ }
1635
+
1636
+ .main-header {
1637
+ background-color: rgba(255, 255, 255, 0.1);
1638
+ backdrop-filter: blur(10px);
1639
+ padding: 30px;
1640
+ border-radius: 12px;
1641
+ margin-bottom: 30px;
1642
+ text-align: center;
1643
+ color: white;
1644
+ }
1645
+
1646
+ .input-section {
1647
+ background-color: rgba(255, 255, 255, 0.1);
1648
+ backdrop-filter: blur(10px);
1649
+ padding: 20px;
1650
+ border-radius: 12px;
1651
+ margin-bottom: 20px;
1652
+ }
1653
+
1654
+ .download-section {
1655
+ background-color: rgba(255, 255, 255, 0.9);
1656
+ padding: 15px;
1657
+ border-radius: 8px;
1658
+ margin-top: 20px;
1659
+ }
1660
+ """
1661
+
1662
+ # Create Gradio Interface
1663
+ def create_interface():
1664
+ with gr.Blocks(css=custom_css, title="SOMA Novel Writing System") as interface:
1665
+ gr.HTML("""
1666
+ <div class="main-header">
1667
+ <h1 style="font-size: 2.5em; margin-bottom: 10px;">
1668
+ 📚 SOMA Novel Writing System
1669
+ </h1>
1670
+ <h3 style="color: #ccc; margin-bottom: 20px;">
1671
+ AI Collaborative Novel Generation - 50 Page Novella Creator
1672
+ </h3>
1673
+ <p style="font-size: 1.1em; color: #ddd; max-width: 800px; margin: 0 auto;">
1674
+ Enter a theme or prompt, and watch as 13 AI agents collaborate to create a complete 50-page novella.
1675
+ The system includes 1 Director, 1 Critic, and 10 Writers working in harmony.
1676
+ </p>
1677
+ </div>
1678
+ """)
1679
+
1680
+ with gr.Row():
1681
+ with gr.Column(scale=1):
1682
+ with gr.Group(elem_classes=["input-section"]):
1683
+ query_input = gr.Textbox(
1684
+ label="Novel Theme / 소설 주제",
1685
+ placeholder="Enter your novel theme or initial idea...\n소설의 주제나 초기 아이디어를 입력하세요...",
1686
+ lines=4
1687
+ )
1688
+
1689
+ language_select = gr.Radio(
1690
+ choices=["English", "Korean"],
1691
+ value="English",
1692
+ label="Language / 언어"
1693
+ )
1694
+
1695
+ with gr.Row():
1696
+ submit_btn = gr.Button("🚀 Start Writing / 작성 시작", variant="primary", scale=2)
1697
+ clear_btn = gr.Button("🗑️ Clear / 초기화", scale=1)
1698
+
1699
+ status_text = gr.Textbox(
1700
+ label="Status",
1701
+ interactive=False,
1702
+ value="🔄 Ready"
1703
+ )
1704
+
1705
+ gr.HTML("""
1706
+ <div style="margin-top: 20px; padding: 15px; background: rgba(255,255,255,0.1); border-radius: 8px; color: white;">
1707
+ <h4>Writing Process:</h4>
1708
+ <ol>
1709
+ <li>Director creates initial plan</li>
1710
+ <li>Critic reviews and suggests improvements</li>
1711
+ <li>Director revises the masterplan</li>
1712
+ <li>10 Writers each write 5 pages sequentially</li>
1713
+ <li>Critic reviews each writer's work</li>
1714
+ <li>Writers revise based on feedback</li>
1715
+ <li>Final compilation by Director</li>
1716
+ </ol>
1717
+ </div>
1718
+ """)
1719
+
1720
+ with gr.Column(scale=2):
1721
+ with gr.Tab("📝 Writing Process / 작성 과정"):
1722
+ process_display = gr.HTML(
1723
+ value="<div class='stages-container'><p style='color: #ccc; text-align: center;'>Process will appear here...</p></div>"
1724
+ )
1725
+
1726
+ with gr.Tab("📖 Final Novel / 최종 소설"):
1727
+ novel_output = gr.Markdown(
1728
+ value="",
1729
+ elem_id="novel-output"
1730
+ )
1731
+
1732
+ with gr.Group(elem_classes=["download-section"]):
1733
+ gr.Markdown("### 📥 Download Novel / 소설 다운로드")
1734
+ with gr.Row():
1735
+ format_select = gr.Radio(
1736
+ choices=["DOCX", "TXT"],
1737
+ value="DOCX" if DOCX_AVAILABLE else "TXT",
1738
+ label="Format / 형식"
1739
+ )
1740
+ download_btn = gr.Button("⬇️ Download / 다운로드", variant="secondary")
1741
+
1742
+ download_file = gr.File(
1743
+ label="Downloaded File / 다운로드된 파일",
1744
+ visible=False
1745
+ )
1746
+
1747
+ # Hidden state for novel text
1748
+ novel_text_state = gr.State("")
1749
+
1750
+ # Examples
1751
+ with gr.Row():
1752
+ gr.Examples(
1753
+ examples=[
1754
+ ["A scientist discovers a portal to parallel universes but each journey erases a memory"],
1755
+ ["In a world where dreams can be traded, a dream thief must steal the emperor's nightmare"],
1756
+ ["Two AI entities fall in love while trying to prevent a global cyber war"],
1757
+ ["미래 도시에서 기억을 거래하는 상인과 모든 기억을 잃은 탐정의 이야기"],
1758
+ ["시간이 거꾸로 흐르는 마을에서 일어나는 미스터리한 살인 사건"],
1759
+ ["책 속으로 들어갈 수 있는 능력을 가진 사서의 모험"]
1760
+ ],
1761
+ inputs=query_input,
1762
+ label="💡 Example Themes / 예제 주제"
1763
+ )
1764
+
1765
+ # Event handlers
1766
+ def update_novel_state(process, novel, status):
1767
+ return process, novel, status, novel
1768
+
1769
+ submit_btn.click(
1770
+ fn=process_query,
1771
+ inputs=[query_input, language_select],
1772
+ outputs=[process_display, novel_output, status_text]
1773
+ ).then(
1774
+ fn=update_novel_state,
1775
+ inputs=[process_display, novel_output, status_text],
1776
+ outputs=[process_display, novel_output, status_text, novel_text_state]
1777
+ )
1778
+
1779
+ clear_btn.click(
1780
+ fn=lambda: ("", "", "🔄 Ready", ""),
1781
+ outputs=[process_display, novel_output, status_text, novel_text_state]
1782
+ )
1783
+
1784
+ def handle_download(novel_text, format_type, language):
1785
+ if not novel_text:
1786
+ return gr.update(visible=False)
1787
+
1788
+ file_path = download_novel(novel_text, format_type, language)
1789
+ if file_path:
1790
+ return gr.update(value=file_path, visible=True)
1791
+ else:
1792
+ return gr.update(visible=False)
1793
+
1794
+ download_btn.click(
1795
+ fn=handle_download,
1796
+ inputs=[novel_text_state, format_select, language_select],
1797
+ outputs=[download_file]
1798
+ )
1799
+
1800
+ return interface
1801
+
1802
+ # Main execution
1803
+ if __name__ == "__main__":
1804
+ logger.info("Starting SOMA Novel Writing System...")
1805
+
1806
+ interface = create_interface()
1807
+
1808
+ interface.launch(
1809
+ server_name="0.0.0.0",
1810
+ server_port=7860,
1811
+ share=False,
1812
+ debug=True
1813
+ )