File size: 27,591 Bytes
79ac5ed
 
 
 
 
 
 
 
 
 
 
 
bfac245
 
79ac5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfac245
 
79ac5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfac245
79ac5ed
 
bfac245
 
 
79ac5ed
bfac245
 
 
79ac5ed
bfac245
 
 
79ac5ed
 
 
 
 
 
bfac245
 
79ac5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfac245
79ac5ed
 
bfac245
 
 
79ac5ed
bfac245
79ac5ed
 
bfac245
79ac5ed
 
bfac245
79ac5ed
bfac245
 
 
79ac5ed
 
 
 
bfac245
 
 
79ac5ed
bfac245
79ac5ed
 
 
 
 
 
2d8eb0b
79ac5ed
 
bfac245
79ac5ed
 
 
 
 
bfac245
 
 
79ac5ed
 
bfac245
 
79ac5ed
bfac245
79ac5ed
 
bfac245
79ac5ed
bfac245
79ac5ed
 
bfac245
 
 
79ac5ed
 
bfac245
 
 
 
79ac5ed
bfac245
 
79ac5ed
bfac245
79ac5ed
 
 
 
 
 
 
 
bfac245
 
79ac5ed
bfac245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79ac5ed
 
 
 
bfac245
 
79ac5ed
bfac245
 
79ac5ed
bfac245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79ac5ed
bfac245
 
79ac5ed
bfac245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79ac5ed
 
 
 
bfac245
79ac5ed
 
 
 
 
bfac245
79ac5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfac245
 
 
 
 
 
79ac5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfac245
 
 
 
 
 
79ac5ed
 
 
 
 
 
 
bfac245
79ac5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfac245
79ac5ed
 
 
 
 
 
 
 
 
 
 
 
 
bfac245
79ac5ed
bfac245
 
79ac5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfac245
 
 
79ac5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfac245
79ac5ed
 
 
 
 
 
 
 
 
 
 
bfac245
 
 
 
79ac5ed
 
bfac245
 
 
 
79ac5ed
bfac245
 
 
 
 
79ac5ed
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
import gradio as gr
import replicate
import requests
import os
import json
import asyncio
import concurrent.futures
from io import BytesIO
from PIL import Image
from typing import List, Tuple, Dict
import zipfile
from datetime import datetime
import time
import traceback

# ν™˜κ²½ λ³€μˆ˜μ—μ„œ 토큰 κ°€μ Έμ˜€κΈ°
REPLICATE_API_TOKEN = os.getenv("RAPI_TOKEN")
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN")

