reels-bench / tools /sync_comment_lib.py
neosimHan's picture
Initial deploy: Google Workspace SSO + reels-bench v2.1.3
a3c17c2
Raw History Blame Contribute Delete
10.4 kB
"""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()