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

# Try to import moviepy; we will fall back gracefully if import fails
try:
    from moviepy.editor import AudioFileClip, VideoFileClip
    from moviepy.audio.fx.all import audio_loop
    HAS_MOVIEPY = True
except ImportError:
    HAS_MOVIEPY = False
    print("Warning: moviepy not installed. Audio mixing will be disabled.")

# Font setup for Korean text rendering
FONT_PATH = "NotoSansKR-Regular.ttf"

def download_font():
    """Downloads a Korean font if it doesn't exist to render subtitles properly."""
    if not os.path.exists(FONT_PATH):
        print("Downloading NotoSansKR-Regular.ttf...")
        url = "https://github.com/google/fonts/raw/main/ofl/notosanskr/NotoSansKR-Regular.ttf"
        try:
            # User-Agent header to avoid block from Github
            req = urllib.request.Request(
                url, 
                headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
            )
            with urllib.request.urlopen(req) as response, open(FONT_PATH, 'wb') as out_file:
                out_file.write(response.read())
            print("Font download complete.")
        except Exception as e:
            print(f"Error downloading font: {e}")
            # We will use default PIL font if download fails, though Korean won't render.

# Helper function to resize and pad an image to 1080x1920
def fit_image_to_canvas(pil_img, target_w=1080, target_h=1920):
    w, h = pil_img.size
    scale = min(target_w / w, target_h / h)
    new_w = int(w * scale)
    new_h = int(h * scale)
    resized = pil_img.resize((new_w, new_h), Image.Resampling.LANCZOS)
    
    # Create black canvas
    canvas = Image.new("RGB", (target_w, target_h), (0, 0, 0))
    # Paste centered
    x = (target_w - new_w) // 2
    y = (target_h - new_h) // 2
    canvas.paste(resized, (x, y))
    return canvas

# Effect 1: Camera Panning and Zooming on original image
def apply_camera_effect(original_img, effect_name, frame_idx, total_frames, target_w=1080, target_h=1920):
    w, h = original_img.size
    
    # Normalize progress (0.0 to 1.0)
    progress = frame_idx / (total_frames - 1) if total_frames > 1 else 0
    
    if effect_name == "천천히 쀌인":
        # Crop from full size down to 85% size
        crop_ratio = 1.0 - 0.15 * progress
        cw = int(w * crop_ratio)
        ch = int(h * crop_ratio)
        cx1 = (w - cw) // 2
        cy1 = (h - ch) // 2
        cropped = original_img.crop((cx1, cy1, cx1 + cw, cy1 + ch))
    elif effect_name == "천천히 μ€Œμ•„μ›ƒ":
        # Crop from 85% size up to full size
        crop_ratio = 0.85 + 0.15 * progress
        cw = int(w * crop_ratio)
        ch = int(h * crop_ratio)
        cx1 = (w - cw) // 2
        cy1 = (h - ch) // 2
        cropped = original_img.crop((cx1, cy1, cx1 + cw, cy1 + ch))
    elif effect_name == "쒌 -> 우 이동":
        # Crop 85% window, move crop x from left to right
        crop_ratio = 0.85
        cw = int(w * crop_ratio)
        ch = int(h * crop_ratio)
        max_shift = w - cw
        cx1 = int(max_shift * progress)
        cy1 = (h - ch) // 2
        cropped = original_img.crop((cx1, cy1, cx1 + cw, cy1 + ch))
    elif effect_name == "우 -> 쒌 이동":
        # Crop 85% window, move crop x from right to left
        crop_ratio = 0.85
        cw = int(w * crop_ratio)
        ch = int(h * crop_ratio)
        max_shift = w - cw
        cx1 = int(max_shift * (1.0 - progress))
        cy1 = (h - ch) // 2
        cropped = original_img.crop((cx1, cy1, cx1 + cw, cy1 + ch))
    elif effect_name == "μœ„ -> μ•„λž˜ 이동":
        # Crop 85% window, move crop y from top to bottom
        crop_ratio = 0.85
        cw = int(w * crop_ratio)
        ch = int(h * crop_ratio)
        max_shift = h - ch
        cx1 = (w - cw) // 2
        cy1 = int(max_shift * progress)
        cropped = original_img.crop((cx1, cy1, cx1 + cw, cy1 + ch))
    elif effect_name == "μ•„λž˜ -> μœ„ 이동":
        # Crop 85% window, move crop y from bottom to top
        crop_ratio = 0.85
        cw = int(w * crop_ratio)
        ch = int(h * crop_ratio)
        max_shift = h - ch
        cx1 = (w - cw) // 2
        cy1 = int(max_shift * (1.0 - progress))
        cropped = original_img.crop((cx1, cy1, cx1 + cw, cy1 + ch))
    else: # Fallback / None
        cropped = original_img
        
    return fit_image_to_canvas(cropped, target_w, target_h)