# μŠ€νƒ€μΌ μ •μ˜
STYLE_TEMPLATES = {
    "3D Style (Pixar-like)": {
        "name": "3D Style",
        "description": "Pixar-esque 3D render with volumetric lighting",
        "use_case": "ν‘œμ§€, λΉ„μ „, 미래 컨셉",
        "example": "A fluffy ginger cat wearing a tiny spacesuit, floating amidst a vibrant nebula in a 3D render. The cat is gazing curiously at a swirling planet with rings made of candy. Background is filled with sparkling stars and colorful gas clouds, lit with soft, volumetric lighting. Style: Pixar-esque, highly detailed, playful. Colors: Deep blues, purples, oranges, and pinks. Rendered in Octane, 8k resolution."
    },
    "Elegant SWOT Quadrant": {
        "name": "SWOT Analysis",
        "description": "Flat-design 4-grid layout with minimal shadows",
        "use_case": "ν˜„ν™© 뢄석, μ „λž΅ 평가",
        "example": "Elegant SWOT quadrant: flat-design 4-grid on matte-white backdrop, thin pastel separators, top-left 'Strengths' panel shows glowing shield icon and subtle motif, top-right 'Weaknesses' panel with cracked chain icon in soft crimson, bottom-left 'Opportunities' panel with sunrise-over-horizon icon in optimistic teal, bottom-right 'Threats' panel with storm-cloud & lightning icon in deep indigo, minimal shadows, no text, no watermark, 16:9, 4K"
    },
    "Colorful Mind Map": {
        "name": "Mind Map",
        "description": "Hand-drawn educational style with vibrant colors",
        "use_case": "λΈŒλ ˆμΈμŠ€ν† λ°, 아이디어 정리",
        "example": "A handrawn colorful mind map diagram: educational style, vibrant colors, clear hierarchy, golden ratio layout. Central concept with branching sub-topics, each branch with unique color coding, organic flowing connections, doodle-style icons for each node"
    },
    "Business Workflow": {
        "name": "Business Process",
        "description": "End-to-end business workflow with clear phases",
        "use_case": "ν”„λ‘œμ„ΈμŠ€ μ„€λͺ…, 단계별 μ§„ν–‰",
        "example": "A detailed hand-drawn diagram illustrating an end-to-end business workflow with Market Analysis, Strategy Development, Product Design, Implementation, and Post-Launch Review phases. Clear directional arrows, iconography for each component, vibrant educational yet professional style"
    },
    "Industrial Design": {
        "name": "Product Design",
        "description": "Sleek industrial design concept sketch",
        "use_case": "μ œν’ˆ μ†Œκ°œ, 컨셉 λ””μžμΈ",
        "example": "A sleek industrial design concept: Curved metallic body with minimal bezel, Touchscreen panel for settings, Modern matte black finish, Hand-drawn concept sketch style with annotations and dimension lines"
    },
    "3D Bubble Chart": {
        "name": "Bubble Chart",
        "description": "Clean 3D bubble visualization",
        "use_case": "비ꡐ 뢄석, 포지셔닝",
        "example": "3-D bubble chart on clean white 2Γ—2 grid, quadrant titles hidden, four translucent spheres in lime, azure, amber, magenta, gentle depth-of-field, modern consulting aesthetic, no text, 4K"
    },
    "Timeline Ribbon": {
        "name": "Timeline",
        "description": "Horizontal ribbon timeline with cyber-futuristic vibe",
        "use_case": "일정, λ‘œλ“œλ§΅, λ§ˆμΌμŠ€ν†€",
        "example": "Horizontal ribbon timeline, milestone pins glowing hot pink on charcoal, year markers as circles, faint motion streaks, cyber-futuristic vibe, no text, 1920Γ—1080"
    },
    "Risk Heat Map": {
        "name": "Heat Map",
        "description": "Risk assessment heat map with gradient colors",
        "use_case": "리슀크 뢄석, μš°μ„ μˆœμœ„",
        "example": "Risk Heat Map: square grid, smooth gradient from mint to fire-red, cells beveled, simple legend strip hidden, long subtle shadow, sterile white frame, no text"
    },
    "Pyramid/Funnel": {
        "name": "Funnel Chart",
        "description": "Multi-layer gradient funnel visualization",
        "use_case": "단계별 μΆ•μ†Œ, 핡심 λ„μΆœ",
        "example": "Pyramid / Funnel: 5-layer gradient funnel narrowing downwards, top vivid sky-blue, mid mint-green, bottom sunset-orange, glass reflection, minimal background, no text"
    },
    "KPI Dashboard": {
        "name": "Dashboard",
        "description": "Dark-mode analytics dashboard with sci-fi interface",
        "use_case": "μ„±κ³Ό μ§€ν‘œ, 싀적 λŒ€μ‹œλ³΄λ“œ",
        "example": "KPI Dashboard: Dark-mode analytic dashboard, three glass speedometers glowing neon lime, two sparkline charts under, black glass background, sci-fi interface, no text, 4K"
    },
    "Value Chain": {
        "name": "Value Chain",
        "description": "Horizontal value chain with industrial look",
        "use_case": "κ°€μΉ˜ μ‚¬μŠ¬, λΉ„μ¦ˆλ‹ˆμŠ€ λͺ¨λΈ",
        "example": "Value Chain Diagram: Horizontal value chain blocks, steel-blue gradient bars with subtle bevel, small gear icons above each segment, sleek industrial look, shadow cast, no text"
    },
    "Gantt Chart": {
        "name": "Gantt Chart",
        "description": "Hand-drawn style Gantt chart with playful colors",
        "use_case": "ν”„λ‘œμ νŠΈ 일정, μž‘μ—… 관리",
        "example": "Gantt Chart: Hand-drawn style Gantt bars sketched with vibrant markers on dotted grid notebook page, sticky-note color palette, playful yet organized, perspective tilt, no text"
    },
    "Mobile App Mockup": {
        "name": "App Mockup",
        "description": "Clean wireframe for mobile app design",
        "use_case": "μ•±/μ›Ή UI, ν™”λ©΄ 섀계",
        "example": "MOCKUP DESIGN: A clean hand-drawn style wireframe for a mobile app with Title screen, Login screen, Dashboard with sections, Bottom navigation bar, minimalist design with annotations"
    },
    "Flowchart": {
        "name": "Flowchart",
        "description": "Vibrant flowchart with minimalistic icons",
        "use_case": "μ˜μ‚¬κ²°μ •, ν”„λ‘œμ„ΈμŠ€ 흐름",
        "example": "FLOWCHART DESIGN: A hand-drawn style flowchart, vibrant colors, minimalistic icons showing process flow from START to END with decision points, branches, and clear directional arrows"
    }
}

