hung9066 commited on
Commit
5b2fc22
·
verified ·
1 Parent(s): 6c79e0e

Sync QuickVocabCapture.py

Browse files
Files changed (1) hide show
  1. QuickVocabCapture.py +1675 -0
QuickVocabCapture.py ADDED
@@ -0,0 +1,1675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ QuickVocabCapture - Từ điển Tiếng Anh (IELTS/CEFR) & Tiếng Pháp (DELF/DALF) - Giao diện MochiMochi Chuẩn
4
+ Tính năng nổi bật:
5
+ 1. Giao diện chuẩn MochiMochi theo đúng mẫu thiết kế:
6
+ - Thanh Header với Logo MochiMochi, nút Nghe 🎧, Sổ từ đã lưu 📓, nút chuyển ngôn ngữ En - Vi ▾ / Fr - Vi ▾, Avatar Mochi, Ghim ⚙️
7
+ - Ô tìm kiếm bo tròn viền vàng cam kèm vạch ngăn cách và kính lúp 🔍
8
+ - Thanh Tab loại từ (Noun / Verb / Adjective ▾ | CEFR / DELF Context | Definition | Word Forms)
9
+ - Tiêu đề từ vựng chữ lớn màu xanh đậm (#1E3A8A) + từ loại in nghiêng + nút [⊕ Lưu từ]
10
+ - Dòng phát âm EN / FR 🔊 /ipa/
11
+ - Danh sách các phiên bản nghĩa (1., 2., 3....) kèm huy hiệu CEFR (A1..C2),
12
+ nút [⊕ Lưu từ] riêng cho từng nghĩa, và câu ví dụ + dịch tiếng Việt in nghiêng bên dưới.
13
+ 2. Hai bộ cơ sở dữ liệu từ điển độc lập:
14
+ - Tiếng Anh (En - Vi): E:\\tools\\english_dictionary.db -> lưu vào deck "hoc_lom" & danh_sach_tu_en.txt -> đồng bộ Hugging Face hung9066/mochi-english-anki-data
15
+ - Tiếng Pháp (Fr - Vi): E:\\tools\\french_dictionary.db -> lưu vào deck "french2" & danh_sach_tu.txt -> đồng bộ Hugging Face hung9066/mochi-french-anki-data
16
+ 3. Tự động bắt từ khi BÔI ĐEN + NHẤN PHÍM CTRL 2 LẦN LIÊN TIẾP (Double-Ctrl) hoặc nhập trực tiếp vào ô tra cứu.
17
+ """
18
+
19
+ import sys
20
+ import os
21
+ import re
22
+ import json
23
+ import io
24
+ import base64
25
+ import time
26
+ import html
27
+ import random
28
+ import sqlite3
29
+ import threading
30
+ import queue
31
+ import urllib.parse
32
+ import unicodedata
33
+ import winsound
34
+ import ctypes
35
+ import subprocess
36
+ from concurrent.futures import ThreadPoolExecutor
37
+ from PIL import Image
38
+ from bs4 import BeautifulSoup
39
+
40
+ if hasattr(sys.stdout, "reconfigure"):
41
+ sys.stdout.reconfigure(encoding="utf-8")
42
+ if hasattr(sys.stderr, "reconfigure"):
43
+ sys.stderr.reconfigure(encoding="utf-8")
44
+
45
+ try:
46
+ import requests
47
+ import customtkinter as ctk
48
+ import pyperclip
49
+ from pynput import mouse, keyboard
50
+ except ImportError as e:
51
+ print(f"[!] Thư viện còn thiếu: {e}. Vui lòng cài đặt: pip install customtkinter pyperclip pynput requests pillow beautifulsoup4")
52
+
53
+ # ==============================================================================
54
+ # ĐƯỜNG DẪN ỨNG DỤNG TRONG E:\tools
55
+ # ==============================================================================
56
+ if getattr(sys, "frozen", False):
57
+ APP_DIR = os.path.dirname(os.path.abspath(sys.executable))
58
+ else:
59
+ APP_DIR = os.path.dirname(os.path.abspath(__file__))
60
+
61
+ FR_SQLITE_DB_PATH = os.path.join(APP_DIR, "french_dictionary.db")
62
+ EN_SQLITE_DB_PATH = os.path.join(APP_DIR, "english_dictionary.db")
63
+ LANG_PREF_FILE = os.path.join(APP_DIR, "vocab_lang_pref.json")
64
+ LOGO_PATH = os.path.join(APP_DIR, "mochimochi_logo.png")
65
+ AVATAR_PATH = os.path.join(APP_DIR, "mochi_head.png")
66
+
67
+ PROJECT_QUEUE_DIR = r"E:\AnkiProject\queue"
68
+ FR_PROJECT_QUEUE = os.path.join(PROJECT_QUEUE_DIR, "danh_sach_tu.txt")
69
+ EN_PROJECT_QUEUE = os.path.join(PROJECT_QUEUE_DIR, "danh_sach_tu_en.txt")
70
+
71
+ FR_LOCAL_LIST_FILE = os.path.join(APP_DIR, "danh_sach_tu.txt")
72
+ EN_LOCAL_LIST_FILE = os.path.join(APP_DIR, "danh_sach_tu_en.txt")
73
+
74
+ FR_LIST_FILE = FR_PROJECT_QUEUE if os.path.exists(PROJECT_QUEUE_DIR) else FR_LOCAL_LIST_FILE
75
+ EN_LIST_FILE = EN_PROJECT_QUEUE if os.path.exists(PROJECT_QUEUE_DIR) else EN_LOCAL_LIST_FILE
76
+
77
+ CLOUD_CONFIG_PATH = r"C:\Users\ASUS\.gemini\antigravity\scratch\anki_web_server\cloud_config.json"
78
+ FR_HF_DATASET_REPO = "hung9066/mochi-french-anki-data"
79
+ EN_HF_DATASET_REPO = "hung9066/mochi-english-anki-data"
80
+
81
+ ANKI_URL = "http://127.0.0.1:8765"
82
+ ANKI_BAT_PATH = r"E:\Chay_Anki.bat"
83
+ ANKI_EXE_PATH = r"E:\AnkiPortable\AnkiProgram\Anki.exe"
84
+ ANKI_DATA_PATH = r"E:\AnkiPortable\AnkiData"
85
+
86
+ anki_session = requests.Session()
87
+
88
+ DISTRACTOR_POOL_FR = [
89
+ "Cải thiện, làm cho tốt hơn", "Đòi hỏi, yêu cầu khắt khe", "Bồi thường, đền bù thiệt hại",
90
+ "Phát triển, mở rộng quy mô", "Quan sát, theo dõi kỹ lưỡng", "Giải thích, làm sáng tỏ vấn đề",
91
+ "Duy trì, bảo tồn lâu dài", "Thúc đẩy, khuyến khích phát triển", "Ngăn cản, cản trở tiến trình",
92
+ "Đánh giá, phân tích chi tiết", "Thích nghi với hoàn cảnh mới", "Đạt được mục tiêu đề ra"
93
+ ]
94
+ DISTRACTOR_POOL_EN = [
95
+ "to make something less severe or painful", "to encourage or promote the development of",
96
+ "to examine or inspect closely and thoroughly", "to confirm or give support to a statement",
97
+ "to reduce in extent or quantity; restrict", "able to withstand or recover quickly from difficulty",
98
+ "lasting for only a very short time", "present, appearing, or found everywhere",
99
+ "to make a problem or bad situation worse", "based on observation or experience rather than theory",
100
+ "to officially forbid something by law or rule", "to produce or provide a natural or industrial result"
101
+ ]
102
+ DISTRACTOR_WORDS_FR = ["améliorer", "exiger", "compenser", "développer", "observer", "maintenir", "favoriser", "évaluer"]
103
+ DISTRACTOR_WORDS_EN = ["mitigate", "foster", "scrutinize", "corroborate", "curtail", "resilient", "ephemeral", "ubiquitous"]
104
+
105
+ ANKI_NOTES_CACHE = {"fr": {}, "en": {}}
106
+ ANKI_CACHE_READY = {"fr": False, "en": False}
107
+ SAVED_WORDS_SET = {"fr": set(), "en": set()}
108
+ WORD_LIST_LOCK = threading.Lock()
109
+
110
+
111
+ # ==============================================================================
112
+ # TIỆN ÍCH LÀM SẠCH TỪ & PHÂN LOẠI TRÌNH ĐỘ CEFR / DELF / IELTS
113
+ # ==============================================================================
114
+ def clean_word_stem(w, lang="fr"):
115
+ w = unicodedata.normalize("NFC", (w or "").lower().strip())
116
+ if lang == "en":
117
+ w = re.sub(r"^(to |a |an |the )", "", w)
118
+ else:
119
+ w = re.sub(r"^(l'|d'|le |la |les |un |une |des |du |de la |de l'|se |s')", "", w)
120
+ w = re.sub(r"\s*\([^)]*\)", "", w).strip()
121
+ return w
122
+
123
+
124
+ def get_short_cefr(level_str):
125
+ for code in ("A1", "A2", "B1", "B2", "C1", "C2"):
126
+ if code in (level_str or ""):
127
+ return code
128
+ return "B2"
129
+
130
+
131
+ def estimate_delf_dalf_level(word, sense_idx=0):
132
+ stem = clean_word_stem(word, "fr")
133
+ levels = ["DELF A1", "DELF A2", "DELF B1", "DELF B2", "DALF C1", "DALF C2"]
134
+ if any(stem.endswith(s) for s in ["isation", "isme", "ologie", "archie", "cratie", "phobie"]):
135
+ base = 4
136
+ elif any(stem.endswith(s) for s in ["ment", "tion", "sion", "ence", "ance", "ité", "able", "ible", "ique"]):
137
+ base = 3 if len(stem) >= 9 else 2
138
+ elif len(stem) <= 4:
139
+ base = 0
140
+ elif len(stem) <= 6:
141
+ base = 1
142
+ elif len(stem) <= 9:
143
+ base = 2
144
+ elif len(stem) <= 12:
145
+ base = 3
146
+ else:
147
+ base = 4
148
+ idx = min(5, base + (1 if sense_idx >= 2 and base < 4 else 0))
149
+ return levels[idx]
150
+
151
+
152
+ def estimate_english_cefr_level(word, sense_idx=0):
153
+ stem = clean_word_stem(word, "en")
154
+ levels = ["CEFR A1", "CEFR A2", "CEFR B1", "IELTS 6.5 / B2", "IELTS 7.5 / C1", "IELTS 8.5 / C2"]
155
+ if any(stem.endswith(s) for s in ["ization", "isation", "ology", "cracy", "phobia", "escence", "itious"]):
156
+ base = 4
157
+ elif any(stem.endswith(s) for s in ["ment", "tion", "sion", "ence", "ance", "ity", "able", "ible", "ous", "ive", "ate"]):
158
+ base = 4 if len(stem) >= 10 else 3
159
+ elif len(stem) <= 4:
160
+ base = 1
161
+ elif len(stem) <= 6:
162
+ base = 2
163
+ elif len(stem) <= 9:
164
+ base = 3
165
+ elif len(stem) <= 12:
166
+ base = 4
167
+ else:
168
+ base = 5
169
+ idx = min(5, base + (1 if sense_idx >= 2 and base < 4 else 0))
170
+ return levels[idx]
171
+
172
+
173
+ # ==============================================================================
174
+ # QUẢN LÝ FILE DANH SÁCH TỪ ĐÃ LƯU & ĐỒNG BỘ ANKI + HUGGING FACE
175
+ # ==============================================================================
176
+ def init_saved_word_list():
177
+ for lang, paths in (("fr", {FR_LIST_FILE, FR_LOCAL_LIST_FILE}), ("en", {EN_LIST_FILE, EN_LOCAL_LIST_FILE})):
178
+ for path in paths:
179
+ try:
180
+ if not os.path.exists(path):
181
+ os.makedirs(os.path.dirname(path), exist_ok=True)
182
+ open(path, "w", encoding="utf-8").close()
183
+ else:
184
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
185
+ for line in f:
186
+ s = line.strip().lower()
187
+ if s:
188
+ SAVED_WORDS_SET[lang].add(s)
189
+ if "\t" in s:
190
+ SAVED_WORDS_SET[lang].add(s.split("\t")[0].strip())
191
+ except Exception as e:
192
+ print(f"[!] Lỗi đọc file từ vựng ({lang}): {e}")
193
+
194
+
195
+ def upload_word_list_to_hf_sync(lang="fr"):
196
+ try:
197
+ if lang == "en":
198
+ src_path = EN_LOCAL_LIST_FILE if os.path.exists(EN_LOCAL_LIST_FILE) else EN_LIST_FILE
199
+ repo_id = EN_HF_DATASET_REPO
200
+ remote_name = "danh_sach_tu_en.txt"
201
+ else:
202
+ src_path = FR_LOCAL_LIST_FILE if os.path.exists(FR_LOCAL_LIST_FILE) else FR_LIST_FILE
203
+ repo_id = FR_HF_DATASET_REPO
204
+ remote_name = "danh_sach_tu.txt"
205
+
206
+ if not os.path.exists(src_path) or not os.path.exists(CLOUD_CONFIG_PATH):
207
+ return False
208
+ with open(CLOUD_CONFIG_PATH, "r", encoding="utf-8-sig") as f:
209
+ cfg = json.load(f)
210
+ token = (cfg.get("token") or cfg.get("hf_token") or "").strip()
211
+ if not token:
212
+ return False
213
+ with open(src_path, "rb") as f:
214
+ raw_bytes = f.read()
215
+ b64 = base64.b64encode(raw_bytes).decode("ascii")
216
+ ndjson_body = (
217
+ json.dumps({"key": "header", "value": {"summary": f"Sync {remote_name} from QuickVocabCapture"}}) + "\n" +
218
+ json.dumps({"key": "file", "value": {"content": b64, "path": remote_name, "encoding": "base64"}}) + "\n"
219
+ )
220
+ headers = {
221
+ "Authorization": f"Bearer {token}",
222
+ "Content-Type": "application/x-ndjson"
223
+ }
224
+ resp = requests.post(
225
+ f"https://huggingface.co/api/datasets/{repo_id}/commit/main",
226
+ data=ndjson_body.encode("utf-8"),
227
+ headers=headers,
228
+ timeout=6.0
229
+ )
230
+ return resp.status_code == 200
231
+ except Exception:
232
+ return False
233
+
234
+
235
+ def save_to_word_list(word_clean, level_text="", meaning_text="", example_text="", lang="fr"):
236
+ with WORD_LIST_LOCK:
237
+ line_to_write = f"{word_clean}\t{level_text}\t{meaning_text}\t{example_text}".strip()
238
+ key = f"{word_clean.lower().strip()}\t{meaning_text.lower().strip()}"
239
+ if key in SAVED_WORDS_SET[lang]:
240
+ return
241
+ paths = {EN_LIST_FILE, EN_LOCAL_LIST_FILE} if lang == "en" else {FR_LIST_FILE, FR_LOCAL_LIST_FILE}
242
+ for path in paths:
243
+ try:
244
+ os.makedirs(os.path.dirname(path), exist_ok=True)
245
+ with open(path, "a", encoding="utf-8") as f:
246
+ f.write(f"{line_to_write}\n")
247
+ f.flush()
248
+ except Exception:
249
+ pass
250
+ SAVED_WORDS_SET[lang].add(key)
251
+ SAVED_WORDS_SET[lang].add(word_clean.lower().strip())
252
+ threading.Thread(target=upload_word_list_to_hf_sync, args=(lang,), daemon=True).start()
253
+
254
+
255
+ def anki_request(action, **params):
256
+ try:
257
+ payload = {"action": action, "params": params, "version": 6}
258
+ resp = anki_session.post(ANKI_URL, json=payload, timeout=2.0)
259
+ if resp.status_code == 200:
260
+ return resp.json()
261
+ except Exception:
262
+ pass
263
+ return None
264
+
265
+
266
+ def check_anki_connection():
267
+ data = anki_request("version")
268
+ return bool(data and data.get("result"))
269
+
270
+
271
+ def launch_anki_background():
272
+ if check_anki_connection():
273
+ return True
274
+ try:
275
+ if os.path.exists(ANKI_BAT_PATH):
276
+ subprocess.Popen([ANKI_BAT_PATH], shell=True)
277
+ elif os.path.exists(ANKI_EXE_PATH):
278
+ subprocess.Popen([ANKI_EXE_PATH, "-b", ANKI_DATA_PATH])
279
+ for _ in range(14):
280
+ time.sleep(0.4)
281
+ if check_anki_connection():
282
+ init_anki_cache_background()
283
+ return True
284
+ except Exception as e:
285
+ print(f"[!] Không thể mở Anki: {e}")
286
+ return check_anki_connection()
287
+
288
+
289
+ def record_card_in_anki_cache(word, meaning, lang="fr"):
290
+ w_k = clean_word_stem(word, lang)
291
+ m_k = meaning.strip().lower()
292
+ ANKI_NOTES_CACHE[lang].setdefault(w_k, set()).add(m_k)
293
+
294
+
295
+ def init_anki_cache_background():
296
+ def worker():
297
+ for lang, deck_name, pool_m, pool_w in (
298
+ ("fr", "french2", DISTRACTOR_POOL_FR, DISTRACTOR_WORDS_FR),
299
+ ("en", "hoc_lom", DISTRACTOR_POOL_EN, DISTRACTOR_WORDS_EN),
300
+ ):
301
+ try:
302
+ data = anki_request("findNotes", query=f'deck:"{deck_name}"')
303
+ if not data or not data.get("result"):
304
+ continue
305
+ notes = data["result"]
306
+ for i in range(0, len(notes), 500):
307
+ chunk = notes[i:i + 500]
308
+ info_data = anki_request("notesInfo", notes=chunk)
309
+ if info_data and info_data.get("result"):
310
+ for n in info_data["result"]:
311
+ w = n.get("fields", {}).get("word", {}).get("value", "").strip()
312
+ m = n.get("fields", {}).get("meaning", {}).get("value", "").strip()
313
+ if w and m:
314
+ record_card_in_anki_cache(w, m, lang)
315
+ if len(m) < 70 and m not in pool_m:
316
+ pool_m.append(m)
317
+ if len(w) < 35 and w not in pool_w:
318
+ pool_w.append(w)
319
+ ANKI_CACHE_READY[lang] = True
320
+ except Exception:
321
+ pass
322
+ threading.Thread(target=worker, daemon=True).start()
323
+
324
+
325
+ def is_card_already_in_anki(word, meaning, deck_name="french2", lang="fr"):
326
+ w_k = clean_word_stem(word, lang)
327
+ m_k = meaning.strip().lower()
328
+ if ANKI_CACHE_READY.get(lang) and w_k in ANKI_NOTES_CACHE[lang]:
329
+ return m_k in ANKI_NOTES_CACHE[lang][w_k]
330
+
331
+ escaped = word.replace('"', '\\"')
332
+ data = anki_request("findNotes", query=f'deck:"{deck_name}" "word:{escaped}"')
333
+ if not data or not data.get("result"):
334
+ return False
335
+ info_data = anki_request("notesInfo", notes=data["result"])
336
+ if not info_data or not info_data.get("result"):
337
+ return False
338
+ for n in info_data["result"]:
339
+ m = n.get("fields", {}).get("meaning", {}).get("value", "").strip().lower()
340
+ if m == m_k:
341
+ record_card_in_anki_cache(word, meaning, lang)
342
+ return True
343
+ return False
344
+
345
+
346
+ def get_distractors(target_meaning, lang="fr", count=3):
347
+ base_pool = DISTRACTOR_POOL_EN if lang == "en" else DISTRACTOR_POOL_FR
348
+ pool = [d for d in base_pool if d.lower() != target_meaning.lower()]
349
+ if len(pool) >= count:
350
+ return random.sample(pool, count)
351
+ return (pool + base_pool)[:count]
352
+
353
+
354
+ def get_word_distractors(target_word, lang="fr", count=3):
355
+ base_pool = DISTRACTOR_WORDS_EN if lang == "en" else DISTRACTOR_WORDS_FR
356
+ pool = [w for w in base_pool if w.lower() != target_word.lower()]
357
+ if len(pool) >= count:
358
+ return random.sample(pool, count)
359
+ return (pool + base_pool)[:count]
360
+
361
+
362
+ def add_card_to_anki(word, sense_data, pos_text="Noun", ipa_text="", lang="fr"):
363
+ deck_name = "hoc_lom" if lang == "en" else "french2"
364
+ word_clean = word.strip()
365
+ meaning_text = sense_data.get("meaning", "").strip()
366
+ level_text = sense_data.get("level", "CEFR B2" if lang == "en" else "DELF B1").strip()
367
+ ex_main = sense_data.get("example", "").strip()
368
+ ex_vi = sense_data.get("example_vi", "").strip()
369
+ if " — " in ex_main and not ex_vi:
370
+ parts = ex_main.split(" — ", 1)
371
+ ex_main, ex_vi = parts[0].strip(), parts[1].strip()
372
+
373
+ # Luôn lưu vào danh sách từ đã lưu (danh_sach_tu_en.txt hoặc danh_sach_tu.txt) & đẩy lên Hugging Face
374
+ save_to_word_list(word_clean, level_text, meaning_text, ex_main, lang=lang)
375
+
376
+ if not check_anki_connection():
377
+ return "SAVED_LOCAL", "Đã lưu vào danh sách từ"
378
+
379
+ if is_card_already_in_anki(word_clean, meaning_text, deck_name, lang=lang):
380
+ return "ALREADY_EXISTS", "Đã có thẻ với nghĩa này"
381
+
382
+ distractors = get_distractors(meaning_text, lang, 3)
383
+ choices = distractors + [meaning_text]
384
+ random.shuffle(choices)
385
+ correct_idx = str(choices.index(meaning_text) + 1)
386
+
387
+ w_distractors = get_word_distractors(word_clean, lang, 3)
388
+ w_choices = w_distractors + [word_clean]
389
+ random.shuffle(w_choices)
390
+ correct_w_idx = str(w_choices.index(word_clean) + 1)
391
+
392
+ ipa_formatted = ipa_text if (ipa_text.startswith("/") and ipa_text.endswith("/")) else f"/{ipa_text.strip('/') or word_clean}/"
393
+
394
+ note = {
395
+ "deckName": deck_name,
396
+ "modelName": "(Anki) Template học từ vựng của Admin Phúc [2026]",
397
+ "fields": {
398
+ "word": word_clean,
399
+ "meaning": meaning_text,
400
+ "pos": pos_text,
401
+ "pronunciation": ipa_formatted,
402
+ "explain": f"[{level_text}] {meaning_text}",
403
+ "example": ex_main,
404
+ "example_translated": ex_vi,
405
+ "collocation": "",
406
+ "synonym": "",
407
+ "antonym": "",
408
+ "image": "",
409
+ "choice_1": choices[0] if len(choices) > 0 else "",
410
+ "choice_2": choices[1] if len(choices) > 1 else "",
411
+ "choice_3": choices[2] if len(choices) > 2 else "",
412
+ "choice_4": choices[3] if len(choices) > 3 else "",
413
+ "correct_choice": correct_idx,
414
+ "choice_word_1": w_choices[0] if len(w_choices) > 0 else "",
415
+ "choice_word_2": w_choices[1] if len(w_choices) > 1 else "",
416
+ "choice_word_3": w_choices[2] if len(w_choices) > 2 else "",
417
+ "choice_word_4": w_choices[3] if len(w_choices) > 3 else "",
418
+ "correct_choice_word": correct_w_idx,
419
+ "choice_audio_1": "",
420
+ "choice_audio_2": "",
421
+ "choice_audio_3": "",
422
+ "choice_audio_4": "",
423
+ "correct_choice_audio": correct_w_idx,
424
+ "audio": "",
425
+ "audio_word": "",
426
+ "audio_meaning": ""
427
+ },
428
+ "options": {"allowDuplicate": True}
429
+ }
430
+
431
+ res_data = anki_request("addNote", note=note)
432
+ if res_data and res_data.get("result"):
433
+ record_card_in_anki_cache(word_clean, meaning_text, lang)
434
+ return "SUCCESS", ""
435
+ return "SAVED_LOCAL", "Đã lưu vào danh sách từ"
436
+
437
+
438
+ # ==============================================================================
439
+ # 1. ĐỘNG CƠ TRA CỨU TỪ ĐIỂN TIẾNG ANH - VIỆT (IELTS / CEFR + ONLINE FALLBACK)
440
+ # ==============================================================================
441
+ class EnglishCEFRDictionary:
442
+ def __init__(self):
443
+ self.web_session = requests.Session()
444
+ self.web_session.headers.update({
445
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0 Safari/537.36"
446
+ })
447
+
448
+ def _query_sqlite(self, key):
449
+ if not os.path.exists(EN_SQLITE_DB_PATH):
450
+ return None
451
+ try:
452
+ with sqlite3.connect(EN_SQLITE_DB_PATH, timeout=2.0) as conn:
453
+ row = conn.execute(
454
+ "SELECT word, level, pos, ipa, meanings_json FROM dictionary WHERE word_key = ? LIMIT 1",
455
+ (key.lower(),)
456
+ ).fetchone()
457
+ if row:
458
+ word_str, level_str, pos_str, ipa_str, meanings_json = row
459
+ senses = json.loads(meanings_json)
460
+ ipa_fmt = ipa_str if ipa_str.startswith("/") else f"/{ipa_str.strip('/') or word_str}/"
461
+ return {
462
+ "word": word_str,
463
+ "level": level_str if "CEFR" in level_str or "IELTS" in level_str else f"CEFR {level_str}",
464
+ "pos": (pos_str or "Noun").capitalize(),
465
+ "ipa": ipa_fmt,
466
+ "meanings": senses
467
+ }
468
+ except Exception as e:
469
+ print(f"[!] Lỗi đọc English SQLite: {e}")
470
+ return None
471
+
472
+ def get_candidate_stems(self, raw_word):
473
+ w = unicodedata.normalize("NFC", raw_word.strip().lower())
474
+ stem = clean_word_stem(w, "en")
475
+ cands = []
476
+ for c in [w, stem]:
477
+ if c and c not in cands:
478
+ cands.append(c)
479
+ if len(stem) > 3:
480
+ if stem.endswith("ies") and len(stem) > 4:
481
+ cands.append(stem[:-3] + "y")
482
+ if stem.endswith("es") and len(stem) > 4:
483
+ cands.extend([stem[:-2], stem[:-1]])
484
+ if stem.endswith("s") and not stem.endswith("ss"):
485
+ cands.append(stem[:-1])
486
+ if stem.endswith("ied") and len(stem) > 4:
487
+ cands.append(stem[:-3] + "y")
488
+ if stem.endswith("ed") and len(stem) > 4:
489
+ cands.extend([stem[:-2], stem[:-1]])
490
+ if len(stem) > 5 and stem[-3] == stem[-4]:
491
+ cands.append(stem[:-3])
492
+ if stem.endswith("ing") and len(stem) > 5:
493
+ cands.extend([stem[:-3], stem[:-3] + "e"])
494
+ if len(stem) > 6 and stem[-4] == stem[-5]:
495
+ cands.append(stem[:-4])
496
+ if stem.endswith("ly") and len(stem) > 4:
497
+ cands.append(stem[:-2])
498
+ return cands
499
+
500
+ def lookup(self, word):
501
+ word = unicodedata.normalize("NFC", (word or "").strip())
502
+ if not word:
503
+ return None
504
+
505
+ for cand in self.get_candidate_stems(word):
506
+ res = self._query_sqlite(cand)
507
+ if res and res.get("meanings"):
508
+ return res
509
+
510
+ online_res = self.fetch_online_and_save(word)
511
+ if online_res:
512
+ return online_res
513
+
514
+ lvl = estimate_english_cefr_level(word, 0)
515
+ return {
516
+ "word": word,
517
+ "level": lvl,
518
+ "pos": "Noun",
519
+ "ipa": f"/{word}/",
520
+ "meanings": [{
521
+ "word": word,
522
+ "level": lvl,
523
+ "meaning": f"Từ vựng tiếng Anh: {word}",
524
+ "example": f"Recent academic studies highlight the significance of {word} in modern society.",
525
+ "example_vi": f"Các nghiên cứu học thuật gần đây làm nổi bật tầm quan trọng của “{word}” trong xã hội hiện đại."
526
+ }]
527
+ }
528
+
529
+ def fetch_online_and_save(self, word):
530
+ stem = clean_word_stem(word, "en")
531
+
532
+ def fetch_free_dict():
533
+ pos_out = "Noun"
534
+ ipa_out = ""
535
+ defs_out = []
536
+ try:
537
+ url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{urllib.parse.quote(stem)}"
538
+ r = self.web_session.get(url, timeout=3.5)
539
+ if r.status_code == 200:
540
+ arr = r.json()
541
+ if isinstance(arr, list) and arr:
542
+ entry = arr[0]
543
+ ipa_out = (entry.get("phonetic") or "").strip()
544
+ if not ipa_out:
545
+ for p in entry.get("phonetics", []):
546
+ if p.get("text"):
547
+ ipa_out = p["text"].strip()
548
+ break
549
+ meanings_list = entry.get("meanings", [])
550
+ if meanings_list:
551
+ pos_out = (meanings_list[0].get("partOfSpeech") or "Noun").capitalize()
552
+ for m_obj in meanings_list:
553
+ p_cur = (m_obj.get("partOfSpeech") or pos_out).capitalize()
554
+ for d_obj in m_obj.get("definitions", [])[:2]:
555
+ d_en = (d_obj.get("definition") or "").strip()
556
+ ex_en = (d_obj.get("example") or "").strip()
557
+ if d_en:
558
+ defs_out.append({"pos": p_cur, "def_en": d_en, "ex_en": ex_en})
559
+ except Exception:
560
+ pass
561
+ return pos_out, ipa_out, defs_out
562
+
563
+ def fetch_google_vi():
564
+ vi_terms = []
565
+ main_trans = ""
566
+ try:
567
+ url = (
568
+ "https://translate.googleapis.com/translate_a/single?client=gtx"
569
+ f"&sl=en&tl=vi&dt=t&dt=bd&q={urllib.parse.quote(stem)}"
570
+ )
571
+ r = self.web_session.get(url, timeout=3.0)
572
+ if r.status_code == 200:
573
+ data = r.json()
574
+ if data and data[0]:
575
+ main_trans = "".join(seg[0] for seg in data[0] if seg and seg[0]).strip()
576
+ if len(data) > 1 and data[1]:
577
+ for pos_block in data[1]:
578
+ if len(pos_block) > 1 and isinstance(pos_block[1], list):
579
+ for term in pos_block[1][:4]:
580
+ if isinstance(term, str) and term.strip():
581
+ t_clean = term.strip().capitalize()
582
+ if t_clean.lower() not in [x.lower() for x in vi_terms]:
583
+ vi_terms.append(t_clean)
584
+ except Exception:
585
+ pass
586
+ if main_trans and main_trans.lower() != stem.lower():
587
+ m_cap = main_trans[0].upper() + main_trans[1:]
588
+ if m_cap.lower() not in [x.lower() for x in vi_terms]:
589
+ vi_terms.insert(0, m_cap)
590
+ return vi_terms
591
+
592
+ def translate_en_to_vi(text_en):
593
+ if not text_en:
594
+ return ""
595
+ try:
596
+ url = (
597
+ "https://translate.googleapis.com/translate_a/single?client=gtx"
598
+ f"&sl=en&tl=vi&dt=t&q={urllib.parse.quote(text_en)}"
599
+ )
600
+ r = self.web_session.get(url, timeout=2.5)
601
+ if r.status_code == 200:
602
+ data = r.json()
603
+ if data and data[0]:
604
+ return "".join(seg[0] for seg in data[0] if seg and seg[0]).strip()
605
+ except Exception:
606
+ pass
607
+ return ""
608
+
609
+ with ThreadPoolExecutor(max_workers=2) as ex:
610
+ f_dict = ex.submit(fetch_free_dict)
611
+ f_vi = ex.submit(fetch_google_vi)
612
+ pos, ipa, en_defs = f_dict.result()
613
+ vi_terms = f_vi.result()
614
+
615
+ if not vi_terms and not en_defs:
616
+ return None
617
+
618
+ ipa_fmt = ipa if (ipa.startswith("/") and ipa.endswith("/")) else f"/{ipa.strip('/') or stem}/"
619
+ senses = []
620
+ max_senses = max(len(vi_terms), len(en_defs), 1)
621
+ for idx in range(min(4, max_senses)):
622
+ lvl = estimate_english_cefr_level(stem, idx)
623
+ vi_part = vi_terms[idx] if idx < len(vi_terms) else (vi_terms[0] if vi_terms else "")
624
+ en_part = en_defs[idx]["def_en"] if idx < len(en_defs) else ""
625
+ ex_en = en_defs[idx]["ex_en"] if idx < len(en_defs) and en_defs[idx]["ex_en"] else f"Academic studies frequently examine the role of {stem} in modern contexts."
626
+ ex_vi = translate_en_to_vi(ex_en) or f"Các nghiên cứu học thuật thường xem xét vai trò của “{stem}” trong bối cảnh hiện đại."
627
+
628
+ if vi_part and en_part:
629
+ short_en = en_part if len(en_part) <= 75 else en_part[:72] + "..."
630
+ meaning_combined = f"{vi_part} ({short_en})"
631
+ else:
632
+ meaning_combined = vi_part or en_part
633
+
634
+ senses.append({
635
+ "word": stem,
636
+ "level": lvl,
637
+ "meaning": meaning_combined,
638
+ "example": ex_en,
639
+ "example_vi": ex_vi
640
+ })
641
+
642
+ entry_data = {
643
+ "word": stem,
644
+ "level": senses[0]["level"],
645
+ "pos": pos or "Noun",
646
+ "ipa": ipa_fmt,
647
+ "meanings": senses
648
+ }
649
+
650
+ try:
651
+ with sqlite3.connect(EN_SQLITE_DB_PATH, timeout=2.0) as conn:
652
+ conn.execute(
653
+ "INSERT OR REPLACE INTO dictionary (word_key, word, level, pos, ipa, meanings_json) VALUES (?, ?, ?, ?, ?, ?)",
654
+ (stem.lower(), stem, entry_data["level"], pos, ipa_fmt.strip("/"), json.dumps(senses, ensure_ascii=False))
655
+ )
656
+ conn.commit()
657
+ except Exception:
658
+ pass
659
+
660
+ return entry_data
661
+
662
+
663
+ # ==============================================================================
664
+ # 2. ĐỘNG CƠ TRA CỨU TỪ ĐIỂN PHÁP - VIỆT DELF/DALF (SQLITE 48,000+ TỪ + ONLINE FALLBACK)
665
+ # ==============================================================================
666
+ class FrenchDELFDictionary:
667
+ def __init__(self):
668
+ self.web_session = requests.Session()
669
+ self.web_session.headers.update({
670
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0 Safari/537.36"
671
+ })
672
+
673
+ def _query_sqlite(self, key):
674
+ if not os.path.exists(FR_SQLITE_DB_PATH):
675
+ return None
676
+ try:
677
+ with sqlite3.connect(FR_SQLITE_DB_PATH, timeout=2.0) as conn:
678
+ row = conn.execute(
679
+ "SELECT word, level, pos, ipa, meanings_json FROM dictionary WHERE word_key = ? LIMIT 1",
680
+ (key.lower(),)
681
+ ).fetchone()
682
+ if row:
683
+ word_str, level_str, pos_str, ipa_str, meanings_json = row
684
+ senses = json.loads(meanings_json)
685
+ return {
686
+ "word": word_str,
687
+ "level": level_str,
688
+ "pos": pos_str or "Noun",
689
+ "ipa": ipa_str or f"/{word_str}/",
690
+ "meanings": senses
691
+ }
692
+ except Exception as e:
693
+ print(f"[!] Lỗi đọc SQLite: {e}")
694
+ return None
695
+
696
+ def get_candidate_stems(self, raw_word):
697
+ w = unicodedata.normalize("NFC", raw_word.strip().lower())
698
+ stem = clean_word_stem(w, "fr")
699
+ cands = []
700
+ for c in [w, stem]:
701
+ if c and c not in cands:
702
+ cands.append(c)
703
+
704
+ if len(stem) > 3:
705
+ if stem.endswith("aux"):
706
+ cands.append(stem[:-3] + "al")
707
+ if stem.endswith("eaux"):
708
+ cands.append(stem[:-1])
709
+ if stem.endswith("s") or stem.endswith("x"):
710
+ cands.append(stem[:-1])
711
+ if stem.endswith("es") and len(stem) > 4:
712
+ cands.extend([stem[:-2], stem[:-1], stem[:-2] + "er"])
713
+ if stem.endswith("e") and len(stem) > 4:
714
+ cands.extend([stem[:-1], stem + "r"])
715
+ if stem.endswith("ée") or stem.endswith("és") or stem.endswith("ées"):
716
+ base = re.sub(r"(ée|és|ées)$", "", stem)
717
+ cands.extend([base + "er", base + "é"])
718
+ if stem.endswith("é") and len(stem) > 3:
719
+ cands.append(stem[:-1] + "er")
720
+ for v_end in ("ent", "ons", "ez", "ais", "ait", "aient", "era", "eront", "ant"):
721
+ if stem.endswith(v_end) and len(stem) > len(v_end) + 2:
722
+ root = stem[:-len(v_end)]
723
+ cands.extend([root + "er", root + "ir", root + "re", root + "e"])
724
+ if stem.endswith("issement") and len(stem) > 10:
725
+ cands.append(stem[:-8] + "ir")
726
+ return cands
727
+
728
+ def lookup(self, word):
729
+ word = unicodedata.normalize("NFC", (word or "").strip())
730
+ if not word:
731
+ return None
732
+
733
+ for cand in self.get_candidate_stems(word):
734
+ res = self._query_sqlite(cand)
735
+ if res and res.get("meanings"):
736
+ return res
737
+
738
+ online_res = self.fetch_online_and_save(word)
739
+ if online_res:
740
+ return online_res
741
+
742
+ lvl = estimate_delf_dalf_level(word, 0)
743
+ return {
744
+ "word": word,
745
+ "level": lvl,
746
+ "pos": "Noun",
747
+ "ipa": f"/{word}/",
748
+ "meanings": [{
749
+ "word": word,
750
+ "level": lvl,
751
+ "meaning": f"Từ vựng tiếng Pháp: {word}",
752
+ "example": f"On utilise souvent le terme « {word} » dans ce contexte.",
753
+ "example_vi": f"Người ta thường sử dụng từ “{word}” trong ngữ cảnh này."
754
+ }]
755
+ }
756
+
757
+ def fetch_online_and_save(self, word):
758
+ stem = clean_word_stem(word, "fr")
759
+ glosbe_means = []
760
+ lar_defs = []
761
+ pos = "Noun"
762
+ ipa = f"/{stem}/"
763
+
764
+ def fetch_glosbe():
765
+ out = []
766
+ try:
767
+ url = f"https://glosbe.com/fr/vi/{urllib.parse.quote(stem)}"
768
+ r = self.web_session.get(url, timeout=3.0)
769
+ if r.status_code == 200:
770
+ soup = BeautifulSoup(r.text, "html.parser")
771
+ for tag in soup.find_all(class_=re.compile(r"translation__item__phar?se", re.I)):
772
+ t = tag.get_text(strip=True)
773
+ t = re.sub(r"FVDP[^\n]*", "", t).strip()
774
+ if t and len(t) < 60 and t.lower() not in [x.lower() for x in out]:
775
+ out.append(t[0].upper() + t[1:])
776
+ except Exception:
777
+ pass
778
+ return out
779
+
780
+ def fetch_larousse():
781
+ defs = []
782
+ p = "Noun"
783
+ try:
784
+ url = f"https://www.larousse.fr/dictionnaires/francais/{urllib.parse.quote(stem)}"
785
+ r = self.web_session.get(url, timeout=3.0)
786
+ if r.status_code == 200:
787
+ soup = BeautifulSoup(r.text, "html.parser")
788
+ cat = soup.find("p", class_="CatgramDefinition")
789
+ if cat:
790
+ c_txt = cat.get_text(strip=True).lower()
791
+ if "verbe" in c_txt:
792
+ p = "Verb"
793
+ elif "adjectif" in c_txt:
794
+ p = "Adjective"
795
+ elif "adverbe" in c_txt:
796
+ p = "Adverb"
797
+ for li in soup.find_all("li", class_="DivisionDefinition")[:4]:
798
+ ex = li.find("span", class_="ExempleDefinition")
799
+ ex_text = ex.get_text(strip=True) if ex else ""
800
+ defs.append({"ex": ex_text})
801
+ except Exception:
802
+ pass
803
+ return defs, p
804
+
805
+ def fetch_mymemory():
806
+ try:
807
+ url = f"https://api.mymemory.translated.net/get?q={urllib.parse.quote(stem)}&langpair=fr|vi"
808
+ r = self.web_session.get(url, timeout=2.5)
809
+ if r.status_code == 200:
810
+ t = r.json().get("responseData", {}).get("translatedText", "").strip()
811
+ if t and "MYMEMORY" not in t and t.lower() != stem.lower():
812
+ return t[0].upper() + t[1:]
813
+ except Exception:
814
+ pass
815
+ return ""
816
+
817
+ with ThreadPoolExecutor(max_workers=3) as ex:
818
+ f1 = ex.submit(fetch_glosbe)
819
+ f2 = ex.submit(fetch_larousse)
820
+ f3 = ex.submit(fetch_mymemory)
821
+ glosbe_means = f1.result()
822
+ lar_defs, pos = f2.result()
823
+ mm_vi = f3.result()
824
+
825
+ if mm_vi and mm_vi.lower() not in [x.lower() for x in glosbe_means]:
826
+ glosbe_means.insert(0, mm_vi)
827
+
828
+ if not glosbe_means:
829
+ return None
830
+
831
+ senses = []
832
+ for idx, m_txt in enumerate(glosbe_means[:4]):
833
+ lvl = estimate_delf_dalf_level(stem, idx)
834
+ ex_fr = lar_defs[idx]["ex"] if idx < len(lar_defs) and lar_defs[idx]["ex"] else f"Exemple avec le mot « {stem} » dans une phrase."
835
+ ex_vi = f"Ví dụ sử dụng từ “{m_txt.lower()}” trong câu."
836
+ senses.append({
837
+ "word": stem,
838
+ "level": lvl,
839
+ "meaning": m_txt,
840
+ "example": ex_fr,
841
+ "example_vi": ex_vi
842
+ })
843
+
844
+ entry_data = {
845
+ "word": stem,
846
+ "level": senses[0]["level"],
847
+ "pos": pos,
848
+ "ipa": ipa,
849
+ "meanings": senses
850
+ }
851
+
852
+ try:
853
+ with sqlite3.connect(FR_SQLITE_DB_PATH, timeout=2.0) as conn:
854
+ conn.execute(
855
+ "INSERT OR REPLACE INTO dictionary VALUES (?, ?, ?, ?, ?, ?)",
856
+ (stem.lower(), stem, entry_data["level"], pos, ipa, json.dumps(senses, ensure_ascii=False))
857
+ )
858
+ conn.commit()
859
+ except Exception:
860
+ pass
861
+
862
+ return entry_data
863
+
864
+
865
+ # ==============================================================================
866
+ # GIAO DIỆN MOCHIMOCHI ĐA NGÔN NGỮ: ANH - VIỆT (hoc_lom) & PHÁP - VIỆT (french2)
867
+ # ==============================================================================
868
+ class MochiVocabCapture(ctk.CTk):
869
+ def __init__(self):
870
+ super().__init__()
871
+
872
+ ctk.set_appearance_mode("Light")
873
+ ctk.set_default_color_theme("green")
874
+
875
+ self.current_lang = self._load_lang_pref()
876
+ self.fr_engine = FrenchDELFDictionary()
877
+ self.en_engine = EnglishCEFRDictionary()
878
+
879
+ self.geometry("500x700")
880
+ self.minsize(460, 560)
881
+ self.configure(fg_color="#FFFFFF")
882
+
883
+ self.is_pinned = True
884
+ self.attributes("-topmost", True)
885
+
886
+ init_saved_word_list()
887
+ self.current_data = None
888
+ self.queue = queue.Queue()
889
+
890
+ # Trạng thái bắt phím Ctrl 2 lần liên tiếp (Double-Ctrl) & Giữ Ctrl bôi đen
891
+ self.is_ctrl_down = False
892
+ self.is_simulating_copy = False
893
+ self.is_processing_copy = False
894
+ self.last_ctrl_release_time = 0.0
895
+ self.other_key_pressed_during_ctrl = False
896
+
897
+ self._build_header()
898
+ self._build_search_bar()
899
+ self._build_category_tabs()
900
+ self._build_scrollable_body()
901
+ self._apply_lang_ui_state()
902
+
903
+ self.after(80, self._process_queue)
904
+ self.after(600, init_anki_cache_background)
905
+ self._start_global_listener()
906
+
907
+ # Hiển thị từ mẫu ngay khi mở ứng dụng
908
+ sample_word = "mitigate" if self.current_lang == "en" else "améliorer"
909
+ self.after(150, lambda: self.search_word(sample_word))
910
+ self.protocol("WM_DELETE_WINDOW", self._on_close_app)
911
+
912
+ def _load_lang_pref(self):
913
+ try:
914
+ if os.path.exists(LANG_PREF_FILE):
915
+ with open(LANG_PREF_FILE, "r", encoding="utf-8") as f:
916
+ d = json.load(f)
917
+ if d.get("lang") in ("en", "fr"):
918
+ return d["lang"]
919
+ except Exception:
920
+ pass
921
+ return "en"
922
+
923
+ def _save_lang_pref(self):
924
+ try:
925
+ with open(LANG_PREF_FILE, "w", encoding="utf-8") as f:
926
+ json.dump({"lang": self.current_lang}, f)
927
+ except Exception:
928
+ pass
929
+
930
+ def toggle_language(self):
931
+ self.current_lang = "fr" if self.current_lang == "en" else "en"
932
+ self._save_lang_pref()
933
+ self._apply_lang_ui_state()
934
+ cur_query = (self.search_entry.get() or "").strip()
935
+ if not cur_query or cur_query.lower() in ("améliorer", "compenser", "mitigate", "ubiquitous"):
936
+ cur_query = "mitigate" if self.current_lang == "en" else "améliorer"
937
+ self.search_word(cur_query)
938
+
939
+ def _apply_lang_ui_state(self):
940
+ if self.current_lang == "en":
941
+ self.title("MochiMochi Dictionary - Tiếng Anh IELTS / CEFR (Deck: hoc_lom)")
942
+ self.btn_lang.configure(text="En - Vi ▾", fg_color="#0284C7", hover_color="#0369A1")
943
+ self.search_entry.configure(placeholder_text="Nhập từ tiếng Anh hoặc Bôi đen + Nhấn Ctrl 2 lần...")
944
+ self.lbl_context_tab.configure(text="IELTS / CEFR")
945
+ else:
946
+ self.title("MochiMochi Dictionary - Tiếng Pháp DELF / DALF (Deck: french2)")
947
+ self.btn_lang.configure(text="Fr - Vi ▾", fg_color="#2563EB", hover_color="#1D4ED8")
948
+ self.search_entry.configure(placeholder_text="Nhập từ tiếng Pháp hoặc Bôi đen + Nhấn Ctrl 2 lần...")
949
+ self.lbl_context_tab.configure(text="DELF Context")
950
+
951
+ def _on_close_app(self):
952
+ try:
953
+ for local_f, proj_f, lg in (
954
+ (FR_LOCAL_LIST_FILE, FR_LIST_FILE, "fr"),
955
+ (EN_LOCAL_LIST_FILE, EN_LIST_FILE, "en")
956
+ ):
957
+ if os.path.exists(local_f) and proj_f != local_f:
958
+ os.makedirs(os.path.dirname(proj_f), exist_ok=True)
959
+ with open(local_f, "rb") as f_src:
960
+ data = f_src.read()
961
+ with open(proj_f, "wb") as f_dst:
962
+ f_dst.write(data)
963
+ upload_word_list_to_hf_sync(lg)
964
+ except Exception:
965
+ pass
966
+ self.destroy()
967
+ os._exit(0)
968
+
969
+ def _load_ctk_image(self, path, size):
970
+ try:
971
+ if os.path.exists(path):
972
+ pil_img = Image.open(path)
973
+ return ctk.CTkImage(light_image=pil_img, dark_image=pil_img, size=size)
974
+ except Exception:
975
+ pass
976
+ return None
977
+
978
+ # --------------------------------------------------------------------------
979
+ # 1. THANH HEADER TRÊN CÙNG (GIỐNG HỆT HÌNH MẪU MOCHIMOCHI)
980
+ # --------------------------------------------------------------------------
981
+ def _build_header(self):
982
+ header_wrap = ctk.CTkFrame(self, fg_color="#FFFFFF")
983
+ header_wrap.pack(fill="x", padx=0, pady=0)
984
+
985
+ header_frame = ctk.CTkFrame(header_wrap, fg_color="#FFFFFF", height=54)
986
+ header_frame.pack(fill="x", padx=18, pady=(10, 8))
987
+
988
+ # Logo MOCHIMOCHI bên trái
989
+ self.logo_img = self._load_ctk_image(LOGO_PATH, (142, 28))
990
+ if self.logo_img:
991
+ self.logo_label = ctk.CTkLabel(header_frame, image=self.logo_img, text="")
992
+ else:
993
+ self.logo_label = ctk.CTkLabel(
994
+ header_frame,
995
+ text="MOCHIMOCHI",
996
+ font=("Arial Rounded MT Bold", 20, "bold"),
997
+ text_color="#F59E0B"
998
+ )
999
+ self.logo_label.pack(side="left", pady=4)
1000
+
1001
+ # Cụm nút bên phải: 🎧 Xanh lá | 📓 Trắng viền | En - Vi ▾ / Fr - Vi ▾ | Avatar Mochi | ⚙️
1002
+ right_bar = ctk.CTkFrame(header_frame, fg_color="transparent")
1003
+ right_bar.pack(side="right")
1004
+
1005
+ # Nút Tai nghe phát âm 🎧 (Tròn xanh lá #22C55E)
1006
+ self.btn_headphone = ctk.CTkButton(
1007
+ right_bar,
1008
+ text="🎧",
1009
+ width=38,
1010
+ height=38,
1011
+ corner_radius=19,
1012
+ fg_color="#22C55E",
1013
+ hover_color="#16A34A",
1014
+ text_color="#FFFFFF",
1015
+ font=("Segoe UI Emoji", 16),
1016
+ command=self.play_audio
1017
+ )
1018
+ self.btn_headphone.pack(side="left", padx=4)
1019
+
1020
+ # Nút Sổ tay từ đã lưu 📓 (Tròn trắng viền xám nhạt)
1021
+ self.btn_notebook = ctk.CTkButton(
1022
+ right_bar,
1023
+ text="📕",
1024
+ width=38,
1025
+ height=38,
1026
+ corner_radius=19,
1027
+ fg_color="#FFFFFF",
1028
+ hover_color="#F8FAFC",
1029
+ border_color="#E2E8F0",
1030
+ border_width=1.5,
1031
+ text_color="#F43F5E",
1032
+ font=("Segoe UI Emoji", 15),
1033
+ command=self.open_saved_file
1034
+ )
1035
+ self.btn_notebook.pack(side="left", padx=4)
1036
+
1037
+ # Vạch ngăn cách dọc mảnh
1038
+ sep1 = ctk.CTkFrame(right_bar, width=1, height=24, fg_color="#E2E8F0")
1039
+ sep1.pack(side="left", padx=6)
1040
+
1041
+ # Nút pill chuyển ngôn ngữ "En - Vi ▾" / "Fr - Vi ▾"
1042
+ self.btn_lang = ctk.CTkButton(
1043
+ right_bar,
1044
+ text="En - Vi ▾",
1045
+ width=82,
1046
+ height=34,
1047
+ corner_radius=17,
1048
+ fg_color="#0284C7",
1049
+ hover_color="#0369A1",
1050
+ text_color="#FFFFFF",
1051
+ font=("Segoe UI", 13, "bold"),
1052
+ command=self.toggle_language
1053
+ )
1054
+ self.btn_lang.pack(side="left", padx=4)
1055
+
1056
+ # Avatar Mochi tròn viền xanh lá
1057
+ self.avatar_img = self._load_ctk_image(AVATAR_PATH, (28, 28))
1058
+ self.btn_avatar = ctk.CTkButton(
1059
+ right_bar,
1060
+ image=self.avatar_img,
1061
+ text="" if self.avatar_img else "🍡",
1062
+ width=38,
1063
+ height=38,
1064
+ corner_radius=19,
1065
+ fg_color="#FFFFFF",
1066
+ hover_color="#F0FDF4",
1067
+ border_color="#22C55E",
1068
+ border_width=2,
1069
+ command=self._on_anki_status_click
1070
+ )
1071
+ self.btn_avatar.pack(side="left", padx=4)
1072
+
1073
+ # Vạch ngăn cách dọc mảnh
1074
+ sep2 = ctk.CTkFrame(right_bar, width=1, height=24, fg_color="#E2E8F0")
1075
+ sep2.pack(side="left", padx=4)
1076
+
1077
+ # Nút bánh răng cài đặt / Ghim cửa sổ ⚙️
1078
+ self.btn_gear = ctk.CTkButton(
1079
+ right_bar,
1080
+ text="⚙️",
1081
+ width=34,
1082
+ height=34,
1083
+ corner_radius=17,
1084
+ fg_color="transparent",
1085
+ hover_color="#F1F5F9",
1086
+ text_color="#64748B",
1087
+ font=("Segoe UI Emoji", 17),
1088
+ command=self.toggle_pin
1089
+ )
1090
+ self.btn_gear.pack(side="left", padx=(2, 0))
1091
+
1092
+ # Đường kẻ ngang phân tách dưới Header
1093
+ header_line = ctk.CTkFrame(header_wrap, height=1, fg_color="#E2E8F0")
1094
+ header_line.pack(fill="x")
1095
+
1096
+ # --------------------------------------------------------------------------
1097
+ # 2. Ô TÌM KIẾM BO TRÒN VIỀN VÀNG CAM + VẠCH DỌC + KÍNH LÚP
1098
+ # --------------------------------------------------------------------------
1099
+ def _build_search_bar(self):
1100
+ search_outer = ctk.CTkFrame(self, fg_color="#FFFFFF")
1101
+ search_outer.pack(fill="x", padx=22, pady=(16, 14))
1102
+
1103
+ search_box = ctk.CTkFrame(
1104
+ search_outer,
1105
+ fg_color="#FFFFFF",
1106
+ border_color="#F59E0B",
1107
+ border_width=2,
1108
+ corner_radius=27,
1109
+ height=54
1110
+ )
1111
+ search_box.pack(fill="x")
1112
+ search_box.pack_propagate(False)
1113
+
1114
+ self.search_entry = ctk.CTkEntry(
1115
+ search_box,
1116
+ placeholder_text="Nhập từ tiếng Anh hoặc Bôi đen + Nhấn Ctrl 2 lần...",
1117
+ fg_color="transparent",
1118
+ border_width=0,
1119
+ font=("Segoe UI", 17, "bold"),
1120
+ text_color="#0F172A"
1121
+ )
1122
+ self.search_entry.pack(side="left", fill="both", expand=True, padx=(22, 8), pady=6)
1123
+ self.search_entry.bind("<Return>", lambda e: self.search_word(self.search_entry.get()))
1124
+
1125
+ # Nút kính lúp bên phải
1126
+ search_btn = ctk.CTkButton(
1127
+ search_box,
1128
+ text="🔍",
1129
+ width=48,
1130
+ height=40,
1131
+ corner_radius=20,
1132
+ fg_color="transparent",
1133
+ hover_color="#F1F5F9",
1134
+ text_color="#0284C7",
1135
+ font=("Segoe UI Emoji", 18),
1136
+ command=lambda: self.search_word(self.search_entry.get())
1137
+ )
1138
+ search_btn.pack(side="right", padx=(6, 12))
1139
+
1140
+ # Vạch ngăn cách dọc trước kính lúp
1141
+ divider = ctk.CTkFrame(search_box, width=1.5, height=28, fg_color="#CBD5E1")
1142
+ divider.pack(side="right", pady=12)
1143
+
1144
+ # --------------------------------------------------------------------------
1145
+ # 3. THANH TAB LOẠI TỪ (Verb / Noun ▾ | Context | Definition | Verb Forms)
1146
+ # --------------------------------------------------------------------------
1147
+ def _build_category_tabs(self):
1148
+ tabs_wrap = ctk.CTkFrame(self, fg_color="#FFFFFF")
1149
+ tabs_wrap.pack(fill="x")
1150
+
1151
+ top_border = ctk.CTkFrame(tabs_wrap, height=1, fg_color="#F1F5F9")
1152
+ top_border.pack(fill="x")
1153
+
1154
+ tabs_bar = ctk.CTkFrame(tabs_wrap, fg_color="#FFFFFF", height=42)
1155
+ tabs_bar.pack(fill="x", padx=6)
1156
+ tabs_bar.pack_propagate(False)
1157
+
1158
+ self.tab_pos_btn = ctk.CTkLabel(
1159
+ tabs_bar,
1160
+ text="Verb ▾",
1161
+ font=("Segoe UI", 14, "bold"),
1162
+ fg_color="#FEF3C7",
1163
+ text_color="#0F172A",
1164
+ corner_radius=0,
1165
+ padx=18,
1166
+ pady=9
1167
+ )
1168
+ self.tab_pos_btn.pack(side="left", fill="y")
1169
+
1170
+ self.lbl_context_tab = ctk.CTkLabel(
1171
+ tabs_bar,
1172
+ text="IELTS / CEFR",
1173
+ font=("Segoe UI", 13, "bold"),
1174
+ fg_color="transparent",
1175
+ text_color="#A1A1AA",
1176
+ padx=12
1177
+ )
1178
+ self.lbl_context_tab.pack(side="left", fill="y")
1179
+
1180
+ for tab_name in ("Definition", "Word Forms"):
1181
+ lbl = ctk.CTkLabel(
1182
+ tabs_bar,
1183
+ text=tab_name,
1184
+ font=("Segoe UI", 13, "bold"),
1185
+ fg_color="transparent",
1186
+ text_color="#A1A1AA",
1187
+ padx=12
1188
+ )
1189
+ lbl.pack(side="left", fill="y")
1190
+
1191
+ bottom_border = ctk.CTkFrame(tabs_wrap, height=1, fg_color="#F1F5F9")
1192
+ bottom_border.pack(fill="x")
1193
+
1194
+ # --------------------------------------------------------------------------
1195
+ # 4. VÙNG NỘI DUNG CUỘN (TIÊU ĐỀ TỪ LỚN + IPA + CÁC PHIÊN BẢN NGHĨA 1., 2., 3.)
1196
+ # --------------------------------------------------------------------------
1197
+ def _build_scrollable_body(self):
1198
+ self.scroll_body = ctk.CTkScrollableFrame(
1199
+ self,
1200
+ fg_color="#FFFFFF",
1201
+ scrollbar_button_color="#CBD5E1",
1202
+ scrollbar_button_hover_color="#94A3B8"
1203
+ )
1204
+ self.scroll_body.pack(fill="both", expand=True, padx=8, pady=(4, 8))
1205
+
1206
+ def _on_anki_status_click(self):
1207
+ if not check_anki_connection():
1208
+ threading.Thread(target=launch_anki_background, daemon=True).start()
1209
+
1210
+ def search_word(self, word):
1211
+ word = (word or "").strip()
1212
+ if not word:
1213
+ return
1214
+ self.search_entry.delete(0, "end")
1215
+ self.search_entry.insert(0, word)
1216
+ threading.Thread(target=self._search_worker, args=(word, self.current_lang), daemon=True).start()
1217
+
1218
+ def _search_worker(self, word, lang):
1219
+ engine = self.en_engine if lang == "en" else self.fr_engine
1220
+ data = engine.lookup(word)
1221
+ if data:
1222
+ data["lang"] = lang
1223
+ self.queue.put(("RENDER_WORD", data))
1224
+
1225
+ def _process_queue(self):
1226
+ try:
1227
+ while True:
1228
+ msg_type, payload = self.queue.get_nowait()
1229
+ if msg_type == "RENDER_WORD":
1230
+ self._render_word_data(payload)
1231
+ elif msg_type == "POPUP_WORD":
1232
+ self.search_word(payload)
1233
+ self.deiconify()
1234
+ self.lift()
1235
+ self.attributes("-topmost", True)
1236
+ self.focus_force()
1237
+ try:
1238
+ winsound.Beep(1200, 90)
1239
+ except Exception:
1240
+ pass
1241
+ except queue.Empty:
1242
+ pass
1243
+ self.after(70, self._process_queue)
1244
+
1245
+ def _render_word_data(self, data):
1246
+ self.current_data = data
1247
+ if not data:
1248
+ return
1249
+
1250
+ pos_display = data.get("pos", "Noun")
1251
+ self.tab_pos_btn.configure(text=f"{pos_display} ▾")
1252
+
1253
+ for child in self.scroll_body.winfo_children():
1254
+ child.destroy()
1255
+
1256
+ word_str = data.get("word", "")
1257
+ ipa_str = data.get("ipa", f"/{word_str}/")
1258
+ lang = data.get("lang", self.current_lang)
1259
+ main_level = data.get("level", "CEFR B2" if lang == "en" else "DELF B1")
1260
+ meanings = data.get("meanings", [])
1261
+
1262
+ # --- PHẦN ĐẦU: TỪ VỰNG CHỮ LỚN MÀU XANH ĐẬM + TỪ LOẠI IN NGHIÊNG + TRÌNH ĐỘ + NÚT LƯU TỪ ---
1263
+ word_header_row = ctk.CTkFrame(self.scroll_body, fg_color="transparent")
1264
+ word_header_row.pack(fill="x", padx=12, pady=(14, 4))
1265
+
1266
+ lbl_word_title = ctk.CTkLabel(
1267
+ word_header_row,
1268
+ text=word_str,
1269
+ font=("Segoe UI", 28, "bold"),
1270
+ text_color="#1E3A8A"
1271
+ )
1272
+ lbl_word_title.pack(side="left", anchor="s")
1273
+
1274
+ lbl_pos_italic = ctk.CTkLabel(
1275
+ word_header_row,
1276
+ text=f" {pos_display.lower()}",
1277
+ font=("Segoe UI", 16, "italic"),
1278
+ text_color="#94A3B8"
1279
+ )
1280
+ lbl_pos_italic.pack(side="left", anchor="s", padx=(4, 8), pady=(0, 3))
1281
+
1282
+ # Huy hiệu trình độ CEFR / IELTS / DELF ngay sau từ chính
1283
+ lbl_word_delf = ctk.CTkLabel(
1284
+ word_header_row,
1285
+ text=main_level,
1286
+ font=("Segoe UI", 12, "bold"),
1287
+ fg_color="#EFF6FF",
1288
+ text_color="#1D4ED8",
1289
+ corner_radius=8,
1290
+ padx=8,
1291
+ pady=2
1292
+ )
1293
+ lbl_word_delf.pack(side="left", anchor="s", pady=(0, 5))
1294
+
1295
+ # Nút [+ Lưu từ] bên cạnh từ chính (lưu nghĩa số 1 của từ)
1296
+ if meanings:
1297
+ btn_save_main = ctk.CTkButton(
1298
+ word_header_row,
1299
+ text="⊕ Lưu từ",
1300
+ width=94,
1301
+ height=34,
1302
+ corner_radius=17,
1303
+ fg_color="#22C55E",
1304
+ hover_color="#16A34A",
1305
+ text_color="#FFFFFF",
1306
+ font=("Segoe UI", 13, "bold"),
1307
+ command=lambda m0=meanings[0]: self._on_save_clicked(word_str, m0, pos_display, ipa_str, btn_save_main, lang)
1308
+ )
1309
+ btn_save_main.pack(side="right", anchor="center")
1310
+
1311
+ # --- DÒNG PHÁT ÂM (EN / FR 🔊 /ipa/) ---
1312
+ pron_row = ctk.CTkFrame(self.scroll_body, fg_color="transparent")
1313
+ pron_row.pack(fill="x", padx=12, pady=(4, 14))
1314
+
1315
+ lbl_lang_tag = ctk.CTkLabel(
1316
+ pron_row,
1317
+ text="EN" if lang == "en" else "FR",
1318
+ font=("Segoe UI", 13, "bold"),
1319
+ text_color="#0284C7" if lang == "en" else "#F87171"
1320
+ )
1321
+ lbl_lang_tag.pack(side="left", padx=(0, 8))
1322
+
1323
+ btn_speaker = ctk.CTkButton(
1324
+ pron_row,
1325
+ text="🔊",
1326
+ width=36,
1327
+ height=36,
1328
+ corner_radius=18,
1329
+ fg_color="#FFFFFF",
1330
+ hover_color="#F1F5F9",
1331
+ border_color="#E2E8F0",
1332
+ border_width=1.5,
1333
+ text_color="#EF4444",
1334
+ font=("Segoe UI Emoji", 14),
1335
+ command=self.play_audio
1336
+ )
1337
+ btn_speaker.pack(side="left", padx=(0, 10))
1338
+
1339
+ lbl_ipa = ctk.CTkLabel(
1340
+ pron_row,
1341
+ text=ipa_str,
1342
+ font=("Segoe UI", 15),
1343
+ text_color="#334155"
1344
+ )
1345
+ lbl_ipa.pack(side="left")
1346
+
1347
+ # --- DANH SÁCH CÁC PHIÊN BẢN NGHĨA (1., 2., 3....) ---
1348
+ for idx, m_item in enumerate(meanings, start=1):
1349
+ self._render_meaning_block(idx, word_str, pos_display, ipa_str, m_item, lang)
1350
+
1351
+ def _render_meaning_block(self, number, word_str, pos_display, ipa_str, m_item, lang):
1352
+ block = ctk.CTkFrame(self.scroll_body, fg_color="#FFFFFF")
1353
+ block.pack(fill="x", padx=10, pady=(6, 14))
1354
+
1355
+ top_row = ctk.CTkFrame(block, fg_color="transparent")
1356
+ top_row.pack(fill="x")
1357
+
1358
+ lbl_num = ctk.CTkLabel(
1359
+ top_row,
1360
+ text=f"{number}.",
1361
+ font=("Segoe UI", 15, "bold"),
1362
+ text_color="#0F172A"
1363
+ )
1364
+ lbl_num.pack(side="left", anchor="n", padx=(0, 6), pady=(2, 0))
1365
+
1366
+ level_full = m_item.get("level") or self.current_data.get("level", "CEFR B2" if lang == "en" else "DELF B1")
1367
+ short_cefr = get_short_cefr(level_full)
1368
+
1369
+ badge_cefr = ctk.CTkLabel(
1370
+ top_row,
1371
+ text=short_cefr,
1372
+ font=("Segoe UI", 12, "bold"),
1373
+ fg_color="#1D4ED8",
1374
+ text_color="#FFFFFF",
1375
+ corner_radius=9,
1376
+ padx=8,
1377
+ pady=1
1378
+ )
1379
+ badge_cefr.pack(side="left", anchor="n", padx=(0, 8), pady=(3, 0))
1380
+
1381
+ btn_save = ctk.CTkButton(
1382
+ top_row,
1383
+ text="⊕ Lưu từ",
1384
+ width=94,
1385
+ height=34,
1386
+ corner_radius=17,
1387
+ fg_color="#22C55E",
1388
+ hover_color="#16A34A",
1389
+ text_color="#FFFFFF",
1390
+ font=("Segoe UI", 13, "bold")
1391
+ )
1392
+ btn_save.configure(command=lambda b=btn_save, m=m_item: self._on_save_clicked(word_str, m, pos_display, ipa_str, b, lang))
1393
+ btn_save.pack(side="right", anchor="n", padx=(8, 0), pady=(2, 0))
1394
+
1395
+ meaning_txt = m_item.get("meaning", "")
1396
+ lbl_meaning = ctk.CTkLabel(
1397
+ top_row,
1398
+ text=meaning_txt,
1399
+ font=("Segoe UI", 15, "bold"),
1400
+ text_color="#0F172A",
1401
+ wraplength=265,
1402
+ justify="left"
1403
+ )
1404
+ lbl_meaning.pack(side="left", fill="x", expand=True, anchor="n")
1405
+
1406
+ badge_row = ctk.CTkFrame(block, fg_color="transparent")
1407
+ badge_row.pack(fill="x", padx=(26, 0), pady=(4, 6))
1408
+
1409
+ delf_pill = ctk.CTkFrame(
1410
+ badge_row,
1411
+ fg_color="#FFFFFF",
1412
+ border_color="#E11D48",
1413
+ border_width=1.5,
1414
+ corner_radius=10
1415
+ )
1416
+ delf_pill.pack(side="left", padx=(0, 6))
1417
+
1418
+ pill_label = level_full if ("DELF" in level_full or "DALF" in level_full or "IELTS" in level_full or "CEFR" in level_full) else (f"IELTS / CEFR {level_full}" if lang == "en" else f"DELF {level_full}")
1419
+ lbl_delf_pill = ctk.CTkLabel(
1420
+ delf_pill,
1421
+ text=pill_label,
1422
+ font=("Segoe UI", 12, "bold"),
1423
+ text_color="#E11D48",
1424
+ padx=9,
1425
+ pady=1
1426
+ )
1427
+ lbl_delf_pill.pack()
1428
+
1429
+ lbl_excl = ctk.CTkLabel(
1430
+ badge_row,
1431
+ text="ⓘ",
1432
+ font=("Segoe UI", 14),
1433
+ text_color="#94A3B8"
1434
+ )
1435
+ lbl_excl.pack(side="left")
1436
+
1437
+ ex_main = m_item.get("example", "").strip()
1438
+ ex_vi = m_item.get("example_vi", "").strip()
1439
+ if " — " in ex_main and not ex_vi:
1440
+ parts = ex_main.split(" — ", 1)
1441
+ ex_main, ex_vi = parts[0].strip(), parts[1].strip()
1442
+
1443
+ if ex_main:
1444
+ ex_row = ctk.CTkFrame(block, fg_color="transparent")
1445
+ ex_row.pack(fill="x", padx=(8, 4), pady=(2, 2))
1446
+
1447
+ dot = ctk.CTkLabel(
1448
+ ex_row,
1449
+ text="•",
1450
+ font=("Segoe UI", 16, "bold"),
1451
+ text_color="#CBD5E1"
1452
+ )
1453
+ dot.pack(side="left", anchor="n", padx=(0, 8))
1454
+
1455
+ ex_text_col = ctk.CTkFrame(ex_row, fg_color="transparent")
1456
+ ex_text_col.pack(side="left", fill="x", expand=True)
1457
+
1458
+ lbl_ex_main = ctk.CTkLabel(
1459
+ ex_text_col,
1460
+ text=ex_main,
1461
+ font=("Segoe UI", 13.5),
1462
+ text_color="#1E293B",
1463
+ wraplength=410,
1464
+ justify="left"
1465
+ )
1466
+ lbl_ex_main.pack(anchor="w")
1467
+
1468
+ if ex_vi:
1469
+ lbl_ex_vi = ctk.CTkLabel(
1470
+ ex_text_col,
1471
+ text=ex_vi,
1472
+ font=("Segoe UI", 13, "italic"),
1473
+ text_color="#64748B",
1474
+ wraplength=410,
1475
+ justify="left"
1476
+ )
1477
+ lbl_ex_vi.pack(anchor="w", pady=(1, 0))
1478
+
1479
+ def _on_save_clicked(self, word_str, m_item, pos_display, ipa_str, btn_widget, lang):
1480
+ btn_widget.configure(text="Đang lưu...", state="disabled")
1481
+
1482
+ def save_task():
1483
+ status, _ = add_card_to_anki(word_str, m_item, pos_display, ipa_str, lang=lang)
1484
+
1485
+ def update_ui():
1486
+ if status in ("SUCCESS", "SAVED_LOCAL"):
1487
+ btn_widget.configure(text="✓ Đã lưu", fg_color="#10B981", state="disabled")
1488
+ try:
1489
+ winsound.Beep(1200, 120)
1490
+ except Exception:
1491
+ pass
1492
+ elif status == "ALREADY_EXISTS":
1493
+ btn_widget.configure(text="✓ Đã có thẻ", fg_color="#64748B", state="disabled")
1494
+ else:
1495
+ btn_widget.configure(text="✓ Đã lưu", fg_color="#10B981", state="disabled")
1496
+
1497
+ self.after(0, update_ui)
1498
+
1499
+ threading.Thread(target=save_task, daemon=True).start()
1500
+
1501
+ def play_audio(self):
1502
+ if not self.current_data:
1503
+ return
1504
+ raw_word = self.current_data.get("word", "")
1505
+ if not raw_word:
1506
+ return
1507
+ lang = self.current_data.get("lang", self.current_lang)
1508
+ word_to_speak = clean_word_stem(raw_word, lang)
1509
+
1510
+ def audio_task():
1511
+ try:
1512
+ cache_dir = os.path.join(APP_DIR, "audio_cache")
1513
+ os.makedirs(cache_dir, exist_ok=True)
1514
+ safe_name = re.sub(r"[^\w\-]", "_", word_to_speak.lower()).strip("_") or "word"
1515
+ mp3_file = os.path.join(cache_dir, f"{safe_name}_{lang}.mp3")
1516
+ tl_code = "en" if lang == "en" else "fr"
1517
+
1518
+ if not os.path.exists(mp3_file) or os.path.getsize(mp3_file) < 500:
1519
+ url = f"https://translate.google.com/translate_tts?ie=UTF-8&q={urllib.parse.quote(word_to_speak)}&tl={tl_code}&client=tw-ob"
1520
+ headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
1521
+ resp = requests.get(url, headers=headers, timeout=4)
1522
+ if resp.status_code == 200 and len(resp.content) > 500:
1523
+ with open(mp3_file, "wb") as f:
1524
+ f.write(resp.content)
1525
+
1526
+ if os.path.exists(mp3_file) and os.path.getsize(mp3_file) > 500:
1527
+ alias = f"audio_{int(time.time() * 1000)}"
1528
+ mci = ctypes.windll.winmm.mciSendStringW
1529
+ mci("close all", None, 0, None)
1530
+ mci(f'open "{mp3_file}" type mpegvideo alias {alias}', None, 0, None)
1531
+ mci(f"play {alias} wait", None, 0, None)
1532
+ mci(f"close {alias}", None, 0, None)
1533
+ return
1534
+ except Exception:
1535
+ pass
1536
+
1537
+ try:
1538
+ escaped = word_to_speak.replace("'", "''")
1539
+ culture_prefix = "en*" if lang == "en" else "fr*"
1540
+ ps_cmd = (
1541
+ f"Add-Type -AssemblyName System.Speech; "
1542
+ f"$s = New-Object System.Speech.Synthesis.SpeechSynthesizer; "
1543
+ f"$v = $s.GetInstalledVoices() | Where-Object {{ $_.VoiceInfo.Culture.Name -like '{culture_prefix}' }} | Select-Object -First 1; "
1544
+ f"if ($v) {{ $s.SelectVoice($v.VoiceInfo.Name) }}; "
1545
+ f"$s.Speak('{escaped}')"
1546
+ )
1547
+ subprocess.run(
1548
+ f'powershell -Command "{ps_cmd}"',
1549
+ shell=True,
1550
+ timeout=5,
1551
+ creationflags=0x08000000 if os.name == "nt" else 0
1552
+ )
1553
+ except Exception:
1554
+ pass
1555
+
1556
+ threading.Thread(target=audio_task, daemon=True).start()
1557
+
1558
+ def toggle_pin(self):
1559
+ self.is_pinned = not self.is_pinned
1560
+ self.attributes("-topmost", self.is_pinned)
1561
+ self.btn_gear.configure(
1562
+ fg_color="#FEF3C7" if self.is_pinned else "transparent",
1563
+ text_color="#D97706" if self.is_pinned else "#64748B"
1564
+ )
1565
+
1566
+ def open_saved_file(self):
1567
+ if self.current_lang == "en":
1568
+ target = EN_LOCAL_LIST_FILE if os.path.exists(EN_LOCAL_LIST_FILE) else EN_LIST_FILE
1569
+ else:
1570
+ target = FR_LOCAL_LIST_FILE if os.path.exists(FR_LOCAL_LIST_FILE) else FR_LIST_FILE
1571
+ if not os.path.exists(target):
1572
+ open(target, "w", encoding="utf-8").close()
1573
+ os.startfile(target)
1574
+
1575
+ # --------------------------------------------------------------------------
1576
+ # 5. BẮT TỪ TOÀN CỤC KHI BÔI ĐEN + NHẤN CTRL 2 LẦN LIÊN TIẾP (DOUBLE-CTRL)
1577
+ # --------------------------------------------------------------------------
1578
+ def _start_global_listener(self):
1579
+ self.kb_controller = keyboard.Controller()
1580
+ self.mouse_pressed = False
1581
+ self.press_pos = (0, 0)
1582
+ self.ctrl_at_press = False
1583
+ self.last_mouse_release = 0.0
1584
+
1585
+ def is_ctrl_pressed_win():
1586
+ return bool(ctypes.windll.user32.GetAsyncKeyState(0x11) & 0x8000)
1587
+
1588
+ def on_key_press(key):
1589
+ if self.is_simulating_copy:
1590
+ return
1591
+ if key in (keyboard.Key.ctrl, keyboard.Key.ctrl_l, keyboard.Key.ctrl_r):
1592
+ if not self.is_ctrl_down:
1593
+ self.is_ctrl_down = True
1594
+ self.other_key_pressed_during_ctrl = False
1595
+ else:
1596
+ if self.is_ctrl_down:
1597
+ self.other_key_pressed_during_ctrl = True
1598
+
1599
+ def on_key_release(key):
1600
+ if self.is_simulating_copy:
1601
+ return
1602
+ if key in (keyboard.Key.ctrl, keyboard.Key.ctrl_l, keyboard.Key.ctrl_r):
1603
+ self.is_ctrl_down = False
1604
+ if not self.other_key_pressed_during_ctrl:
1605
+ now = time.time()
1606
+ delta = now - self.last_ctrl_release_time
1607
+ if 0.04 <= delta <= 0.55:
1608
+ self.last_ctrl_release_time = 0.0
1609
+ threading.Timer(0.03, self._trigger_copy_and_capture).start()
1610
+ else:
1611
+ self.last_ctrl_release_time = now
1612
+ else:
1613
+ self.last_ctrl_release_time = 0.0
1614
+
1615
+ def on_mouse_click(x, y, button, pressed):
1616
+ if button != mouse.Button.left:
1617
+ return
1618
+ now = time.time()
1619
+ if pressed:
1620
+ self.mouse_pressed = True
1621
+ self.press_pos = (x, y)
1622
+ self.ctrl_at_press = self.is_ctrl_down or is_ctrl_pressed_win()
1623
+ else:
1624
+ ctrl_active = self.ctrl_at_press or self.is_ctrl_down or is_ctrl_pressed_win()
1625
+ if ctrl_active and not self.is_simulating_copy:
1626
+ dist = ((x - self.press_pos[0]) ** 2 + (y - self.press_pos[1]) ** 2) ** 0.5
1627
+ is_dbl = (now - self.last_mouse_release) < 0.45
1628
+ self.last_mouse_release = now
1629
+ if dist > 6 or is_dbl:
1630
+ threading.Timer(0.05, self._trigger_copy_and_capture).start()
1631
+ self.mouse_pressed = False
1632
+
1633
+ threading.Thread(
1634
+ target=lambda: keyboard.Listener(on_press=on_key_press, on_release=on_key_release).run(),
1635
+ daemon=True
1636
+ ).start()
1637
+ threading.Thread(
1638
+ target=lambda: mouse.Listener(on_click=on_mouse_click).run(),
1639
+ daemon=True
1640
+ ).start()
1641
+
1642
+ def _trigger_copy_and_capture(self):
1643
+ if self.is_processing_copy:
1644
+ return
1645
+ threading.Thread(target=self._capture_worker, daemon=True).start()
1646
+
1647
+ def _capture_worker(self):
1648
+ self.is_processing_copy = True
1649
+ self.is_simulating_copy = True
1650
+ try:
1651
+ time.sleep(0.04)
1652
+ with self.kb_controller.pressed(keyboard.Key.ctrl):
1653
+ self.kb_controller.press("c")
1654
+ self.kb_controller.release("c")
1655
+
1656
+ time.sleep(0.10)
1657
+ raw_text = pyperclip.paste()
1658
+ if not raw_text:
1659
+ return
1660
+
1661
+ text = raw_text.strip()
1662
+ clean = re.sub(r"^[^\w']+|[^\w']+$", "", text, flags=re.UNICODE)
1663
+ if 1 <= len(clean) <= 60 and "\n" not in clean:
1664
+ self.queue.put(("POPUP_WORD", clean))
1665
+ except Exception as e:
1666
+ print(f"[!] Lỗi bắt từ: {e}")
1667
+ finally:
1668
+ time.sleep(0.08)
1669
+ self.is_simulating_copy = False
1670
+ self.is_processing_copy = False
1671
+
1672
+
1673
+ if __name__ == "__main__":
1674
+ app = MochiVocabCapture()
1675
+ app.mainloop()