"""4개 예시 영상 일괄 분석 — Streamlit 없이 빠르게 검증. 사용: python cli_test.py # `리쥬올 OKR/영상 예시 모음/` 4개 자동 분석 python cli_test.py path.mp4 # 특정 파일만 python cli_test.py path.mp4 --focus "..." # 집중 분석 질문 추가 (7번 카테고리) python cli_test.py --focus "PDRN 농도가 나오나?" # 4개 모두 동일 질문으로 """ from __future__ import annotations import os import sys import tempfile from pathlib import Path # 프로젝트 루트 경로 추가 ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT)) import schema import pipeline DEFAULT_VIDEO_DIR = ROOT.parent / "영상 예시 모음" def _load_secrets() -> str | None: """환경변수 → .streamlit/secrets.toml 순으로 API 키 로드.""" key = os.environ.get("ANTHROPIC_API_KEY") if key: return key secrets_path = ROOT / ".streamlit" / "secrets.toml" if secrets_path.exists(): # toml 파싱 (간단) for line in secrets_path.read_text(encoding="utf-8").splitlines(): line = line.strip() if line.startswith("ANTHROPIC_API_KEY"): _, _, v = line.partition("=") v = v.strip().strip('"').strip("'") if v and not v.startswith("sk-ant-여기에"): return v return None def _print_progress(label: str, pct: float) -> None: bar = "█" * int(pct * 30) + "░" * (30 - int(pct * 30)) print(f" [{bar}] {pct*100:5.1f}% — {label}") def analyze_file(client, mp4: Path, focus_question: str | None = None) -> None: print(f"\n{'═'*70}") print(f"▶ 분석: {mp4.name}") if focus_question: print(f" 집중 질문: {focus_question}") print(f"{'═'*70}") with tempfile.TemporaryDirectory(prefix="reelsbench_cli_") as tmp: try: a = pipeline.run_pipeline( client=client, input_source=mp4, workdir_root=Path(tmp), keep_mp4=False, progress=_print_progress, focus_question=focus_question, ) except Exception as e: print(f"❌ 실패: {e}") import traceback; traceback.print_exc() return print(f"\n✅ video_id={a.video_id}") print(f" 비용: ${a.cost_usd:.4f}") print(f" 검증 실패: {a.verification_failed_count}건") print(f"\n📊 카테고리 요약:") print(f" 1. 제품/브랜드: {len(a.products)}건") print(f" 2. 소구 효능: {len(a.efficacy_claims)}건") print(f" 3. 핵심 성분: {len(a.ingredients)}건") print(f" 4. 후킹 포인트: {len(a.hooks)}건") print(f" 5. 학술/메커니즘: {len(a.science)}건") print(f" 6. 타깃 & 톤: {len(a.audiences)}건") if a.focus_answer: fa = a.focus_answer print(f" 7. 집중 포인트: {'답변 있음' if fa.get('stated_in_video') else '영상에서 답을 못 찾음'}") # 자세한 출력 for cat_name, items in [ ("제품", a.products), ("효능", a.efficacy_claims), ("성분", a.ingredients), ("후킹", a.hooks), ("학술", a.science), ("타깃", a.audiences), ]: if not items: continue print(f"\n [{cat_name}]") for it in items: conf = it.get("confidence", 0) print(f" · conf={conf:.2f} eid={it.get('evidence_id')} → {it}") if a.focus_answer: fa = a.focus_answer print(f"\n [집중 포인트 7번]") print(f" Q: {a.focus_question}") print(f" A: {fa.get('answer')}") print(f" 근거 evidence_ids: {fa.get('evidence_ids')} (conf={fa.get('confidence'):.2f})") for q in (fa.get("key_quotes") or []): print(f" \"{q}\"") def main(): key = _load_secrets() if not key: print("❌ ANTHROPIC_API_KEY 설정 안 됨.") print(" .streamlit/secrets.toml 또는 환경변수에 설정 후 재실행.") sys.exit(1) from anthropic import Anthropic client = Anthropic(api_key=key) # --focus "..." 파싱 (간단한 인자 처리) focus_question: str | None = None raw_args = sys.argv[1:] cleaned_args: list[str] = [] i = 0 while i < len(raw_args): if raw_args[i] == "--focus" and i + 1 < len(raw_args): focus_question = raw_args[i + 1] i += 2 else: cleaned_args.append(raw_args[i]) i += 1 if cleaned_args: targets = [Path(a) for a in cleaned_args] else: if not DEFAULT_VIDEO_DIR.exists(): print(f"❌ 기본 영상 폴더 없음: {DEFAULT_VIDEO_DIR}") sys.exit(1) targets = sorted([p for p in DEFAULT_VIDEO_DIR.glob("*.mp4")]) if not targets: print(f"❌ {DEFAULT_VIDEO_DIR} 안에 .mp4 파일 없음.") sys.exit(1) print(f"🎬 reels-bench CLI 테스트 — {len(targets)}개 영상") print(f" 모델: {schema.HAIKU_MODEL} (Pass 1) + {schema.SONNET_MODEL} (Pass 2)") if focus_question: print(f" 집중 질문: {focus_question}") for mp4 in targets: analyze_file(client, mp4, focus_question=focus_question) print(f"\n{'═'*70}") print("✅ 전체 완료. Streamlit으로 결과 보기: `streamlit run app.py`") if __name__ == "__main__": main()