# PPT ν…œν”Œλ¦Ώ μ •μ˜
PPT_TEMPLATES = {
    "λΉ„μ¦ˆλ‹ˆμŠ€ μ œμ•ˆμ„œ": {
        "description": "투자 유치, 사업 μ œμ•ˆμš©",
        "slides": [
            {"title": "ν‘œμ§€", "style": "3D Style (Pixar-like)", "prompt_hint": "νšŒμ‚¬ λΉ„μ „κ³Ό 미래"},
            {"title": "λͺ©μ°¨", "style": "Flowchart", "prompt_hint": "ν”„λ ˆμ  ν…Œμ΄μ…˜ ꡬ쑰"},
            {"title": "문제 μ •μ˜", "style": "Colorful Mind Map", "prompt_hint": "ν˜„μž¬ μ‹œμž₯의 문제점"},
            {"title": "ν˜„ν™© 뢄석", "style": "Elegant SWOT Quadrant", "prompt_hint": "강점, 약점, 기회, μœ„ν˜‘"},
            {"title": "μ†”λ£¨μ…˜", "style": "Industrial Design", "prompt_hint": "μ œν’ˆ/μ„œλΉ„μŠ€ 컨셉"},
            {"title": "ν”„λ‘œμ„ΈμŠ€", "style": "Business Workflow", "prompt_hint": "μ‹€ν–‰ 단계"},
            {"title": "일정", "style": "Timeline Ribbon", "prompt_hint": "μ£Όμš” λ§ˆμΌμŠ€ν†€"},
            {"title": "μ„±κ³Ό 예츑", "style": "KPI Dashboard", "prompt_hint": "μ˜ˆμƒ μ„±κ³Ό μ§€ν‘œ"},
            {"title": "투자 μš”μ²­", "style": "Pyramid/Funnel", "prompt_hint": "투자 규λͺ¨μ™€ ν™œμš©"}
        ]
    },
    "μ œν’ˆ μ†Œκ°œ": {
        "description": "μ‹ μ œν’ˆ 런칭, μ„œλΉ„μŠ€ μ†Œκ°œμš©",
        "slides": [
            {"title": "μ œν’ˆ 컨셉", "style": "Industrial Design", "prompt_hint": "μ œν’ˆ λ””μžμΈ"},
            {"title": "μ‚¬μš©μž λ‹ˆμ¦ˆ", "style": "Colorful Mind Map", "prompt_hint": "고객 페인포인트"},
            {"title": "κΈ°λŠ₯ μ†Œκ°œ", "style": "Mobile App Mockup", "prompt_hint": "UI/UX ν™”λ©΄"},
            {"title": "μž‘λ™ 원리", "style": "Flowchart", "prompt_hint": "κΈ°λŠ₯ ν”Œλ‘œμš°"},
            {"title": "μ‹œμž₯ ν¬μ§€μ…˜", "style": "3D Bubble Chart", "prompt_hint": "κ²½μŸμ‚¬ 비ꡐ"},
            {"title": "μΆœμ‹œ 일정", "style": "Timeline Ribbon", "prompt_hint": "런칭 λ‘œλ“œλ§΅"}
        ]
    },
    "ν”„λ‘œμ νŠΈ 보고": {
        "description": "μ§„ν–‰ 상황, μ„±κ³Ό 보고용",
        "slides": [
            {"title": "ν”„λ‘œμ νŠΈ κ°œμš”", "style": "Business Workflow", "prompt_hint": "전체 ν”„λ‘œμ„ΈμŠ€"},
            {"title": "μ§„ν–‰ ν˜„ν™©", "style": "Gantt Chart", "prompt_hint": "μž‘μ—… 일정"},
            {"title": "리슀크 관리", "style": "Risk Heat Map", "prompt_hint": "μœ„ν—˜ μš”μ†Œ"},
            {"title": "μ„±κ³Ό μ§€ν‘œ", "style": "KPI Dashboard", "prompt_hint": "달성 싀적"},
            {"title": "ν–₯ν›„ κ³„νš", "style": "Timeline Ribbon", "prompt_hint": "λ‹€μŒ 단계"}
        ]
    },
    "μ „λž΅ 기획": {
        "description": "쀑μž₯κΈ° μ „λž΅, λΉ„μ „ 수립용",
        "slides": [
            {"title": "λΉ„μ „", "style": "3D Style (Pixar-like)", "prompt_hint": "미래 λΉ„μ „"},
            {"title": "ν™˜κ²½ 뢄석", "style": "Elegant SWOT Quadrant", "prompt_hint": "λ‚΄μ™ΈλΆ€ ν™˜κ²½"},
            {"title": "μ „λž΅ 체계", "style": "Colorful Mind Map", "prompt_hint": "μ „λž΅ ꡬ쑰"},
            {"title": "κ°€μΉ˜ μ‚¬μŠ¬", "style": "Value Chain", "prompt_hint": "λΉ„μ¦ˆλ‹ˆμŠ€ λͺ¨λΈ"},
            {"title": "μ‹€ν–‰ λ‘œλ“œλ§΅", "style": "Timeline Ribbon", "prompt_hint": "단계별 κ³„νš"},
            {"title": "λͺ©ν‘œ μ§€ν‘œ", "style": "KPI Dashboard", "prompt_hint": "KPI λͺ©ν‘œ"}
        ]
    },
    "μ‚¬μš©μž μ •μ˜": {
        "description": "직접 κ΅¬μ„±ν•˜κΈ°",
        "slides": []
    }
}

