Spaces:
Sleeping
Sleeping
Download app.py from malvec/model_update_test: direct link, hf CLI and curl.
- Browser
- Download file 6.81 kB
-
https://huggingface.co/spaces/malvec/model_update_test/resolve/main/app.py
- Command line
-
hf download hf://spaces/malvec/model_update_test/app.py
-
curl -L -o app.py https://huggingface.co/spaces/malvec/model_update_test/resolve/main/app.py
6.81 kB
| from fastapi import FastAPI | |
| import os, random, time, json | |
| from fastapi import FastAPI, Query | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import httpx | |
| # ============================================================ | |
| # app_spaceB_demo.py — Demo版 Active Learning Space (模擬流程) | |
| # ============================================================ | |
| # === 全域計數器 === | |
| FILE_COUNTER = 0 | |
| FILE_THRESHOLD = 1000 | |
| # === FastAPI 初始化 === | |
| app = FastAPI( | |
| title="Malvec Space B (Demo)", | |
| description="Simulated Active Learning backend, connected to real Space A.", | |
| version="demo-2.0" | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], allow_methods=["*"], allow_headers=["*"] | |
| ) | |
| # === 模擬參數 ===(這邊你可以把它改成你想要的md5) | |
| SIMULATED_BRANCHES = ["round_1", "round_2", "round_3"] | |
| SIMULATED_FILES = [ | |
| "dropper_payload.exe", "trojbanker_loader.exe", | |
| "ransom_v2.exe", "spyeye_injector.exe", "worm_autoexec.exe" | |
| ] | |
| # === Space A 連線設定(請改成你的真實 Space A API endpoint)=== | |
| SPACE_A_URL = os.getenv("SPACE_A_URL", "https://malvec-test.hf.space") | |
| def greet_json(): | |
| return {"Hello": "World!"} | |
| # ============================================================ | |
| # 🧠 Endpoint 1️⃣: 模擬 Entropy 決策 | |
| # ============================================================ | |
| # @app.post("/check-new-samples") | |
| # def check_new_samples(entropy_threshold: float = Query(0.9)): | |
| # """ | |
| # 模擬 Active Learning 決策: | |
| # entropy 隨機 → 若高於門檻則要求人工標註; | |
| # 否則推薦既有模型分支。 | |
| # """ | |
| # mean_entropy = round(random.uniform(0.5, 1.5), 3) | |
| # print(f"[Demo B] 模擬 mean_entropy={mean_entropy}") | |
| # # 高熵 → 模擬需要人工標註 | |
| # if mean_entropy > entropy_threshold: | |
| # samples = random.sample(SIMULATED_FILES, k=min(3, len(SIMULATED_FILES))) | |
| # label_file = f"./demo_selected_for_labeling_{time.strftime('%H%M%S')}.json" | |
| # result = { | |
| # "status": "need_labeling", | |
| # "mean_entropy": mean_entropy, | |
| # "samples_to_label": [ | |
| # {"source": s, "entropy": round(random.uniform(1.2, 1.8), 3)} for s in samples | |
| # ], | |
| # "label_file": label_file, | |
| # "cached_branches": len(SIMULATED_BRANCHES) | |
| # } | |
| # print(f"⚠️ 高熵 → 請人工標註: {samples}") | |
| # print(result) | |
| # return result | |
| # # 低熵 → 模擬選擇最佳分支 | |
| # else: | |
| # branch = random.choice(SIMULATED_BRANCHES) | |
| # result = { | |
| # "status": "use_existing_model", | |
| # "recommended_branch": branch, | |
| # "mean_entropy": mean_entropy, | |
| # "cached_branches": len(SIMULATED_BRANCHES) | |
| # } | |
| # print(f"✅ 低熵 → 推薦使用分支: {branch}") | |
| # print(result) | |
| # return result | |
| def check_new_samples(entropy_threshold: float = Query(0.9)): | |
| global FILE_COUNTER | |
| # Demo: 每次呼叫視為一個新 sample | |
| FILE_COUNTER += 1 | |
| print(f"[Demo B] Accumulated samples: {FILE_COUNTER}/{FILE_THRESHOLD}") | |
| # 未達 1000 → 只回覆「累積中」 | |
| if FILE_COUNTER < FILE_THRESHOLD: | |
| return { | |
| "status": "accumulating", | |
| "received_samples": FILE_COUNTER, | |
| "remaining": FILE_THRESHOLD - FILE_COUNTER | |
| } | |
| # === 達到 1000 隻 → 執行一次 entropy 評估 === | |
| FILE_COUNTER = 0 # reset | |
| mean_entropy = round(random.uniform(0.5, 1.5), 3) | |
| print(f"[Demo B] Batch entropy evaluation: mean_entropy={mean_entropy}") | |
| # 高熵(需要人工標註) | |
| if mean_entropy > entropy_threshold: | |
| samples = random.sample(SIMULATED_FILES, k=min(3, len(SIMULATED_FILES))) | |
| label_file = f"./demo_selected_for_labeling_{time.strftime('%H%M%S')}.json" | |
| return { | |
| "status": "need_labeling", | |
| "mean_entropy": mean_entropy, | |
| "samples_to_label": [ | |
| {"source": s, "entropy": round(random.uniform(1.2, 1.8), 3)} | |
| for s in samples | |
| ], | |
| "label_file": label_file, | |
| "cached_branches": len(SIMULATED_BRANCHES), | |
| "batch_size": FILE_THRESHOLD | |
| } | |
| # 低熵(選 existing branch) | |
| else: | |
| branch = random.choice(SIMULATED_BRANCHES) | |
| return { | |
| "status": "use_existing_model", | |
| "recommended_branch": branch, | |
| "mean_entropy": mean_entropy, | |
| "cached_branches": len(SIMULATED_BRANCHES), | |
| "batch_size": FILE_THRESHOLD | |
| } | |
| # ============================================================ | |
| # 🧩 Endpoint 2️⃣: 模擬人工標註後的訓練 | |
| # ============================================================ | |
| async def train_from_labeled(label_file: str = Query(...)): | |
| """ | |
| 模擬人工標註完成後自動更新模型(假訓練) | |
| 並通知真正的 Space A。 | |
| """ | |
| print(f"🧠 模擬訓練資料: {label_file}") | |
| time.sleep(2.0) | |
| tag = f"demo-al-{time.strftime('%H%M%S')}" | |
| payload = {"status": "updated", "tag": tag} | |
| print(f"📡 通知 Space A: {payload}") | |
| try: | |
| async with httpx.AsyncClient(timeout=10) as client: | |
| resp = await client.post(SPACE_A_URL, json=payload) | |
| print(f"✅ Space A 回應: {resp.status_code}") | |
| return { | |
| "status": "ok", | |
| "output_dir": f"./demo_output/{tag}", | |
| "tag": tag, | |
| "notified_spaceA": True, | |
| "spaceA_response": resp.text | |
| } | |
| except Exception as e: | |
| print(f"⚠️ 通知 Space A 失敗: {e}") | |
| return { | |
| "status": "ok", | |
| "output_dir": f"./demo_output/{tag}", | |
| "tag": tag, | |
| "notified_spaceA": False, | |
| "error": str(e) | |
| } | |
| # ============================================================ | |
| # 🧭 Endpoint 3️⃣: 模擬列出快取 LoRA 分支 | |
| # ============================================================ | |
| def list_lora_cache(): | |
| branches = [{"branch": b, "num_samples": random.randint(600, 1200)} for b in SIMULATED_BRANCHES] | |
| print("[Demo B] 回傳模擬 LoRA 分支列表") | |
| return {"status": "ok", "total_branches": len(branches), "branches": branches} | |
| # ============================================================ | |
| # ❤️ Endpoint 4️⃣: 健康檢查 | |
| # ============================================================ | |
| def health_check(): | |
| return { | |
| "status": "running", | |
| "mode": "demo", | |
| "connected_to": SPACE_A_URL, | |
| "branches": SIMULATED_BRANCHES | |
| } | |