File size: 36,511 Bytes
a3e25fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
import os
import time
from typing import Callable, List

import cv2
import yt_dlp
import google.generativeai as genai

from prompts import GeminiPrompts
from datetime import datetime


class VideoProcessor:
    def __init__(self, api_key: str = None):
        # API ν‚€κ°€ 직접 μ „λ‹¬λ˜λ©΄ μ‚¬μš©, μ•„λ‹ˆλ©΄ ν™˜κ²½λ³€μˆ˜μ—μ„œ
        self.api_key = api_key or os.getenv("GEMINI_API_KEY")
        genai.configure(api_key=self.api_key)
        self.stop_flag = False
        self.last_descriptions = []

    def set_stop_flag(self, value: bool):
        self.stop_flag = value

    def analyze_video(

        self,

        video_input: str,

        is_youtube_url: bool,

        output_folder: str,

        interval_seconds: int,

        analysis_mode: str,

        progress_callback: Callable[[int, int, float, str], None] = None

    ) -> str:
        if self.stop_flag:
            raise RuntimeError("μž‘μ—…μ΄ μ€‘λ‹¨λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
        downloaded_file_path, video_title = self._download_video(video_input, is_youtube_url, progress_callback)

        # 특수문자 제거
        safe_video_title = "".join(c if c.isalnum() or c in (' ', '.', '_', '-') else '_' for c in video_title).strip()
        safe_video_title = "_".join(safe_video_title.split()).strip('_')

        # 파일λͺ… 길이 μ œν•œ (Windows 경둜 ν•œκ³„ κ³ λ €)
        max_title_length = 50  # 50자둜 μ œν•œ
        if len(safe_video_title) > max_title_length:
            safe_video_title = safe_video_title[:max_title_length].rstrip('_')

        # 빈 제λͺ©μΈ 경우 κΈ°λ³Έκ°’ μ„€μ •
        if not safe_video_title:
            safe_video_title = "Unknown_Video"

        print(f"πŸ” 원본 제λͺ©: {video_title}")
        print(f"πŸ” μ•ˆμ „ν•œ 제λͺ©: {safe_video_title} (길이: {len(safe_video_title)})")
        
        final_output_folder = os.path.join(output_folder, safe_video_title)
        os.makedirs(final_output_folder, exist_ok=True)

        # πŸ†• λ‹€μš΄λ‘œλ“œλœ νŒŒμΌμ„ 폴더λͺ…κ³Ό λ™μΌν•œ μ΄λ¦„μœΌλ‘œ λ³€κ²½
        file_extension = os.path.splitext(downloaded_file_path)[1]  # ν™•μž₯자 μΆ”μΆœ (.mp4, .webm λ“±)
        new_video_filename = f"{safe_video_title}{file_extension}"
        new_temp_path = os.path.join(final_output_folder, new_video_filename)
        
        # πŸ”§ 둜컬 파일 처리 κ°œμ„  (URL μ²˜λ¦¬λŠ” κ·ΈλŒ€λ‘œ)
        if not is_youtube_url and downloaded_file_path == video_input:
            # 둜컬 파일인 경우: 볡사본 생성 (원본 보쑴)
            import shutil
            try:
                if os.path.exists(new_temp_path):
                    os.remove(new_temp_path)  # κΈ°μ‘΄ 파일이 있으면 μ‚­μ œ
                shutil.copy2(downloaded_file_path, new_temp_path)
                print(f"πŸ” 둜컬 파일 볡사: {downloaded_file_path} β†’ {new_temp_path}")
            except Exception as e:
                # 볡사 μ‹€νŒ¨ν•˜λ©΄ 원본 κ·ΈλŒ€λ‘œ μ‚¬μš©
                print(f"πŸ” 볡사 μ‹€νŒ¨, 원본 μ‚¬μš©: {e}")
                new_temp_path = downloaded_file_path
        else:
            # URL λ‹€μš΄λ‘œλ“œ 파일인 경우: 이동 (κΈ°μ‘΄ 둜직 μœ μ§€)
            if downloaded_file_path != new_temp_path:
                if os.path.exists(new_temp_path):
                    os.remove(new_temp_path)  # κΈ°μ‘΄ 파일이 있으면 μ‚­μ œ
                os.rename(downloaded_file_path, new_temp_path)
                print(f"πŸ” λ‹€μš΄λ‘œλ“œ 파일 이동: {downloaded_file_path} β†’ {new_temp_path}")
        
        temp_path = new_temp_path
        print(f"πŸ” μ΅œμ’… μ˜μƒ 파일: {temp_path}")

        # πŸ” μ—¬κΈ°μ„œ _extract_framesκ°€ 무엇을 λ°˜ν™˜ν•˜λŠ”μ§€ 확인
        descriptions = self._extract_frames(temp_path, interval_seconds, final_output_folder, progress_callback)
        
        print(f"πŸ” DEBUG: _extract_frames λ°˜ν™˜κ°’ νƒ€μž…: {type(descriptions)}")
        print(f"πŸ” DEBUG: _extract_frames λ°˜ν™˜κ°’ 길이: {len(descriptions) if descriptions else 0}")
        if descriptions:
            print(f"πŸ” DEBUG: 첫 번째 μ•„μ΄ν…œ νƒ€μž…: {type(descriptions[0])}")
            print(f"πŸ” DEBUG: 첫 번째 μ•„μ΄ν…œ λ‚΄μš©: {str(descriptions[0])[:200]}...")
        
        # self.last_descriptions μ„€μ •
        self.last_descriptions = descriptions
        print(f"πŸ” DEBUG: self.last_descriptions μ„€μ • μ™„λ£Œ, 길이: {len(self.last_descriptions)}")
        
        # _run_general_summary 호좜 μ „ 확인
        print(f"πŸ” DEBUG: _run_general_summary 호좜 μ „ descriptions νƒ€μž…: {type(descriptions)}")
        
        report_content = self._run_general_summary(descriptions, progress_callback)
        
        print(f"πŸ” DEBUG: _run_general_summary μ™„λ£Œ, λ³΄κ³ μ„œ 길이: {len(report_content)}")
        print(f"πŸ” DEBUG: 'ν”„λ ˆμž„λ³„ 상세 뢄석' 포함 μ—¬λΆ€: {'ν”„λ ˆμž„λ³„ 상세 뢄석' in report_content}")

        return self._save_report(report_content, final_output_folder)


    def _download_video(

        self,

        video_input: str,

        is_youtube_url: bool,

        progress_callback: Callable[[int, int, float, str], None] = None

    ) -> tuple[str, str]:
        if self.stop_flag:
            raise RuntimeError("μž‘μ—…μ΄ μ€‘λ‹¨λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
        
        # πŸ” 이 ν•¨μˆ˜λŠ” 이제 URLμ—μ„œλ§Œ 호좜됨
        print(f"πŸ” URL λ‹€μš΄λ‘œλ“œ μ‹œμž‘: {video_input}")
        
        # URL인 κ²½μš°μ—λ§Œ yt-dlp μ‚¬μš©
        temp_download_dir = "temp_downloads"
        os.makedirs(temp_download_dir, exist_ok=True)
        
        temp_filename = f"temp_video_{int(time.time())}.%(ext)s"
        output_filepath = os.path.join(temp_download_dir, temp_filename)
        
        ydl_opts = {
            'outtmpl': output_filepath,
            'format': 'bestvideo+bestaudio/best',
            'noprogress': True,
            'overwrites': True,
            'progress_hooks': [lambda d: self._download_progress_hook(d, progress_callback)],
            'no_playlist': True,
            'retries': 5,
            'merge_output_format': 'mp4',
            'quiet': False,
            'no_warnings': True,
            # μΈμŠ€νƒ€κ·Έλž¨ 지원 μ˜΅μ…˜ μΆ”κ°€
            'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'referer': 'https://www.instagram.com/',
            'http_headers': {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language': 'en-us,en;q=0.5',
                'Sec-Fetch-Mode': 'navigate',
            },
            'extract_flat': False,
            'no_check_certificate': True,
        }
        
        try:
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(video_input, download=True)
                
                filename = None
                
                # κΈ°λ³Έ 파일 경둜 μ°ΎκΈ° μ‹œλ„
                if 'requested_downloads' in info and info['requested_downloads']:
                    filename = info['requested_downloads'][0]['filepath']
                elif '_filename' in info:
                    filename = info['_filename']
                elif 'filepath' in info:
                    filename = info['filepath']
                
                print(f"πŸ” λ‹€μš΄λ‘œλ“œ μ™„λ£Œ ν›„ 파일 κ²½λ‘œλ“€:")
                print(f"  - requested_downloads: {info.get('requested_downloads')}")
                print(f"  - _filename: {info.get('_filename')}")
                print(f"  - μ΅œμ’… μ„ νƒλœ 파일: {filename}")
                
                # κΈ°λ³Έ κ²½λ‘œμ—μ„œ νŒŒμΌμ„ μ°Ύμ§€ λͺ»ν•œ 경우, temp ν΄λ”μ—μ„œ μ΅œμ‹  파일 μ°ΎκΈ°
                if not filename or not os.path.exists(filename) or os.path.getsize(filename) == 0:
                    print("πŸ” κΈ°λ³Έ κ²½λ‘œμ—μ„œ νŒŒμΌμ„ μ°Ύμ§€ λͺ»ν•¨. temp 폴더 검색 쀑...")
                    
                    # temp_downloads ν΄λ”μ—μ„œ κ°€μž₯ 졜근 파일 μ°ΎκΈ°
                    temp_files = []
                    for file in os.listdir(temp_download_dir):
                        if file.startswith("temp_video_") and file.endswith((".mp4", ".webm", ".mkv", ".m4v")):
                            file_path = os.path.join(temp_download_dir, file)
                            temp_files.append((file_path, os.path.getmtime(file_path)))
                    
                    if temp_files:
                        # κ°€μž₯ 졜근 파일 μ‚¬μš©
                        filename = max(temp_files, key=lambda x: x[1])[0]
                        print(f"πŸ” λŒ€μ²΄ 파일 발견: {filename}")
                    else:
                        raise RuntimeError("λ‹€μš΄λ‘œλ“œλœ νŒŒμΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
                
                # 파일 쑴재 확인을 μœ„ν•œ μž¬μ‹œλ„ 둜직
                max_retries = 10
                for i in range(max_retries):
                    if os.path.exists(filename) and os.path.getsize(filename) > 0:
                        print(f"πŸ” 파일 확인 μ™„λ£Œ: {filename} ({os.path.getsize(filename)} bytes)")
                        break
                    print(f"πŸ” 파일 λŒ€κΈ° 쀑... ({i+1}/{max_retries})")
                    time.sleep(1)
                else:
                    raise RuntimeError(f"λ‹€μš΄λ‘œλ“œλœ λ™μ˜μƒ 파일이 μ‘΄μž¬ν•˜μ§€ μ•Šκ±°λ‚˜ λΉ„μ–΄ μžˆμŠ΅λ‹ˆλ‹€: {filename} (μ΅œλŒ€ μž¬μ‹œλ„ 횟수 초과)")
                
                video_title = info.get('title', 'Unknown_Video')
                print(f"πŸ” μ΅œμ’… λΉ„λ””μ˜€ 제λͺ©: {video_title}")
                return filename, video_title
                
        except yt_dlp.utils.DownloadError as e:
            if progress_callback:
                progress_callback(0, 1, 0.0, f"λ‹€μš΄λ‘œλ“œ 였λ₯˜: {e}")
            raise RuntimeError(f"λ™μ˜μƒ λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨: {e}")
        except Exception as e:
            if progress_callback:
                progress_callback(0, 1, 0.0, f"λ‹€μš΄λ‘œλ“œ 쀑 μ˜ˆμ™Έ λ°œμƒ: {e}")
            raise RuntimeError(f"λ™μ˜μƒ λ‹€μš΄λ‘œλ“œ 쀑 μ•Œ 수 μ—†λŠ” 였λ₯˜ λ°œμƒ: {e}")

    def _extract_frames(

        self,

        video_path: str,

        interval: int,

        output_folder: str,

        progress_callback: Callable[[int, int, float, str], None] = None

    ) -> List[str]:
        print(f"πŸ” _extract_frames μ‹œμž‘: {video_path}")
        print(f"πŸ” 파일 쑴재: {os.path.exists(video_path)}")
        print(f"πŸ” 파일 크기: {os.path.getsize(video_path) if os.path.exists(video_path) else 0}")
        
        # 🎯 TikTok용 νŠΉλ³„ 처리: λ‹€μ–‘ν•œ λ°©λ²•μœΌλ‘œ μ˜μƒ μ—΄κΈ° μ‹œλ„
        cap = None
        open_methods = [
            lambda: cv2.VideoCapture(video_path),
            lambda: cv2.VideoCapture(video_path, cv2.CAP_FFMPEG),
            lambda: cv2.VideoCapture(video_path, cv2.CAP_ANY)
        ]
        
        for i, method in enumerate(open_methods):
            try:
                cap = method()
                if cap.isOpened():
                    print(f"🎯 방법 {i+1}둜 μ˜μƒ μ—΄κΈ° 성곡!")
                    break
                else:
                    if cap:
                        cap.release()
                    cap = None
            except Exception as e:
                print(f"πŸ” 방법 {i+1} μ‹€νŒ¨: {e}")
                if cap:
                    cap.release()
                cap = None
        
        if not cap or not cap.isOpened():
            # λ§ˆμ§€λ§‰ μ‹œλ„: 파일 경둜 문제일 수 μžˆμœΌλ‹ˆ μ ˆλŒ€ 경둜둜 λ³€ν™˜
            abs_path = os.path.abspath(video_path)
            print(f"πŸ” μ ˆλŒ€ 경둜둜 μž¬μ‹œλ„: {abs_path}")
            cap = cv2.VideoCapture(abs_path)
            
            if not cap.isOpened():
                error_message = f"였λ₯˜: λ™μ˜μƒ νŒŒμΌμ„ μ—΄ 수 μ—†μŠ΅λ‹ˆλ‹€: {video_path}"
                print(f"DEBUG: _extract_frames - λͺ¨λ“  λ°©λ²•μœΌλ‘œ μ—΄κΈ° μ‹€νŒ¨")
                
                # 파일 μƒνƒœ 상세 확인
                if not os.path.exists(video_path):
                    error_message += " (파일이 μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.)"
                elif os.path.getsize(video_path) == 0:
                    error_message += " (파일 크기가 0μž…λ‹ˆλ‹€.)"
                else:
                    error_message += " (TikTok μ˜μƒμ€ νŠΉλ³„ν•œ 인코딩을 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.)"
                    
                    # 파일 ν™•μž₯자 확인
                    ext = os.path.splitext(video_path)[1].lower()
                    print(f"DEBUG: File extension: {ext}")
                
                if progress_callback:
                    progress_callback(0, 1, 0.0, error_message)
                raise RuntimeError(error_message)

        # μ˜μƒ 정보 확인 (TikTok μ•ˆμ „ λͺ¨λ“œ)
        try:
            fps = cap.get(cv2.CAP_PROP_FPS) or 25.0  # TikTok κΈ°λ³Έ FPS
            total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        except Exception as e:
            print(f"πŸ” μ˜μƒ 정보 읽기 였λ₯˜: {e}")
            fps = 25.0  # κΈ°λ³Έκ°’
            total_frames = 0
            width = height = 0
        
        print(f"πŸ” μ˜μƒ 정보:")
        print(f"  - FPS: {fps}")
        print(f"  - 총 ν”„λ ˆμž„: {total_frames}")
        print(f"  - 해상도: {width}x{height}")
        
        # TikTok은 λ•Œλ‘œ ν”„λ ˆμž„ 수λ₯Ό μ •ν™•νžˆ λͺ» 읽을 수 있음
        if total_frames <= 0:
            print("πŸ” ν”„λ ˆμž„ 수λ₯Ό 읽을 수 μ—†μŒ. 순차 읽기 λͺ¨λ“œλ‘œ μ „ν™˜")
            return self._extract_frames_sequential(cap, interval, output_folder, progress_callback)
        
        duration = total_frames / fps if fps > 0 else 0
        print(f"  - μ˜μƒ 길이: {duration:.2f}초")
        
        step = max(1, int(interval * fps))
        descriptions = []
        start = time.time()
        
        frame_count = 0
        total_expected_frames = max(1, total_frames // step)
        
        print(f"πŸ” ν”„λ ˆμž„ μΆ”μΆœ κ³„νš:")
        print(f"  - μΆ”μΆœ 간격: {step} ν”„λ ˆμž„λ§ˆλ‹€ ({interval}초)")
        print(f"  - μ˜ˆμƒ μΆ”μΆœ ν”„λ ˆμž„ 수: {total_expected_frames}")
        
        for i in range(0, total_frames, step):
            if self.stop_flag:
                cap.release()
                raise RuntimeError("μž‘μ—…μ΄ μ€‘λ‹¨λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
            
            # TikTok μ•ˆμ „ λͺ¨λ“œ: ν”„λ ˆμž„ μœ„μΉ˜ μ„€μ •
            try:
                cap.set(cv2.CAP_PROP_POS_FRAMES, i)
                ret, frame = cap.read()
            except Exception as e:
                print(f"πŸ” ν”„λ ˆμž„ {i} μœ„μΉ˜ μ„€μ •/읽기 였λ₯˜: {e}")
                continue
            
            if not ret or frame is None:
                print(f"πŸ” ν”„λ ˆμž„ {i} 읽기 μ‹€νŒ¨")
                continue
            
            # ν”„λ ˆμž„ μœ νš¨μ„± 검사
            if frame.size == 0:
                print(f"πŸ” ν”„λ ˆμž„ {i} λΉ„μ–΄μžˆμŒ")
                continue
                
            frame_count += 1
            
            # 이미지 파일둜 μ €μž₯ (TikTok μ•ˆμ „ λͺ¨λ“œ)
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
            frame_filename = os.path.join(output_folder, f"frame_{i:05d}_{timestamp}.jpg")
            
            try:
                # JPEG ν’ˆμ§ˆμ„ λ†’μ—¬μ„œ μ €μž₯
                save_success = cv2.imwrite(frame_filename, frame, [cv2.IMWRITE_JPEG_QUALITY, 95])
                if save_success and os.path.exists(frame_filename):
                    print(f"πŸ” ν”„λ ˆμž„ μ €μž₯ 성곡: {frame_filename}")
                else:
                    print(f"🚨 ν”„λ ˆμž„ μ €μž₯ μ‹€νŒ¨: {frame_filename}")
                    continue
            except Exception as e:
                print(f"🚨 ν”„λ ˆμž„ μ €μž₯ μ˜ˆμ™Έ: {e}")
                continue
            
            # ν”„λ ˆμž„μ„ μ¦‰μ‹œ λΆ„μ„ν•˜μ—¬ μ„€λͺ… 생성
            try:
                description = self._describe_frame(frame)
                descriptions.append(description)
            except Exception as e:
                print(f"🚨 ν”„λ ˆμž„ 뢄석 μ‹€νŒ¨: {e}")
                descriptions.append(f"ν”„λ ˆμž„ {frame_count} 뢄석 μ‹€νŒ¨: {e}")
            
            # frame λ³€μˆ˜λ₯Ό λͺ…μ‹œμ μœΌλ‘œ μ‚­μ œ (λ©”λͺ¨λ¦¬ ν•΄μ œ)
            del frame
            
            if progress_callback:
                progress_callback(frame_count, total_expected_frames, time.time()-start, 
                                f"ν”„λ ˆμž„ 뢄석 쀑 {frame_count}/{total_expected_frames}")
        
        cap.release()
        print(f"πŸ” _extract_frames μ™„λ£Œ - 처리된 ν”„λ ˆμž„ 개수: {len(descriptions)}")
        
        # μ‹€μ œ μ €μž₯된 파일 확인
        saved_frames = [f for f in os.listdir(output_folder) if f.startswith('frame_') and f.endswith('.jpg')]
        print(f"πŸ” μ €μž₯된 이미지 파일 개수: {len(saved_frames)}")
        
        if len(descriptions) == 0:
            print("🚨 WARNING: λΆ„μ„λœ ν”„λ ˆμž„μ΄ μ—†μŠ΅λ‹ˆλ‹€!")
            # 빈 뢄석이라도 κΈ°λ³Έ λ©”μ‹œμ§€ λ°˜ν™˜
            descriptions = ["TikTok μ˜μƒ 뢄석 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μ˜μƒ ν˜•μ‹μ΄λ‚˜ 인코딩 문제일 수 μžˆμŠ΅λ‹ˆλ‹€."]
        
        return descriptions

    def _extract_frames_sequential(self, cap, interval, output_folder, progress_callback):
        """TikTok용 순차 읽기 λͺ¨λ“œ"""
        print("πŸ” TikTok 순차 읽기 λͺ¨λ“œ μ‹œμž‘")
        
        descriptions = []
        frame_count = 0
        frames_read = 0
        start = time.time()
        fps_estimate = 25.0  # TikTok μΆ”μ • FPS
        
        while True:
            if self.stop_flag:
                break
                
            ret, frame = cap.read()
            if not ret or frame is None:
                break
                
            frames_read += 1
            
            # interval μ΄ˆλ§ˆλ‹€ ν”„λ ˆμž„ μ €μž₯
            if frames_read % int(interval * fps_estimate) == 0:
                frame_count += 1
                
                # 이미지 파일둜 μ €μž₯
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
                frame_filename = os.path.join(output_folder, f"frame_{frames_read:05d}_{timestamp}.jpg")
                
                try:
                    save_success = cv2.imwrite(frame_filename, frame, [cv2.IMWRITE_JPEG_QUALITY, 95])
                    if save_success:
                        print(f"πŸ” 순차 ν”„λ ˆμž„ μ €μž₯: {frame_filename}")
                        description = self._describe_frame(frame)
                        descriptions.append(description)
                    else:
                        print(f"🚨 순차 ν”„λ ˆμž„ μ €μž₯ μ‹€νŒ¨: {frame_filename}")
                except Exception as e:
                    print(f"🚨 순차 ν”„λ ˆμž„ 처리 였λ₯˜: {e}")
                
                if progress_callback:
                    progress_callback(frame_count, 10, time.time()-start, 
                                    f"TikTok 순차 뢄석 쀑 {frame_count}")
            
            # λ„ˆλ¬΄ λ§Žμ€ ν”„λ ˆμž„μ„ 읽지 μ•Šλ„λ‘ μ œν•œ (μ΅œλŒ€ 30초 λΆ„λŸ‰)
            if frames_read > fps_estimate * 30:
                print("πŸ” 30초 μ œν•œ 도달, 순차 읽기 μ’…λ£Œ")
                break
        
        cap.release()
        print(f"πŸ” TikTok 순차 읽기 μ™„λ£Œ - 총 읽은 ν”„λ ˆμž„: {frames_read}, λΆ„μ„λœ ν”„λ ˆμž„: {len(descriptions)}")
        
        if len(descriptions) == 0:
            descriptions = ["TikTok μ˜μƒμ„ 읽을 수 μžˆμ§€λ§Œ ν”„λ ˆμž„ μΆ”μΆœμ— μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€."]
        
        return descriptions


    def analyze_images_from_folder(

        self,

        folder_path: str,

        analysis_mode: str,

        progress_callback: Callable[[int, int, float, str], None] = None

    ) -> str:
        if self.stop_flag:
            raise RuntimeError("μž‘μ—…μ΄ μ€‘λ‹¨λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
        files = sorted([
            os.path.join(folder_path, f)
            for f in os.listdir(folder_path)
            if f.lower().endswith((".png", ".jpg", ".jpeg"))
        ])
        descriptions: List[str] = []
        start = time.time()
        total = len(files)
        for idx, img_path in enumerate(files):
            if self.stop_flag:
                raise RuntimeError("μž‘μ—…μ΄ μ€‘λ‹¨λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
            img = cv2.imread(img_path)
            desc = self._describe_frame(img)
            descriptions.append(desc)
            if progress_callback:
                progress_callback(idx+1, total, time.time()-start, f"이미지 뢄석 {idx+1}/{total}")
        print(f"DEBUG: analyze_images_from_folder - μˆ˜μ§‘λœ μ„€λͺ… 개수: {len(descriptions)}")
        print(f"DEBUG: analyze_images_from_folder - 첫 번째 μ„€λͺ…: {descriptions[0][:100]}..." if descriptions else "μ„€λͺ… μ—†μŒ")

        report_content = self._run_general_summary(descriptions, progress_callback)
        return self._save_report(report_content, folder_path)

    def _download_video(

        self,

        video_input: str,

        is_youtube_url: bool,

        progress_callback: Callable[[int, int, float, str], None] = None

    ) -> tuple[str, str]:
        if self.stop_flag:
            raise RuntimeError("μž‘μ—…μ΄ μ€‘λ‹¨λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
        
        # 둜컬 파일인 경우 yt-dlp κ±΄λ„ˆλ›°κΈ°
        if not is_youtube_url:
            if os.path.exists(video_input):
                # 둜컬 νŒŒμΌμ€ κ·ΈλŒ€λ‘œ λ°˜ν™˜ (파일λͺ…μ—μ„œ 제λͺ© μΆ”μΆœ)
                video_title = os.path.splitext(os.path.basename(video_input))[0]
                print(f"πŸ” 둜컬 파일 μ‚¬μš©: {video_input}")
                print(f"πŸ” μΆ”μΆœλœ 제λͺ©: {video_title}")
                if progress_callback:
                    progress_callback(100, 100, 0.0, "둜컬 파일 λ‘œλ“œ μ™„λ£Œ")
                return video_input, video_title
            else:
                raise RuntimeError(f"둜컬 파일이 μ‘΄μž¬ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€: {video_input}")
        
        # URL인 κ²½μš°μ—λ§Œ yt-dlp μ‚¬μš©
        temp_download_dir = "temp_downloads"
        os.makedirs(temp_download_dir, exist_ok=True)
        
        temp_filename = f"temp_video_{int(time.time())}.%(ext)s"
        output_filepath = os.path.join(temp_download_dir, temp_filename)
        
        ydl_opts = {
            'outtmpl': output_filepath,
            'format': 'bestvideo+bestaudio/best',
            'noprogress': True,
            'overwrites': True,
            'progress_hooks': [lambda d: self._download_progress_hook(d, progress_callback)],
            'no_playlist': True,
            'retries': 5,
            'merge_output_format': 'mp4',
            'quiet': False,
            'no_warnings': True,
            # μΈμŠ€νƒ€κ·Έλž¨ 지원 μ˜΅μ…˜ μΆ”κ°€
            'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'referer': 'https://www.instagram.com/',
            'http_headers': {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language': 'en-us,en;q=0.5',
                'Sec-Fetch-Mode': 'navigate',
            },
            'extract_flat': False,
            'no_check_certificate': True,
        }
        
        try:
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(video_input, download=True)
                
                filename = None
                
                # κΈ°λ³Έ 파일 경둜 μ°ΎκΈ° μ‹œλ„
                if 'requested_downloads' in info and info['requested_downloads']:
                    filename = info['requested_downloads'][0]['filepath']
                elif '_filename' in info:
                    filename = info['_filename']
                elif 'filepath' in info:
                    filename = info['filepath']
                
                print(f"πŸ” λ‹€μš΄λ‘œλ“œ μ™„λ£Œ ν›„ 파일 κ²½λ‘œλ“€:")
                print(f"  - requested_downloads: {info.get('requested_downloads')}")
                print(f"  - _filename: {info.get('_filename')}")
                print(f"  - μ΅œμ’… μ„ νƒλœ 파일: {filename}")
                
                # κΈ°λ³Έ κ²½λ‘œμ—μ„œ νŒŒμΌμ„ μ°Ύμ§€ λͺ»ν•œ 경우, temp ν΄λ”μ—μ„œ μ΅œμ‹  파일 μ°ΎκΈ°
                if not filename or not os.path.exists(filename) or os.path.getsize(filename) == 0:
                    print("πŸ” κΈ°λ³Έ κ²½λ‘œμ—μ„œ νŒŒμΌμ„ μ°Ύμ§€ λͺ»ν•¨. temp 폴더 검색 쀑...")
                    
                    # temp_downloads ν΄λ”μ—μ„œ κ°€μž₯ 졜근 파일 μ°ΎκΈ°
                    temp_files = []
                    for file in os.listdir(temp_download_dir):
                        if file.startswith("temp_video_") and file.endswith((".mp4", ".webm", ".mkv", ".m4v")):
                            file_path = os.path.join(temp_download_dir, file)
                            temp_files.append((file_path, os.path.getmtime(file_path)))
                    
                    if temp_files:
                        # κ°€μž₯ 졜근 파일 μ‚¬μš©
                        filename = max(temp_files, key=lambda x: x[1])[0]
                        print(f"πŸ” λŒ€μ²΄ 파일 발견: {filename}")
                    else:
                        raise RuntimeError("λ‹€μš΄λ‘œλ“œλœ νŒŒμΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
                
                # 파일 쑴재 확인을 μœ„ν•œ μž¬μ‹œλ„ 둜직
                max_retries = 10
                for i in range(max_retries):
                    if os.path.exists(filename) and os.path.getsize(filename) > 0:
                        print(f"πŸ” 파일 확인 μ™„λ£Œ: {filename} ({os.path.getsize(filename)} bytes)")
                        break
                    print(f"πŸ” 파일 λŒ€κΈ° 쀑... ({i+1}/{max_retries})")
                    time.sleep(1)
                else:
                    raise RuntimeError(f"λ‹€μš΄λ‘œλ“œλœ λ™μ˜μƒ 파일이 μ‘΄μž¬ν•˜μ§€ μ•Šκ±°λ‚˜ λΉ„μ–΄ μžˆμŠ΅λ‹ˆλ‹€: {filename} (μ΅œλŒ€ μž¬μ‹œλ„ 횟수 초과)")
                
                video_title = info.get('title', 'Unknown_Video')
                print(f"πŸ” μ΅œμ’… λΉ„λ””μ˜€ 제λͺ©: {video_title}")
                return filename, video_title
                
        except yt_dlp.utils.DownloadError as e:
            if progress_callback:
                progress_callback(0, 1, 0.0, f"λ‹€μš΄λ‘œλ“œ 였λ₯˜: {e}")
            raise RuntimeError(f"λ™μ˜μƒ λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨: {e}")
        except Exception as e:
            if progress_callback:
                progress_callback(0, 1, 0.0, f"λ‹€μš΄λ‘œλ“œ 쀑 μ˜ˆμ™Έ λ°œμƒ: {e}")
            raise RuntimeError(f"λ™μ˜μƒ λ‹€μš΄λ‘œλ“œ 쀑 μ•Œ 수 μ—†λŠ” 였λ₯˜ λ°œμƒ: {e}")

    def _describe_frame(self, frame) -> str:
        """단일 ν”„λ ˆμž„μ— λŒ€ν•œ μ„€λͺ…을 Gemini Vision λͺ¨λΈλ‘œ 생성"""
        _, enc_image = cv2.imencode(".jpg", frame)
        image_data = enc_image.tobytes()

        model = genai.GenerativeModel('gemini-2.5-flash-preview-05-20')
        
        try:
            if self.stop_flag:
                raise RuntimeError("μž‘μ—…μ΄ μ€‘λ‹¨λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
            response = model.generate_content([
                GeminiPrompts.image_analysis_general(),
                {"mime_type": "image/jpeg", "data": image_data}
            ])
            if not response.candidates:
                finish_reason = response.prompt_feedback.block_reason if response.prompt_feedback else "UNKNOWN"
                error_message = f"ν”„λ ˆμž„ μ„€λͺ… 생성 μ‹€νŒ¨: μœ νš¨ν•œ 후보 μ—†μŒ. Finish Reason: {finish_reason}"
                print(f"ERROR: _describe_frame - {error_message}")
                return f"였λ₯˜: {error_message}"
            
            print(f"DEBUG: _describe_frame - μ„€λͺ… 생성 성곡: {response.text[:100]}...")
            return response.text
        except Exception as e:
            error_message = f"ν”„λ ˆμž„ μ„€λͺ… 생성 쀑 예기치 μ•Šμ€ 였λ₯˜ λ°œμƒ: {e}"
            print(f"ERROR: _describe_frame - {error_message}")
            return f"였λ₯˜: {error_message}"

    def _run_general_summary(

        self,

        descriptions: List[str],

        progress_callback: Callable[[int, int, float, str], None] = None

    ) -> str:
        if self.stop_flag:
            raise RuntimeError("μž‘μ—…μ΄ μ€‘λ‹¨λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
        
        print(f"DEBUG: _run_general_summary - 받은 descriptions 개수: {len(descriptions)}")
        
        # ν”„λ ˆμž„λ³„ 상세 뢄석을 ν•©μΉ¨
        combined_text = ""
        for i, desc in enumerate(descriptions):
            combined_text += f"**ν”„λ ˆμž„ {i+1}:**\n{desc}\n\n"

        prompt = GeminiPrompts.video_content_summary().format(
            combined_text=combined_text
        )

        if progress_callback:
            progress_callback(1, 1, 0.0, "μ’…ν•© 뢄석 쀑...")

        model = genai.GenerativeModel('gemini-2.5-flash-preview-05-20')
        
        try:
            response = model.generate_content(prompt)
            
            if not response.candidates:
                finish_reason = response.prompt_feedback.block_reason if response.prompt_feedback else "UNKNOWN"
                error_message = f"Gemini μ’…ν•© 뢄석 응닡 생성 μ‹€νŒ¨: μœ νš¨ν•œ 후보 μ—†μŒ. Finish Reason: {finish_reason}"
                print(f"ERROR: _run_general_summary - {error_message}")
                debug_output_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gemini_analysis_error_debug.txt")
                with open(debug_output_path, "w", encoding="utf-8") as f:
                    f.write(f"였λ₯˜ λ°œμƒ: {error_message}\n")
                    f.write(f"ν”„λ‘¬ν”„νŠΈ λ‚΄μš©:\n{prompt}\n")
                raise RuntimeError(error_message)

            summary_text = response.text


            # μ΅œμ’… λ³΄κ³ μ„œ ꡬ성: μ’…ν•© 뢄석 + ν”„λ ˆμž„λ³„ 상세 μ„€λͺ…
            final_report = f"{summary_text}\n\n"
            final_report += "=" * 80 + "\n"
            final_report += "## πŸ“‹ ν”„λ ˆμž„λ³„ 상세 뢄석\n\n"
            
            # πŸ” 디버깅 정보 μΆ”κ°€
            print(f"πŸ” CRITICAL DEBUG: descriptions νƒ€μž…: {type(descriptions)}")
            print(f"πŸ” CRITICAL DEBUG: descriptions 길이: {len(descriptions)}")
            print(f"πŸ” CRITICAL DEBUG: descriptions λ‚΄μš©: {descriptions}")
            
            if not descriptions:
                final_report += "⚠️ ERROR: ν”„λ ˆμž„λ³„ μ„€λͺ… 데이터가 μ—†μŠ΅λ‹ˆλ‹€!\n"
                print("🚨 ERROR: descriptionsκ°€ λΉ„μ–΄μžˆμŠ΅λ‹ˆλ‹€!")
            else:
                print(f"πŸ” ν”„λ ˆμž„λ³„ μ„€λͺ… μΆ”κ°€ μ‹œμž‘ - descriptions 개수: {len(descriptions)}")
                
                for i, desc in enumerate(descriptions):
                    print(f"πŸ” ν”„λ ˆμž„ {i+1} 처리 쀑: {str(desc)[:50]}...")
                    final_report += f"### 🎬 ν”„λ ˆμž„ {i+1}\n"
                    final_report += f"{desc}\n\n"
                    final_report += "-" * 50 + "\n\n"
            
            print(f"πŸ” μ΅œμ’… λ³΄κ³ μ„œ 길이: {len(final_report)} 문자")
            print(f"πŸ” 'ν”„λ ˆμž„ 1' 포함 μ—¬λΆ€: {'ν”„λ ˆμž„ 1' in final_report}")


        except Exception as e:
            error_message = f"Gemini μ’…ν•© 뢄석 호좜 쀑 예기치 μ•Šμ€ 였λ₯˜ λ°œμƒ: {e}"
            print(f"ERROR: _run_general_summary - {error_message}")
            debug_output_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gemini_analysis_error_debug.txt")
            with open(debug_output_path, "w", encoding="utf-8") as f:
                f.write(f"였λ₯˜ λ°œμƒ: {error_message}\n")
                f.write(f"ν”„λ‘¬ν”„νŠΈ λ‚΄μš©:\n{prompt}\n")
            raise

        return final_report
        

    def _download_progress_hook(self, d, progress_callback):
        if self.stop_flag:
            raise RuntimeError("μž‘μ—…μ΄ μ€‘λ‹¨λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
        if progress_callback:
            if d['status'] == 'downloading':
                downloaded = d.get('downloaded_bytes', 0)
                total = d.get('total_bytes') or d.get('total_bytes_estimate')
                if total:
                    percent = downloaded / total * 100
                    progress_callback(int(percent), 100, 0.0, f"λ™μ˜μƒ λ‹€μš΄λ‘œλ“œ 쀑: {percent:.1f}%")
                else:
                    progress_callback(0, 100, 0.0, "λ™μ˜μƒ λ‹€μš΄λ‘œλ“œ 쀑...")
            elif d['status'] == 'finished':
                progress_callback(100, 100, 0.0, "λ™μ˜μƒ λ‹€μš΄λ‘œλ“œ μ™„λ£Œ")
            elif d['status'] == 'error':
                progress_callback(0, 100, 0.0, f"λ‹€μš΄λ‘œλ“œ 였λ₯˜: {d.get('error', 'μ•Œ 수 μ—†λŠ” 였λ₯˜')}")
 
    def _format_report_markdown(self, report_text: str) -> str:
        lines = report_text.split('\n')
        formatted_lines = []
        
        main_section_counter = 0
        sub_section_counter = {}

        for line in lines:
            stripped_line = line.strip()

            if stripped_line.startswith('**') and stripped_line.endswith('**'):
                formatted_lines.append(f"## {stripped_line.strip('*').strip(':')}\n")
                main_section_counter = 0
                sub_section_counter = {}
            elif stripped_line.startswith('1.') or stripped_line.startswith('2.'):
                main_section_counter += 1
                formatted_lines.append(f"{main_section_counter}. {stripped_line[stripped_line.find(' ')+1:]}\n")
                sub_section_counter[main_section_counter] = 0
            elif stripped_line.startswith('*   '):
                if main_section_counter > 0:
                    sub_section_counter[main_section_counter] += 1
                    formatted_lines.append(f"    {main_section_counter}.{sub_section_counter[main_section_counter]} {stripped_line[4:]}\n")
                else:
                    formatted_lines.append(f"- {stripped_line[4:]}\n")
            elif stripped_line:
                cleaned_line = stripped_line.replace('*', '').strip()
                if cleaned_line:
                    formatted_lines.append(f"{cleaned_line}\n")
            else:
                formatted_lines.append("\n")
        
        return "".join(formatted_lines)

    
    def _save_report(self, report: str, folder: str) -> str:
        # πŸ” λ¦¬ν¬νŠΈκ°€ None인지 확인
        if report is None:
            print("🚨 ERROR: reportκ°€ Noneμž…λ‹ˆλ‹€!")
            report = "였λ₯˜: 뢄석 κ²°κ³Όλ₯Ό 생성할 수 μ—†μŠ΅λ‹ˆλ‹€."
        
        if not isinstance(report, str):
            print(f"🚨 ERROR: report νƒ€μž…μ΄ 잘λͺ»λ¨: {type(report)}")
            report = str(report) if report else "였λ₯˜: 뢄석 κ²°κ³Όλ₯Ό λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•  수 μ—†μŠ΅λ‹ˆλ‹€."
        
        print(f"πŸ” _save_report - report 길이: {len(report)}")
        print(f"πŸ” _save_report - report 첫 100자: {report[:100]}...")
        
        os.makedirs(folder, exist_ok=True)

        date_str = datetime.now().strftime("%Y%m%d")
        folder_name = os.path.basename(folder.rstrip(os.sep))
        filename = f"{folder_name}_{date_str}.txt"
        path = os.path.join(folder, filename)
        
        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(report)
            print(f"πŸ” _save_report - 파일 μ €μž₯ μ™„λ£Œ: {path}")
        except Exception as e:
            print(f"🚨 ERROR: 파일 μ €μž₯ 쀑 였λ₯˜: {e}")
            raise
        
        return path