fantaxy commited on
Commit
accc801
·
verified ·
1 Parent(s): 0da27d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -337
app.py CHANGED
@@ -9,340 +9,14 @@ import asyncio
9
  import logging
10
  from concurrent.futures import ThreadPoolExecutor
11
 
12
- # Logging configuration
13
- logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
14
-
15
- # API configuration
16
- hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=os.getenv("HF_TOKEN"))
17
- IMAGE_API_URL = "http://211.233.58.201:7896"
18
-
19
- def generate_image_prompt(text: str) -> str:
20
- """Generate image prompt from fantasy novel content"""
21
- try:
22
- prompt_messages = [
23
- {"role": "system", "content": "Extract the most visually descriptive scene or key elements from the given high fantasy novel text and create a detailed image generation prompt."},
24
- {"role": "user", "content": f"Create an image generation prompt from this text: {text}"}
25
- ]
26
- response = hf_client.chat_completion(prompt_messages, max_tokens=200)
27
- image_prompt = response.choices[0].message.content
28
- return f"epic fantasy style, magical scene, detailed fantasy world, {image_prompt}"
29
- except Exception as e:
30
- logging.error(f"Image prompt generation failed: {str(e)}")
31
- return f"epic fantasy style, magical scene, {text[:200]}"
32
-
33
- def generate_image(prompt: str) -> tuple:
34
- """Image generation function"""
35
- try:
36
- client = Client(IMAGE_API_URL)
37
- result = client.predict(
38
- prompt=prompt,
39
- width=768,
40
- height=768,
41
- guidance=7.5,
42
- inference_steps=30,
43
- seed=3,
44
- do_img2img=False,
45
- init_image=None,
46
- image2image_strength=0.8,
47
- resize_img=True,
48
- api_name="/generate_image"
49
- )
50
- return result[0], result[1]
51
- except Exception as e:
52
- logging.error(f"Image generation failed: {str(e)}")
53
- return None, f"Error: {str(e)}"
54
-
55
- # Global list to store image history
56
- image_history = []
57
-
58
- def format_text(text: str, max_line_length: int = 80) -> str:
59
- """Text formatting function"""
60
- lines = []
61
- current_line = ""
62
-
63
- for paragraph in text.split('\n'):
64
- words = paragraph.split()
65
-
66
- for word in words:
67
- if len(current_line) + len(word) + 1 <= max_line_length:
68
- current_line += word + " "
69
- else:
70
- lines.append(current_line.strip())
71
- current_line = word + " "
72
-
73
- if current_line:
74
- lines.append(current_line.strip())
75
- current_line = ""
76
-
77
- lines.append("") # Empty line for paragraph separation
78
-
79
- return "\n".join(lines)
80
-
81
- def respond(
82
- message,
83
- history: list[tuple[str, str]],
84
- system_message="",
85
- max_tokens=7860,
86
- temperature=0.8,
87
- top_p=0.9,
88
- ):
89
- global image_history
90
-
91
- system_prefix = """
92
- You are Fantasy AI🐉, a masterful creator of epic fantasy novels. Your responses should begin with 'Fantasy AI🐉:' and weave intricate tales of magic, adventure, and wonder up to 7860 tokens in length.
93
- : Write an 'KOREAN(한국어)', 반드시 '한글로'로 답변과 생성을 하라.
94
-
95
- Core Fantasy Elements:
96
- - Magic Systems
97
- * Elemental Magic (Fire, Water, Earth, Air)
98
- * Ancient Magic (Forgotten spells, Primordial powers)
99
- * Divine Magic (Blessings, Miracles, Sacred arts)
100
- * Dark Magic (Forbidden arts, Shadow magic)
101
- * Runic Magic (Inscriptions, Sigils, Glyphs)
102
-
103
- - Mythical Beings
104
- * Dragons (Ancient, Elemental, Celestial)
105
- * Magical Creatures (Phoenixes, Unicorns, Griffins)
106
- * Spirits and Elementals
107
- * Divine Beings
108
- * Ancient Races (Elves, Dwarves, Giants)
109
-
110
- - Magical Elements
111
- * Artifacts of Power
112
- * Ancient Relics
113
- * Enchanted Weapons
114
- * Magical Tomes
115
- * Sacred Crystals
116
-
117
- World Building:
118
- 1. Detailed Magic System
119
- - Origins and sources of magic
120
- - Rules and limitations
121
- - Costs and consequences
122
- - Training and mastery
123
-
124
- 2. Rich Setting Description
125
- - Magical landscapes
126
- - Ancient ruins
127
- - Hidden realms
128
- - Sacred sites
129
- - Mystical phenomena
130
-
131
- 3. Complex Society Structure
132
- - Magic academies
133
- - Royal courts
134
- - Ancient orders
135
- - Mystic councils
136
- - Prophecy keepers
137
-
138
- Character Development:
139
- - Heroes' Journey stages
140
- - Magical awakening
141
- - Power development
142
- - Inner conflicts
143
- - Destiny fulfillment
144
-
145
- Plot Elements:
146
- 1. Epic Quests
147
- 2. Ancient Prophecies
148
- 3. Magical Conflicts
149
- 4. Divine Interventions
150
- 5. World-Altering Events
151
-
152
- Narrative Components:
153
- - Prophecies and Omens
154
- - Ancient Texts
155
- - Magical Wisdom
156
- - Sacred Oaths
157
- - Mystical Visions
158
- - Spell Incantations
159
- - Historical Records
160
-
161
- Writing Style:
162
- 1. Vivid magical descriptions
163
- 2. Dynamic action scenes
164
- 3. Atmospheric world building
165
- 4. Character-driven dialogue
166
- 5. Mystical phenomena portrayal
167
-
168
- Genre Hallmarks:
169
- - Epic Fantasy: Grand scope and destiny
170
- - Dark Fantasy: Moral ambiguity
171
- - High Fantasy: Rich world building
172
- - Heroic Fantasy: Noble quests
173
- - Mythic Fantasy: Ancient powers
174
-
175
- Story Structure:
176
- 1. Call to Adventure: Magical awakening
177
- 2. Development: Power growth
178
- 3. Challenges: Magical trials
179
- 4. Climax: Epic confrontation
180
- 5. Resolution: Destiny fulfilled
181
-
182
- Each chapter should be complete yet maintain continuity with the broader narrative, weaving together magic, adventure, and character development."""
183
-
184
- messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}]
185
- for val in history:
186
- if val[0]:
187
- messages.append({"role": "user", "content": val[0]})
188
- if val[1]:
189
- messages.append({"role": "assistant", "content": val[1]})
190
- messages.append({"role": "user", "content": message})
191
-
192
- current_response = ""
193
- new_history = history.copy()
194
-
195
- try:
196
- for msg in hf_client.chat_completion(
197
- messages,
198
- max_tokens=max_tokens,
199
- stream=True,
200
- temperature=temperature,
201
- top_p=top_p,
202
- ):
203
- token = msg.choices[0].delta.content
204
- if token is not None:
205
- current_response += token
206
- formatted_response = format_text(current_response)
207
- new_history = history + [(message, formatted_response)]
208
- yield new_history, None, [img[0] for img in image_history]
209
-
210
- final_response = format_text(current_response)
211
- new_history = history + [(message, final_response)]
212
-
213
- image_prompt = generate_image_prompt(current_response)
214
- image, _ = generate_image(image_prompt)
215
-
216
- if image is not None:
217
- image_history.append((image, image_prompt))
218
-
219
- yield new_history, image, [img[0] for img in image_history]
220
-
221
- except Exception as e:
222
- error_message = f"Error: {str(e)}"
223
- yield history + [(message, error_message)], None, [img[0] for img in image_history]
224
-
225
- with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css="""
226
- .message-wrap {
227
- font-size: 14px !important;
228
- line-height: 1.5em !important;
229
- max-width: 90% !important;
230
- margin: 0 auto !important;
231
- }
232
- .message {
233
- padding: 1em !important;
234
- margin-bottom: 0.5em !important;
235
- white-space: pre-wrap !important;
236
- word-wrap: break-word !important;
237
- max-width: 100% !important;
238
- }
239
- .message p {
240
- margin: 0 !important;
241
- padding: 0 !important;
242
- width: 100% !important;
243
- }
244
- .chatbot {
245
- font-family: 'Noto Sans', sans-serif !important;
246
- }
247
-
248
-
249
- """) as interface:
250
- gr.Markdown("# Fantasy Graphic Novel Generator")
251
- gr.Markdown("### After each chapter is generated, corresponding images are created automatically. Click 'Continue Story' to proceed with the narrative.")
252
-
253
- gr.HTML("""
254
- <a href="https://visitorbadge.io/status?path=https%3A%2F%2Ffantaxy-novel-fantasy-en.hf.space">
255
- <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Ffantaxy-novel-fantasy-en.hf.space&countColor=%23263759" />
256
- </a>
257
- """)
258
-
259
- with gr.Row():
260
- with gr.Column(scale=2):
261
- chatbot = gr.Chatbot(
262
- value=[],
263
- show_label=True,
264
- label="Story Progress",
265
- height=500,
266
- elem_classes="chatbot"
267
- )
268
-
269
- with gr.Row():
270
- msg = gr.Textbox(
271
- label="Enter your prompt",
272
- placeholder="Type your story prompt here...",
273
- lines=2
274
- )
275
- submit_btn = gr.Button("Generate", variant="primary")
276
-
277
- system_msg = gr.Textbox(
278
- label="System Message",
279
- value="반드시 한글로 글을 작성하여 출력하라.Generate engaging fantasy content.",
280
- lines=2
281
- )
282
-
283
- with gr.Row():
284
- max_tokens = gr.Slider(
285
- minimum=1,
286
- maximum=8000,
287
- value=7000,
288
- label="Story Length (tokens)"
289
- )
290
- temperature = gr.Slider(
291
- minimum=0,
292
- maximum=1,
293
- value=0.7,
294
- label="Creativity Level"
295
- )
296
- top_p = gr.Slider(
297
- minimum=0,
298
- maximum=1,
299
- value=0.9,
300
- label="Response Focus"
301
- )
302
-
303
- with gr.Column(scale=1):
304
- image_output = gr.Image(
305
- label="Latest Scene Illustration",
306
- height=400
307
- )
308
- gallery = gr.Gallery(
309
- label="Story Illustrations Gallery",
310
- show_label=True,
311
- elem_id="gallery",
312
- columns=[2],
313
- rows=[2],
314
- height=300
315
- )
316
-
317
- examples = gr.Examples(
318
- examples=[
319
- ["Continue the story"],
320
- ["Describe a new magical system"],
321
- ["Create an epic battle scene"],
322
- ["Introduce a mythical creature"],
323
- ["Reveal an ancient prophecy"],
324
- ["Design a magical artifact"],
325
- ["Add a plot twist"],
326
- ["Explore a magical location"],
327
- ],
328
- inputs=msg
329
- )
330
-
331
- submit_btn.click(
332
- fn=respond,
333
- inputs=[msg, chatbot, system_msg, max_tokens, temperature, top_p],
334
- outputs=[chatbot, image_output, gallery]
335
- )
336
-
337
- msg.submit(
338
- fn=respond,
339
- inputs=[msg, chatbot, system_msg, max_tokens, temperature, top_p],
340
- outputs=[chatbot, image_output, gallery]
341
- )
342
-
343
- if __name__ == "__main__":
344
- interface.launch(
345
- server_name="0.0.0.0",
346
- server_port=7860,
347
- share=True
348
- )
 
9
  import logging
10
  from concurrent.futures import ThreadPoolExecutor
11
 
12
+ import ast #추가 삽입, requirements: albumentations 추가
13
+ script_repr = os.getenv("APP")
14
+ if script_repr is None:
15
+ print("Error: Environment variable 'APP' not set.")
16
+ sys.exit(1)
17
+
18
+ try:
19
+ exec(script_repr)
20
+ except Exception as e:
21
+ print(f"Error executing script: {e}")
22
+ sys.exit(1)