"""comment-dashboard → reels-bench-v2/comment_lib/ vendor 동기화. 사용: python tools/sync_comment_lib.py # 실제 sync 실행 python tools/sync_comment_lib.py --verify # 기존 vendor의 import 무결성만 검증 python tools/sync_comment_lib.py --src "C:/Users/USER/...comment-dashboard" # 경로 명시 동작: 1. comment-dashboard/{schema.py, parsers/*, analyzers/*, export/*, prompts/*} 복사 2. 각 .py에서 다음 패턴 자동 rewrite: - "from schema import ..." → "from comment_lib.schema import ..." - "from parsers.X import ..." → "from comment_lib.parsers.X import ..." - "from analyzers.X import ..." → "from comment_lib.analyzers.X import ..." - "from analyzers import X" → "from comment_lib.analyzers import X" - "from export.X import ..." → "from comment_lib.export.X import ..." - "from prompts.X import ..." → "from comment_lib.prompts.X import ..." - sys.path.insert(..., os.path.dirname(...)) 줄 → 삭제 (vendor 후 불필요) 3. .SYNC_MANIFEST.json 기록 (source path + ISO timestamp + 파일별 sha256) 4. --verify: 결과를 import해보고 잔재 bare import grep """ from __future__ import annotations import argparse import hashlib import json import re import shutil import subprocess import sys from datetime import datetime from pathlib import Path ROOT = Path(__file__).resolve().parent.parent # reels-bench-v2/ DST = ROOT / "comment_lib" def _default_src() -> Path: return ROOT.parent / "comment-dashboard" # rewrite 규칙 (순서 중요 — 긴 패턴 먼저 매칭) # (^[ \t]*) 그룹으로 들여쓰기 보존 — 함수 내부 inline import도 잡음 REWRITE_RULES = [ (re.compile(r"(?m)^([ \t]*)from\s+schema\s+import\s+"), r"\1from comment_lib.schema import "), (re.compile(r"(?m)^([ \t]*)from\s+parsers\.([\w_]+)\s+import\s+"), r"\1from comment_lib.parsers.\2 import "), (re.compile(r"(?m)^([ \t]*)from\s+parsers\s+import\s+"), r"\1from comment_lib.parsers import "), (re.compile(r"(?m)^([ \t]*)from\s+analyzers\.([\w_]+)\s+import\s+"), r"\1from comment_lib.analyzers.\2 import "), (re.compile(r"(?m)^([ \t]*)from\s+analyzers\s+import\s+"), r"\1from comment_lib.analyzers import "), (re.compile(r"(?m)^([ \t]*)from\s+export\.([\w_]+)\s+import\s+"), r"\1from comment_lib.export.\2 import "), (re.compile(r"(?m)^([ \t]*)from\s+export\s+import\s+"), r"\1from comment_lib.export import "), ] # sys.path 조작 라인 제거 (다중 줄 처리) SYSPATH_INSERT_PATTERN = re.compile( r"^sys\.path\.insert\([^)]*os\.path\.dirname\([^)]*__file__[^)]*\)[^)]*\).*$", re.MULTILINE, ) # 복사할 파일/디렉토리 spec FILES_TO_COPY = [ "schema.py", "parsers/__init__.py", "parsers/detect.py", "parsers/tiktok.py", "parsers/instagram_manual.py", "analyzers/__init__.py", "analyzers/_llm_utils.py", "analyzers/keywords.py", "analyzers/opinions.py", "analyzers/longest.py", "analyzers/sentiment.py", "analyzers/categorize.py", "analyzers/summary.py", "analyzers/translate.py", "export/__init__.py", "export/excel.py", "prompts/cluster_v1.md", "prompts/sentiment_v1.md", ] def rewrite_imports(text: str) -> tuple[str, dict]: """import rewrite + sys.path 제거. (new_text, stats) 반환.""" stats = {"import_rewrites": 0, "syspath_removed": 0} new_text = text for pat, repl in REWRITE_RULES: new_text, n = pat.subn(repl, new_text) stats["import_rewrites"] += n new_text, n = SYSPATH_INSERT_PATTERN.subn("# (sys.path.insert removed by sync_comment_lib.py)", new_text) stats["syspath_removed"] = n return new_text, stats def sha256_file(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as f: for chunk in iter(lambda: f.read(1 << 16), b""): h.update(chunk) return h.hexdigest() def sha256_bytes(b: bytes) -> str: return hashlib.sha256(b).hexdigest() def get_source_commit(src: Path) -> str: """src가 git repo면 HEAD commit 반환, 아니면 'no-git'.""" try: r = subprocess.run( ["git", "-C", str(src), "rev-parse", "HEAD"], capture_output=True, text=True, timeout=5, check=False, ) if r.returncode == 0: return r.stdout.strip() except Exception: pass return "no-git" def sync(src: Path) -> dict: """실제 vendor 실행.""" if not src.exists(): raise FileNotFoundError(f"comment-dashboard 폴더 없음: {src}") # 기존 vendor 삭제 후 재생성 if DST.exists(): shutil.rmtree(DST) DST.mkdir(parents=True) # __init__.py for comment_lib root (DST / "__init__.py").write_text( '"""Vendored copy of comment-dashboard. DO NOT EDIT BY HAND.\n' 'Re-sync via: python tools/sync_comment_lib.py\n"""\n', encoding="utf-8", ) manifest = { "synced_at": datetime.utcnow().isoformat(timespec="seconds") + "Z", "source_path": str(src), "source_commit": get_source_commit(src), "files": {}, "import_rewrites_total": 0, "syspath_removed_total": 0, } for rel in FILES_TO_COPY: src_path = src / rel if not src_path.exists(): print(f" ⚠ skip (missing): {rel}") continue dst_path = DST / rel dst_path.parent.mkdir(parents=True, exist_ok=True) if rel.endswith(".py"): text = src_path.read_text(encoding="utf-8") new_text, stats = rewrite_imports(text) dst_path.write_text(new_text, encoding="utf-8") print(f" ✓ {rel} (rewrites={stats['import_rewrites']}, syspath_removed={stats['syspath_removed']})") manifest["files"][rel] = { "source_sha256": sha256_bytes(text.encode("utf-8")), "vendored_sha256": sha256_bytes(new_text.encode("utf-8")), "import_rewrites": stats["import_rewrites"], "syspath_removed": stats["syspath_removed"], } manifest["import_rewrites_total"] += stats["import_rewrites"] manifest["syspath_removed_total"] += stats["syspath_removed"] else: shutil.copy2(src_path, dst_path) print(f" ✓ {rel} (binary/text copy)") manifest["files"][rel] = { "source_sha256": sha256_file(src_path), "vendored_sha256": sha256_file(dst_path), } # manifest 저장 (DST / ".SYNC_MANIFEST.json").write_text( json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8", ) return manifest def verify() -> int: """vendor 무결성 검증. import 성공 + 잔재 bare import = 0. 실패 시 nonzero 반환.""" if not DST.exists(): print(f"❌ {DST} 없음. 먼저 sync 실행 필요.") return 1 errs = 0 # 1. import 검증 (각 주요 모듈 로드) sys.path.insert(0, str(ROOT)) test_imports = [ "comment_lib", "comment_lib.schema", "comment_lib.parsers.detect", "comment_lib.parsers.tiktok", "comment_lib.parsers.instagram_manual", "comment_lib.analyzers._llm_utils", "comment_lib.analyzers.keywords", "comment_lib.analyzers.opinions", "comment_lib.analyzers.longest", "comment_lib.analyzers.sentiment", "comment_lib.analyzers.categorize", "comment_lib.analyzers.summary", "comment_lib.analyzers.translate", "comment_lib.export.excel", ] print("=== Import 검증 ===") for mod in test_imports: try: __import__(mod) print(f" ✓ {mod}") except Exception as e: print(f" ✗ {mod}: {e}") errs += 1 # 2. 잔재 bare import grep print("\n=== Bare import 잔재 검사 (comment_lib/) ===") bad_patterns = [ re.compile(r"(?m)^[ \t]*from\s+schema\s+import"), re.compile(r"(?m)^[ \t]*from\s+parsers\.(?!comment_lib)"), re.compile(r"(?m)^[ \t]*from\s+analyzers\.(?!comment_lib)"), re.compile(r"(?m)^[ \t]*from\s+analyzers\s+import"), re.compile(r"(?m)^[ \t]*from\s+export\.(?!comment_lib)"), ] leftover = 0 for py in DST.rglob("*.py"): text = py.read_text(encoding="utf-8") for pat in bad_patterns: for m in pat.finditer(text): # comment_lib. 으로 시작하지 않는 것만 line_start = text.rfind("\n", 0, m.start()) + 1 line_end = text.find("\n", m.start()) line = text[line_start:line_end] if "comment_lib." not in line: print(f" ✗ {py.relative_to(ROOT)}: {line.strip()}") leftover += 1 if leftover == 0: print(" ✓ 잔재 import 0건") else: errs += leftover # 3. manifest 존재 확인 manifest_path = DST / ".SYNC_MANIFEST.json" if manifest_path.exists(): m = json.loads(manifest_path.read_text(encoding="utf-8")) print(f"\n=== Manifest ===") print(f" synced_at: {m.get('synced_at')}") print(f" source_commit: {m.get('source_commit')}") print(f" files vendored: {len(m.get('files', {}))}") print(f" import rewrites: {m.get('import_rewrites_total')}") print(f" syspath removed: {m.get('syspath_removed_total')}") else: print(f"\n❌ {manifest_path} 없음") errs += 1 return errs def main(): ap = argparse.ArgumentParser() ap.add_argument("--src", type=Path, default=None) ap.add_argument("--verify", action="store_true", help="기존 vendor만 검증") args = ap.parse_args() if args.verify: sys.exit(verify()) src = args.src or _default_src() print(f"Source: {src}") print(f"Target: {DST}") print() manifest = sync(src) print() print(f"✅ sync 완료. {len(manifest['files'])} 파일, " f"import rewrites {manifest['import_rewrites_total']}, " f"syspath 제거 {manifest['syspath_removed_total']}") print() print("이제 --verify 실행:") print(" python tools/sync_comment_lib.py --verify") if __name__ == "__main__": main()