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