davidtran999 commited on
Commit
1462240
·
verified ·
1 Parent(s): c0ae464

Upload backend/scripts/seed_synonyms.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. backend/scripts/seed_synonyms.py +141 -0
backend/scripts/seed_synonyms.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Seed synonyms for search query expansion.
3
+ """
4
+ import argparse
5
+ import csv
6
+ import os
7
+ import sys
8
+ from datetime import datetime
9
+ from pathlib import Path
10
+ from typing import Iterable, List, Tuple
11
+
12
+ import django
13
+
14
+
15
+ ROOT_DIR = Path(__file__).resolve().parents[2]
16
+ BACKEND_DIR = ROOT_DIR / "backend"
17
+ DATA_DIR = ROOT_DIR / "tài nguyên"
18
+ LOG_DIR = BACKEND_DIR / "logs" / "data_quality"
19
+
20
+ HUE_PORTAL_DIR = BACKEND_DIR / "hue_portal"
21
+
22
+ for path in (HUE_PORTAL_DIR, BACKEND_DIR, ROOT_DIR):
23
+ if str(path) not in sys.path:
24
+ sys.path.insert(0, str(path))
25
+
26
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hue_portal.hue_portal.settings")
27
+ django.setup()
28
+
29
+ from hue_portal.core.models import Synonym
30
+
31
+ DEFAULT_SEEDS: List[Tuple[str, str]] = [
32
+ ("đèn đỏ", "vượt đèn đỏ"),
33
+ ("vượt đèn", "vượt đèn đỏ"),
34
+ ("nồng độ cồn", "rượu bia"),
35
+ ("nồng độ cồn", "say xỉn"),
36
+ ("nồng độ cồn", "uống rượu"),
37
+ ("mũ bảo hiểm", "nón bảo hiểm"),
38
+ ("mũ bảo hiểm", "mũ"),
39
+ ("giấy phép lái xe", "bằng lái"),
40
+ ("giấy phép lái xe", "GPLX"),
41
+ ("giấy phép lái xe", "bằng"),
42
+ ("đăng ký xe", "đăng ký"),
43
+ ("đăng ký xe", "giấy đăng ký"),
44
+ ("dừng đỗ", "đỗ xe"),
45
+ ("dừng đỗ", "dừng xe"),
46
+ ("dây an toàn", "thắt dây an toàn"),
47
+ ("tốc độ", "vượt tốc độ"),
48
+ ("tốc độ", "quá tốc độ"),
49
+ ("sai làn", "sai đường"),
50
+ ("sai làn", "đi sai làn"),
51
+ ("điện thoại", "sử dụng điện thoại"),
52
+ ("điện thoại", "gọi điện"),
53
+ ("cư trú", "thủ tục cư trú"),
54
+ ("cư trú", "đăng ký cư trú"),
55
+ ("cư trú", "tạm trú"),
56
+ ("cư trú", "thường trú"),
57
+ ("ANTT", "an ninh trật tự"),
58
+ ("ANTT", "an ninh"),
59
+ ("PCCC", "phòng cháy chữa cháy"),
60
+ ("PCCC", "cháy nổ"),
61
+ ("thủ tục", "hành chính"),
62
+ ("thủ tục", "TTHC"),
63
+ ("công an", "CA"),
64
+ ("công an", "cảnh sát"),
65
+ ("tiếp dân", "tiếp công dân"),
66
+ ("tiếp dân", "một cửa"),
67
+ ("đơn vị", "cơ quan"),
68
+ ("đơn vị", "phòng ban"),
69
+ ]
70
+
71
+
72
+ def load_from_csv(path: Path) -> List[Tuple[str, str]]:
73
+ if not path.exists():
74
+ return []
75
+ pairs: List[Tuple[str, str]] = []
76
+ with path.open(encoding="utf-8") as handle:
77
+ reader = csv.DictReader(handle)
78
+ for row in reader:
79
+ keyword = (row.get("keyword") or "").strip()
80
+ alias = (row.get("alias") or "").strip()
81
+ if keyword and alias:
82
+ pairs.append((keyword, alias))
83
+ return pairs
84
+
85
+
86
+ def seed_synonyms(pairs: Iterable[Tuple[str, str]], log_path: Path) -> None:
87
+ created = 0
88
+ updated = 0
89
+ skipped = 0
90
+
91
+ with log_path.open("a", encoding="utf-8") as log_file:
92
+ for keyword, alias in pairs:
93
+ try:
94
+ synonym, was_created = Synonym.objects.get_or_create(
95
+ keyword=keyword,
96
+ defaults={"alias": alias}
97
+ )
98
+ if was_created:
99
+ created += 1
100
+ log_file.write(f"{datetime.utcnow().isoformat()}Z CREATED {keyword} -> {alias}\n")
101
+ else:
102
+ if synonym.alias != alias:
103
+ synonym.alias = alias
104
+ synonym.save(update_fields=["alias"])
105
+ updated += 1
106
+ log_file.write(f"{datetime.utcnow().isoformat()}Z UPDATED {keyword} -> {alias}\n")
107
+ else:
108
+ skipped += 1
109
+ except Exception as exc:
110
+ log_file.write(f"{datetime.utcnow().isoformat()}Z ERROR {keyword} -> {alias} :: {exc}\n")
111
+
112
+ total = Synonym.objects.count()
113
+ print(f"✅ Seeded {created} mới, cập nhật {updated}, bỏ qua {skipped}. Tổng: {total}")
114
+ print(f"Log chi tiết: {log_path}")
115
+
116
+
117
+ def parse_args():
118
+ parser = argparse.ArgumentParser(description="Seed synonyms cho chatbot")
119
+ parser.add_argument("--source", type=Path, default=DATA_DIR / "synonyms.csv", help="Đường dẫn CSV synonyms")
120
+ parser.add_argument("--include-default", action="store_true", help="Bao gồm seed mặc định trong script")
121
+ return parser.parse_args()
122
+
123
+
124
+ def main():
125
+ args = parse_args()
126
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
127
+ log_path = LOG_DIR / f"synonyms_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.log"
128
+
129
+ pairs: List[Tuple[str, str]] = []
130
+ csv_pairs = load_from_csv(args.source)
131
+ if csv_pairs:
132
+ pairs.extend(csv_pairs)
133
+ if args.include_default or not pairs:
134
+ pairs.extend(DEFAULT_SEEDS)
135
+
136
+ seed_synonyms(pairs, log_path)
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()
141
+