video_analyzer_simple / video_processor.py
SG34's picture
Upload 4 files
a3e25fc verified
Raw History Blame Contribute Delete
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