def generate_prompt_with_llm(topic: str, style_example: str = None, slide_context: str = None) -> str:
    """μ£Όμ œμ™€ μŠ€νƒ€μΌ 예제λ₯Ό λ°›μ•„μ„œ LLM을 μ‚¬μš©ν•΄ 이미지 ν”„λ‘¬ν”„νŠΈλ₯Ό 생성"""
    print(f"[LLM] ν”„λ‘¬ν”„νŠΈ 생성 μ‹œμž‘: {slide_context}")
    
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    system_prompt = """You are an expert image prompt engineer specializing in creating prompts for professional presentation slides. 

Your task is to create prompts that:
1. Are highly specific and visual, perfect for PPT backgrounds or main visuals
2. Consider the slide's purpose and maintain consistency across a presentation
3. Include style references matching the given example
4. Focus on clean, professional visuals that won't distract from text overlays
5. Ensure high contrast areas for text readability when needed
6. Maintain brand consistency and professional aesthetics

Important guidelines:
- If given a style example, adapt the topic to match that specific visual style
- Consider the slide context (e.g., "ν‘œμ§€", "ν˜„ν™© 뢄석") to create appropriate visuals
- Always output ONLY the prompt without any explanation
- Keep prompts between 50-150 words for optimal results
- Ensure the visual supports rather than overwhelms the slide content"""
    
    user_message = f"Topic: {topic}"
    if style_example:
        user_message += f"\n\nStyle reference to follow:\n{style_example}"
    if slide_context:
        user_message += f"\n\nSlide context: {slide_context}"
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": system_prompt
            },
            {
                "role": "user",
                "content": user_message
            }
        ],
        "max_tokens": 300,
        "top_p": 0.8,
        "temperature": 0.7,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            prompt = result['choices'][0]['message']['content'].strip()
            print(f"[LLM] ν”„λ‘¬ν”„νŠΈ 생성 μ™„λ£Œ: {prompt[:50]}...")
            return prompt
        else:
            error_msg = f"ν”„λ‘¬ν”„νŠΈ 생성 μ‹€νŒ¨: {response.status_code}"
            print(f"[LLM] {error_msg}")
            return error_msg
    except Exception as e:
        error_msg = f"ν”„λ‘¬ν”„νŠΈ 생성 쀑 였λ₯˜ λ°œμƒ: {str(e)}"
        print(f"[LLM] {error_msg}")
        return error_msg

