ginipick commited on
Commit
0de860d
Β·
verified Β·
1 Parent(s): 68af0a6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1728 -0
app.py ADDED
@@ -0,0 +1,1728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import replicate
3
+ import requests
4
+ import os
5
+ import json
6
+ import asyncio
7
+ import concurrent.futures
8
+ from io import BytesIO
9
+ from PIL import Image
10
+ from typing import List, Tuple, Dict
11
+ import zipfile
12
+ from datetime import datetime
13
+ import time
14
+ import traceback
15
+ import base64
16
+ from pptx import Presentation
17
+ from pptx.util import Inches, Pt
18
+ from pptx.dml.color import RGBColor
19
+ from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
20
+ from pptx.enum.shapes import MSO_SHAPE
21
+ import PyPDF2
22
+ import pandas as pd
23
+ import chardet
24
+
25
+ # ν™˜κ²½ λ³€μˆ˜μ—μ„œ 토큰 κ°€μ Έμ˜€κΈ°
26
+ REPLICATE_API_TOKEN = os.getenv("RAPI_TOKEN")
27
+ FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN")
28
+ BRAVE_API_TOKEN = os.getenv("BAPI_TOKEN")
29
+
30
+ # λ””μžμΈ ν…Œλ§ˆ μ •μ˜
31
+ DESIGN_THEMES = {
32
+ "λ―Έλ‹ˆλ©€ 라이트": {
33
+ "name": "Minimal Light",
34
+ "description": "밝고 κΉ¨λ—ν•œ λ―Έλ‹ˆλ©€ λ””μžμΈ",
35
+ "background": RGBColor(250, 250, 252),
36
+ "title_color": RGBColor(33, 37, 41),
37
+ "subtitle_color": RGBColor(52, 58, 64),
38
+ "text_color": RGBColor(73, 80, 87),
39
+ "accent_color": RGBColor(0, 123, 255),
40
+ "box_fill": RGBColor(255, 255, 255),
41
+ "box_opacity": 0.95,
42
+ "shadow": True,
43
+ "gradient": False
44
+ },
45
+ "λͺ¨λ˜ κ·ΈλΌλ””μ–ΈνŠΈ": {
46
+ "name": "Modern Gradient",
47
+ "description": "λΆ€λ“œλŸ¬μš΄ κ·ΈλΌλ””μ–ΈνŠΈμ™€ ν˜„λŒ€μ  λŠλ‚Œ",
48
+ "background": RGBColor(245, 247, 250),
49
+ "title_color": RGBColor(25, 42, 86),
50
+ "subtitle_color": RGBColor(68, 85, 102),
51
+ "text_color": RGBColor(85, 102, 119),
52
+ "accent_color": RGBColor(103, 58, 183),
53
+ "box_fill": RGBColor(249, 250, 251),
54
+ "box_opacity": 0.9,
55
+ "shadow": True,
56
+ "gradient": True
57
+ },
58
+ "닀크 μ—˜λ ˆκ°•μŠ€": {
59
+ "name": "Dark Elegance",
60
+ "description": "μ„Έλ ¨λœ 닀크 λͺ¨λ“œ λ””μžμΈ",
61
+ "background": RGBColor(25, 25, 35),
62
+ "title_color": RGBColor(240, 240, 245),
63
+ "subtitle_color": RGBColor(200, 200, 210),
64
+ "text_color": RGBColor(170, 170, 180),
65
+ "accent_color": RGBColor(0, 188, 212),
66
+ "box_fill": RGBColor(35, 35, 45),
67
+ "box_opacity": 0.85,
68
+ "shadow": False,
69
+ "gradient": False
70
+ },
71
+ "λ„€μ΄μ²˜ κ·Έλ¦°": {
72
+ "name": "Nature Green",
73
+ "description": "μžμ—° μΉœν™”μ μΈ κ·Έλ¦° ν…Œλ§ˆ",
74
+ "background": RGBColor(242, 248, 244),
75
+ "title_color": RGBColor(27, 67, 50),
76
+ "subtitle_color": RGBColor(45, 106, 79),
77
+ "text_color": RGBColor(64, 125, 98),
78
+ "accent_color": RGBColor(76, 175, 80),
79
+ "box_fill": RGBColor(255, 255, 255),
80
+ "box_opacity": 0.92,
81
+ "shadow": True,
82
+ "gradient": False
83
+ },
84
+ "μ½”νΌλ ˆμ΄νŠΈ 블루": {
85
+ "name": "Corporate Blue",
86
+ "description": "전문적인 λΉ„μ¦ˆλ‹ˆμŠ€ μŠ€νƒ€μΌ",
87
+ "background": RGBColor(244, 247, 252),
88
+ "title_color": RGBColor(13, 71, 161),
89
+ "subtitle_color": RGBColor(25, 118, 210),
90
+ "text_color": RGBColor(42, 63, 84),
91
+ "accent_color": RGBColor(33, 150, 243),
92
+ "box_fill": RGBColor(255, 255, 255),
93
+ "box_opacity": 0.95,
94
+ "shadow": True,
95
+ "gradient": False
96
+ }
97
+ }
98
+
99
+ # μŠ€νƒ€μΌ μ •μ˜ (ν‘œμ§€μ™€ μ’…λ£Œ μŠ¬λΌμ΄λ“œ μŠ€νƒ€μΌ μΆ”κ°€)
100
+ STYLE_TEMPLATES = {
101
+ "Title Slide (Hero)": {
102
+ "name": "Title Slide",
103
+ "description": "Impactful hero image for title slide",
104
+ "use_case": "ν‘œμ§€, 타이틀",
105
+ "example": "A dramatic wide-angle view of a modern glass skyscraper reaching into clouds with golden sunset lighting, symbolizing growth and ambition. Ultra-realistic photography style, cinematic composition, lens flare, professional corporate aesthetic"
106
+ },
107
+ "Thank You Slide": {
108
+ "name": "Thank You",
109
+ "description": "Elegant closing slide design",
110
+ "use_case": "λ§ˆμ§€λ§‰ 인사",
111
+ "example": "Abstract elegant background with soft gradient from deep blue to purple, golden particles floating like celebration confetti, subtle light rays, with space for 'Thank You' text. Minimalist, professional, warm feeling"
112
+ },
113
+ "3D Style (Pixar-like)": {
114
+ "name": "3D Style",
115
+ "description": "Pixar-esque 3D render with volumetric lighting",
116
+ "use_case": "ν‘œμ§€, λΉ„μ „, 미래 컨셉",
117
+ "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."
118
+ },
119
+ "Elegant SWOT Quadrant": {
120
+ "name": "SWOT Analysis",
121
+ "description": "Flat-design 4-grid layout with minimal shadows",
122
+ "use_case": "ν˜„ν™© 뢄석, μ „λž΅ 평가",
123
+ "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"
124
+ },
125
+ "Colorful Mind Map": {
126
+ "name": "Mind Map",
127
+ "description": "Hand-drawn educational style with vibrant colors",
128
+ "use_case": "λΈŒλ ˆμΈμŠ€ν† λ°, 아이디어 정리",
129
+ "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"
130
+ },
131
+ "Business Workflow": {
132
+ "name": "Business Process",
133
+ "description": "End-to-end business workflow with clear phases",
134
+ "use_case": "ν”„λ‘œμ„ΈμŠ€ μ„€λͺ…, 단계별 μ§„ν–‰",
135
+ "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"
136
+ },
137
+ "Industrial Design": {
138
+ "name": "Product Design",
139
+ "description": "Sleek industrial design concept sketch",
140
+ "use_case": "μ œν’ˆ μ†Œκ°œ, 컨셉 λ””μžμΈ",
141
+ "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"
142
+ },
143
+ "3D Bubble Chart": {
144
+ "name": "Bubble Chart",
145
+ "description": "Clean 3D bubble visualization",
146
+ "use_case": "비ꡐ 뢄석, 포지셔닝",
147
+ "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"
148
+ },
149
+ "Timeline Ribbon": {
150
+ "name": "Timeline",
151
+ "description": "Horizontal ribbon timeline with cyber-futuristic vibe",
152
+ "use_case": "일정, λ‘œλ“œλ§΅, λ§ˆμΌμŠ€ν†€",
153
+ "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"
154
+ },
155
+ "Risk Heat Map": {
156
+ "name": "Heat Map",
157
+ "description": "Risk assessment heat map with gradient colors",
158
+ "use_case": "리슀크 뢄석, μš°μ„ μˆœμœ„",
159
+ "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"
160
+ },
161
+ "Pyramid/Funnel": {
162
+ "name": "Funnel Chart",
163
+ "description": "Multi-layer gradient funnel visualization",
164
+ "use_case": "단계별 μΆ•μ†Œ, 핡심 λ„μΆœ",
165
+ "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"
166
+ },
167
+ "KPI Dashboard": {
168
+ "name": "Dashboard",
169
+ "description": "Dark-mode analytics dashboard with sci-fi interface",
170
+ "use_case": "μ„±κ³Ό μ§€ν‘œ, 싀적 λŒ€μ‹œλ³΄λ“œ",
171
+ "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"
172
+ },
173
+ "Value Chain": {
174
+ "name": "Value Chain",
175
+ "description": "Horizontal value chain with industrial look",
176
+ "use_case": "κ°€μΉ˜ μ‚¬μŠ¬, λΉ„μ¦ˆλ‹ˆμŠ€ λͺ¨λΈ",
177
+ "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"
178
+ },
179
+ "Gantt Chart": {
180
+ "name": "Gantt Chart",
181
+ "description": "Hand-drawn style Gantt chart with playful colors",
182
+ "use_case": "ν”„λ‘œμ νŠΈ 일정, μž‘μ—… 관리",
183
+ "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"
184
+ },
185
+ "Mobile App Mockup": {
186
+ "name": "App Mockup",
187
+ "description": "Clean wireframe for mobile app design",
188
+ "use_case": "μ•±/μ›Ή UI, ν™”λ©΄ 섀계",
189
+ "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"
190
+ },
191
+ "Flowchart": {
192
+ "name": "Flowchart",
193
+ "description": "Vibrant flowchart with minimalistic icons",
194
+ "use_case": "μ˜μ‚¬κ²°μ •, ν”„λ‘œμ„ΈμŠ€ 흐름",
195
+ "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"
196
+ }
197
+ }
198
+
199
+ # PPT ν…œν”Œλ¦Ώ μ •μ˜ (λ™μ μœΌλ‘œ μŠ¬λΌμ΄λ“œ 수 μ‘°μ • κ°€λŠ₯)
200
+ PPT_TEMPLATES = {
201
+ "λΉ„μ¦ˆλ‹ˆμŠ€ μ œμ•ˆμ„œ": {
202
+ "description": "투자 유치, 사업 μ œμ•ˆμš©",
203
+ "core_slides": [
204
+ {"title": "λͺ©μ°¨", "style": "Flowchart", "prompt_hint": "ν”„λ ˆμ  ν…Œμ΄μ…˜ ꡬ쑰"},
205
+ {"title": "문제 μ •μ˜", "style": "Colorful Mind Map", "prompt_hint": "ν˜„μž¬ μ‹œμž₯의 문제점"},
206
+ {"title": "ν˜„ν™© 뢄석", "style": "Elegant SWOT Quadrant", "prompt_hint": "강점, 약점, 기회, μœ„ν˜‘"},
207
+ {"title": "μ†”λ£¨μ…˜", "style": "Industrial Design", "prompt_hint": "μ œν’ˆ/μ„œλΉ„μŠ€ 컨셉"},
208
+ {"title": "ν”„λ‘œμ„ΈμŠ€", "style": "Business Workflow", "prompt_hint": "μ‹€ν–‰ 단계"},
209
+ {"title": "일정", "style": "Timeline Ribbon", "prompt_hint": "μ£Όμš” λ§ˆμΌμŠ€ν†€"}
210
+ ],
211
+ "optional_slides": [
212
+ {"title": "μ‹œμž₯ 규λͺ¨", "style": "3D Bubble Chart", "prompt_hint": "μ‹œμž₯ κΈ°νšŒμ™€ μ„±μž₯μ„±"},
213
+ {"title": "경쟁 뢄석", "style": "Risk Heat Map", "prompt_hint": "κ²½μŸμ‚¬ 포지셔닝"},
214
+ {"title": "λΉ„μ¦ˆλ‹ˆμŠ€ λͺ¨λΈ", "style": "Value Chain", "prompt_hint": "수읡 ꡬ쑰"},
215
+ {"title": "νŒ€ μ†Œκ°œ", "style": "Colorful Mind Map", "prompt_hint": "핡심 νŒ€μ›κ³Ό μ—­λŸ‰"},
216
+ {"title": "재무 κ³„νš", "style": "KPI Dashboard", "prompt_hint": "μ˜ˆμƒ 맀좜과 손읡"},
217
+ {"title": "μœ„ν—˜ 관리", "style": "Risk Heat Map", "prompt_hint": "μ£Όμš” λ¦¬μŠ€ν¬μ™€ λŒ€μ‘"},
218
+ {"title": "νŒŒνŠΈλ„ˆμ‹­", "style": "Business Workflow", "prompt_hint": "μ „λž΅μ  제휴"},
219
+ {"title": "기술 μŠ€νƒ", "style": "Flowchart", "prompt_hint": "핡심 기술 ꡬ쑰"},
220
+ {"title": "고객 사둀", "style": "Industrial Design", "prompt_hint": "성곡 사둀"},
221
+ {"title": "μ„±μž₯ μ „λž΅", "style": "Timeline Ribbon", "prompt_hint": "ν™•μž₯ κ³„νš"},
222
+ {"title": "투자 ν™œμš©", "style": "Pyramid/Funnel", "prompt_hint": "자금 μ‚¬μš© κ³„νš"},
223
+ {"title": "Exit μ „λž΅", "style": "Timeline Ribbon", "prompt_hint": "좜ꡬ μ „λž΅"}
224
+ ]
225
+ },
226
+ "μ œν’ˆ μ†Œκ°œ": {
227
+ "description": "μ‹ μ œν’ˆ 런칭, μ„œλΉ„μŠ€ μ†Œκ°œμš©",
228
+ "core_slides": [
229
+ {"title": "μ œν’ˆ 컨셉", "style": "Industrial Design", "prompt_hint": "μ œν’ˆ λ””μžμΈ"},
230
+ {"title": "μ‚¬μš©μž λ‹ˆμ¦ˆ", "style": "Colorful Mind Map", "prompt_hint": "고객 페인포인트"},
231
+ {"title": "κΈ°λŠ₯ μ†Œκ°œ", "style": "Mobile App Mockup", "prompt_hint": "UI/UX ν™”λ©΄"},
232
+ {"title": "μž‘λ™ 원리", "style": "Flowchart", "prompt_hint": "κΈ°λŠ₯ ν”Œλ‘œμš°"},
233
+ {"title": "μ‹œμž₯ ν¬μ§€μ…˜", "style": "3D Bubble Chart", "prompt_hint": "κ²½μŸμ‚¬ 비ꡐ"},
234
+ {"title": "μΆœμ‹œ 일정", "style": "Timeline Ribbon", "prompt_hint": "런칭 λ‘œλ“œλ§΅"}
235
+ ],
236
+ "optional_slides": [
237
+ {"title": "νƒ€κ²Ÿ 고객", "style": "Colorful Mind Map", "prompt_hint": "μ£Όμš” 고객측"},
238
+ {"title": "가격 μ •μ±…", "style": "Pyramid/Funnel", "prompt_hint": "가격 μ „λž΅"},
239
+ {"title": "기술 μš°μœ„", "style": "Industrial Design", "prompt_hint": "핡심 기술"},
240
+ {"title": "μ‚¬μš© μ‹œλ‚˜λ¦¬μ˜€", "style": "Business Workflow", "prompt_hint": "ν™œμš© 사둀"},
241
+ {"title": "고객 ν›„κΈ°", "style": "KPI Dashboard", "prompt_hint": "μ‚¬μš©μž 평가"},
242
+ {"title": "판맀 채널", "style": "Value Chain", "prompt_hint": "μœ ν†΅ μ „λž΅"},
243
+ {"title": "λ§ˆμΌ€νŒ… μ „λž΅", "style": "Timeline Ribbon", "prompt_hint": "홍보 κ³„νš"},
244
+ {"title": "μ„±λŠ₯ 비ꡐ", "style": "3D Bubble Chart", "prompt_hint": "벀치마크"}
245
+ ]
246
+ },
247
+ "ν”„λ‘œμ νŠΈ 보고": {
248
+ "description": "μ§„ν–‰ 상황, μ„±κ³Ό 보고용",
249
+ "core_slides": [
250
+ {"title": "ν”„λ‘œμ νŠΈ κ°œμš”", "style": "Business Workflow", "prompt_hint": "전체 ν”„λ‘œμ„ΈμŠ€"},
251
+ {"title": "μ§„ν–‰ ν˜„ν™©", "style": "Gantt Chart", "prompt_hint": "μž‘μ—… 일정"},
252
+ {"title": "리슀크 관리", "style": "Risk Heat Map", "prompt_hint": "μœ„ν—˜ μš”μ†Œ"},
253
+ {"title": "μ„±κ³Ό μ§€ν‘œ", "style": "KPI Dashboard", "prompt_hint": "달성 싀적"},
254
+ {"title": "ν–₯ν›„ κ³„νš", "style": "Timeline Ribbon", "prompt_hint": "λ‹€μŒ 단계"}
255
+ ],
256
+ "optional_slides": [
257
+ {"title": "μ˜ˆμ‚° ν˜„ν™©", "style": "Pyramid/Funnel", "prompt_hint": "μ˜ˆμ‚° μ§‘ν–‰"},
258
+ {"title": "νŒ€ μ„±κ³Ό", "style": "3D Bubble Chart", "prompt_hint": "νŒ€λ³„ 기여도"},
259
+ {"title": "이슈 관리", "style": "Risk Heat Map", "prompt_hint": "μ£Όμš” 이슈"},
260
+ {"title": "κ°œμ„  사항", "style": "Colorful Mind Map", "prompt_hint": "ν”„λ‘œμ„ΈμŠ€ κ°œμ„ "},
261
+ {"title": "κ΅ν›ˆ", "style": "Business Workflow", "prompt_hint": "배운 점"}
262
+ ]
263
+ },
264
+ "μ „λž΅ 기획": {
265
+ "description": "쀑μž₯κΈ° μ „λž΅, λΉ„μ „ 수립용",
266
+ "core_slides": [
267
+ {"title": "λΉ„μ „", "style": "3D Style (Pixar-like)", "prompt_hint": "미래 λΉ„μ „"},
268
+ {"title": "ν™˜κ²½ 뢄석", "style": "Elegant SWOT Quadrant", "prompt_hint": "λ‚΄μ™ΈλΆ€ ν™˜κ²½"},
269
+ {"title": "μ „λž΅ 체계", "style": "Colorful Mind Map", "prompt_hint": "μ „λž΅ ꡬ쑰"},
270
+ {"title": "κ°€μΉ˜ μ‚¬μŠ¬", "style": "Value Chain", "prompt_hint": "λΉ„μ¦ˆλ‹ˆμŠ€ λͺ¨λΈ"},
271
+ {"title": "μ‹€ν–‰ λ‘œλ“œλ§΅", "style": "Timeline Ribbon", "prompt_hint": "단계별 κ³„νš"},
272
+ {"title": "λͺ©ν‘œ μ§€ν‘œ", "style": "KPI Dashboard", "prompt_hint": "KPI λͺ©ν‘œ"}
273
+ ],
274
+ "optional_slides": [
275
+ {"title": "μ‹œμž₯ 전망", "style": "3D Bubble Chart", "prompt_hint": "미래 μ‹œμž₯"},
276
+ {"title": "ν˜μ‹  λ°©ν–₯", "style": "Industrial Design", "prompt_hint": "ν˜μ‹  μ „λž΅"},
277
+ {"title": "쑰직 λ³€ν™”", "style": "Business Workflow", "prompt_hint": "쑰직 개편"},
278
+ {"title": "λ””μ§€ν„Έ μ „ν™˜", "style": "Flowchart", "prompt_hint": "DX μ „λž΅"},
279
+ {"title": "지속가λŠ₯μ„±", "style": "Timeline Ribbon", "prompt_hint": "ESG μ „λž΅"}
280
+ ]
281
+ },
282
+ "μ‚¬μš©μž μ •μ˜": {
283
+ "description": "직접 κ΅¬μ„±ν•˜κΈ°",
284
+ "core_slides": [],
285
+ "optional_slides": []
286
+ }
287
+ }
288
+
289
+ def brave_search(query: str) -> List[Dict]:
290
+ """Brave Search APIλ₯Ό μ‚¬μš©ν•œ μ›Ή 검색"""
291
+ if not BRAVE_API_TOKEN:
292
+ print("[Brave Search] API 토큰이 μ—†μ–΄ 검색을 κ±΄λ„ˆλœλ‹ˆλ‹€.")
293
+ return []
294
+
295
+ print(f"[Brave Search] 검색어: {query}")
296
+
297
+ headers = {
298
+ "Accept": "application/json",
299
+ "X-Subscription-Token": BRAVE_API_TOKEN
300
+ }
301
+
302
+ params = {
303
+ "q": query,
304
+ "count": 5
305
+ }
306
+
307
+ try:
308
+ response = requests.get(
309
+ "https://api.search.brave.com/res/v1/web/search",
310
+ headers=headers,
311
+ params=params,
312
+ timeout=10
313
+ )
314
+
315
+ if response.status_code == 200:
316
+ data = response.json()
317
+ results = []
318
+ for item in data.get("web", {}).get("results", [])[:3]:
319
+ results.append({
320
+ "title": item.get("title", ""),
321
+ "description": item.get("description", ""),
322
+ "url": item.get("url", "")
323
+ })
324
+ print(f"[Brave Search] {len(results)}개 κ²°κ³Ό νšλ“")
325
+ return results
326
+ else:
327
+ print(f"[Brave Search] 였λ₯˜: {response.status_code}")
328
+ return []
329
+ except Exception as e:
330
+ print(f"[Brave Search] μ˜ˆμ™Έ: {str(e)}")
331
+ return []
332
+
333
+ def read_uploaded_file(file_path: str) -> str:
334
+ """μ—…λ‘œλ“œλœ 파일 읽기 (PDF, CSV, TXT)"""
335
+ print(f"[파일 읽기] {file_path}")
336
+
337
+ try:
338
+ # 파일 ν™•μž₯자 확인
339
+ ext = os.path.splitext(file_path)[1].lower()
340
+
341
+ if ext == '.pdf':
342
+ # PDF 읽기
343
+ with open(file_path, 'rb') as file:
344
+ pdf_reader = PyPDF2.PdfReader(file)
345
+ text = ""
346
+ for page in pdf_reader.pages:
347
+ text += page.extract_text() + "\n"
348
+ return text[:5000] # μ΅œλŒ€ 5000자
349
+
350
+ elif ext == '.csv':
351
+ # CSV 읽기
352
+ # 인코딩 감지
353
+ with open(file_path, 'rb') as file:
354
+ raw_data = file.read()
355
+ result = chardet.detect(raw_data)
356
+ encoding = result['encoding'] or 'utf-8'
357
+
358
+ df = pd.read_csv(file_path, encoding=encoding)
359
+ return f"CSV 데이터:\n{df.head(20).to_string()}\n\nμš”μ•½: {len(df)} ν–‰, {len(df.columns)} μ—΄"
360
+
361
+ elif ext in ['.txt', '.text']:
362
+ # ν…μŠ€νŠΈ 파일 읽기
363
+ with open(file_path, 'rb') as file:
364
+ raw_data = file.read()
365
+ result = chardet.detect(raw_data)
366
+ encoding = result['encoding'] or 'utf-8'
367
+
368
+ with open(file_path, 'r', encoding=encoding) as file:
369
+ return file.read()[:5000] # μ΅œλŒ€ 5000자
370
+ else:
371
+ return "μ§€μ›ν•˜μ§€ μ•ŠλŠ” 파일 ν˜•μ‹μž…λ‹ˆλ‹€."
372
+
373
+ except Exception as e:
374
+ return f"파일 읽기 였λ₯˜: {str(e)}"
375
+
376
+ def generate_presentation_notes(topic: str, slide_title: str, content: Dict) -> str:
377
+ """각 μŠ¬λΌμ΄λ“œμ˜ λ°œν‘œμž λ…ΈνŠΈ 생성 (ꡬ어체)"""
378
+ print(f"[λ°œν‘œμž λ…ΈνŠΈ] {slide_title} 생성 쀑...")
379
+
380
+ url = "https://api.friendli.ai/dedicated/v1/chat/completions"
381
+ headers = {
382
+ "Authorization": f"Bearer {FRIENDLI_TOKEN}",
383
+ "Content-Type": "application/json"
384
+ }
385
+
386
+ system_prompt = """You are a professional presentation coach who creates natural, conversational speaker notes.
387
+
388
+ Create speaker notes that:
389
+ 1. Sound natural and conversational, as if speaking to an audience
390
+ 2. Include transitions and engagement phrases
391
+ 3. Reference the slide content but expand with additional context
392
+ 4. Use a warm, professional tone
393
+ 5. Be 100-150 words long
394
+ 6. Include pauses and emphasis markers where appropriate
395
+
396
+ Format:
397
+ - Use conversational language
398
+ - Include transition phrases
399
+ - Add engagement questions or comments
400
+ - Keep it professional but friendly"""
401
+
402
+ bullet_text = "\n".join(content.get("bullet_points", []))
403
+ user_message = f"""Topic: {topic}
404
+ Slide Title: {slide_title}
405
+ Subtitle: {content.get('subtitle', '')}
406
+ Key Points:
407
+ {bullet_text}
408
+
409
+ Create natural speaker notes for presenting this slide."""
410
+
411
+ payload = {
412
+ "model": "dep89a2fld32mcm",
413
+ "messages": [
414
+ {
415
+ "role": "system",
416
+ "content": system_prompt
417
+ },
418
+ {
419
+ "role": "user",
420
+ "content": user_message
421
+ }
422
+ ],
423
+ "max_tokens": 300,
424
+ "temperature": 0.8,
425
+ "stream": False
426
+ }
427
+
428
+ try:
429
+ response = requests.post(url, json=payload, headers=headers, timeout=30)
430
+ if response.status_code == 200:
431
+ result = response.json()
432
+ notes = result['choices'][0]['message']['content'].strip()
433
+
434
+ # ν•œκΈ€ 주제인 경우 λ²ˆμ—­
435
+ if any(ord('κ°€') <= ord(char) <= ord('힣') for char in topic):
436
+ notes = translate_content_to_korean(notes)
437
+
438
+ return notes
439
+ else:
440
+ return "이 μŠ¬λΌμ΄λ“œμ—μ„œλŠ” 핡심 λ‚΄μš©μ„ μ„€λͺ…ν•΄ μ£Όμ„Έμš”."
441
+ except Exception as e:
442
+ print(f"[λ°œν‘œμž λ…ΈνŠΈ] 였λ₯˜: {str(e)}")
443
+ return "이 μŠ¬λΌμ΄λ“œμ—μ„œλŠ” 핡심 λ‚΄μš©μ„ μ„€λͺ…ν•΄ μ£Όμ„Έμš”."
444
+
445
+ def generate_slide_content(topic: str, slide_title: str, slide_context: str, uploaded_content: str = None, web_search_results: List[Dict] = None) -> Dict[str, str]:
446
+ """각 μŠ¬λΌμ΄λ“œμ˜ ν…μŠ€νŠΈ λ‚΄μš© 생성"""
447
+ print(f"[μŠ¬λΌμ΄λ“œ λ‚΄μš©] {slide_title} ν…μŠ€νŠΈ 생성 쀑...")
448
+
449
+ url = "https://api.friendli.ai/dedicated/v1/chat/completions"
450
+ headers = {
451
+ "Authorization": f"Bearer {FRIENDLI_TOKEN}",
452
+ "Content-Type": "application/json"
453
+ }
454
+
455
+ system_prompt = """You are a professional presentation content writer specializing in creating concise, impactful slide content.
456
+
457
+ Your task is to create:
458
+ 1. A compelling subtitle (max 10 words)
459
+ 2. Exactly 5 bullet points, each being a complete, concise sentence
460
+ 3. Each bullet point should be 10-15 words
461
+
462
+ Guidelines:
463
+ - Be specific and actionable
464
+ - Use professional business language
465
+ - Include relevant data points or metrics when appropriate
466
+ - Ensure content aligns with the slide's purpose
467
+ - Make each point distinct and valuable
468
+ - Use active voice and strong verbs
469
+
470
+ Output format:
471
+ Subtitle: [subtitle here]
472
+ β€’ [Point 1]
473
+ β€’ [Point 2]
474
+ β€’ [Point 3]
475
+ β€’ [Point 4]
476
+ β€’ [Point 5]"""
477
+
478
+ user_message = f"""Topic: {topic}
479
+ Slide Title: {slide_title}
480
+ Context: {slide_context}"""
481
+
482
+ # μ—…λ‘œλ“œλœ μ½˜ν…μΈ κ°€ 있으면 μΆ”κ°€
483
+ if uploaded_content:
484
+ user_message += f"\n\nReference Material:\n{uploaded_content[:1000]}"
485
+
486
+ # μ›Ή 검색 κ²°κ³Όκ°€ 있으면 μΆ”κ°€
487
+ if web_search_results:
488
+ search_context = "\n\nWeb Search Results:\n"
489
+ for result in web_search_results[:3]:
490
+ search_context += f"- {result['title']}: {result['description']}\n"
491
+ user_message += search_context
492
+
493
+ user_message += "\n\nCreate compelling content for this presentation slide."
494
+
495
+ payload = {
496
+ "model": "dep89a2fld32mcm",
497
+ "messages": [
498
+ {
499
+ "role": "system",
500
+ "content": system_prompt
501
+ },
502
+ {
503
+ "role": "user",
504
+ "content": user_message
505
+ }
506
+ ],
507
+ "max_tokens": 300,
508
+ "top_p": 0.8,
509
+ "temperature": 0.7,
510
+ "stream": False
511
+ }
512
+
513
+ try:
514
+ response = requests.post(url, json=payload, headers=headers, timeout=30)
515
+ if response.status_code == 200:
516
+ result = response.json()
517
+ content = result['choices'][0]['message']['content'].strip()
518
+
519
+ # Parse content
520
+ lines = content.split('\n')
521
+ subtitle = ""
522
+ bullet_points = []
523
+
524
+ for line in lines:
525
+ if line.startswith("Subtitle:"):
526
+ subtitle = line.replace("Subtitle:", "").strip()
527
+ elif line.strip().startswith("β€’"):
528
+ bullet_points.append(line.strip())
529
+
530
+ # ν•œκΈ€λ‘œ λ²ˆμ—­μ΄ ν•„μš”ν•œ 경우
531
+ if any(ord('κ°€') <= ord(char) <= ord('힣') for char in topic):
532
+ subtitle = translate_content_to_korean(subtitle)
533
+ bullet_points = [translate_content_to_korean(point) for point in bullet_points]
534
+
535
+ return {
536
+ "subtitle": subtitle,
537
+ "bullet_points": bullet_points[:5] # μ΅œλŒ€ 5개
538
+ }
539
+ else:
540
+ return {
541
+ "subtitle": slide_title,
542
+ "bullet_points": ["λ‚΄μš©μ„ 생성할 수 μ—†μŠ΅λ‹ˆλ‹€."] * 5
543
+ }
544
+ except Exception as e:
545
+ print(f"[μŠ¬λΌμ΄λ“œ λ‚΄μš©] 였λ₯˜: {str(e)}")
546
+ return {
547
+ "subtitle": slide_title,
548
+ "bullet_points": ["λ‚΄μš©μ„ 생성할 수 μ—†μŠ΅λ‹ˆλ‹€."] * 5
549
+ }
550
+
551
+ def translate_content_to_korean(text: str) -> str:
552
+ """μ˜μ–΄ ν…μŠ€νŠΈλ₯Ό ν•œκΈ€λ‘œ λ²ˆμ—­"""
553
+ url = "https://api.friendli.ai/dedicated/v1/chat/completions"
554
+ headers = {
555
+ "Authorization": f"Bearer {FRIENDLI_TOKEN}",
556
+ "Content-Type": "application/json"
557
+ }
558
+
559
+ payload = {
560
+ "model": "dep89a2fld32mcm",
561
+ "messages": [
562
+ {
563
+ "role": "system",
564
+ "content": "You are a translator. Translate the given English text to Korean. Maintain professional business tone. Only return the translation without any explanation."
565
+ },
566
+ {
567
+ "role": "user",
568
+ "content": text
569
+ }
570
+ ],
571
+ "max_tokens": 200,
572
+ "top_p": 0.8,
573
+ "stream": False
574
+ }
575
+
576
+ try:
577
+ response = requests.post(url, json=payload, headers=headers, timeout=30)
578
+ if response.status_code == 200:
579
+ result = response.json()
580
+ return result['choices'][0]['message']['content'].strip()
581
+ else:
582
+ return text
583
+ except Exception as e:
584
+ return text
585
+
586
+ def generate_prompt_with_llm(topic: str, style_example: str = None, slide_context: str = None, uploaded_content: str = None) -> str:
587
+ """μ£Όμ œμ™€ μŠ€νƒ€μΌ 예제λ₯Ό λ°›μ•„μ„œ LLM을 μ‚¬μš©ν•΄ 이미지 ν”„λ‘¬ν”„νŠΈλ₯Ό 생성"""
588
+ print(f"[LLM] ν”„λ‘¬ν”„νŠΈ 생성 μ‹œμž‘: {slide_context}")
589
+
590
+ url = "https://api.friendli.ai/dedicated/v1/chat/completions"
591
+ headers = {
592
+ "Authorization": f"Bearer {FRIENDLI_TOKEN}",
593
+ "Content-Type": "application/json"
594
+ }
595
+
596
+ system_prompt = """You are an expert image prompt engineer specializing in creating prompts for professional presentation slides.
597
+
598
+ Your task is to create prompts that:
599
+ 1. Are highly specific and visual, perfect for PPT backgrounds or main visuals
600
+ 2. Consider the slide's purpose and maintain consistency across a presentation
601
+ 3. Include style references matching the given example
602
+ 4. Focus on clean, professional visuals that won't distract from text overlays
603
+ 5. Ensure high contrast areas for text readability when needed
604
+ 6. Maintain brand consistency and professional aesthetics
605
+
606
+ Important guidelines:
607
+ - If given a style example, adapt the topic to match that specific visual style
608
+ - Consider the slide context (e.g., "ν‘œμ§€", "ν˜„ν™© 뢄석") to create appropriate visuals
609
+ - Always output ONLY the prompt without any explanation
610
+ - Keep prompts between 50-150 words for optimal results
611
+ - Ensure the visual supports rather than overwhelms the slide content"""
612
+
613
+ user_message = f"Topic: {topic}"
614
+ if style_example:
615
+ user_message += f"\n\nStyle reference to follow:\n{style_example}"
616
+ if slide_context:
617
+ user_message += f"\n\nSlide context: {slide_context}"
618
+ if uploaded_content:
619
+ user_message += f"\n\nAdditional context from document:\n{uploaded_content[:500]}"
620
+
621
+ payload = {
622
+ "model": "dep89a2fld32mcm",
623
+ "messages": [
624
+ {
625
+ "role": "system",
626
+ "content": system_prompt
627
+ },
628
+ {
629
+ "role": "user",
630
+ "content": user_message
631
+ }
632
+ ],
633
+ "max_tokens": 300,
634
+ "top_p": 0.8,
635
+ "temperature": 0.7,
636
+ "stream": False
637
+ }
638
+
639
+ try:
640
+ response = requests.post(url, json=payload, headers=headers, timeout=30)
641
+ if response.status_code == 200:
642
+ result = response.json()
643
+ prompt = result['choices'][0]['message']['content'].strip()
644
+ print(f"[LLM] ν”„λ‘¬ν”„νŠΈ 생성 μ™„λ£Œ: {prompt[:50]}...")
645
+ return prompt
646
+ else:
647
+ error_msg = f"ν”„λ‘¬ν”„νŠΈ 생성 μ‹€νŒ¨: {response.status_code}"
648
+ print(f"[LLM] {error_msg}")
649
+ return error_msg
650
+ except Exception as e:
651
+ error_msg = f"ν”„λ‘¬ν”„νŠΈ 생성 쀑 였λ₯˜ λ°œμƒ: {str(e)}"
652
+ print(f"[LLM] {error_msg}")
653
+ return error_msg
654
+
655
+ def translate_to_english(text: str) -> str:
656
+ """ν•œκΈ€ ν…μŠ€νŠΈλ₯Ό μ˜μ–΄λ‘œ λ²ˆμ—­ (LLM μ‚¬μš©)"""
657
+ if not any(ord('κ°€') <= ord(char) <= ord('힣') for char in text):
658
+ return text
659
+
660
+ print(f"[λ²ˆμ—­] ν•œκΈ€ 감지, μ˜μ–΄λ‘œ λ²ˆμ—­ μ‹œμž‘")
661
+
662
+ url = "https://api.friendli.ai/dedicated/v1/chat/completions"
663
+ headers = {
664
+ "Authorization": f"Bearer {FRIENDLI_TOKEN}",
665
+ "Content-Type": "application/json"
666
+ }
667
+
668
+ payload = {
669
+ "model": "dep89a2fld32mcm",
670
+ "messages": [
671
+ {
672
+ "role": "system",
673
+ "content": "You are a translator. Translate the given Korean text to English. Only return the translation without any explanation."
674
+ },
675
+ {
676
+ "role": "user",
677
+ "content": text
678
+ }
679
+ ],
680
+ "max_tokens": 500,
681
+ "top_p": 0.8,
682
+ "stream": False
683
+ }
684
+
685
+ try:
686
+ response = requests.post(url, json=payload, headers=headers, timeout=30)
687
+ if response.status_code == 200:
688
+ result = response.json()
689
+ translated = result['choices'][0]['message']['content'].strip()
690
+ print(f"[λ²ˆμ—­] μ™„λ£Œ")
691
+ return translated
692
+ else:
693
+ print(f"[λ²ˆμ—­] μ‹€νŒ¨, 원본 μ‚¬μš©")
694
+ return text
695
+ except Exception as e:
696
+ print(f"[λ²ˆμ—­] 였λ₯˜: {str(e)}, 원본 μ‚¬μš©")
697
+ return text
698
+
699
+ def generate_image(prompt: str, seed: int = 10, slide_info: str = "") -> Tuple[Image.Image, str]:
700
+ """Replicate APIλ₯Ό μ‚¬μš©ν•΄ 이미지 생성"""
701
+ print(f"\n[이미지 생성] {slide_info}")
702
+ print(f"[이미지 생성] ν”„λ‘¬ν”„νŠΈ: {prompt[:50]}...")
703
+
704
+ try:
705
+ english_prompt = translate_to_english(prompt)
706
+
707
+ if not REPLICATE_API_TOKEN:
708
+ error_msg = "RAPI_TOKEN ν™˜κ²½λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€."
709
+ print(f"[이미지 생성] 였λ₯˜: {error_msg}")
710
+ return None, error_msg
711
+
712
+ print(f"[이미지 생성] Replicate API 호좜 쀑...")
713
+ client = replicate.Client(api_token=REPLICATE_API_TOKEN)
714
+
715
+ input_params = {
716
+ "seed": seed,
717
+ "prompt": english_prompt,
718
+ "speed_mode": "Extra Juiced πŸš€ (even more speed)",
719
+ "output_quality": 100
720
+ }
721
+
722
+ start_time = time.time()
723
+ output = client.run(
724
+ "prunaai/hidream-l1-fast:17c237d753218fed0ed477cb553902b6b75735f48c128537ab829096ef3d3645",
725
+ input=input_params
726
+ )
727
+
728
+ elapsed = time.time() - start_time
729
+ print(f"[이미지 생성] API 응닡 λ°›μŒ ({elapsed:.1f}초)")
730
+
731
+ if output:
732
+ if isinstance(output, str) and output.startswith('http'):
733
+ print(f"[이미지 생성] URLμ—μ„œ 이미지 λ‹€μš΄λ‘œλ“œ 쀑...")
734
+ response = requests.get(output, timeout=30)
735
+ img = Image.open(BytesIO(response.content))
736
+ print(f"[이미지 생성] μ™„λ£Œ!")
737
+ return img, english_prompt
738
+ else:
739
+ print(f"[이미지 생성] λ°”μ΄λ„ˆλ¦¬ 데이터 처리 쀑...")
740
+ img = Image.open(BytesIO(output.read()))
741
+ print(f"[이미지 생성] μ™„λ£Œ!")
742
+ return img, english_prompt
743
+ else:
744
+ error_msg = "이미지 생성 μ‹€νŒ¨ - 빈 응닡"
745
+ print(f"[이미지 생성] {error_msg}")
746
+ return None, error_msg
747
+
748
+ except Exception as e:
749
+ error_msg = f"였λ₯˜: {str(e)}"
750
+ print(f"[이미지 생성] {error_msg}")
751
+ print(f"[이미지 생성] 상세 였λ₯˜:\n{traceback.format_exc()}")
752
+ return None, error_msg
753
+
754
+ def create_slide_preview_html(slide_data: Dict) -> str:
755
+ """16:9 λΉ„μœ¨μ˜ μŠ¬λΌμ΄λ“œ 프리뷰 HTML 생성 (λ‘₯κ·Ό λͺ¨μ„œλ¦¬μ™€ μž…μ²΄κ°)"""
756
+
757
+ # 이미지λ₯Ό base64둜 인코딩
758
+ img_base64 = ""
759
+ if slide_data.get("image"):
760
+ buffered = BytesIO()
761
+ slide_data["image"].save(buffered, format="PNG")
762
+ img_base64 = base64.b64encode(buffered.getvalue()).decode()
763
+
764
+ # ν…μŠ€νŠΈ λ‚΄μš© κ°€μ Έμ˜€κΈ°
765
+ subtitle = slide_data.get("subtitle", "")
766
+ bullet_points = slide_data.get("bullet_points", [])
767
+
768
+ # HTML 생성
769
+ html = f"""
770
+ <div class="slide-container" style="
771
+ width: 100%;
772
+ max-width: 1200px;
773
+ margin: 20px auto;
774
+ background: white;
775
+ border-radius: 12px;
776
+ box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
777
+ overflow: hidden;
778
+ ">
779
+ <div class="slide-header" style="
780
+ background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
781
+ color: white;
782
+ padding: 15px 30px;
783
+ font-size: 18px;
784
+ font-weight: bold;
785
+ ">
786
+ μŠ¬λΌμ΄λ“œ {slide_data.get('slide_number', '')}: {slide_data.get('title', '')}
787
+ </div>
788
+
789
+ <div class="slide-content" style="
790
+ display: flex;
791
+ height: 0;
792
+ padding-bottom: 56.25%; /* 16:9 λΉ„μœ¨ */
793
+ position: relative;
794
+ background: #fafbfc;
795
+ ">
796
+ <div class="slide-inner" style="
797
+ position: absolute;
798
+ top: 0;
799
+ left: 0;
800
+ width: 100%;
801
+ height: 100%;
802
+ display: flex;
803
+ padding: 20px;
804
+ gap: 20px;
805
+ ">
806
+ """
807
+
808
+ # ν‘œμ§€μ™€ λ§ˆμ§€λ§‰ μŠ¬λΌμ΄λ“œλŠ” 전체 ν™”λ©΄ 이미지
809
+ if slide_data.get('title') in ['ν‘œμ§€', 'Thank You']:
810
+ html += f"""
811
+ <!-- 전체 ν™”λ©΄ 이미지 -->
812
+ <div style="
813
+ width: 100%;
814
+ height: 100%;
815
+ position: relative;
816
+ background: #e9ecef;
817
+ border-radius: 12px;
818
+ overflow: hidden;
819
+ ">
820
+ """
821
+
822
+ if img_base64:
823
+ html += f"""
824
+ <img src="data:image/png;base64,{img_base64}" style="
825
+ width: 100%;
826
+ height: 100%;
827
+ object-fit: cover;
828
+ " alt="Slide Image">
829
+ <div style="
830
+ position: absolute;
831
+ top: 50%;
832
+ left: 50%;
833
+ transform: translate(-50%, -50%);
834
+ text-align: center;
835
+ color: white;
836
+ text-shadow: 2px 2px 4px rgba(0,0,0,0.8);
837
+ ">
838
+ <h1 style="font-size: 48px; margin-bottom: 20px;">{slide_data.get('topic', '')}</h1>
839
+ <h2 style="font-size: 24px;">{subtitle}</h2>
840
+ </div>
841
+ """
842
+
843
+ html += """
844
+ </div>
845
+ """
846
+ else:
847
+ # 일반 μŠ¬λΌμ΄λ“œ λ ˆμ΄μ•„μ›ƒ
848
+ html += f"""
849
+ <!-- ν…μŠ€νŠΈ μ˜μ—­ (쒌츑) -->
850
+ <div class="text-area" style="
851
+ flex: 1;
852
+ padding: 30px;
853
+ display: flex;
854
+ flex-direction: column;
855
+ justify-content: center;
856
+ background: rgba(255, 255, 255, 0.95);
857
+ border-radius: 12px;
858
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
859
+ ">
860
+ <h2 style="
861
+ color: #212529;
862
+ font-size: 28px;
863
+ margin-bottom: 30px;
864
+ font-weight: 600;
865
+ ">{subtitle}</h2>
866
+
867
+ <ul style="
868
+ list-style: none;
869
+ padding: 0;
870
+ margin: 0;
871
+ ">
872
+ """
873
+
874
+ for point in bullet_points:
875
+ html += f"""
876
+ <li style="
877
+ margin-bottom: 16px;
878
+ padding-left: 28px;
879
+ position: relative;
880
+ color: #495057;
881
+ font-size: 16px;
882
+ line-height: 1.6;
883
+ ">
884
+ <span style="
885
+ position: absolute;
886
+ left: 0;
887
+ color: #007bff;
888
+ font-size: 18px;
889
+ ">β€’</span>
890
+ {point.replace('β€’', '').strip()}
891
+ </li>
892
+ """
893
+
894
+ html += f"""
895
+ </ul>
896
+ </div>
897
+
898
+ <!-- 이미지 μ˜μ—­ (우츑) -->
899
+ <div class="image-area" style="
900
+ flex: 1;
901
+ background: rgba(248, 249, 250, 0.9);
902
+ border-radius: 12px;
903
+ display: flex;
904
+ align-items: center;
905
+ justify-content: center;
906
+ padding: 20px;
907
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
908
+ ">
909
+ """
910
+
911
+ if img_base64:
912
+ html += f"""
913
+ <img src="data:image/png;base64,{img_base64}" style="
914
+ max-width: 100%;
915
+ max-height: 100%;
916
+ object-fit: contain;
917
+ border-radius: 8px;
918
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
919
+ " alt="Slide Image">
920
+ """
921
+ else:
922
+ html += """
923
+ <div style="
924
+ color: #6c757d;
925
+ text-align: center;
926
+ ">
927
+ <div style="font-size: 48px;">πŸ–ΌοΈ</div>
928
+ <p>이미지 생성 쀑...</p>
929
+ </div>
930
+ """
931
+
932
+ html += """
933
+ </div>
934
+ """
935
+
936
+ html += """
937
+ </div>
938
+ </div>
939
+ </div>
940
+ """
941
+
942
+ return html
943
+
944
+ def create_pptx_file(results: List[Dict], topic: str, template_name: str, theme_name: str = "λ―Έλ‹ˆλ©€ 라이트") -> str:
945
+ """μƒμ„±λœ κ²°κ³Όλ₯Ό PPTX 파일둜 λ³€ν™˜ (λ°œν‘œμž λ…ΈνŠΈ 포함)"""
946
+ print(f"[PPTX] 파일 생성 μ‹œμž‘... ν…Œλ§ˆ: {theme_name}")
947
+
948
+ # ν”„λ ˆμ  ν…Œμ΄μ…˜ 생성 (16:9 λΉ„μœ¨)
949
+ prs = Presentation()
950
+ prs.slide_width = Inches(16)
951
+ prs.slide_height = Inches(9)
952
+
953
+ # μ„ νƒλœ ν…Œλ§ˆ κ°€μ Έμ˜€κΈ°
954
+ theme = DESIGN_THEMES.get(theme_name, DESIGN_THEMES["λ―Έλ‹ˆλ©€ 라이트"])
955
+
956
+ # 각 κ²°κ³Ό μŠ¬λΌμ΄λ“œ μΆ”κ°€
957
+ for i, result in enumerate(results):
958
+ if not result.get("success", False):
959
+ continue
960
+
961
+ slide_data = result.get("slide_data", {})
962
+
963
+ # 빈 λ ˆμ΄μ•„μ›ƒ μ‚¬μš© (제λͺ© ν”Œλ ˆμ΄μŠ€ν™€λ” μ—†λŠ” μ™„μ „ν•œ 빈 μŠ¬λΌμ΄λ“œ)
964
+ blank_layout = prs.slide_layouts[6] # μ™„μ „νžˆ 빈 λ ˆμ΄μ•„μ›ƒ
965
+ slide = prs.slides.add_slide(blank_layout)
966
+
967
+ # ν‘œμ§€ μŠ¬λΌμ΄λ“œ
968
+ if slide_data.get('title') == 'ν‘œμ§€':
969
+ # λ°°κ²½ 이미지 μΆ”κ°€
970
+ if slide_data.get('image'):
971
+ try:
972
+ img_buffer = BytesIO()
973
+ slide_data['image'].save(img_buffer, format='PNG')
974
+ img_buffer.seek(0)
975
+
976
+ # 전체 ν™”λ©΄ λ°°κ²½ 이미지
977
+ pic = slide.shapes.add_picture(
978
+ img_buffer,
979
+ 0, 0,
980
+ width=prs.slide_width,
981
+ height=prs.slide_height
982
+ )
983
+ # 맨 λ’€λ‘œ 보내기
984
+ slide.shapes._spTree.remove(pic._element)
985
+ slide.shapes._spTree.insert(2, pic._element)
986
+ except Exception as e:
987
+ print(f"[PPTX] ν‘œμ§€ 이미지 μΆ”κ°€ μ‹€νŒ¨: {str(e)}")
988
+
989
+ # 제λͺ© λ°°κ²½ λ°•μŠ€ (반투λͺ…)
990
+ title_bg = slide.shapes.add_shape(
991
+ MSO_SHAPE.ROUNDED_RECTANGLE,
992
+ Inches(2), Inches(2.5),
993
+ Inches(12), Inches(4)
994
+ )
995
+ title_bg.fill.solid()
996
+ title_bg.fill.fore_color.rgb = RGBColor(0, 0, 0)
997
+ title_bg.fill.transparency = 0.5
998
+ title_bg.adjustments[0] = 0.1
999
+ title_bg.line.fill.background()
1000
+
1001
+ # 제λͺ© ν…μŠ€νŠΈ μΆ”κ°€
1002
+ title_box = slide.shapes.add_textbox(
1003
+ Inches(2), Inches(3),
1004
+ Inches(12), Inches(3)
1005
+ )
1006
+ title_frame = title_box.text_frame
1007
+ title_frame.text = topic
1008
+ title_para = title_frame.paragraphs[0]
1009
+ title_para.font.size = Pt(48)
1010
+ title_para.font.bold = True
1011
+ title_para.font.color.rgb = RGBColor(255, 255, 255)
1012
+ title_para.alignment = PP_ALIGN.CENTER
1013
+
1014
+ # λΆ€μ œλͺ© μΆ”κ°€
1015
+ subtitle_box = slide.shapes.add_textbox(
1016
+ Inches(2), Inches(6),
1017
+ Inches(12), Inches(2)
1018
+ )
1019
+ subtitle_frame = subtitle_box.text_frame
1020
+ subtitle_frame.text = slide_data.get('subtitle', f'{template_name} - AI ν”„λ ˆμ  ν…Œμ΄μ…˜')
1021
+ subtitle_para = subtitle_frame.paragraphs[0]
1022
+ subtitle_para.font.size = Pt(24)
1023
+ subtitle_para.font.color.rgb = RGBColor(255, 255, 255)
1024
+ subtitle_para.alignment = PP_ALIGN.CENTER
1025
+
1026
+ # Thank You μŠ¬λΌμ΄λ“œ
1027
+ elif slide_data.get('title') == 'Thank You':
1028
+ # λ°°κ²½ 이미지 μΆ”κ°€
1029
+ if slide_data.get('image'):
1030
+ try:
1031
+ img_buffer = BytesIO()
1032
+ slide_data['image'].save(img_buffer, format='PNG')
1033
+ img_buffer.seek(0)
1034
+
1035
+ # 전체 ν™”λ©΄ λ°°κ²½ 이미지
1036
+ pic = slide.shapes.add_picture(
1037
+ img_buffer,
1038
+ 0, 0,
1039
+ width=prs.slide_width,
1040
+ height=prs.slide_height
1041
+ )
1042
+ # 맨 λ’€λ‘œ 보내기
1043
+ slide.shapes._spTree.remove(pic._element)
1044
+ slide.shapes._spTree.insert(2, pic._element)
1045
+ except Exception as e:
1046
+ print(f"[PPTX] Thank You 이미지 μΆ”κ°€ μ‹€νŒ¨: {str(e)}")
1047
+
1048
+ # Thank You λ°°κ²½ λ°•μŠ€
1049
+ thanks_bg = slide.shapes.add_shape(
1050
+ MSO_SHAPE.ROUNDED_RECTANGLE,
1051
+ Inches(3), Inches(3),
1052
+ Inches(10), Inches(3)
1053
+ )
1054
+ thanks_bg.fill.solid()
1055
+ thanks_bg.fill.fore_color.rgb = RGBColor(0, 0, 0)
1056
+ thanks_bg.fill.transparency = 0.5
1057
+ thanks_bg.adjustments[0] = 0.1
1058
+ thanks_bg.line.fill.background()
1059
+
1060
+ # Thank You ν…μŠ€νŠΈ
1061
+ thanks_box = slide.shapes.add_textbox(
1062
+ Inches(2), Inches(3.5),
1063
+ Inches(12), Inches(2)
1064
+ )
1065
+ thanks_frame = thanks_box.text_frame
1066
+ thanks_frame.text = "Thank You"
1067
+ thanks_para = thanks_frame.paragraphs[0]
1068
+ thanks_para.font.size = Pt(60)
1069
+ thanks_para.font.bold = True
1070
+ thanks_para.font.color.rgb = RGBColor(255, 255, 255)
1071
+ thanks_para.alignment = PP_ALIGN.CENTER
1072
+
1073
+ # 일반 μŠ¬λΌμ΄λ“œ
1074
+ else:
1075
+ # 배경색 μ„€μ •
1076
+ background = slide.background
1077
+ fill = background.fill
1078
+ fill.solid()
1079
+ fill.fore_color.rgb = theme["background"]
1080
+
1081
+ # μŠ¬λΌμ΄λ“œ 제λͺ© λ°°κ²½ λ°•μŠ€ (λ‘₯κ·Ό λͺ¨μ„œλ¦¬ 효과)
1082
+ title_box_bg = slide.shapes.add_shape(
1083
+ MSO_SHAPE.ROUNDED_RECTANGLE,
1084
+ Inches(0.3), Inches(0.2),
1085
+ Inches(15.4), Inches(1.0)
1086
+ )
1087
+ title_box_bg.fill.solid()
1088
+ title_box_bg.fill.fore_color.rgb = theme["box_fill"]
1089
+ title_box_bg.fill.transparency = 1 - theme["box_opacity"]
1090
+
1091
+ # λ‘₯κ·Ό 정도 μ‘°μ •
1092
+ title_box_bg.adjustments[0] = 0.15 # λ‘₯κ·Ό 정도 (0-1)
1093
+
1094
+ # 그림자 효과
1095
+ if theme["shadow"]:
1096
+ shadow = title_box_bg.shadow
1097
+ shadow.visible = True
1098
+ shadow.distance = Pt(4)
1099
+ shadow.size = 100
1100
+ shadow.blur_radius = Pt(8)
1101
+ shadow.transparency = 0.75
1102
+ shadow.angle = 45
1103
+
1104
+ title_box_bg.line.fill.background() # ν…Œλ‘λ¦¬ μ—†μŒ
1105
+
1106
+ # μŠ¬λΌμ΄λ“œ 제λͺ© μΆ”κ°€
1107
+ title_box = slide.shapes.add_textbox(
1108
+ Inches(0.5), Inches(0.3),
1109
+ Inches(15), Inches(0.8)
1110
+ )
1111
+ title_frame = title_box.text_frame
1112
+ title_frame.text = f"{slide_data.get('title', '')}"
1113
+ title_para = title_frame.paragraphs[0]
1114
+ title_para.font.size = Pt(28)
1115
+ title_para.font.bold = True
1116
+ title_para.font.color.rgb = theme["title_color"]
1117
+
1118
+ # 쒌츑 ν…μŠ€νŠΈ μ˜μ—­ λ°°κ²½ λ°•μŠ€
1119
+ text_box_bg = slide.shapes.add_shape(
1120
+ MSO_SHAPE.ROUNDED_RECTANGLE,
1121
+ Inches(0.3), Inches(1.4),
1122
+ Inches(7.8), Inches(6.8)
1123
+ )
1124
+ text_box_bg.fill.solid()
1125
+ text_box_bg.fill.fore_color.rgb = theme["box_fill"]
1126
+ text_box_bg.fill.transparency = 1 - theme["box_opacity"]
1127
+
1128
+ # λ‘₯κ·Ό 정도 μ‘°μ •
1129
+ text_box_bg.adjustments[0] = 0.12
1130
+
1131
+ if theme["shadow"]:
1132
+ shadow = text_box_bg.shadow
1133
+ shadow.visible = True
1134
+ shadow.distance = Pt(5)
1135
+ shadow.size = 100
1136
+ shadow.blur_radius = Pt(10)
1137
+ shadow.transparency = 0.7
1138
+ shadow.angle = 45
1139
+
1140
+ text_box_bg.line.fill.background()
1141
+
1142
+ # 쒌츑 ν…μŠ€νŠΈ μ˜μ—­
1143
+ text_box = slide.shapes.add_textbox(
1144
+ Inches(0.8), Inches(1.8),
1145
+ Inches(7.0), Inches(6.0)
1146
+ )
1147
+ text_frame = text_box.text_frame
1148
+ text_frame.word_wrap = True
1149
+
1150
+ # μ†Œμ œλͺ© μΆ”κ°€
1151
+ subtitle_para = text_frame.paragraphs[0]
1152
+ subtitle_para.text = slide_data.get('subtitle', '')
1153
+ subtitle_para.font.size = Pt(20)
1154
+ subtitle_para.font.bold = True
1155
+ subtitle_para.font.color.rgb = theme["subtitle_color"]
1156
+ subtitle_para.space_after = Pt(20)
1157
+
1158
+ # 뢈릿 포인트 μΆ”κ°€
1159
+ bullet_points = slide_data.get('bullet_points', [])
1160
+ for point in bullet_points:
1161
+ p = text_frame.add_paragraph()
1162
+ p.text = point.replace('β€’', '').strip()
1163
+ p.font.size = Pt(16)
1164
+ p.font.color.rgb = theme["text_color"]
1165
+ p.level = 0
1166
+ p.space_after = Pt(12)
1167
+ p.line_spacing = 1.5
1168
+
1169
+ # 뢈릿 색상
1170
+ p.font.color.rgb = theme["text_color"]
1171
+
1172
+ # 우츑 이미지 μ˜μ—­ λ°°κ²½ λ°•μŠ€
1173
+ img_box_bg = slide.shapes.add_shape(
1174
+ MSO_SHAPE.ROUNDED_RECTANGLE,
1175
+ Inches(8.3), Inches(1.4),
1176
+ Inches(7.4), Inches(6.8)
1177
+ )
1178
+ img_box_bg.fill.solid()
1179
+ img_box_bg.fill.fore_color.rgb = RGBColor(248, 249, 250)
1180
+ img_box_bg.fill.transparency = 0.1
1181
+
1182
+ # λ‘₯κ·Ό 정도 μ‘°μ •
1183
+ img_box_bg.adjustments[0] = 0.12
1184
+
1185
+ if theme["shadow"]:
1186
+ shadow = img_box_bg.shadow
1187
+ shadow.visible = True
1188
+ shadow.distance = Pt(5)
1189
+ shadow.size = 100
1190
+ shadow.blur_radius = Pt(10)
1191
+ shadow.transparency = 0.7
1192
+ shadow.angle = 45
1193
+
1194
+ img_box_bg.line.fill.background()
1195
+
1196
+ # 우츑 이미지 μΆ”κ°€
1197
+ if slide_data.get('image'):
1198
+ try:
1199
+ img_buffer = BytesIO()
1200
+ slide_data['image'].save(img_buffer, format='PNG')
1201
+ img_buffer.seek(0)
1202
+
1203
+ pic = slide.shapes.add_picture(
1204
+ img_buffer,
1205
+ Inches(8.5), Inches(1.6),
1206
+ width=Inches(6.8), height=Inches(6.4)
1207
+ )
1208
+
1209
+ # 이미지 ν…Œλ‘λ¦¬ 제거
1210
+ pic.line.fill.background()
1211
+
1212
+ except Exception as e:
1213
+ print(f"[PPTX] 이미지 μΆ”κ°€ μ‹€νŒ¨: {str(e)}")
1214
+
1215
+ # νŽ˜μ΄μ§€ 번호 μΆ”κ°€
1216
+ page_num = slide.shapes.add_textbox(
1217
+ Inches(15), Inches(8.5),
1218
+ Inches(1), Inches(0.5)
1219
+ )
1220
+ page_frame = page_num.text_frame
1221
+ page_frame.text = str(i + 1)
1222
+ page_para = page_frame.paragraphs[0]
1223
+ page_para.font.size = Pt(12)
1224
+ page_para.font.color.rgb = theme["text_color"]
1225
+ page_para.alignment = PP_ALIGN.RIGHT
1226
+
1227
+ # λ°œν‘œμž λ…ΈνŠΈ μΆ”κ°€
1228
+ notes_slide = slide.notes_slide
1229
+ notes_slide.notes_text_frame.text = slide_data.get('speaker_notes', '')
1230
+
1231
+ # 파일 μ €μž₯
1232
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1233
+ filename = f"presentation_{timestamp}.pptx"
1234
+ filepath = os.path.join("/tmp", filename)
1235
+ prs.save(filepath)
1236
+
1237
+ print(f"[PPTX] 파일 생성 μ™„λ£Œ: {filename}")
1238
+ return filepath
1239
+
1240
+ def generate_dynamic_slides(topic: str, template: Dict, slide_count: int) -> List[Dict]:
1241
+ """μ„ νƒλœ μŠ¬λΌμ΄λ“œ μˆ˜μ— 따라 λ™μ μœΌλ‘œ μŠ¬λΌμ΄λ“œ ꡬ성"""
1242
+ core_slides = template.get("core_slides", [])
1243
+ optional_slides = template.get("optional_slides", [])
1244
+
1245
+ # ν‘œμ§€μ™€ Thank Youλ₯Ό μ œμ™Έν•œ λ³Έλ¬Έ μŠ¬λΌμ΄λ“œ 수
1246
+ content_slide_count = slide_count
1247
+
1248
+ # μ½”μ–΄ μŠ¬λΌμ΄λ“œκ°€ μš”μ²­λœ μˆ˜λ³΄λ‹€ 많으면 μ‘°μ •
1249
+ if len(core_slides) > content_slide_count:
1250
+ selected_slides = core_slides[:content_slide_count]
1251
+ else:
1252
+ # μ½”μ–΄ μŠ¬λΌμ΄λ“œ + μ˜΅μ…”λ„ μŠ¬λΌμ΄λ“œμ—μ„œ 선택
1253
+ selected_slides = core_slides.copy()
1254
+ remaining = content_slide_count - len(core_slides)
1255
+
1256
+ if remaining > 0 and optional_slides:
1257
+ # μ˜΅μ…”λ„ μŠ¬λΌμ΄λ“œμ—μ„œ μΆ”κ°€ 선택
1258
+ additional = optional_slides[:remaining]
1259
+ selected_slides.extend(additional)
1260
+
1261
+ # ν‘œμ§€ μΆ”κ°€ (맨 μ•ž)
1262
+ slides = [{"title": "ν‘œμ§€", "style": "Title Slide (Hero)", "prompt_hint": "ν”„λ ˆμ  ν…Œμ΄μ…˜ ν‘œμ§€"}]
1263
+
1264
+ # λ³Έλ¬Έ μŠ¬λΌμ΄λ“œ μΆ”κ°€
1265
+ slides.extend(selected_slides)
1266
+
1267
+ # Thank You μŠ¬λΌμ΄λ“œ μΆ”κ°€ (맨 λ’€)
1268
+ slides.append({"title": "Thank You", "style": "Thank You Slide", "prompt_hint": "감사 인사"})
1269
+
1270
+ return slides
1271
+
1272
+ def generate_ppt_with_content(topic: str, template_name: str, custom_slides: List[Dict],
1273
+ slide_count: int, seed: int, uploaded_file: str,
1274
+ use_web_search: bool, theme_name: str = "λ―Έλ‹ˆλ©€ 라이트",
1275
+ progress=gr.Progress()):
1276
+ """PPT 이미지와 ν…μŠ€νŠΈ λ‚΄μš©μ„ ν•¨κ»˜ 생성 (λ°œν‘œμž λ…ΈνŠΈ 포함)"""
1277
+ results = []
1278
+ preview_html = ""
1279
+
1280
+ # μ—…λ‘œλ“œλœ 파일 λ‚΄μš© 읽기
1281
+ uploaded_content = ""
1282
+ if uploaded_file:
1283
+ uploaded_content = read_uploaded_file(uploaded_file.name)
1284
+ print(f"[파일 μ—…λ‘œλ“œ] λ‚΄μš© 길이: {len(uploaded_content)}자")
1285
+
1286
+ # ν…œν”Œλ¦Ώ 선택 및 μŠ¬λΌμ΄λ“œ ꡬ성
1287
+ if template_name == "μ‚¬μš©μž μ •μ˜" and custom_slides:
1288
+ slides = [{"title": "ν‘œμ§€", "style": "Title Slide (Hero)", "prompt_hint": "ν”„λ ˆμ  ν…Œμ΄μ…˜ ν‘œμ§€"}]
1289
+ slides.extend(custom_slides)
1290
+ slides.append({"title": "Thank You", "style": "Thank You Slide", "prompt_hint": "감사 인사"})
1291
+ else:
1292
+ template = PPT_TEMPLATES[template_name]
1293
+ slides = generate_dynamic_slides(topic, template, slide_count)
1294
+
1295
+ if not slides:
1296
+ yield "", "μŠ¬λΌμ΄λ“œκ°€ μ •μ˜λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.", None
1297
+ return
1298
+
1299
+ total_slides = len(slides)
1300
+ print(f"\n[PPT 생성] μ‹œμž‘ - 총 {total_slides}개 μŠ¬λΌμ΄λ“œ (ν‘œμ§€ + λ³Έλ¬Έ {slide_count} + Thank You)")
1301
+ print(f"[PPT 생성] 주제: {topic}")
1302
+ print(f"[PPT 생성] ν…œν”Œλ¦Ώ: {template_name}")
1303
+ print(f"[PPT 생성] λ””μžμΈ ν…Œλ§ˆ: {theme_name}")
1304
+ print(f"[PPT 생성] μ›Ή 검색: {'μ‚¬μš©' if use_web_search else 'λ―Έμ‚¬μš©'}")
1305
+
1306
+ # μ›Ή 검색 μ‹€ν–‰ (μ„ νƒλœ 경우)
1307
+ web_search_results = []
1308
+ if use_web_search and BRAVE_API_TOKEN:
1309
+ progress(0.05, "μ›Ή 검색 쀑...")
1310
+ web_search_results = brave_search(topic)
1311
+
1312
+ # CSS μŠ€νƒ€μΌ μΆ”κ°€
1313
+ preview_html = """
1314
+ <style>
1315
+ .slides-container {
1316
+ width: 100%;
1317
+ max-width: 1400px;
1318
+ margin: 0 auto;
1319
+ }
1320
+ </style>
1321
+ <div class="slides-container">
1322
+ """
1323
+
1324
+ # 각 μŠ¬λΌμ΄λ“œ 순차 처리
1325
+ for i, slide in enumerate(slides):
1326
+ progress((i + 1) / (total_slides + 1), f"μŠ¬λΌμ΄λ“œ {i+1}/{total_slides} 처리 쀑...")
1327
+
1328
+ slide_info = f"μŠ¬λΌμ΄λ“œ {i+1}: {slide['title']}"
1329
+
1330
+ # ν…μŠ€νŠΈ λ‚΄μš© 생성
1331
+ slide_context = f"{slide['title']} - {slide.get('prompt_hint', '')}"
1332
+ content = generate_slide_content(
1333
+ topic, slide['title'], slide_context,
1334
+ uploaded_content, web_search_results
1335
+ )
1336
+
1337
+ # λ°œν‘œμž λ…ΈνŠΈ 생성
1338
+ speaker_notes = generate_presentation_notes(topic, slide['title'], content)
1339
+
1340
+ # ν”„λ‘¬ν”„νŠΈ 생성 및 이미지 생성
1341
+ style_key = slide["style"]
1342
+ if style_key in STYLE_TEMPLATES:
1343
+ style_info = STYLE_TEMPLATES[style_key]
1344
+ prompt = generate_prompt_with_llm(
1345
+ topic, style_info["example"],
1346
+ slide_context, uploaded_content
1347
+ )
1348
+
1349
+ # 이미지 생성
1350
+ slide_seed = seed + i
1351
+ img, used_prompt = generate_image(prompt, slide_seed, slide_info)
1352
+
1353
+ # μŠ¬λΌμ΄λ“œ 데이터 ꡬ성
1354
+ slide_data = {
1355
+ "slide_number": i + 1,
1356
+ "title": slide["title"],
1357
+ "subtitle": content["subtitle"],
1358
+ "bullet_points": content["bullet_points"],
1359
+ "image": img,
1360
+ "style": style_info["name"],
1361
+ "speaker_notes": speaker_notes,
1362
+ "topic": topic # ν‘œμ§€μš©
1363
+ }
1364
+
1365
+ # 프리뷰 HTML 생성
1366
+ preview_html += create_slide_preview_html(slide_data)
1367
+
1368
+ # ν˜„μž¬κΉŒμ§€μ˜ μƒνƒœ μ—…λ°μ΄νŠΈ
1369
+ yield preview_html + "</div>", f"### πŸ”„ {slide_info} 생성 쀑...", None
1370
+
1371
+ results.append({
1372
+ "slide_data": slide_data,
1373
+ "success": img is not None
1374
+ })
1375
+
1376
+ # PPTX 파일 생성
1377
+ progress(0.95, "PPTX 파일 생성 쀑...")
1378
+ pptx_path = None
1379
+ try:
1380
+ pptx_path = create_pptx_file(results, topic, template_name, theme_name)
1381
+ except Exception as e:
1382
+ print(f"[PPTX] 파일 생성 였λ₯˜: {str(e)}")
1383
+
1384
+ # μ΅œμ’… κ²°κ³Ό
1385
+ preview_html += "</div>"
1386
+ progress(1.0, "μ™„λ£Œ!")
1387
+ successful = sum(1 for r in results if r["success"])
1388
+ final_status = f"### πŸŽ‰ 생성 μ™„λ£Œ! 총 {total_slides}개 μŠ¬λΌμ΄λ“œ 쀑 {successful}개 성곡"
1389
+
1390
+ if pptx_path:
1391
+ final_status += f"\n\n### πŸ“₯ PPTX 파일이 μ€€λΉ„λ˜μ—ˆμŠ΅λ‹ˆλ‹€! μ•„λž˜μ—μ„œ λ‹€μš΄λ‘œλ“œν•˜μ„Έμš”."
1392
+ final_status += f"\n\nπŸ’‘ **λ°œν‘œμž λ…ΈνŠΈκ°€ 각 μŠ¬λΌμ΄λ“œμ— ν¬ν•¨λ˜μ–΄ μžˆμŠ΅λ‹ˆλ‹€!**"
1393
+
1394
+ yield preview_html, final_status, pptx_path
1395
+
1396
+ def create_custom_slides_ui():
1397
+ """μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ ꡬ성 UI (3-20μž₯)"""
1398
+ slides = []
1399
+ for i in range(20): # μ΅œλŒ€ 20μž₯
1400
+ with gr.Row(visible=(i < 3)): # κΈ°λ³Έ 3μž₯만 ν‘œμ‹œ
1401
+ with gr.Column(scale=2):
1402
+ title = gr.Textbox(
1403
+ label=f"μŠ¬λΌμ΄λ“œ {i+1} 제λͺ©",
1404
+ placeholder="예: ν˜„ν™© 뢄석, μ†”λ£¨μ…˜, λ‘œλ“œλ§΅...",
1405
+ )
1406
+ with gr.Column(scale=3):
1407
+ style = gr.Dropdown(
1408
+ choices=list(STYLE_TEMPLATES.keys()),
1409
+ label=f"μŠ€νƒ€μΌ 선택",
1410
+ value="Colorful Mind Map"
1411
+ )
1412
+ with gr.Column(scale=3):
1413
+ hint = gr.Textbox(
1414
+ label=f"ν”„λ‘¬ν”„νŠΈ 힌트",
1415
+ placeholder="이 μŠ¬λΌμ΄λ“œμ—μ„œ ν‘œν˜„ν•˜κ³  싢은 λ‚΄μš©"
1416
+ )
1417
+ slides.append({"title": title, "style": style, "hint": hint, "row": gr.Row})
1418
+ return slides
1419
+
1420
+ # Gradio μΈν„°νŽ˜μ΄μŠ€ 생성
1421
+ with gr.Blocks(title="PPT 이미지 생성기", theme=gr.themes.Soft(), css="""
1422
+ .preview-container { max-width: 1400px; margin: 0 auto; }
1423
+ """) as demo:
1424
+ gr.Markdown("""
1425
+ # 🎯 AI 기반 PPT 톡합 생성기 (λ””μžμΈ ν…Œλ§ˆ 포함)
1426
+
1427
+ ### ν…μŠ€νŠΈμ™€ 이미지가 μ™„λ²½ν•˜κ²Œ μ‘°ν™”λœ ν”„λ ˆμ  ν…Œμ΄μ…˜μ„ μžλ™μœΌλ‘œ μƒμ„±ν•˜κ³  λ‹€μš΄λ‘œλ“œν•˜μ„Έμš”!
1428
+
1429
+ #### πŸ†• μƒˆλ‘œμš΄ κΈ°λŠ₯:
1430
+ - 🎨 **λ””μžμΈ ν…Œλ§ˆ**: 5κ°€μ§€ 전문적인 λ””μžμΈ ν…Œλ§ˆ 선택 κ°€λŠ₯
1431
+ - πŸ“Š **ν‘œμ§€μ™€ Thank You μŠ¬λΌμ΄λ“œ** μžλ™ μΆ”κ°€
1432
+ - πŸ“ **λ°œν‘œμž λ…ΈνŠΈ** μžλ™ 생성 (ꡬ어체)
1433
+ - πŸ“ **파일 μ—…λ‘œλ“œ** 지원 (PDF/CSV/TXT)
1434
+ - πŸ” **μ›Ή 검색** κΈ°λŠ₯ (Brave Search)
1435
+ - 🎚️ **μŠ¬λΌμ΄λ“œ 수 쑰절** (6-20μž₯)
1436
+ - πŸ’Ž **μž…μ²΄κ° μžˆλŠ” λ””μžμΈ**: λ‘₯κ·Ό λͺ¨μ„œλ¦¬μ™€ 그림자 효과
1437
+ """)
1438
+
1439
+ # API 토큰 μƒνƒœ 확인
1440
+ token_status = []
1441
+ if not REPLICATE_API_TOKEN:
1442
+ token_status.append("��️ RAPI_TOKEN ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
1443
+ if not FRIENDLI_TOKEN:
1444
+ token_status.append("⚠️ FRIENDLI_TOKEN ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
1445
+ if not BRAVE_API_TOKEN:
1446
+ token_status.append("ℹ️ BAPI_TOKEN이 μ—†μ–΄ μ›Ή 검색 κΈ°λŠ₯이 λΉ„ν™œμ„±ν™”λ©λ‹ˆλ‹€.")
1447
+
1448
+ if token_status:
1449
+ gr.Markdown("\n".join(token_status))
1450
+
1451
+ with gr.Row():
1452
+ with gr.Column(scale=1):
1453
+ # κΈ°λ³Έ μž…λ ₯
1454
+ topic_input = gr.Textbox(
1455
+ label="ν”„λ ˆμ  ν…Œμ΄μ…˜ 주제",
1456
+ placeholder="예: AI μŠ€νƒ€νŠΈμ—… 투자 유치, μ‹ μ œν’ˆ 런칭, λ””μ§€ν„Έ μ „ν™˜ μ „λž΅",
1457
+ lines=2
1458
+ )
1459
+
1460
+ # PPT ν…œν”Œλ¦Ώ 선택
1461
+ template_select = gr.Dropdown(
1462
+ choices=list(PPT_TEMPLATES.keys()),
1463
+ label="PPT ν…œν”Œλ¦Ώ 선택",
1464
+ value="λΉ„μ¦ˆλ‹ˆμŠ€ μ œμ•ˆμ„œ",
1465
+ info="λͺ©μ μ— λ§žλŠ” ν…œν”Œλ¦Ώμ„ μ„ νƒν•˜μ„Έμš”"
1466
+ )
1467
+
1468
+ # λ””μžμΈ ν…Œλ§ˆ 선택
1469
+ theme_select = gr.Dropdown(
1470
+ choices=list(DESIGN_THEMES.keys()),
1471
+ label="λ””μžμΈ ν…Œλ§ˆ 선택",
1472
+ value="λ―Έλ‹ˆλ©€ 라이트",
1473
+ info="ν”„λ ˆμ  ν…Œμ΄μ…˜μ˜ 전체적인 λ””μžμΈ μŠ€νƒ€μΌ"
1474
+ )
1475
+
1476
+ # ν…Œλ§ˆ 미리보기
1477
+ theme_preview = gr.HTML()
1478
+
1479
+ # μŠ¬λΌμ΄λ“œ 수 선택
1480
+ slide_count = gr.Slider(
1481
+ minimum=6,
1482
+ maximum=20,
1483
+ value=8,
1484
+ step=1,
1485
+ label="λ³Έλ¬Έ μŠ¬λΌμ΄λ“œ 수 (ν‘œμ§€μ™€ Thank You μ œμ™Έ)",
1486
+ info="생성할 λ³Έλ¬Έ μŠ¬λΌμ΄λ“œ 수λ₯Ό μ„ νƒν•˜μ„Έμš”"
1487
+ )
1488
+
1489
+ # 파일 μ—…λ‘œλ“œ
1490
+ file_upload = gr.File(
1491
+ label="μ°Έκ³  자료 μ—…λ‘œλ“œ (선택)",
1492
+ file_types=[".pdf", ".csv", ".txt"],
1493
+ type="filepath"
1494
+ )
1495
+
1496
+ # μ›Ή 검색 μ˜΅μ…˜
1497
+ use_web_search = gr.Checkbox(
1498
+ label="μ›Ή 검색 μ‚¬μš©",
1499
+ value=False,
1500
+ info="Brave Searchλ₯Ό μ‚¬μš©ν•˜μ—¬ μ΅œμ‹  정보 반영"
1501
+ )
1502
+
1503
+ # ν…œν”Œλ¦Ώ μ„€λͺ…
1504
+ template_info = gr.Markdown()
1505
+
1506
+ # μ‹œλ“œ κ°’
1507
+ seed_input = gr.Slider(
1508
+ minimum=1,
1509
+ maximum=100,
1510
+ value=10,
1511
+ step=1,
1512
+ label="μ‹œλ“œ κ°’"
1513
+ )
1514
+
1515
+ generate_btn = gr.Button("πŸš€ PPT 전체 생성 (ν…μŠ€νŠΈ + 이미지 + λ°œν‘œλ…ΈνŠΈ)", variant="primary", size="lg")
1516
+
1517
+ # PPTX λ‹€μš΄λ‘œλ“œ μ˜μ—­
1518
+ with gr.Row():
1519
+ download_file = gr.File(
1520
+ label="πŸ“₯ μƒμ„±λœ PPTX 파일 λ‹€μš΄λ‘œλ“œ",
1521
+ visible=True,
1522
+ elem_id="download-file"
1523
+ )
1524
+
1525
+ # μ‚¬μš©μž μ •μ˜ μ„Ήμ…˜
1526
+ with gr.Accordion("πŸ“ μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ ꡬ성", open=False) as custom_accordion:
1527
+ gr.Markdown("ν…œν”Œλ¦Ώμ„ μ‚¬μš©ν•˜μ§€ μ•Šκ³  직접 μŠ¬λΌμ΄λ“œλ₯Ό κ΅¬μ„±ν•˜μ„Έμš”. (3-20μž₯)")
1528
+
1529
+ # μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ 수 선택
1530
+ custom_slide_count = gr.Slider(
1531
+ minimum=3,
1532
+ maximum=20,
1533
+ value=3,
1534
+ step=1,
1535
+ label="μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ 수"
1536
+ )
1537
+
1538
+ custom_slides_components = create_custom_slides_ui()
1539
+
1540
+ # μƒνƒœ ν‘œμ‹œ
1541
+ status_output = gr.Markdown(
1542
+ value="### πŸ‘† ν…œν”Œλ¦Ώμ„ μ„ νƒν•˜κ³  생성 λ²„νŠΌμ„ ν΄λ¦­ν•˜μ„Έμš”!"
1543
+ )
1544
+
1545
+ # 프리뷰 μ˜μ—­
1546
+ preview_output = gr.HTML(
1547
+ label="PPT 프리뷰 (16:9)",
1548
+ elem_classes="preview-container"
1549
+ )
1550
+
1551
+ # 이벀트 ν•Έλ“€λŸ¬
1552
+ def update_theme_preview(theme_name):
1553
+ """ν…Œλ§ˆ 미리보기 HTML 생성"""
1554
+ theme = DESIGN_THEMES.get(theme_name, DESIGN_THEMES["λ―Έλ‹ˆλ©€ 라이트"])
1555
+
1556
+ # RGB 값을 hex둜 λ³€ν™˜
1557
+ def rgb_to_hex(rgb_color):
1558
+ return f"#{rgb_color.r:02x}{rgb_color.g:02x}{rgb_color.b:02x}"
1559
+
1560
+ bg_hex = rgb_to_hex(theme["background"])
1561
+ box_hex = rgb_to_hex(theme["box_fill"])
1562
+ title_hex = rgb_to_hex(theme["title_color"])
1563
+ text_hex = rgb_to_hex(theme["text_color"])
1564
+ accent_hex = rgb_to_hex(theme["accent_color"])
1565
+
1566
+ preview_html = f"""
1567
+ <div style="
1568
+ background: {bg_hex};
1569
+ padding: 20px;
1570
+ border-radius: 8px;
1571
+ margin: 10px 0;
1572
+ ">
1573
+ <div style="
1574
+ background: {box_hex};
1575
+ opacity: {theme['box_opacity']};
1576
+ padding: 15px;
1577
+ border-radius: 12px;
1578
+ margin-bottom: 10px;
1579
+ {'box-shadow: 0 4px 8px rgba(0,0,0,0.1);' if theme['shadow'] else ''}
1580
+ ">
1581
+ <h4 style="color: {title_hex}; margin: 0 0 10px 0;">{theme['name']}</h4>
1582
+ <p style="color: {text_hex}; margin: 0; font-size: 14px;">
1583
+ {theme['description']}
1584
+ </p>
1585
+ <div style="
1586
+ width: 40px;
1587
+ height: 4px;
1588
+ background: {accent_hex};
1589
+ margin-top: 10px;
1590
+ border-radius: 2px;
1591
+ "></div>
1592
+ </div>
1593
+ </div>
1594
+ """
1595
+ return preview_html
1596
+
1597
+ def update_template_info(template_name, slide_count):
1598
+ if template_name in PPT_TEMPLATES:
1599
+ template = PPT_TEMPLATES[template_name]
1600
+ info = f"**{template['description']}**\n\n"
1601
+
1602
+ # λ™μ μœΌλ‘œ 생성될 μŠ¬λΌμ΄λ“œ ꡬ성 ν‘œμ‹œ
1603
+ slides = generate_dynamic_slides("", template, slide_count)
1604
+ info += f"생성될 μŠ¬λΌμ΄λ“œ ({len(slides)}μž₯):\n"
1605
+ for i, slide in enumerate(slides):
1606
+ style_info = STYLE_TEMPLATES.get(slide['style'], {})
1607
+ info += f"{i+1}. {slide['title']} - {style_info.get('use_case', '')}\n"
1608
+
1609
+ return info
1610
+ return ""
1611
+
1612
+ def update_custom_slides_visibility(count):
1613
+ """μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ μˆ˜μ— 따라 UI ν‘œμ‹œ/μˆ¨κΉ€"""
1614
+ updates = []
1615
+ for i in range(20):
1616
+ updates.extend([
1617
+ gr.update(visible=(i < count)), # title
1618
+ gr.update(visible=(i < count)), # style
1619
+ gr.update(visible=(i < count)) # hint
1620
+ ])
1621
+ return updates
1622
+
1623
+ def generate_ppt_handler(topic, template_name, theme_name, slide_count, seed, file_upload,
1624
+ use_web_search, custom_slide_count, progress=gr.Progress(),
1625
+ *custom_inputs):
1626
+ if not topic.strip():
1627
+ yield "", "❌ 주제λ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”.", None
1628
+ return
1629
+
1630
+ # μ‚¬μš©μž μ •μ˜ μŠ¬λΌμ΄λ“œ 처리
1631
+ custom_slides = []
1632
+ if template_name == "μ‚¬μš©μž μ •μ˜":
1633
+ for i in range(0, custom_slide_count * 3, 3):
1634
+ if i < len(custom_inputs):
1635
+ title = custom_inputs[i]
1636
+ style = custom_inputs[i+1] if i+1 < len(custom_inputs) else None
1637
+ hint = custom_inputs[i+2] if i+2 < len(custom_inputs) else ""
1638
+
1639
+ if title and style:
1640
+ custom_slides.append({
1641
+ "title": title,
1642
+ "style": style,
1643
+ "prompt_hint": hint
1644
+ })
1645
+
1646
+ # PPT 생성
1647
+ for preview, status, pptx_file in generate_ppt_with_content(
1648
+ topic, template_name, custom_slides, slide_count, seed,
1649
+ file_upload, use_web_search, theme_name, progress
1650
+ ):
1651
+ yield preview, status, pptx_file
1652
+
1653
+ # 이벀트 μ—°κ²°
1654
+ theme_select.change(
1655
+ fn=update_theme_preview,
1656
+ inputs=[theme_select],
1657
+ outputs=[theme_preview]
1658
+ )
1659
+
1660
+ template_select.change(
1661
+ fn=update_template_info,
1662
+ inputs=[template_select, slide_count],
1663
+ outputs=[template_info]
1664
+ )
1665
+
1666
+ slide_count.change(
1667
+ fn=update_template_info,
1668
+ inputs=[template_select, slide_count],
1669
+ outputs=[template_info]
1670
+ )
1671
+
1672
+ custom_slide_count.change(
1673
+ fn=update_custom_slides_visibility,
1674
+ inputs=[custom_slide_count],
1675
+ outputs=[comp for slide in custom_slides_components for comp in [slide["title"], slide["style"], slide["hint"]]]
1676
+ )
1677
+
1678
+ # μ‚¬μš©μž μ •μ˜ μž…λ ₯ μˆ˜μ§‘
1679
+ all_custom_inputs = []
1680
+ for slide_components in custom_slides_components:
1681
+ all_custom_inputs.extend([
1682
+ slide_components["title"],
1683
+ slide_components["style"],
1684
+ slide_components["hint"]
1685
+ ])
1686
+
1687
+ generate_btn.click(
1688
+ fn=generate_ppt_handler,
1689
+ inputs=[topic_input, template_select, theme_select, slide_count, seed_input,
1690
+ file_upload, use_web_search, custom_slide_count] + all_custom_inputs,
1691
+ outputs=[preview_output, status_output, download_file]
1692
+ )
1693
+
1694
+ # 초기 ν…œν”Œλ¦Ώ 정보 ν‘œμ‹œ
1695
+ demo.load(
1696
+ fn=lambda template, slide_count, theme: (
1697
+ update_template_info(template, slide_count),
1698
+ update_theme_preview(theme)
1699
+ ),
1700
+ inputs=[template_select, slide_count, theme_select],
1701
+ outputs=[template_info, theme_preview]
1702
+ )
1703
+
1704
+ # μ•± μ‹€ν–‰
1705
+ if __name__ == "__main__":
1706
+ print("\n" + "="*50)
1707
+ print("πŸš€ PPT 톡합 생성기 (λ””μžμΈ ν…Œλ§ˆ 버전) μ‹œμž‘!")
1708
+ print("="*50)
1709
+
1710
+ # ν™˜κ²½ λ³€μˆ˜ 확인
1711
+ if not REPLICATE_API_TOKEN:
1712
+ print("⚠️ κ²½κ³ : RAPI_TOKEN ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
1713
+ else:
1714
+ print("βœ… RAPI_TOKEN 확인됨")
1715
+
1716
+ if not FRIENDLI_TOKEN:
1717
+ print("⚠️ κ²½κ³ : FRIENDLI_TOKEN ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
1718
+ else:
1719
+ print("βœ… FRIENDLI_TOKEN 확인됨")
1720
+
1721
+ if not BRAVE_API_TOKEN:
1722
+ print("ℹ️ BAPI_TOKEN이 μ—†μ–΄ μ›Ή 검색 κΈ°λŠ₯이 λΉ„ν™œμ„±ν™”λ©λ‹ˆλ‹€.")
1723
+ else:
1724
+ print("βœ… BAPI_TOKEN 확인됨")
1725
+
1726
+ print("="*50 + "\n")
1727
+
1728
+ demo.launch()