Download replace_brand_names.py from tencent/GroupAssistBench: direct link, hf CLI and curl.
- Browser
- Download file 7.82 kB
-
https://huggingface.co/datasets/tencent/GroupAssistBench/resolve/main/replace_brand_names.py
- Command line
-
hf download hf://datasets/tencent/GroupAssistBench/replace_brand_names.py
-
curl -L -o replace_brand_names.py https://huggingface.co/datasets/tencent/GroupAssistBench/resolve/main/replace_brand_names.py
7.82 kB
| #!/usr/bin/env python3 | |
| """Replace 元宝 / 元宝派 / yuanbao brand strings under a dataset directory. | |
| Rules (longer matches first, single pass): | |
| 元宝派, Yuanbao Pai -> bot群聊 | |
| 元宝 + ASCII letter -> "bot " + that letter (元宝AI -> bot AI) | |
| 元宝 -> bot | |
| Yuanbao + uppercase -> "bot " + that letter (YuanbaoYuanbao -> bot bot) | |
| yuanbao -> bot (Yuanbaos -> bots) | |
| The script walks every file in the target directory. It rewrites text files | |
| in place and refreshes sha256 entries in dataset_meta.json when present. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import sys | |
| # Longer / more specific alternatives must come first. | |
| BRAND_RE = re.compile( | |
| r"元宝派" | |
| r"|元宝\s*[Pp]ai" | |
| r"|(?i:yuanbao\s+pai)" | |
| r"|元宝" | |
| r"|(?i:yuanbao)" | |
| ) | |
| RULE_YUANBAO_PAI = "元宝派/Yuanbao Pai -> bot群聊" | |
| RULE_YUANBAO_SPACE = "元宝+英文字母 -> bot + 空格" | |
| RULE_YUANBAO = "元宝 -> bot" | |
| RULE_YUANBAO_EN_SPACE = "Yuanbao+大写字母 -> bot + 空格" | |
| RULE_YUANBAO_EN = "yuanbao -> bot" | |
| def _is_ascii_alpha(ch): | |
| return len(ch) == 1 and ch.isalpha() and ord(ch) < 128 | |
| def _is_ascii_upper(ch): | |
| return len(ch) == 1 and ch.isupper() and ord(ch) < 128 | |
| def classify(matched, nxt): | |
| if matched == "元宝派" or re.fullmatch(r"(?i)yuanbao\s+pai|元宝\s*[Pp]ai", matched): | |
| return RULE_YUANBAO_PAI | |
| if matched == "元宝": | |
| if _is_ascii_alpha(nxt): | |
| return RULE_YUANBAO_SPACE | |
| return RULE_YUANBAO | |
| if re.fullmatch(r"(?i)yuanbao", matched): | |
| if _is_ascii_upper(nxt): | |
| return RULE_YUANBAO_EN_SPACE | |
| return RULE_YUANBAO_EN | |
| raise ValueError("unhandled match: %r" % (matched,)) | |
| def replace_text(text): | |
| counts = {} | |
| def repl(match): | |
| nxt = text[match.end() : match.end() + 1] | |
| rule = classify(match.group(0), nxt) | |
| counts[rule] = counts.get(rule, 0) + 1 | |
| if rule == RULE_YUANBAO_PAI: | |
| return "bot群聊" | |
| if rule in (RULE_YUANBAO_SPACE, RULE_YUANBAO_EN_SPACE): | |
| return "bot " | |
| return "bot" | |
| return BRAND_RE.sub(repl, text), counts | |
| def self_test(): | |
| cases = { | |
| "元宝派": "bot群聊", | |
| "是元宝派派主": "是bot群聊派主", | |
| "正常对话(非元宝派)": "正常对话(非bot群聊)", | |
| "元宝AI助手体验群": "bot AI助手体验群", | |
| "@元宝Leo": "@bot Leo", | |
| "@元宝 你": "@bot 你", | |
| "@元宝2点": "@bot2点", | |
| "@元宝 派主": "@bot 派主", | |
| "yuanbao": "bot", | |
| "Yuanbao": "bot", | |
| "@Yuanbao": "@bot", | |
| "Yuanbaos": "bots", | |
| "@YuanbaoYuanbao": "@bot bot", | |
| "Yuanbao Pai": "bot群聊", | |
| "Yuanbao Pai's": "bot群聊's", | |
| "the Yuanbao group": "the bot group", | |
| "元宝BOT": "bot BOT", | |
| "元宝App": "bot App", | |
| "元宝": "bot", | |
| "我是元宝!": "我是bot!", | |
| } | |
| failed = False | |
| for src, expected in cases.items(): | |
| got, _ = replace_text(src) | |
| if got != expected: | |
| print(f"SELF-TEST FAIL: {src!r} -> {got!r}, expected {expected!r}", file=sys.stderr) | |
| failed = True | |
| if failed: | |
| raise SystemExit(1) | |
| def iter_files(root: str): | |
| for dirpath, dirnames, filenames in os.walk(root): | |
| dirnames[:] = [d for d in dirnames if d not in {".git", "__pycache__"}] | |
| for name in filenames: | |
| yield os.path.join(dirpath, name) | |
| def sha256_file(path): | |
| digest = hashlib.sha256() | |
| with open(path, "rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def refresh_meta_hashes(root, dry_run): | |
| meta_path = os.path.join(root, "dataset_meta.json") | |
| if not os.path.isfile(meta_path): | |
| return [] | |
| raw = open(meta_path, "rb").read() | |
| text = raw.decode("utf-8") | |
| sha_map = json.loads(text).get("sha256") or {} | |
| updated = text | |
| changes = [] | |
| for filename, old in sha_map.items(): | |
| if not isinstance(old, str): | |
| continue | |
| target = os.path.join(root, filename) | |
| if not os.path.isfile(target): | |
| continue | |
| new = sha256_file(target) | |
| if new == old: | |
| continue | |
| if updated.count(old) != 1: | |
| raise SystemExit(f"sha256 {old} for {filename} is not unique in dataset_meta.json") | |
| updated = updated.replace(old, new, 1) | |
| changes.append((filename, old, new)) | |
| if changes and not dry_run: | |
| tmp = meta_path + ".tmp_replace" | |
| with open(tmp, "wb") as handle: | |
| handle.write(updated.encode("utf-8")) | |
| os.replace(tmp, meta_path) | |
| return changes | |
| def process(root, dry_run): | |
| self_test() | |
| root = os.path.abspath(root) | |
| if not os.path.isdir(root): | |
| raise SystemExit(f"not a directory: {root}") | |
| totals = {} | |
| changed_files = 0 | |
| skipped = [] | |
| for path in sorted(iter_files(root)): | |
| raw = open(path, "rb").read() | |
| if b"\0" in raw[:8192]: | |
| skipped.append((path, "binary")) | |
| continue | |
| try: | |
| text = raw.decode("utf-8") | |
| except UnicodeError as exc: | |
| skipped.append((path, f"not utf-8: {exc}")) | |
| continue | |
| new_text, counts = replace_text(text) | |
| if not counts: | |
| continue | |
| changed_files += 1 | |
| for rule, count in counts.items(): | |
| totals[rule] = totals.get(rule, 0) + count | |
| rel = os.path.relpath(path, root) | |
| detail = ", ".join(f"{rule} x{count}" for rule, count in counts.items()) | |
| print(f"{rel}: {detail}") | |
| if not dry_run and new_text != text: | |
| tmp = path + ".tmp_replace" | |
| with open(tmp, "wb") as handle: | |
| handle.write(new_text.encode("utf-8")) | |
| os.replace(tmp, path) | |
| print("\n== totals ==") | |
| if not totals: | |
| print("no brand strings found") | |
| for rule, count in totals.items(): | |
| print(f"{count:6} {rule}") | |
| print(f"files changed: {changed_files}") | |
| if skipped: | |
| print("skipped:") | |
| for path, reason in skipped: | |
| print(f" {os.path.relpath(path, root)}: {reason}") | |
| hash_changes = refresh_meta_hashes(root, dry_run=dry_run) | |
| if hash_changes: | |
| action = "would update" if dry_run else "updated" | |
| print(f"\n== dataset_meta.json sha256 {action} ==") | |
| for filename, old, new in hash_changes: | |
| print(f"{filename}: {old} -> {new}") | |
| leftover_re = re.compile(r"元宝派|元宝|(?i:yuanbao)") | |
| leftovers = 0 | |
| if not dry_run: | |
| for path in sorted(iter_files(root)): | |
| raw = open(path, "rb").read() | |
| if b"\0" in raw[:8192]: | |
| continue | |
| try: | |
| text = raw.decode("utf-8") | |
| except UnicodeError: | |
| continue | |
| hits = leftover_re.findall(text) | |
| if hits: | |
| leftovers += len(hits) | |
| print(f"LEFTOVER {os.path.relpath(path, root)}: {len(hits)}", file=sys.stderr) | |
| if leftovers: | |
| raise SystemExit(f"brand strings still present: {leftovers}") | |
| print("leftover 元宝/元宝派/yuanbao: 0") | |
| return 0 | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| default_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dataset") | |
| parser.add_argument("root", nargs="?", default=default_root, help="directory to walk (default: ./dataset)") | |
| parser.add_argument("--dry-run", action="store_true", help="report replacements without writing") | |
| args = parser.parse_args() | |
| raise SystemExit(process(args.root, dry_run=args.dry_run)) | |
| if __name__ == "__main__": | |
| main() | |