def translate_to_english(text: str) -> str:
    """ν•œκΈ€ ν…μŠ€νŠΈλ₯Ό μ˜μ–΄λ‘œ λ²ˆμ—­ (LLM μ‚¬μš©)"""
    if not any(ord('κ°€') <= ord(char) <= ord('힣') for char in text):
        return text
    
    print(f"[λ²ˆμ—­] ν•œκΈ€ 감지, μ˜μ–΄λ‘œ λ²ˆμ—­ μ‹œμž‘")
    
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {FRIENDLI_TOKEN}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {
                "role": "system",
                "content": "You are a translator. Translate the given Korean text to English. Only return the translation without any explanation."
            },
            {
                "role": "user",
                "content": text
            }
        ],
        "max_tokens": 500,
        "top_p": 0.8,
        "stream": False
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        if response.status_code == 200:
            result = response.json()
            translated = result['choices'][0]['message']['content'].strip()
            print(f"[λ²ˆμ—­] μ™„λ£Œ")
            return translated
        else:
            print(f"[λ²ˆμ—­] μ‹€νŒ¨, 원본 μ‚¬μš©")
            return text
    except Exception as e:
        print(f"[λ²ˆμ—­] 였λ₯˜: {str(e)}, 원본 μ‚¬μš©")
        return text

def generate_image(prompt: str, seed: int = 10, slide_info: str = "") -> Tuple[Image.Image, str]:
    """Replicate APIλ₯Ό μ‚¬μš©ν•΄ 이미지 생성"""
    print(f"\n[이미지 생성] {slide_info}")
    print(f"[이미지 생성] ν”„λ‘¬ν”„νŠΈ: {prompt[:50]}...")
    
    try:
        english_prompt = translate_to_english(prompt)
        
        if not REPLICATE_API_TOKEN:
            error_msg = "RAPI_TOKEN ν™˜κ²½λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€."
            print(f"[이미지 생성] 였λ₯˜: {error_msg}")
            return None, error_msg
        
        print(f"[이미지 생성] Replicate API 호좜 쀑...")
        client = replicate.Client(api_token=REPLICATE_API_TOKEN)
        
        input_params = {
            "seed": seed,
            "prompt": english_prompt,
            "speed_mode": "Extra Juiced πŸš€ (even more speed)",
            "output_quality": 100
        }
        
        start_time = time.time()
        output = client.run(
            "prunaai/hidream-l1-fast:17c237d753218fed0ed477cb553902b6b75735f48c128537ab829096ef3d3645",
            input=input_params
        )
        
        elapsed = time.time() - start_time
        print(f"[이미지 생성] API 응닡 λ°›μŒ ({elapsed:.1f}초)")
        
        if output:
            if isinstance(output, str) and output.startswith('http'):
                print(f"[이미지 생성] URLμ—μ„œ 이미지 λ‹€μš΄λ‘œλ“œ 쀑...")
                response = requests.get(output, timeout=30)
                img = Image.open(BytesIO(response.content))
                print(f"[이미지 생성] μ™„λ£Œ!")
                return img, english_prompt
            else:
                print(f"[이미지 생성] λ°”μ΄λ„ˆλ¦¬ 데이터 처리 쀑...")
                img = Image.open(BytesIO(output.read()))
                print(f"[이미지 생성] μ™„λ£Œ!")
                return img, english_prompt
        else:
            error_msg = "이미지 생성 μ‹€νŒ¨ - 빈 응닡"
            print(f"[이미지 생성] {error_msg}")
            return None, error_msg
            
    except Exception as e:
        error_msg = f"였λ₯˜: {str(e)}"
        print(f"[이미지 생성] {error_msg}")
        print(f"[이미지 생성] 상세 였λ₯˜:\n{traceback.format_exc()}")
        return None, error_msg

