Spaces:
Runtime error
Runtime error
Download video_processor.py from SG34/video_analyzer_simple: direct link, hf CLI and curl.
- Browser
- Download file 36.5 kB
-
https://huggingface.co/spaces/SG34/video_analyzer_simple/resolve/main/video_processor.py
- Command line
-
hf download hf://spaces/SG34/video_analyzer_simple/video_processor.py
-
curl -L -o video_processor.py https://huggingface.co/spaces/SG34/video_analyzer_simple/resolve/main/video_processor.py
36.5 kB
| 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 |