Download Deploy_Va_Dong_Bo_English_Cloud.py from hung9066/QuickVocabCapture: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/hung9066/QuickVocabCapture/resolve/main/Deploy_Va_Dong_Bo_English_Cloud.py
- Command line
-
hf download hf://datasets/hung9066/QuickVocabCapture/Deploy_Va_Dong_Bo_English_Cloud.py
-
curl -L -o Deploy_Va_Dong_Bo_English_Cloud.py https://huggingface.co/datasets/hung9066/QuickVocabCapture/resolve/main/Deploy_Va_Dong_Bo_English_Cloud.py
10.4 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| 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) | |
| - Static Space Web App: https://huggingface.co/spaces/hung9066/mochi-english-anki | |
| -> Link chạy trực tiếp 24/7: https://hung9066-mochi-english-anki.static.hf.space | |
| - Dataset lưu trữ Thẻ & Âm thanh (.mp3): https://huggingface.co/datasets/hung9066/mochi-english-anki-data | |
| """ | |
| import os | |
| import sys | |
| import json | |
| import time | |
| from pathlib import Path | |
| from huggingface_hub import HfApi, CommitOperationAdd | |
| try: | |
| sys.stdout.reconfigure(encoding="utf-8") | |
| except Exception: | |
| pass | |
| BASE_DIR = Path(__file__).parent.resolve() | |
| CONFIG_FILE = BASE_DIR / "cloud_config.json" | |
| APPDATA = os.environ.get("APPDATA", "") | |
| PORTABLE_ANKI_BASE = Path(r"E:\AnkiPortable\AnkiData\User 1") | |
| LOCAL_ANKI_BASE = PORTABLE_ANKI_BASE if PORTABLE_ANKI_BASE.exists() else (Path(APPDATA) / "Anki2" / "User 1") | |
| LOCAL_ANKI_DB = LOCAL_ANKI_BASE / "collection.anki2" | |
| LOCAL_ANKI_MEDIA = LOCAL_ANKI_BASE / "collection.media" | |
| def load_config(): | |
| if CONFIG_FILE.exists(): | |
| try: | |
| return json.loads(CONFIG_FILE.read_text(encoding="utf-8-sig")) | |
| except Exception: | |
| pass | |
| return {} | |
| FIELD_NAMES_29 = [ | |
| "word", "meaning", "pos", "pronunciation", "explain", | |
| "example", "example_translated", "collocation", "synonym", "antonym", | |
| "audio_word", "audio_meaning", "audio", "image", | |
| "choice_1", "choice_2", "choice_3", "choice_4", "correct_choice", | |
| "choice_word_1", "choice_word_2", "choice_word_3", "choice_word_4", "correct_choice_word", | |
| "choice_audio_1", "choice_audio_2", "choice_audio_3", "choice_audio_4", "correct_choice_audio" | |
| ] | |
| TOOLS_TXT = Path(r"E:\tools\danh_sach_tu_en.txt") | |
| QUEUE_TXT = Path(r"E:\AnkiProject\queue\danh_sach_tu_en.txt") | |
| NOTE_TYPE_NAME = "(Anki) Template học từ vựng của Admin Phúc [2026]" | |
| TARGET_DECK = "hoc_lom" | |
| def sync_vocab_txt_and_anki(api: HfApi, dataset_repo: str): | |
| try: | |
| tools_path = str(Path(r"E:\tools")) | |
| if tools_path not in sys.path: | |
| sys.path.insert(0, tools_path) | |
| import batch_importer_en | |
| batch_importer_en.run_pipeline() | |
| except Exception as e: | |
| print(f" [!] Lỗi đồng bộ danh_sach_tu_en qua batch_importer_en: {e}") | |
| def pull_cloud_reviews_into_anki(api: HfApi, dataset_repo: str): | |
| import urllib.request | |
| import server | |
| url = f"https://huggingface.co/datasets/{dataset_repo}/resolve/main/cloud_reviews.json?t={int(time.time())}" | |
| try: | |
| req = urllib.request.Request(url, headers={"Cache-Control": "no-cache"}) | |
| with urllib.request.urlopen(req, timeout=10) as r: | |
| reviews = json.loads(r.read().decode("utf-8")) | |
| if isinstance(reviews, dict) and len(reviews) > 0: | |
| 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...") | |
| server.init_progress_db() | |
| count = 0 | |
| for nid_str, info in reviews.items(): | |
| try: | |
| nid = int(nid_str) | |
| correct = bool(info.get("correct", (info.get("level", 1) >= 2))) | |
| ease = int(info.get("ease", 3 if correct else 1)) | |
| server.record_card_review(nid, correct, ease) | |
| count += 1 | |
| except Exception: | |
| pass | |
| server.flush_pending_anki_writes() | |
| empty_path = BASE_DIR / "cloud_reviews.json" | |
| empty_path.write_text("{}", encoding="utf-8") | |
| api.upload_file( | |
| path_or_fileobj=str(empty_path), | |
| path_in_repo="cloud_reviews.json", | |
| repo_id=dataset_repo, | |
| repo_type="dataset", | |
| commit_message=f"Applied {count} English cloud reviews to local Anki" | |
| ) | |
| print(f" -> Đã cập nhật thành công {count} thẻ từ Web Cloud Tiếng Anh về Anki máy tính!") | |
| except Exception: | |
| pass | |
| def export_english_cards_json(): | |
| import server | |
| 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...") | |
| server.init_progress_db() | |
| server.sync_from_anki_collection(force_overwrite_srs=False) | |
| data = server.fetch_all_cards_for_web("ALL") | |
| all_cards = data.get("cards", []) if isinstance(data, dict) else data | |
| # Lọc các bộ thẻ hoc_lom (và các bộ thẻ con của hoc_lom) cho Server Tiếng Anh | |
| en_cards = [c for c in all_cards if str(c.get("deck", "")).lower().startswith("hoc_lom")] | |
| en_decks = [d for d in data.get("decks", []) if str(d).lower().startswith("hoc_lom")] | |
| if "hoc_lom" in en_decks: | |
| en_decks.remove("hoc_lom") | |
| en_decks.insert(0, "hoc_lom") | |
| en_data = { | |
| "cards": en_cards, | |
| "decks": en_decks, | |
| "deck_stats": {k: v for k, v in (data.get("deck_stats") or {}).items() if str(k).lower().startswith("hoc_lom")} | |
| } | |
| cards_json_path = BASE_DIR / "cards_data_en.json" | |
| cards_json_path.write_text(json.dumps(en_data, ensure_ascii=False), encoding="utf-8") | |
| 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)") | |
| return en_cards, cards_json_path | |
| def deploy_static_space(api: HfApi, space_repo: str, cards_json_path: Path): | |
| print(f"[2/3] Đang tải giao diện Web + Dữ liệu thẻ Tiếng Anh lên Static Space ({space_repo})...") | |
| api.create_repo(repo_id=space_repo, repo_type="space", space_sdk="static", private=False, exist_ok=True) | |
| readme_en = BASE_DIR / "README_en.md" | |
| readme_en.write_text( | |
| "---\n" | |
| "title: Mochi English Anki Web\n" | |
| "emoji: 📚\n" | |
| "colorFrom: blue\n" | |
| "colorTo: green\n" | |
| "sdk: static\n" | |
| "pinned: false\n" | |
| "---\n\n" | |
| "# Mochi English Anki Web (Deck: hoc_lom)\n", | |
| encoding="utf-8" | |
| ) | |
| ops = [ | |
| CommitOperationAdd(path_in_repo="index.html", path_or_fileobj=str(BASE_DIR / "index.html")), | |
| CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=str(readme_en)), | |
| CommitOperationAdd(path_in_repo="cards_data.json", path_or_fileobj=str(cards_json_path)), | |
| ] | |
| if (BASE_DIR / "mochi_logo.png").exists(): | |
| ops.append(CommitOperationAdd(path_in_repo="mochi_logo.png", path_or_fileobj=str(BASE_DIR / "mochi_logo.png"))) | |
| assets_dir = BASE_DIR / "assets" | |
| if assets_dir.exists(): | |
| for f in assets_dir.iterdir(): | |
| if f.is_file(): | |
| ops.append(CommitOperationAdd(path_in_repo=f"assets/{f.name}", path_or_fileobj=str(f))) | |
| api.create_commit( | |
| repo_id=space_repo, | |
| repo_type="space", | |
| operations=ops, | |
| commit_message="Deploy Mochi English Anki Web 24/7 Static Space (hoc_lom)" | |
| ) | |
| print(" -> Đã cập nhật xong Web App Tiếng Anh tại: https://hung9066-mochi-english-anki.static.hf.space") | |
| def deploy_dataset_and_media(api: HfApi, dataset_repo: str, cards: list, cards_json_path: Path, upload_media: bool = True): | |
| print(f"[3/3] Đang đồng bộ Dataset Tiếng Anh ({dataset_repo})...") | |
| api.create_repo(repo_id=dataset_repo, repo_type="dataset", private=False, exist_ok=True) | |
| api.upload_file( | |
| path_or_fileobj=str(cards_json_path), | |
| path_in_repo="cards_data.json", | |
| repo_id=dataset_repo, | |
| repo_type="dataset", | |
| commit_message="Sync English cards_data.json (hoc_lom)" | |
| ) | |
| print(" -> Đã đồng bộ cards_data.json lên Dataset Tiếng Anh!") | |
| if not upload_media or not LOCAL_ANKI_MEDIA.exists(): | |
| return | |
| needed_media = set() | |
| for c in cards: | |
| if not isinstance(c, dict): | |
| continue | |
| if c.get("word_audio"): | |
| needed_media.add(c["word_audio"]) | |
| if c.get("example_audio"): | |
| needed_media.add(c["example_audio"]) | |
| for opt in c.get("audio_choices", []): | |
| if isinstance(opt, dict) and opt.get("audio"): | |
| needed_media.add(opt["audio"]) | |
| try: | |
| existing_files = set(api.list_repo_files(repo_id=dataset_repo, repo_type="dataset")) | |
| except Exception: | |
| existing_files = set() | |
| to_upload = [] | |
| for m in sorted(needed_media): | |
| repo_path = f"media/{m}" | |
| if repo_path not in existing_files: | |
| src = LOCAL_ANKI_MEDIA / m | |
| if src.exists(): | |
| to_upload.append((repo_path, src)) | |
| if not to_upload: | |
| print(f" -> Toàn bộ {len(needed_media)} file âm thanh Tiếng Anh (.mp3) đã có sẵn trên Cloud!") | |
| return | |
| 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)...") | |
| batch_size = 600 | |
| total_batches = (len(to_upload) + batch_size - 1) // batch_size | |
| for b_idx in range(total_batches): | |
| batch = to_upload[b_idx * batch_size : (b_idx + 1) * batch_size] | |
| ops = [ | |
| CommitOperationAdd(path_in_repo=repo_path, path_or_fileobj=str(src_path)) | |
| for repo_path, src_path in batch | |
| ] | |
| print(f" + Đang tải cụm {b_idx + 1}/{total_batches} ({len(ops)} files)...") | |
| api.create_commit( | |
| repo_id=dataset_repo, | |
| repo_type="dataset", | |
| operations=ops, | |
| commit_message=f"Upload English audio batch {b_idx + 1}/{total_batches}", | |
| num_threads=16 | |
| ) | |
| print(" -> Hoàn tất tải toàn bộ âm thanh Tiếng Anh lên Cloud!") | |
| def main(): | |
| cfg = load_config() | |
| token = (cfg.get("token") or cfg.get("hf_token") or "").strip() | |
| username = cfg.get("username", "hung9066").strip() | |
| space_repo = f"{username}/mochi-english-anki" | |
| dataset_repo = f"{username}/mochi-english-anki-data" | |
| if not token: | |
| print("[LỖI] Chưa có token trong cloud_config.json") | |
| return | |
| api = HfApi(token=token) | |
| sync_vocab_txt_and_anki(api, dataset_repo) | |
| pull_cloud_reviews_into_anki(api, dataset_repo) | |
| cards, cards_json_path = export_english_cards_json() | |
| deploy_static_space(api, space_repo, cards_json_path) | |
| upload_media = "--skip-media" not in sys.argv | |
| deploy_dataset_and_media(api, dataset_repo, cards, cards_json_path, upload_media=upload_media) | |
| if __name__ == "__main__": | |
| main() | |