def generate_ppt_images_sequential(topic: str, template_name: str, custom_slides: List[Dict], seed: int, progress=gr.Progress()):
    """PPT ν…œν”Œλ¦Ώμ— 따라 이미지λ₯Ό 순차적으둜 μƒμ„±ν•˜λ©° μ§„ν–‰ 상황 ν‘œμ‹œ"""
    results = []
    images_for_gallery = []
    
    # ν…œν”Œλ¦Ώ 선택
    if template_name == "μ‚¬μš©μž μ •μ˜" and custom_slides:
        slides = custom_slides
    else:
        slides = PPT_TEMPLATES[template_name]["slides"]
    
    if not slides:
        yield [], "μŠ¬λΌμ΄λ“œκ°€ μ •μ˜λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€."
        return
    
    total_slides = len(slides)
    print(f"\n[PPT 생성] μ‹œμž‘ - 총 {total_slides}개 μŠ¬λΌμ΄λ“œ")
    print(f"[PPT 생성] 주제: {topic}")
    print(f"[PPT 생성] ν…œν”Œλ¦Ώ: {template_name}")
    
    # 각 μŠ¬λΌμ΄λ“œ 순차 처리
    for i, slide in enumerate(slides):
        progress((i + 1) / (total_slides + 1), f"μŠ¬λΌμ΄λ“œ {i+1}/{total_slides} 처리 쀑...")
        
        slide_info = f"μŠ¬λΌμ΄λ“œ {i+1}: {slide['title']}"
        status_msg = f"\n### πŸ”„ {slide_info} 생성 쀑...\n"
        
        # ν˜„μž¬κΉŒμ§€μ˜ μƒνƒœ μ—…λ°μ΄νŠΈ
        yield images_for_gallery, status_msg + format_results_status(results)
        
        style_key = slide["style"]
        if style_key in STYLE_TEMPLATES:
            style_info = STYLE_TEMPLATES[style_key]
            slide_context = f"{slide['title']} - {slide.get('prompt_hint', '')}"
            
            # ν”„λ‘¬ν”„νŠΈ 생성
            prompt = generate_prompt_with_llm(topic, style_info["example"], slide_context)
            
            # 이미지 생성
            slide_seed = seed + i
            img, used_prompt = generate_image(prompt, slide_seed, slide_info)
            
            # κ²°κ³Ό μ €μž₯
            result = {
                "slide_title": slide["title"],
                "style": slide["style"],
                "image": img,
                "prompt": prompt,
                "used_prompt": used_prompt,
                "success": img is not None
            }
            results.append(result)
            
            # μ„±κ³΅ν•œ μ΄λ―Έμ§€λŠ” κ°€λŸ¬λ¦¬μ— μΆ”κ°€
            if img is not None:
                caption = f"{i+1}. {slide['title']} ({style_info['name']})"
                images_for_gallery.append((img, caption))
                
                status_msg = f"\n### βœ… {slide_info} μ™„λ£Œ!\n"
            else:
                status_msg = f"\n### ❌ {slide_info} μ‹€νŒ¨: {used_prompt}\n"
            
            # μ¦‰μ‹œ μ—…λ°μ΄νŠΈ
            yield images_for_gallery, status_msg + format_results_status(results)
    
    # μ΅œμ’… κ²°κ³Ό
    progress(1.0, "μ™„λ£Œ!")
    successful = sum(1 for r in results if r["success"])
    final_status = f"\n## πŸŽ‰ 생성 μ™„λ£Œ!\n총 {total_slides}개 μŠ¬λΌμ΄λ“œ 쀑 {successful}개 성곡\n\n"
    final_status += format_results_status(results)
    
    yield images_for_gallery, final_status

def format_results_status(results: List[Dict]) -> str:
    """κ²°κ³Όλ₯Ό μƒνƒœ λ©”μ‹œμ§€λ‘œ 포맷"""
    if not results:
        return ""
    
    status_lines = ["### πŸ“Š 생성 κ²°κ³Ό:\n"]
    for i, result in enumerate(results):
        if result["success"]:
            status_lines.append(f"βœ… **μŠ¬λΌμ΄λ“œ {i+1}: {result['slide_title']}**")
            status_lines.append(f"   - μŠ€νƒ€μΌ: {result['style'].split('(')[0].strip()}")
            status_lines.append(f"   - ν”„λ‘¬ν”„νŠΈ: {result['prompt'][:60]}...\n")
        else:
            status_lines.append(f"❌ **μŠ¬λΌμ΄λ“œ {i+1}: {result['slide_title']}** - μ‹€νŒ¨")
            status_lines.append(f"   - 였λ₯˜: {result['used_prompt']}\n")
    
    return "\n".join(status_lines)

def create_custom_slides_ui():
    """μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ ꡬ성 UI"""
    slides = []
    for i in range(10):
        with gr.Row():
            with gr.Column(scale=2):
                title = gr.Textbox(
                    label=f"μŠ¬λΌμ΄λ“œ {i+1} 제λͺ©",
                    placeholder="예: ν‘œμ§€, λͺ©μ°¨, ν˜„ν™© 뢄석...",
                    visible=(i < 3)
                )
            with gr.Column(scale=3):
                style = gr.Dropdown(
                    choices=list(STYLE_TEMPLATES.keys()),
                    label=f"μŠ€νƒ€μΌ 선택",
                    visible=(i < 3)
                )
            with gr.Column(scale=3):
                hint = gr.Textbox(
                    label=f"ν”„λ‘¬ν”„νŠΈ 힌트",
                    placeholder="이 μŠ¬λΌμ΄λ“œμ—μ„œ ν‘œν˜„ν•˜κ³  싢은 λ‚΄μš©",
                    visible=(i < 3)
                )
        slides.append({"title": title, "style": style, "hint": hint})
    return slides

