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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Tu_Dong_Dien_Tu_21h.py - Tiến trình Tự Động Điền Từ & Cập Nhật Từ Điển Độc Lập
|
| 4 |
+
Tự động:
|
| 5 |
+
1. Đọc danh sách từ vựng tiếng Pháp (danh_sach_tu.txt) & tiếng Anh (danh_sach_tu_en.txt).
|
| 6 |
+
2. Tự động sinh trọn bộ 29 trường chuẩn Note Type "(Anki) Template học từ vựng của Admin Phúc [2026]".
|
| 7 |
+
3. Cập nhật vào Anki (qua AnkiConnect hoặc ghi trực tiếp SQLite).
|
| 8 |
+
4. Lưu ngược lại vào bộ từ điển ngoại tuyến (french_dictionary.db & english_dictionary.db).
|
| 9 |
+
5. Tự động đồng bộ lên Hugging Face Cloud (Web Mochi & Dataset).
|
| 10 |
+
"""
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import re
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
import html
|
| 17 |
+
import random
|
| 18 |
+
import sqlite3
|
| 19 |
+
import unicodedata
|
| 20 |
+
import urllib.request
|
| 21 |
+
import urllib.parse
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
sys.stdout.reconfigure(encoding="utf-8")
|
| 27 |
+
sys.stderr.reconfigure(encoding="utf-8")
|
| 28 |
+
except Exception:
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
BASE_DIR = Path(__file__).parent.resolve()
|
| 32 |
+
FR_TXT = BASE_DIR / "danh_sach_tu.txt"
|
| 33 |
+
EN_TXT = BASE_DIR / "danh_sach_tu_en.txt"
|
| 34 |
+
FR_DB = BASE_DIR / "french_dictionary.db"
|
| 35 |
+
EN_DB = BASE_DIR / "english_dictionary.db"
|
| 36 |
+
|
| 37 |
+
ANKI_CONNECT_URL = "http://127.0.0.1:8765"
|
| 38 |
+
FIELD_ORDER_29 = [
|
| 39 |
+
"word", "meaning", "pos", "pronunciation", "explain",
|
| 40 |
+
"example", "example_translated", "collocation", "synonym", "antonym",
|
| 41 |
+
"audio_word", "audio_meaning", "audio", "image",
|
| 42 |
+
"choice_1", "choice_2", "choice_3", "choice_4", "correct_choice",
|
| 43 |
+
"choice_word_1", "choice_word_2", "choice_word_3", "choice_word_4", "correct_choice_word",
|
| 44 |
+
"choice_audio_1", "choice_audio_2", "choice_audio_3", "choice_audio_4", "correct_choice_audio"
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
NOTE_TYPE = "(Anki) Template học từ vựng của Admin Phúc [2026]"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def anki_invoke(action, **params):
|
| 51 |
+
try:
|
| 52 |
+
req = urllib.request.Request(
|
| 53 |
+
ANKI_CONNECT_URL,
|
| 54 |
+
json.dumps({"action": action, "version": 6, "params": params}).encode("utf-8"),
|
| 55 |
+
headers={"Content-Type": "application/json"}
|
| 56 |
+
)
|
| 57 |
+
with urllib.request.urlopen(req, timeout=10) as resp:
|
| 58 |
+
return json.loads(resp.read().decode("utf-8"))
|
| 59 |
+
except Exception:
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def translate_text(text, sl="auto", tl="vi"):
|
| 64 |
+
if not text:
|
| 65 |
+
return ""
|
| 66 |
+
try:
|
| 67 |
+
url = f"https://clients5.google.com/translate_a/t?client=dict-chrome-ex&sl={sl}&tl={tl}&q=" + urllib.parse.quote(text)
|
| 68 |
+
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
| 69 |
+
with urllib.request.urlopen(req, timeout=8) as r:
|
| 70 |
+
data = json.loads(r.read().decode("utf-8"))
|
| 71 |
+
return data[0].strip() if isinstance(data, list) and data else text
|
| 72 |
+
except Exception:
|
| 73 |
+
return text
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def fetch_en_word_data(word):
|
| 77 |
+
data = {"pos": "noun", "pron": "", "meaning": "", "syn": "N/A", "ant": "N/A"}
|
| 78 |
+
try:
|
| 79 |
+
url = "https://api.datamuse.com/words?sp=" + urllib.parse.quote(word) + "&md=dprf&ipa=1&max=1"
|
| 80 |
+
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
| 81 |
+
with urllib.request.urlopen(req, timeout=6) as r:
|
| 82 |
+
res = json.loads(r.read().decode("utf-8"))
|
| 83 |
+
if res:
|
| 84 |
+
item = res[0]
|
| 85 |
+
tags = item.get("tags", [])
|
| 86 |
+
for t in tags:
|
| 87 |
+
if t.startswith("ipa_pron:"):
|
| 88 |
+
data["pron"] = f"/{t.split(':', 1)[1]}/"
|
| 89 |
+
elif t in ("n", "v", "adj", "adv"):
|
| 90 |
+
m = {"n": "noun", "v": "verb", "adj": "adjective", "adv": "adverb"}
|
| 91 |
+
data["pos"] = m.get(t, "noun")
|
| 92 |
+
defs = item.get("defs", [])
|
| 93 |
+
if defs:
|
| 94 |
+
data["meaning"] = defs[0].split("\t", 1)[-1].strip()
|
| 95 |
+
except Exception:
|
| 96 |
+
pass
|
| 97 |
+
return data
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def enrich_and_sync_deck(lang="fr"):
|
| 101 |
+
deck_name = "french2" if lang == "fr" else "hoc_lom"
|
| 102 |
+
txt_path = FR_TXT if lang == "fr" else EN_TXT
|
| 103 |
+
db_path = FR_DB if lang == "fr" else EN_DB
|
| 104 |
+
|
| 105 |
+
print(f"\n=======================================================")
|
| 106 |
+
print(f" [*] ĐANG XỬ LÝ BỘ THẺ: {deck_name.upper()} ({lang.upper()})")
|
| 107 |
+
print(f"=======================================================")
|
| 108 |
+
|
| 109 |
+
if not txt_path.exists():
|
| 110 |
+
print(f" [!] Không tìm thấy {txt_path}")
|
| 111 |
+
return
|
| 112 |
+
|
| 113 |
+
lines = [l.strip() for l in txt_path.read_text(encoding="utf-8", errors="ignore").splitlines() if l.strip()]
|
| 114 |
+
print(f" -> Tìm thấy {len(lines)} dòng từ vựng trong file text.")
|
| 115 |
+
|
| 116 |
+
conn = sqlite3.connect(db_path) if db_path.exists() else None
|
| 117 |
+
dict_cache = {}
|
| 118 |
+
if conn:
|
| 119 |
+
try:
|
| 120 |
+
for row in conn.execute("SELECT word_key, word, pos, ipa, meanings_json FROM dictionary").fetchall():
|
| 121 |
+
dict_cache[row[0].lower()] = row
|
| 122 |
+
except Exception:
|
| 123 |
+
pass
|
| 124 |
+
|
| 125 |
+
processed_count = 0
|
| 126 |
+
updated_lines = []
|
| 127 |
+
|
| 128 |
+
for raw_line in lines:
|
| 129 |
+
parts = raw_line.split("\t")
|
| 130 |
+
w = parts[0].strip()
|
| 131 |
+
if not w:
|
| 132 |
+
continue
|
| 133 |
+
w_clean = re.sub(r"\[sound:[^\]]*\]", "", w).strip()
|
| 134 |
+
w_key = w_clean.lower()
|
| 135 |
+
|
| 136 |
+
# Đã có đủ 29 trường
|
| 137 |
+
if len(parts) >= 25:
|
| 138 |
+
updated_lines.append(raw_line)
|
| 139 |
+
continue
|
| 140 |
+
|
| 141 |
+
meaning = parts[1].strip() if len(parts) > 1 else ""
|
| 142 |
+
explain = parts[2].strip() if len(parts) > 2 else ""
|
| 143 |
+
example = parts[3].strip() if len(parts) > 3 else ""
|
| 144 |
+
pos = "noun"
|
| 145 |
+
pron = ""
|
| 146 |
+
ex_trans = ""
|
| 147 |
+
|
| 148 |
+
# Tra trong cơ sở dữ liệu từ điển
|
| 149 |
+
if w_key in dict_cache:
|
| 150 |
+
row = dict_cache[w_key]
|
| 151 |
+
pos = row[2] or "noun"
|
| 152 |
+
pron = row[3] or ""
|
| 153 |
+
try:
|
| 154 |
+
m_list = json.loads(row[4])
|
| 155 |
+
if m_list and isinstance(m_list, list):
|
| 156 |
+
first = m_list[0]
|
| 157 |
+
meaning = meaning or first.get("meaning_en") or first.get("meaning") or ""
|
| 158 |
+
explain = explain or first.get("meaning") or ""
|
| 159 |
+
example = example or first.get("example") or ""
|
| 160 |
+
ex_trans = first.get("example_vi") or ""
|
| 161 |
+
except Exception:
|
| 162 |
+
pass
|
| 163 |
+
|
| 164 |
+
if lang == "en":
|
| 165 |
+
api_info = fetch_en_word_data(w_clean)
|
| 166 |
+
pos = pos or api_info["pos"]
|
| 167 |
+
pron = pron or api_info["pron"]
|
| 168 |
+
meaning = meaning or api_info["meaning"] or translate_text(w_clean, "en", "en")
|
| 169 |
+
explain = explain or translate_text(w_clean, "en", "vi")
|
| 170 |
+
if not example:
|
| 171 |
+
example = f"The researcher highlighted that {w_clean} plays a pivotal role in modern economic analysis."
|
| 172 |
+
ex_trans = ex_trans or translate_text(example, "en", "vi")
|
| 173 |
+
else:
|
| 174 |
+
meaning = meaning or translate_text(w_clean, "fr", "en")
|
| 175 |
+
explain = explain or translate_text(w_clean, "fr", "vi")
|
| 176 |
+
if not example:
|
| 177 |
+
example = f"Cette étude démontre que {w_clean} est essentiel pour le développement durable."
|
| 178 |
+
ex_trans = ex_trans or translate_text(example, "fr", "vi")
|
| 179 |
+
|
| 180 |
+
collocation = f"significant {w_clean}; focus on {w_clean}; role of {w_clean}" if lang == "en" else f"rôle de {w_clean}; importance de {w_clean}; effet de {w_clean}"
|
| 181 |
+
synonym = "N/A"
|
| 182 |
+
antonym = "N/A"
|
| 183 |
+
|
| 184 |
+
# Sinh trắc nghiệm 4 lựa chọn
|
| 185 |
+
distractors_m = ["to alleviate or make less severe", "to examine or scrutinize thoroughly", "to encourage rapid development"] if lang == "en" else ["améliorer les conditions", "favoriser le développement", "examiner attentivement"]
|
| 186 |
+
m_choices = [meaning] + distractors_m
|
| 187 |
+
random.shuffle(m_choices)
|
| 188 |
+
correct_m = str(m_choices.index(meaning) + 1)
|
| 189 |
+
|
| 190 |
+
distractors_w = ["mitigate", "foster", "scrutinize"] if lang == "en" else ["développer", "examiner", "maintenir"]
|
| 191 |
+
w_choices = [w_clean] + distractors_w
|
| 192 |
+
random.shuffle(w_choices)
|
| 193 |
+
correct_w = str(w_choices.index(w_clean) + 1)
|
| 194 |
+
|
| 195 |
+
full_fields = [
|
| 196 |
+
w_clean, meaning, pos, pron, explain,
|
| 197 |
+
example, ex_trans, collocation, synonym, antonym,
|
| 198 |
+
"", "", "", "", # 4 trường audio/image đầu
|
| 199 |
+
m_choices[0], m_choices[1], m_choices[2], m_choices[3], correct_m,
|
| 200 |
+
w_choices[0], w_choices[1], w_choices[2], w_choices[3], correct_w,
|
| 201 |
+
"", "", "", "", # 4 trường choice_audio
|
| 202 |
+
correct_w # correct_choice_audio
|
| 203 |
+
]
|
| 204 |
+
|
| 205 |
+
updated_line = "\t".join(full_fields)
|
| 206 |
+
updated_lines.append(updated_line)
|
| 207 |
+
processed_count += 1
|
| 208 |
+
|
| 209 |
+
# Cập nhật hoặc thêm mới vào Anki qua AnkiConnect
|
| 210 |
+
fields_dict = {FIELD_ORDER_29[i]: full_fields[i] for i in range(29)}
|
| 211 |
+
find_res = anki_invoke("findNotes", query=f'deck:"{deck_name}" "word:{w_clean}"')
|
| 212 |
+
if find_res and find_res.get("result"):
|
| 213 |
+
nid = find_res["result"][0]
|
| 214 |
+
anki_invoke("updateNoteFields", note={"id": nid, "fields": fields_dict})
|
| 215 |
+
else:
|
| 216 |
+
anki_invoke("addNote", note={
|
| 217 |
+
"deckName": deck_name,
|
| 218 |
+
"modelName": NOTE_TYPE,
|
| 219 |
+
"fields": fields_dict,
|
| 220 |
+
"options": {"allowDuplicate": True},
|
| 221 |
+
"tags": ["auto_filled_21h"]
|
| 222 |
+
})
|
| 223 |
+
|
| 224 |
+
# Lưu vào từ điển SQLite ngoại tuyến
|
| 225 |
+
if conn:
|
| 226 |
+
try:
|
| 227 |
+
m_entry = [{
|
| 228 |
+
"word": w_clean,
|
| 229 |
+
"level": "C1",
|
| 230 |
+
"meaning": explain,
|
| 231 |
+
"meaning_en": meaning,
|
| 232 |
+
"example": example,
|
| 233 |
+
"example_vi": ex_trans,
|
| 234 |
+
"collocation": collocation,
|
| 235 |
+
"synonym": synonym,
|
| 236 |
+
"antonym": antonym
|
| 237 |
+
}]
|
| 238 |
+
conn.execute("""
|
| 239 |
+
INSERT OR REPLACE INTO dictionary (word_key, word, level, pos, ipa, meanings_json)
|
| 240 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
| 241 |
+
""", (w_key, w_clean, "C1", pos, pron, json.dumps(m_entry, ensure_ascii=False)))
|
| 242 |
+
except Exception:
|
| 243 |
+
pass
|
| 244 |
+
|
| 245 |
+
if conn:
|
| 246 |
+
conn.commit()
|
| 247 |
+
conn.close()
|
| 248 |
+
|
| 249 |
+
txt_path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8")
|
| 250 |
+
print(f" [+] Đã hoàn tất chuẩn hóa {processed_count} từ mới vào Anki, file text và từ điển ngoại tuyến!")
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def sync_cloud():
|
| 254 |
+
print("\n=======================================================")
|
| 255 |
+
print(" [*] ĐỒNG BỘ 2 CHIỀU LÊN HUGGING FACE CLOUD")
|
| 256 |
+
print("=======================================================")
|
| 257 |
+
for script_name in ["Deploy_Va_Dong_Bo_Cloud.py", "Deploy_Va_Dong_Bo_English_Cloud.py"]:
|
| 258 |
+
p = BASE_DIR / script_name
|
| 259 |
+
if not p.exists():
|
| 260 |
+
p = Path(r"C:\Users\ASUS\.gemini\antigravity\scratch\anki_web_server") / script_name
|
| 261 |
+
if p.exists():
|
| 262 |
+
try:
|
| 263 |
+
os.system(f'python "{p}" --skip-media')
|
| 264 |
+
except Exception as e:
|
| 265 |
+
print(f" [!] Lỗi chạy {script_name}: {e}")
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def main():
|
| 269 |
+
print("=======================================================")
|
| 270 |
+
print(" 🚀 BẮT ĐẦU TIẾN TRÌNH TỰ ĐỘNG ĐIỀN TỪ & LƯU TỪ ĐIỂN 21H")
|
| 271 |
+
print("=======================================================")
|
| 272 |
+
enrich_and_sync_deck("fr")
|
| 273 |
+
enrich_and_sync_deck("en")
|
| 274 |
+
sync_cloud()
|
| 275 |
+
print("\n=======================================================")
|
| 276 |
+
print(" ✅ HOÀN THÀNH TOÀN BỘ TIẾN TRÌNH AUTOMATION!")
|
| 277 |
+
print("=======================================================")
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
if __name__ == "__main__":
|
| 281 |
+
main()
|