# Particle class for weather effects
class ParticleSystem:
    def __init__(self, count, p_type, canvas_w=1080, canvas_h=1920):
        self.p_type = p_type
        self.canvas_w = canvas_w
        self.canvas_h = canvas_h
        self.particles = []
        
        for _ in range(count):
            self.particles.append(self._reset_particle(init=True))
            
    def _reset_particle(self, init=False):
        x = random.randint(0, self.canvas_w)
        y = random.randint(0, self.canvas_h) if init else random.randint(-50, 0)
        
        if self.p_type == "눈 λ‚΄λ¦Ό":
            size = random.uniform(2, 6)
            speed = random.uniform(2, 6)
            drift = random.uniform(-0.5, 0.5)
            color = (255, 255, 255, random.randint(150, 230))
        elif self.p_type == "λΉ„ λ‚΄λ¦Ό":
            size = random.uniform(10, 25) # length
            speed = random.uniform(15, 25)
            drift = 1 # slight wind slant
            color = (180, 200, 255, random.randint(80, 150))
        elif self.p_type == "κ½ƒμžŽ 흩날림":
            size = random.uniform(8, 15)
            speed = random.uniform(3, 7)
            drift = random.uniform(1, 3)
            # Cherry blossom pink tones
            color = (255, random.randint(160, 200), random.randint(180, 220), random.randint(120, 200))
        elif self.p_type == "λ‚˜λ­‡μžŽ 흔듀림":
            size = random.uniform(10, 18)
            speed = random.uniform(2, 5)
            drift = random.uniform(-1, 2)
            color = (random.randint(80, 130), random.randint(130, 190), random.randint(60, 100), random.randint(120, 200))
        elif self.p_type == "λ°”λžŒ 효과":
            size = random.uniform(30, 70)
            speed = random.uniform(1, 3)
            drift = random.uniform(4, 9)
            color = (230, 240, 255, random.randint(90, 150))
        else: # Default/Sunshine
            size = 0
            speed = 0
            drift = 0
            color = (0,0,0,0)
            
        return {"x": x, "y": y, "size": size, "speed": speed, "drift": drift, "color": color, "angle": random.uniform(0, 2*math.pi)}

    def update_and_draw(self, draw, frame_idx):
        if self.p_type == "μ—†μŒ":
            return
            
        if self.p_type == "ν–‡μ‚΄ λ°˜μ§μž„":
            # Draw overlay light leak/shimmer
            overlay = Image.new("RGBA", (self.canvas_w, self.canvas_h), (0,0,0,0))
            overlay_draw = ImageDraw.Draw(overlay)
            
            # Oscillate sunshine center and opacity
            pulse = math.sin(frame_idx * 0.08) * 15 + 60
            center_x = 900 + int(math.sin(frame_idx * 0.05) * 30)
            center_y = 100 + int(math.cos(frame_idx * 0.05) * 20)
            
            # Draw concentric warm soft circles
            for r in range(500, 0, -50):
                alpha = int(pulse * (1 - r / 500) * 0.2)
                overlay_draw.ellipse(
                    (center_x - r, center_y - r, center_x + r, center_y + r),
                    fill=(255, 245, 200, alpha)
                )
            draw.bitmap((0, 0), overlay.convert("L"), fill=(255, 245, 200)) # Simple paste helper or blend
            return

        if self.p_type == "ꡬ름 천천히 이동":
            shift = int((frame_idx * 0.6) % (self.canvas_w + 400)) - 300
            for base_x, base_y, scale in [(shift, 180, 1.0), (shift + 430, 320, 0.75), (shift - 520, 520, 0.9)]:
                color = (225, 232, 242)
                draw.ellipse((base_x, base_y, base_x + int(260 * scale), base_y + int(90 * scale)), fill=color)
                draw.ellipse((base_x + int(90 * scale), base_y - int(35 * scale), base_x + int(340 * scale), base_y + int(95 * scale)), fill=color)
            return
            
        # Standard particle types
        for p in self.particles:
            p["y"] += p["speed"]
            p["x"] += p["drift"]
            
            if self.p_type in ["κ½ƒμžŽ 흩날림", "λ‚˜λ­‡μžŽ 흔듀림"]:
                p["x"] += math.sin(frame_idx * 0.1 + p["angle"]) * 2 # Swaying path
                
            # If off screen, reset
            if p["y"] > self.canvas_h or p["x"] < -20 or p["x"] > self.canvas_w + 20:
                p.update(self._reset_particle(init=False))
                
            # Draw particle
            x, y = p["x"], p["y"]
            sz = p["size"]
            col = p["color"]
            
            if self.p_type == "눈 λ‚΄λ¦Ό":
                draw.ellipse((x - sz, y - sz, x + sz, y + sz), fill=col[:3])
            elif self.p_type == "λΉ„ λ‚΄λ¦Ό":
                draw.line((x, y, x + p["drift"] * 3, y + sz), fill=col[:3], width=1)
            elif self.p_type == "κ½ƒμžŽ 흩날림":
                p["angle"] += 0.05
                draw.ellipse((x - sz//2, y - sz//3, x + sz//2, y + sz//3), fill=col[:3])
            elif self.p_type == "λ‚˜λ­‡μžŽ 흔듀림":
                p["angle"] += 0.04
                draw.ellipse((x - sz//2, y - sz//3, x + sz//2, y + sz//3), fill=col[:3])
                draw.line((x, y, x + sz//2, y + sz//3), fill=(70, 110, 55), width=1)
            elif self.p_type == "λ°”λžŒ 효과":
                draw.arc((x, y, x + sz, y + sz // 2), start=190, end=350, fill=col[:3], width=2)

# Helper function to wrap text for subtitles
def wrap_text(text, font, max_width):
    lines = []
    words = list(text) # In Korean, wrap by character rather than space is often preferred if long, but we can do space or chars.
    
    # We will split by spaces first
    space_words = text.split(' ')
    current_line = ""
    
    for word in space_words:
        test_line = current_line + " " + word if current_line else word
        # Calculate width
        w = font.getbbox(test_line)[2]
        if w <= max_width:
            current_line = test_line
        else:
            if current_line:
                lines.append(current_line)
            current_line = word
            
    if current_line:
        lines.append(current_line)
    return lines

# Function to draw subtitles with custom styles
def draw_subtitles(canvas, text, font_size_style, font_color_style, use_bg):
    draw = ImageDraw.Draw(canvas, "RGBA")
    
    # Choose font size
    size = 46 if font_size_style == "큰 글씨" else 32
    
    try:
        download_font()
        font = ImageFont.truetype(FONT_PATH, size)
    except IOError:
        font = ImageFont.load_default()
        
    color = (255, 255, 255) if font_color_style == "흰색" else (255, 242, 0)
    
    # Wrap text
    max_w = 960 # 1080 - 120 padding
    wrapped_lines = wrap_text(text, font, max_w)
    
    # Calculate height and positions
    line_spacing = 8
    total_height = sum([font.getbbox(line)[3] - font.getbbox(line)[1] for line in wrapped_lines]) + (len(wrapped_lines) - 1) * line_spacing
    
    start_y = 1750 - total_height // 2
    
    # Draw background box if enabled
    if use_bg and wrapped_lines:
        bg_padding = 15
        box_y1 = start_y - bg_padding
        box_y2 = start_y + total_height + bg_padding
        
        # Transparent background box
        # Create a temp transparent layer to blend alpha box
        overlay = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
        overlay_draw = ImageDraw.Draw(overlay)
        overlay_draw.rectangle((60, box_y1, 1020, box_y2), fill=(0, 0, 0, 140))
        canvas.paste(overlay, (0, 0), overlay)
        
    # Draw text lines centered
    current_y = start_y
    for line in wrapped_lines:
        w = font.getbbox(line)[2]
        x = (1080 - w) // 2
        draw.text((x, current_y), line, fill=color, font=font)
        current_y += (font.getbbox(line)[3] - font.getbbox(line)[1]) + line_spacing

def generate_default_subtitles(video_type, description, num_images):
    desc = description if description else "ν”„λ‘œκ·Έλž¨ ν™œλ™"
    templates = {
        "κΈ°κ΄€ν™λ³΄ν˜•": [
            f"μ˜€λŠ˜λ„ ν™œκΈ°μ°¨κ²Œ μ‹œμž‘ν•˜λŠ” {desc}",
            "μ„œλ‘œ 돕고 μ›ƒμŒκ½ƒ ν”ΌλŠ” λ”°λœ»ν•œ λŒλ΄„ ν˜„μž₯",
            "μ–΄λ₯΄μ‹ λ“€μ˜ μ•ˆμ „ν•˜κ³  λ“ λ“ ν•œ 보금자리",
            "κ°€μ‘±μ˜ 마음으둜 ν•¨κ»˜ λ™ν–‰ν•˜κ² μŠ΅λ‹ˆλ‹€",
            "늘 κ³μ—μ„œ μ‚¬λž‘κ³Ό μ •μ„±μœΌλ‘œ λ³΄μ‚΄ν•λ‹ˆλ‹€"
        ],
        "κ°λ™λ‹€νν˜•": [
            "주름진 μ†λμ—μ„œ ν”Όμ–΄λ‚˜λŠ” 이야기",
            "ν•¨κ»˜ λ‚˜λˆ„λŠ” λ―Έμ†Œ 속에 흐λ₯΄λŠ” λ”°λœ»ν•œ μ‹œκ°„",
            "κ·Έ μ‹œμ ˆ κ·Έ 고운 마음 κ·ΈλŒ€λ‘œ",
            "μ–΄λ₯΄μ‹ μ˜ μ†Œμ€‘ν•œ 인생 여정을 μ‘μ›ν•©λ‹ˆλ‹€",
            "κΈ°μ–΅ 속에 λ‹΄κΈ΄ λ”°λœ»ν•œ μΆ”μ–΅ ν•œ 쑰각"
        ],
        "μƒμ‹ μΆ•ν•˜ν˜•": [
            "였늘 μ„Έμƒμ—μ„œ κ°€μž₯ νŠΉλ³„ν•˜κ³  기쁜 λ‚ ",
            "μ–΄λ₯΄μ‹ μ˜ μ†Œμ€‘ν•œ 생신을 온 마음으둜 μΆ•ν•˜λ“œλ¦½λ‹ˆλ‹€",
            "늘 κ±΄κ°•ν•˜μ‹œκ³  κ½ƒκΈΈλ§Œ κ±ΈμœΌμ†Œμ„œ",
            "ν•¨κ»˜ν•΄μ£Όμ…”μ„œ μ°Έ κ³ λ§™κ³  ν–‰λ³΅ν•©λ‹ˆλ‹€",
            "μ–Έμ œλ‚˜ κ±΄κ°•ν•˜κ³  ν‰μ˜¨ν•˜μ‹œκΈ°λ₯Ό κΈ°λ„ν•©λ‹ˆλ‹€"
        ],
        "μ°½μž‘ν™œλ™ν˜•": [
            "μ†λμ˜ μ •μ„±μœΌλ‘œ λΉšμ–΄λ‚΄λŠ” μ°½μž‘ ν™œλ™",
            "μ§‘μ€‘ν•˜μ‹œλŠ” λˆˆλΉ› 속 ν”Όμ–΄λ‚˜λŠ” μ—΄μ •",
            "μ–΄λ₯΄μ‹ λ“€μ˜ 창의λ ₯이 가득 λ‹΄κΈ΄ κ·€ν•œ μž‘ν’ˆ",
            "만쑱슀러운 λ―Έμ†Œμ™€ μ„±μ·¨κ°μ˜ μˆœκ°„",
            "μžμ‹ κ°κ³Ό 행볡이 μžλΌλ‚˜λŠ” 미술 ꡐ싀"
        ],
        "μž‘ν’ˆμ „μ‹œν˜•": [
            "세상에 단 ν•˜λ‚˜λΏμΈ κ³ κ·€ν•œ 예술 μž‘ν’ˆ",
            "ν•œ λ•€ ν•œ λ•€ 흘린 μ •μ„±κ³Ό 손길",
            "마음의 μƒ‰κΉ”λ‘œ κ·Έλ €λ‚Έ μ–΄λ₯΄μ‹ μ˜ 우주",
            "λͺ¨λ‘κ°€ κ°νƒ„ν•œ 였늘의 λͺ…μž‘ μ „μ‹œνšŒ",
            "예술둜 μ†Œν†΅ν•˜κ³  μΉ˜μœ λ°›λŠ” νŠΉλ³„ν•œ μ‹œκ°„"
        ],
        "μΆ”μ–΅νšŒμƒν˜•": [
            "μ•„λ ¨νžˆ λ– μ˜€λ₯΄λŠ” κ·Έ μ‹œμ ˆ μš°λ¦¬λ“€μ˜ μΆ”μ–΅",
            "사진첩 속에 κΉƒλ“  그리운 이야기",
            "κ°€μŠ΄μ† 깊이 묻어둔 고운 κΈ°μ–΅λ“€",
            "λ‹€μ‹œκΈˆ κΊΌλ‚΄μ–΄ μ›ƒμŒ μ§€μ–΄λ³΄λŠ” λ‚ ",
            "ν˜λŸ¬κ°„ μ„Έμ›”λ§ˆμ € μ•„λ¦„λ‹€μš΄ μΈμƒμ˜ 쑰각"
        ],
        "μžμ„œμ „ν˜•": [
            "λΉ›λ‚˜λŠ” μ²­μΆ˜μ„ μ§€λ‚˜ λ„λ‹¬ν•œ μ•„λ¦„λ‹€μš΄ κ³„μ ˆ",
            "μ§€ν˜œμ™€ μ‚¬λž‘μœΌλ‘œ μΌκ΅¬μ–΄μ˜¨ μ‚Άμ˜ ꢀ적",
            "κ°€μ‘±λ“€μ˜ λ“ λ“ ν•œ λΏŒλ¦¬κ°€ λ˜μ–΄μ£Όμ‹  고마운 λΆ„",
            "μ–΄λ₯΄μ‹ μ˜ μ‚Ά μžμ²΄κ°€ κ°€μž₯ μœ„λŒ€ν•œ μ†Œμ„€μž…λ‹ˆλ‹€",
            "λ”°λœ»ν•œ 발자취λ₯Ό 온 마음으둜 κΈ°λ‘ν•©λ‹ˆλ‹€"
        ]
    }
    
    sub_list = templates.get(video_type, templates["κ°λ™λ‹€νν˜•"])
    
    # If the user put description, let's format it dynamically
    result = []
    for i in range(num_images):
        idx = i % len(sub_list)
        result.append(sub_list[idx])
    return result

def get_file_path(file_value):
    if isinstance(file_value, str):
        return file_value
    if hasattr(file_value, "path"):
        return file_value.path
    if isinstance(file_value, dict):
        return file_value.get("path") or file_value.get("name")
    return file_value

# Core generator function for Gradio interface
def make_image_drama_video(image_files, video_type, camera_effect, natural_effect,
                           activity_desc, subtitle_mode, subtitle_input, font_size, font_color, use_bg, music_file):
    
    if not image_files or len(image_files) < 3:
        return None, "μ΅œμ†Œ 3μž₯의 사진을 μ—…λ‘œλ“œν•΄ μ£Όμ„Έμš”. v1은 3~5μž₯을 ꢌμž₯ν•©λ‹ˆλ‹€."
        
    if len(image_files) > 5:
        image_files = image_files[:5]
        
    num_images = len(image_files)
    
    # Step 1: Handle subtitles. Institutions either enter subtitles directly or create a clean video without text.
    use_subtitles = subtitle_mode == "μ§μ ‘μž…λ ₯"
    subtitles = []
    if use_subtitles:
        if not subtitle_input or not subtitle_input.strip():
            return None, "μžλ§‰ 방식을 μ§μ ‘μž…λ ₯으둜 μ„ νƒν•œ 경우, μžλ§‰ λ‚΄μš©μ„ μž…λ ₯ν•΄ μ£Όμ„Έμš”."
        subtitles = [s.strip() for s in re.split(r"[,\n]+", subtitle_input) if s.strip()]
        if len(subtitles) < num_images:
            subtitles += [""] * (num_images - len(subtitles))
        subtitles = subtitles[:num_images]
        
    # Step 2: Render Frames
    fps = 24
    frames_per_image = 96  # 4 seconds per image at 24fps
    total_frames = num_images * frames_per_image
    
    # Initialize particle system for natural effects
    p_count = 0
    if natural_effect in ["눈 λ‚΄λ¦Ό", "λΉ„ λ‚΄λ¦Ό"]:
        p_count = 50
    elif natural_effect == "κ½ƒμžŽ 흩날림":
        p_count = 35
    elif natural_effect == "λ‚˜λ­‡μžŽ 흔듀림":
        p_count = 30
    elif natural_effect == "λ°”λžŒ 효과":
        p_count = 18
    particles = ParticleSystem(p_count, natural_effect)
    
    import cv2

    run_id = uuid.uuid4().hex
    output_video_path = os.path.join(tempfile.gettempdir(), f"care_cinema_studio_image_drama_{run_id}.mp4")
    silent_video_path = os.path.join(tempfile.gettempdir(), f"care_cinema_studio_image_drama_silent_{run_id}.mp4")
    for path in [output_video_path, silent_video_path]:
        if os.path.exists(path):
            try:
                os.remove(path)
            except Exception:
                pass

    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    video_writer = cv2.VideoWriter(silent_video_path, fourcc, fps, (1080, 1920))
    if not video_writer.isOpened():
        return None, "μ˜μƒ νŒŒμΌμ„ μ€€λΉ„ν•˜λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μž μ‹œ ν›„ λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”."

    for i, img_file in enumerate(image_files):
        # Open and load image
        img_path = get_file_path(img_file)
        try:
            original_img = Image.open(img_path).convert("RGB")
        except Exception as e:
            print(f"Error opening image {img_path}: {e}")
            original_img = Image.new("RGB", (1080, 1920), (50, 50, 50))
            
        current_subtitle = subtitles[i] if use_subtitles else ""
        
        # Select current camera effect
        eff = camera_effect
        if camera_effect == "랜덀 μ‹œλ„€λ§ˆ 효과":
            random.seed(i) # Fixed random per photo segment
            eff = random.choice([
                "천천히 쀌인", "천천히 μ€Œμ•„μ›ƒ", "쒌 -> 우 이동", 
                "우 -> 쒌 이동", "μœ„ -> μ•„λž˜ 이동", "μ•„λž˜ -> μœ„ 이동"
            ])
            
        for f in range(frames_per_image):
            # Apply camera motion
            frame = apply_camera_effect(original_img, eff, f, frames_per_image)
            
            # Apply natural overlay effects
            frame_draw = ImageDraw.Draw(frame)
            global_frame_idx = i * frames_per_image + f
            particles.update_and_draw(frame_draw, global_frame_idx)
            
            if use_subtitles and current_subtitle:
                draw_subtitles(frame, current_subtitle, font_size, font_color, use_bg)

            video_writer.write(cv2.cvtColor(np.array(frame), cv2.COLOR_RGB2BGR))

    video_writer.release()

    # Step 3: Add optional uploaded music. Silent output remains the safe default.
    music_path = get_file_path(music_file) if music_file else None
    if music_path and HAS_MOVIEPY:
        clip = None
        audio_clip = None
        try:
            clip = VideoFileClip(silent_video_path)
            audio_clip = AudioFileClip(music_path)
            if audio_clip.duration < clip.duration:
                audio_clip = audio_loop(audio_clip, duration=clip.duration)
            else:
                audio_clip = audio_clip.subclip(0, clip.duration)
            clip = clip.set_audio(audio_clip)
            clip.write_videofile(
                output_video_path,
                codec="libx264",
                audio_codec="aac",
                temp_audiofile=os.path.join(tempfile.gettempdir(), f"ccs-temp-audio-{run_id}.m4a"),
                remove_temp=True,
                fps=fps,
            )
            if os.path.exists(silent_video_path):
                os.remove(silent_video_path)
        except Exception as ve:
            print(f"Audio mixing failed, returning silent video: {ve}")
            os.replace(silent_video_path, output_video_path)
        finally:
            if audio_clip is not None:
                audio_clip.close()
            if clip is not None:
                clip.close()
    else:
        os.replace(silent_video_path, output_video_path)
            
    status = (
        "μ˜μƒ 생성이 μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€. "
        f"{num_images}μž₯의 μ‚¬μ§„μœΌλ‘œ 9:16 μ‡ΌμΈ  ν˜•μ‹μ˜ Image Drama μ˜μƒμ„ λ§Œλ“€μ—ˆμŠ΅λ‹ˆλ‹€. "
        f"μžλ§‰ 방식: {subtitle_mode}"
    )
    return output_video_path, status

# CSS for Care Cinema Studio.
custom_css = """
.gradio-container {
    background-color: #0b111e;
    color: #e5e7eb;
    font-family: 'Outfit', 'Inter', -apple-system, sans-serif;
}
.header-box {
    background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 50%, #d946ef 100%);
    padding: 2.5rem;
    border-radius: 8px;
    text-align: center;
    margin-bottom: 2rem;
    box-shadow: 0 10px 30px -5px rgba(139, 92, 246, 0.4);
    border: 1px solid rgba(255, 255, 255, 0.1);
}
.header-box h1 {
    color: #ffffff;
    font-size: 2.8rem;
    font-weight: 800;
    margin-bottom: 0.5rem;
    letter-spacing: -0.03em;
    text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}
.header-box p {
    color: #e0e7ff;
    font-size: 1.2rem;
    font-weight: 300;
}
.primary-btn {
    background: linear-gradient(90deg, #3b82f6 0%, #8b5cf6 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600 !important;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
    border-radius: 8px !important;
    box-shadow: 0 4px 12px rgba(139, 92, 246, 0.2) !important;
}
.primary-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(139, 92, 246, 0.45) !important;
}
.glass-panel {
    background: rgba(17, 24, 39, 0.65) !important;
    backdrop-filter: blur(12px) !important;
    border: 1px solid rgba(255, 255, 255, 0.08) !important;
    border-radius: 8px !important;
    padding: 1.5rem !important;
}
"""

# Build Gradio UI
with gr.Blocks(
    title="Care Cinema Studio - Image Drama Generator",
    css=custom_css,
    theme=gr.themes.Soft(primary_hue="violet", secondary_hue="blue"),
) as demo:
    
    # Top Banner Header
    gr.HTML(
        """
        <div class="header-box">
            <h1>🎬 Care Cinema Studio (CCS)</h1>
            <p>Turn Photos Into Stories | 사진을 μ΄μ•ΌκΈ°λ‘œ λ§Œλ“œλŠ” AI μ˜μƒ 생성기</p>
        </div>
        """
    )
    
    with gr.Row():
        with gr.Column(scale=1, elem_classes="glass-panel"):
            gr.Markdown("### πŸ“Έ 사진 및 λΉ„λ””μ˜€ μ„€μ •")
            gr.Markdown("무료 v1 κΈ°μ€€: ν•˜λ£¨ 2회 생성, 사진 3~5μž₯, μ΅œλŒ€ 20초 MP4 μ‡ΌμΈ ")
            image_input = gr.File(
                file_count="multiple", 
                file_types=["image"], 
                type="filepath",
                label="사진 μ—…λ‘œλ“œ (3~5μž₯ ꢌμž₯)"
            )
            
            video_type_dropdown = gr.Dropdown(
                choices=["κΈ°κ΄€ν™λ³΄ν˜•", "κ°λ™λ‹€νν˜•", "μƒμ‹ μΆ•ν•˜ν˜•", "μ°½μž‘ν™œλ™ν˜•", "μž‘ν’ˆμ „μ‹œν˜•", "μΆ”μ–΅νšŒμƒν˜•"], 
                value="μ°½μž‘ν™œλ™ν˜•", 
                label="μ˜μƒ μœ ν˜•"
            )
            
            activity_desc_input = gr.Textbox(
                label="ν™œλ™ 상세 μ„€λͺ… (AI μžλ§‰ 생성을 λ•μŠ΅λ‹ˆλ‹€)",
                placeholder="예: μ–΄λ₯΄μ‹ λ“€μ˜ 인지 λ°œλ‹¬ 및 손가락 μš΄λ™μ„ μœ„ν•œ 클레이 μ•„νŠΈ λ¬Όκ³ κΈ° λ§Œλ“€κΈ° 미술 치료 ν”„λ‘œκ·Έλž¨ μ§„ν–‰",
                value="μ–΄λ₯΄μ‹ λ“€μ˜ μ†Œκ·Όμœ‘ 자극과 성취감 νšλ“μ„ μœ„ν•œ 색찰흙 μ°½μž‘ ν™œλ™",
                lines=2
            )
            
            gr.Markdown("### 🎨 μ‹œλ„€λ§ˆν‹± 효과")
            camera_effect_dropdown = gr.Dropdown(
                choices=["천천히 쀌인", "천천히 μ€Œμ•„μ›ƒ", "쒌 -> 우 이동", "우 -> 쒌 이동", "μœ„ -> μ•„λž˜ 이동", "μ•„λž˜ -> μœ„ 이동", "랜덀 μ‹œλ„€λ§ˆ 효과"], 
                value="천천히 쀌인", 
                label="카메라 효과"
            )
            
            natural_effect_dropdown = gr.Dropdown(
                choices=["μ—†μŒ", "ꡬ름 천천히 이동", "λ°”λžŒ 효과", "λ‚˜λ­‡μžŽ 흔듀림", "κ½ƒμžŽ 흩날림", "ν–‡μ‚΄ λ°˜μ§μž„", "λΉ„ λ‚΄λ¦Ό", "눈 λ‚΄λ¦Ό"], 
                value="μ—†μŒ", 
                label="μžμ—° 효과 (μ˜€λ²„λ ˆμ΄)"
            )
            
            gr.Markdown("### πŸ’¬ μžλ§‰")
            subtitle_mode_radio = gr.Radio(
                choices=["μ§μ ‘μž…λ ₯", "μžλ§‰μ—†μŒ"],
                value="μ§μ ‘μž…λ ₯",
                label="μžλ§‰ 방식"
            )
            subtitle_input_field = gr.Textbox(
                label="κΈ°κ΄€ μž…λ ₯ μžλ§‰ (μ‰Όν‘œ λ˜λŠ” μ€„λ°”κΏˆ ꡬ뢄)",
                placeholder="예: μ˜€λŠ˜λ„ 즐거운 미술 μ‹œκ°„\nμ†λμ—μ„œ ν”Όμ–΄λ‚œ 예쁜 μž‘ν’ˆ\nν•¨κ»˜ μ›ƒλŠ” λ”°λœ»ν•œ ν•˜λ£¨"
            )
            
            with gr.Row():
                font_size_radio = gr.Radio(choices=["큰 글씨", "μž‘μ€ 글씨"], value="큰 글씨", label="κΈ€μž 크기")
                font_color_radio = gr.Radio(choices=["흰색", "λ…Έλž€μƒ‰"], value="흰색", label="κΈ€μž 색상")
                
            use_bg_checkbox = gr.Checkbox(label="κ²€μ • 반투λͺ… μžλ§‰ λ°°κ²½ 적용", value=True)
            
            gr.Markdown("### 🎡 μ‚¬μš΄λ“œ")
            audio_input = gr.Audio(
                sources=["upload"],
                type="filepath", 
                label="λ°°κ²½ μŒμ•… (MP3 μ—…λ‘œλ“œ, 선택)"
            )
            
            submit_btn = gr.Button("Image Drama μ˜μƒ 생성", elem_classes="primary-btn")
            
        with gr.Column(scale=1, elem_classes="glass-panel"):
            gr.Markdown("### πŸŽ₯ μƒμ„±λœ μ‹œλ„€λ§ˆν‹± μ‡ΌμΈ  (9:16)")
            video_output = gr.Video(label="μ™„λ£Œλœ μ˜μƒ")
            
            gr.Markdown("### 생성 μƒνƒœ")
            status_output = gr.Markdown(value="사진을 μ—…λ‘œλ“œν•˜κ³  생성을 μ‹œμž‘ν•˜λ©΄ 이곳에 μ™„λ£Œ μ•ˆλ‚΄κ°€ ν‘œμ‹œλ©λ‹ˆλ‹€.")
            
    # Connect trigger
    submit_btn.click(
        fn=make_image_drama_video,
        inputs=[
            image_input,
            video_type_dropdown,
            camera_effect_dropdown,
            natural_effect_dropdown,
            activity_desc_input,
            subtitle_mode_radio,
            subtitle_input_field,
            font_size_radio,
            font_color_radio,
            use_bg_checkbox,
            audio_input
        ],
        outputs=[video_output, status_output]
    )

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)