hung9066 commited on
Commit
76706ce
·
verified ·
1 Parent(s): a8138b0

Upload Deploy_Va_Dong_Bo_English_Cloud.py

Browse files
Files changed (1) hide show
  1. Deploy_Va_Dong_Bo_English_Cloud.py +254 -0
Deploy_Va_Dong_Bo_English_Cloud.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Công cụ Deploy & Đồng bộ 2 chiều Mochi English Anki Web (Deck: hoc_lom) lên Hugging Face Cloud (Miễn phí 24/7)
4
+ - Static Space Web App: https://huggingface.co/spaces/hung9066/mochi-english-anki
5
+ -> Link chạy trực tiếp 24/7: https://hung9066-mochi-english-anki.static.hf.space
6
+ - Dataset lưu trữ Thẻ & Âm thanh (.mp3): https://huggingface.co/datasets/hung9066/mochi-english-anki-data
7
+ """
8
+ import os
9
+ import sys
10
+ import json
11
+ import time
12
+ from pathlib import Path
13
+ from huggingface_hub import HfApi, CommitOperationAdd
14
+
15
+ try:
16
+ sys.stdout.reconfigure(encoding="utf-8")
17
+ except Exception:
18
+ pass
19
+
20
+ BASE_DIR = Path(__file__).parent.resolve()
21
+ CONFIG_FILE = BASE_DIR / "cloud_config.json"
22
+
23
+ APPDATA = os.environ.get("APPDATA", "")
24
+ PORTABLE_ANKI_BASE = Path(r"E:\AnkiPortable\AnkiData\User 1")
25
+ LOCAL_ANKI_BASE = PORTABLE_ANKI_BASE if PORTABLE_ANKI_BASE.exists() else (Path(APPDATA) / "Anki2" / "User 1")
26
+ LOCAL_ANKI_DB = LOCAL_ANKI_BASE / "collection.anki2"
27
+ LOCAL_ANKI_MEDIA = LOCAL_ANKI_BASE / "collection.media"
28
+
29
+
30
+ def load_config():
31
+ if CONFIG_FILE.exists():
32
+ try:
33
+ return json.loads(CONFIG_FILE.read_text(encoding="utf-8-sig"))
34
+ except Exception:
35
+ pass
36
+ return {}
37
+
38
+
39
+ FIELD_NAMES_29 = [
40
+ "word", "meaning", "pos", "pronunciation", "explain",
41
+ "example", "example_translated", "collocation", "synonym", "antonym",
42
+ "audio_word", "audio_meaning", "audio", "image",
43
+ "choice_1", "choice_2", "choice_3", "choice_4", "correct_choice",
44
+ "choice_word_1", "choice_word_2", "choice_word_3", "choice_word_4", "correct_choice_word",
45
+ "choice_audio_1", "choice_audio_2", "choice_audio_3", "choice_audio_4", "correct_choice_audio"
46
+ ]
47
+
48
+ TOOLS_TXT = Path(r"E:\tools\danh_sach_tu_en.txt")
49
+ QUEUE_TXT = Path(r"E:\AnkiProject\queue\danh_sach_tu_en.txt")
50
+ NOTE_TYPE_NAME = "(Anki) Template học từ vựng của Admin Phúc [2026]"
51
+ TARGET_DECK = "hoc_lom"
52
+
53
+
54
+ def sync_vocab_txt_and_anki(api: HfApi, dataset_repo: str):
55
+ try:
56
+ tools_path = str(Path(r"E:\tools"))
57
+ if tools_path not in sys.path:
58
+ sys.path.insert(0, tools_path)
59
+ import batch_importer_en
60
+ batch_importer_en.run_pipeline()
61
+ except Exception as e:
62
+ print(f" [!] Lỗi đồng bộ danh_sach_tu_en qua batch_importer_en: {e}")
63
+
64
+
65
+ def pull_cloud_reviews_into_anki(api: HfApi, dataset_repo: str):
66
+ import urllib.request
67
+ import server
68
+ url = f"https://huggingface.co/datasets/{dataset_repo}/resolve/main/cloud_reviews.json?t={int(time.time())}"
69
+ try:
70
+ req = urllib.request.Request(url, headers={"Cache-Control": "no-cache"})
71
+ with urllib.request.urlopen(req, timeout=10) as r:
72
+ reviews = json.loads(r.read().decode("utf-8"))
73
+ if isinstance(reviews, dict) and len(reviews) > 0:
74
+ print(f"[0/3] Phát hiện {len(reviews)} lượt ôn tập mới trên Web Cloud Tiếng Anh -> Đang ghi vào Anki máy tính...")
75
+ server.init_progress_db()
76
+ count = 0
77
+ for nid_str, info in reviews.items():
78
+ try:
79
+ nid = int(nid_str)
80
+ correct = bool(info.get("correct", (info.get("level", 1) >= 2)))
81
+ ease = int(info.get("ease", 3 if correct else 1))
82
+ server.record_card_review(nid, correct, ease)
83
+ count += 1
84
+ except Exception:
85
+ pass
86
+ server.flush_pending_anki_writes()
87
+ empty_path = BASE_DIR / "cloud_reviews.json"
88
+ empty_path.write_text("{}", encoding="utf-8")
89
+ api.upload_file(
90
+ path_or_fileobj=str(empty_path),
91
+ path_in_repo="cloud_reviews.json",
92
+ repo_id=dataset_repo,
93
+ repo_type="dataset",
94
+ commit_message=f"Applied {count} English cloud reviews to local Anki"
95
+ )
96
+ print(f" -> Đã cập nhật thành công {count} thẻ từ Web Cloud Tiếng Anh về Anki máy tính!")
97
+ except Exception:
98
+ pass
99
+
100
+
101
+ def export_english_cards_json():
102
+ import server
103
+ print("[1/3] Đang trích xuất danh sách thẻ từ vựng Tiếng Anh (hoc_lom) mới nhất từ Anki...")
104
+ server.init_progress_db()
105
+ server.sync_from_anki_collection(force_overwrite_srs=False)
106
+ data = server.fetch_all_cards_for_web("ALL")
107
+ all_cards = data.get("cards", []) if isinstance(data, dict) else data
108
+
109
+ # Lọc các bộ thẻ hoc_lom (và các bộ thẻ con của hoc_lom) cho Server Tiếng Anh
110
+ en_cards = [c for c in all_cards if str(c.get("deck", "")).lower().startswith("hoc_lom")]
111
+ en_decks = [d for d in data.get("decks", []) if str(d).lower().startswith("hoc_lom")]
112
+ if "hoc_lom" in en_decks:
113
+ en_decks.remove("hoc_lom")
114
+ en_decks.insert(0, "hoc_lom")
115
+
116
+ en_data = {
117
+ "cards": en_cards,
118
+ "decks": en_decks,
119
+ "deck_stats": {k: v for k, v in (data.get("deck_stats") or {}).items() if str(k).lower().startswith("hoc_lom")}
120
+ }
121
+ cards_json_path = BASE_DIR / "cards_data_en.json"
122
+ cards_json_path.write_text(json.dumps(en_data, ensure_ascii=False), encoding="utf-8")
123
+ print(f" -> Đã xuất {len(en_cards)} thẻ Tiếng Anh ({len(en_decks)} bộ thẻ hoc_lom) ra cards_data_en.json ({cards_json_path.stat().st_size / (1024*1024):.2f} MB)")
124
+ return en_cards, cards_json_path
125
+
126
+
127
+ def deploy_static_space(api: HfApi, space_repo: str, cards_json_path: Path):
128
+ print(f"[2/3] Đang tải giao diện Web + Dữ liệu thẻ Tiếng Anh lên Static Space ({space_repo})...")
129
+ api.create_repo(repo_id=space_repo, repo_type="space", space_sdk="static", private=False, exist_ok=True)
130
+
131
+ readme_en = BASE_DIR / "README_en.md"
132
+ readme_en.write_text(
133
+ "---\n"
134
+ "title: Mochi English Anki Web\n"
135
+ "emoji: 📚\n"
136
+ "colorFrom: blue\n"
137
+ "colorTo: green\n"
138
+ "sdk: static\n"
139
+ "pinned: false\n"
140
+ "---\n\n"
141
+ "# Mochi English Anki Web (Deck: hoc_lom)\n",
142
+ encoding="utf-8"
143
+ )
144
+
145
+ ops = [
146
+ CommitOperationAdd(path_in_repo="index.html", path_or_fileobj=str(BASE_DIR / "index.html")),
147
+ CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=str(readme_en)),
148
+ CommitOperationAdd(path_in_repo="cards_data.json", path_or_fileobj=str(cards_json_path)),
149
+ ]
150
+ if (BASE_DIR / "mochi_logo.png").exists():
151
+ ops.append(CommitOperationAdd(path_in_repo="mochi_logo.png", path_or_fileobj=str(BASE_DIR / "mochi_logo.png")))
152
+
153
+ assets_dir = BASE_DIR / "assets"
154
+ if assets_dir.exists():
155
+ for f in assets_dir.iterdir():
156
+ if f.is_file():
157
+ ops.append(CommitOperationAdd(path_in_repo=f"assets/{f.name}", path_or_fileobj=str(f)))
158
+
159
+ api.create_commit(
160
+ repo_id=space_repo,
161
+ repo_type="space",
162
+ operations=ops,
163
+ commit_message="Deploy Mochi English Anki Web 24/7 Static Space (hoc_lom)"
164
+ )
165
+ print(" -> Đã cập nhật xong Web App Tiếng Anh tại: https://hung9066-mochi-english-anki.static.hf.space")
166
+
167
+
168
+ def deploy_dataset_and_media(api: HfApi, dataset_repo: str, cards: list, cards_json_path: Path, upload_media: bool = True):
169
+ print(f"[3/3] Đang đồng bộ Dataset Tiếng Anh ({dataset_repo})...")
170
+ api.create_repo(repo_id=dataset_repo, repo_type="dataset", private=False, exist_ok=True)
171
+
172
+ api.upload_file(
173
+ path_or_fileobj=str(cards_json_path),
174
+ path_in_repo="cards_data.json",
175
+ repo_id=dataset_repo,
176
+ repo_type="dataset",
177
+ commit_message="Sync English cards_data.json (hoc_lom)"
178
+ )
179
+ print(" -> Đã đồng bộ cards_data.json lên Dataset Tiếng Anh!")
180
+
181
+ if not upload_media or not LOCAL_ANKI_MEDIA.exists():
182
+ return
183
+
184
+ needed_media = set()
185
+ for c in cards:
186
+ if not isinstance(c, dict):
187
+ continue
188
+ if c.get("word_audio"):
189
+ needed_media.add(c["word_audio"])
190
+ if c.get("example_audio"):
191
+ needed_media.add(c["example_audio"])
192
+ for opt in c.get("audio_choices", []):
193
+ if isinstance(opt, dict) and opt.get("audio"):
194
+ needed_media.add(opt["audio"])
195
+
196
+ try:
197
+ existing_files = set(api.list_repo_files(repo_id=dataset_repo, repo_type="dataset"))
198
+ except Exception:
199
+ existing_files = set()
200
+
201
+ to_upload = []
202
+ for m in sorted(needed_media):
203
+ repo_path = f"media/{m}"
204
+ if repo_path not in existing_files:
205
+ src = LOCAL_ANKI_MEDIA / m
206
+ if src.exists():
207
+ to_upload.append((repo_path, src))
208
+
209
+ if not to_upload:
210
+ print(f" -> Toàn bộ {len(needed_media)} file âm thanh Tiếng Anh (.mp3) đã có sẵn trên Cloud!")
211
+ return
212
+
213
+ print(f" -> Đang tải lên {len(to_upload)} file âm thanh Tiếng Anh (.mp3) mới theo từng cụm (batches)...")
214
+ batch_size = 600
215
+ total_batches = (len(to_upload) + batch_size - 1) // batch_size
216
+ for b_idx in range(total_batches):
217
+ batch = to_upload[b_idx * batch_size : (b_idx + 1) * batch_size]
218
+ ops = [
219
+ CommitOperationAdd(path_in_repo=repo_path, path_or_fileobj=str(src_path))
220
+ for repo_path, src_path in batch
221
+ ]
222
+ print(f" + Đang tải cụm {b_idx + 1}/{total_batches} ({len(ops)} files)...")
223
+ api.create_commit(
224
+ repo_id=dataset_repo,
225
+ repo_type="dataset",
226
+ operations=ops,
227
+ commit_message=f"Upload English audio batch {b_idx + 1}/{total_batches}",
228
+ num_threads=16
229
+ )
230
+ print(" -> Hoàn tất tải toàn bộ âm thanh Tiếng Anh lên Cloud!")
231
+
232
+
233
+ def main():
234
+ cfg = load_config()
235
+ token = (cfg.get("token") or cfg.get("hf_token") or "").strip()
236
+ username = cfg.get("username", "hung9066").strip()
237
+ space_repo = f"{username}/mochi-english-anki"
238
+ dataset_repo = f"{username}/mochi-english-anki-data"
239
+
240
+ if not token:
241
+ print("[LỖI] Chưa có token trong cloud_config.json")
242
+ return
243
+
244
+ api = HfApi(token=token)
245
+ sync_vocab_txt_and_anki(api, dataset_repo)
246
+ pull_cloud_reviews_into_anki(api, dataset_repo)
247
+ cards, cards_json_path = export_english_cards_json()
248
+ deploy_static_space(api, space_repo, cards_json_path)
249
+ upload_media = "--skip-media" not in sys.argv
250
+ deploy_dataset_and_media(api, dataset_repo, cards, cards_json_path, upload_media=upload_media)
251
+
252
+
253
+ if __name__ == "__main__":
254
+ main()