# Gradio μΈν„°νŽ˜μ΄μŠ€ 생성
with gr.Blocks(title="PPT 이미지 생성기", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # 🎯 AI 기반 PPT 이미지 생성기
    
    ### 전문적인 ν”„λ ˆμ  ν…Œμ΄μ…˜μ„ μœ„ν•œ λ§žμΆ€ν˜• 이미지λ₯Ό ν•œ λ²ˆμ— μƒμ„±ν•˜μ„Έμš”!
    """)
    
    # API 토큰 μƒνƒœ 확인
    if not REPLICATE_API_TOKEN:
        gr.Markdown("⚠️ **κ²½κ³ **: RAPI_TOKEN ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
    if not FRIENDLI_TOKEN:
        gr.Markdown("⚠️ **κ²½κ³ **: FRIENDLI_TOKEN ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
    
    with gr.Row():
        with gr.Column(scale=1):
            # κΈ°λ³Έ μž…λ ₯
            topic_input = gr.Textbox(
                label="ν”„λ ˆμ  ν…Œμ΄μ…˜ 주제",
                placeholder="예: AI μŠ€νƒ€νŠΈμ—… 투자 유치, μ‹ μ œν’ˆ 런칭, λ””μ§€ν„Έ μ „ν™˜ μ „λž΅",
                lines=2
            )
            
            # PPT ν…œν”Œλ¦Ώ 선택
            template_select = gr.Dropdown(
                choices=list(PPT_TEMPLATES.keys()),
                label="PPT ν…œν”Œλ¦Ώ 선택",
                value="λΉ„μ¦ˆλ‹ˆμŠ€ μ œμ•ˆμ„œ",
                info="λͺ©μ μ— λ§žλŠ” ν…œν”Œλ¦Ώμ„ μ„ νƒν•˜μ„Έμš”"
            )
            
            # ν…œν”Œλ¦Ώ μ„€λͺ…
            template_info = gr.Markdown()
            
            # μ‹œλ“œ κ°’
            seed_input = gr.Slider(
                minimum=1,
                maximum=100,
                value=10,
                step=1,
                label="μ‹œλ“œ κ°’"
            )
            
            generate_btn = gr.Button("πŸš€ PPT 이미지 μ„ΈνŠΈ 생성", variant="primary", size="lg")
            
            # μ‚¬μš©μž μ •μ˜ μ„Ήμ…˜
            with gr.Accordion("πŸ“ μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ ꡬ성", open=False) as custom_accordion:
                gr.Markdown("ν…œν”Œλ¦Ώμ„ μ‚¬μš©ν•˜μ§€ μ•Šκ³  직접 μŠ¬λΌμ΄λ“œλ₯Ό κ΅¬μ„±ν•˜μ„Έμš”.")
                custom_slides_components = create_custom_slides_ui()
            
        with gr.Column(scale=2):
            # μ§„ν–‰ 상황 ν‘œμ‹œ
            status_output = gr.Markdown(
                value="### πŸ‘† ν…œν”Œλ¦Ώμ„ μ„ νƒν•˜κ³  생성 λ²„νŠΌμ„ ν΄λ¦­ν•˜μ„Έμš”!\n\n생성 μ§„ν–‰ 상황이 μ‹€μ‹œκ°„μœΌλ‘œ ν‘œμ‹œλ©λ‹ˆλ‹€."
            )
            
            # 결과 가러리
            output_gallery = gr.Gallery(
                label="μƒμ„±λœ PPT 이미지",
                show_label=True,
                elem_id="gallery",
                columns=3,
                rows=3,
                object_fit="contain",
                height="auto"
            )
    
    # μŠ€νƒ€μΌ κ°€μ΄λ“œ
    with gr.Accordion("πŸ“š μŠ€νƒ€μΌλ³„ ν™œμš© κ°€μ΄λ“œ", open=False):
        style_guide = "### PPT μ œμž‘μ„ μœ„ν•œ μŠ€νƒ€μΌ κ°€μ΄λ“œ\n\n"
        for style_name, style_info in STYLE_TEMPLATES.items():
            style_guide += f"**{style_name}**\n"
            style_guide += f"- μš©λ„: {style_info['use_case']}\n"
            style_guide += f"- νŠΉμ§•: {style_info['description']}\n\n"
        gr.Markdown(style_guide)
    
    # ν™œμš© 팁
    gr.Markdown("""
    ---
    ### πŸ’‘ PPT μ œμž‘ 팁:
    
    1. **ν…œν”Œλ¦Ώ ν™œμš©**: λͺ©μ μ— λ§žλŠ” ν…œν”Œλ¦Ώμ„ μ„ νƒν•˜λ©΄ μ΅œμ ν™”λœ μŠ¬λΌμ΄λ“œ ꡬ성을 μ œκ³΅ν•©λ‹ˆλ‹€
    2. **일관성**: ν•˜λ‚˜μ˜ 주제둜 전체 μŠ¬λΌμ΄λ“œλ₯Ό μƒμ„±ν•˜μ—¬ μ‹œκ°μ  일관성을 μœ μ§€ν•©λ‹ˆλ‹€
    3. **μ‹€μ‹œκ°„ 확인**: 각 μŠ¬λΌμ΄λ“œκ°€ 생성될 λ•Œλ§ˆλ‹€ μ§„ν–‰ 상황을 확인할 수 μžˆμŠ΅λ‹ˆλ‹€
    4. **κ³ ν™”μ§ˆ**: λͺ¨λ“  μ΄λ―Έμ§€λŠ” ν”„λ ˆμ  ν…Œμ΄μ…˜μ— μ ν•©ν•œ κ³ ν•΄μƒλ„λ‘œ μƒμ„±λ©λ‹ˆλ‹€
    """)
    
    # 이벀트 ν•Έλ“€λŸ¬
    def update_template_info(template_name):
        if template_name in PPT_TEMPLATES:
            template = PPT_TEMPLATES[template_name]
            info = f"**{template['description']}**\n\nν¬ν•¨λœ μŠ¬λΌμ΄λ“œ:\n"
            for i, slide in enumerate(template['slides']):
                info += f"{i+1}. {slide['title']} - {STYLE_TEMPLATES[slide['style']]['use_case']}\n"
            return info
        return ""
    
    def generate_ppt_images_handler(topic, template_name, seed, progress=gr.Progress(), *custom_inputs):
        if not topic.strip():
            yield [], "❌ 주제λ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”."
            return
        
        # μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ 처리
        custom_slides = []
        if template_name == "μ‚¬μš©μž μ •μ˜":
            for i in range(0, len(custom_inputs), 3):
                title = custom_inputs[i]
                style = custom_inputs[i+1] if i+1 < len(custom_inputs) else None
                hint = custom_inputs[i+2] if i+2 < len(custom_inputs) else ""
                
                if title and style:
                    custom_slides.append({
                        "title": title,
                        "style": style,
                        "prompt_hint": hint
                    })
        
        # 순차적으둜 이미지 μƒμ„±ν•˜λ©° μ§„ν–‰ 상황 ν‘œμ‹œ
        for gallery, status in generate_ppt_images_sequential(topic, template_name, custom_slides, seed, progress):
            yield gallery, status
    
    # 이벀트 μ—°κ²°
    template_select.change(
        fn=update_template_info,
        inputs=[template_select],
        outputs=[template_info]
    )
    
    # μ‚¬μš©μž μ •μ˜ μž…λ ₯ μˆ˜μ§‘
    all_custom_inputs = []
    for slide_components in custom_slides_components:
        all_custom_inputs.extend([
            slide_components["title"],
            slide_components["style"],
            slide_components["hint"]
        ])
    
    generate_btn.click(
        fn=generate_ppt_images_handler,
        inputs=[topic_input, template_select, seed_input] + all_custom_inputs,
        outputs=[output_gallery, status_output]
    )
    
    # 초기 ν…œν”Œλ¦Ώ 정보 ν‘œμ‹œ
    demo.load(
        fn=update_template_info,
        inputs=[template_select],
        outputs=[template_info]
    )

# μ•± μ‹€ν–‰
if __name__ == "__main__":
    print("\n" + "="*50)
    print("πŸš€ PPT 이미지 생성기 μ‹œμž‘!")
    print("="*50)
    
    # ν™˜κ²½ λ³€μˆ˜ 확인
    if not REPLICATE_API_TOKEN:
        print("⚠️  κ²½κ³ : RAPI_TOKEN ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
    else:
        print("βœ… RAPI_TOKEN 확인됨")
        
    if not FRIENDLI_TOKEN:
        print("⚠️  κ²½κ³ : FRIENDLI_TOKEN ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
    else:
        print("βœ… FRIENDLI_TOKEN 확인됨")
    
    print("="*50 + "\n")
    
    demo.launch()