File size: 6,805 Bytes
dde483a
 
 
 
 
 
 
 
 
 
f07f610
 
 
 
 
dde483a
 
 
 
 
 
 
 
 
 
 
 
 
4a29017
dde483a
 
 
 
 
 
 
06ea87b
dde483a
 
 
 
 
 
 
 
 
f07f610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dde483a
f9bfd83
f07f610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dde483a
f07f610
dde483a
f07f610
dde483a
 
 
 
f07f610
dde483a
 
 
f07f610
 
dde483a
 
f07f610
 
dde483a
 
f07f610
dde483a
 
f07f610
dde483a
 
 
f07f610
 
dde483a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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")

@app.get("/")
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
@app.post("/check-new-samples")
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️⃣: 模擬人工標註後的訓練
# ============================================================
@app.post("/train-from-labeled")
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 分支
# ============================================================
@app.get("/list-lora-cache")
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️⃣: 健康檢查
# ============================================================
@app.get("/health")
def health_check():
    return {
        "status": "running",
        "mode": "demo",
        "connected_to": SPACE_A_URL,
        "branches": SIMULATED_BRANCHES
    }