ginipick commited on
Commit
0eea7ac
Β·
verified Β·
1 Parent(s): cce9022

Create app.py

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