Spaces:
Runtime error
Runtime error
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 |