Download app.py from malvec/test: direct link, hf CLI and curl.
- Browser
- Download file 38.8 kB
-
https://huggingface.co/spaces/malvec/test/resolve/main/app.py
- Command line
-
hf download hf://spaces/malvec/test/app.py
-
curl -L -o app.py https://huggingface.co/spaces/malvec/test/resolve/main/app.py
38.8 kB
import os
import json
import httpx
import torch
from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from typing import List, Optional, Dict
from collections import Counter
from fastapi.staticfiles import StaticFiles
from huggingface_hub import HfApi,hf_hub_download
import datetime
import csv, sys
import io
import numpy as np
from datasets import load_dataset
import time # ✨ 新增:用來量測 performance
import psutil
import shutil
import platform
# ⚠️ 注意: som_analyzer.py 必須存在於同一目錄
try:
from som_analyzer import SOMAnalyzer
SOM_FILE_AVAILABLE = True
except ImportError:
print("⚠️ WARNING: 'som_analyzer.py' not found. SOM features will be disabled.")
SOM_FILE_AVAILABLE = False
CURRENT_TAG = os.getenv("MODEL_TAG", "main")
# ====== FastAPI 初始化 ======
app = FastAPI(
title="Malvec Prediction Space (A)",
description="Handles inference and optionally triggers LoRA fine-tuning (Space B).",
version="1.3"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ====== 模型設定 ======
MODEL_REPO = os.getenv("MODEL_REPO", "malvec/Malvec_predict")
HF_TOKEN = os.getenv("HF_TOKEN")
DEVICE = torch.device("cpu")
HF_DATASET_REPO = "lyi029/malvec-embeddings-new"
# ====== 連接 Space B ======
SPACE_B_URL = os.getenv("SPACE_B_URL", "https://malvec-model-update-test.hf.space")
# ====== Cache & 目錄 ======
CACHE_DIR = "/tmp/hf_cache"
os.environ.update({
"HF_HOME": CACHE_DIR,
"TRANSFORMERS_CACHE": CACHE_DIR,
"HUGGINGFACE_HUB_CACHE": CACHE_DIR
})
os.makedirs(CACHE_DIR, exist_ok=True)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
RESULT_DIR = os.path.join(BASE_DIR, "results")
os.makedirs("results", exist_ok=True)
app.mount("/results", StaticFiles(directory=RESULT_DIR), name="results")
# ====== 簡單 Performance 統計 ======
PERF_STATS = {
"predict_calls": 0,
"predict_total_seconds": 0.0,
"predict_last_ms": 0.0,
"predict_last_files": 0,
"last_updated": None,
}
# ====== 載入模型 ======
print("🤗 Loading model from:", MODEL_REPO)
tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, token=HF_TOKEN)
model = AutoModelForSequenceClassification.from_pretrained(
MODEL_REPO,
token=HF_TOKEN,
output_attentions=True,
output_hidden_states=True
)
model.to(DEVICE).eval()
print("✅ Model loaded successfully")
# ===== 新增:載入 SOM 模型 (from app.py) =====
print("🧠 Initializing SOM Analyzer...")
SOM_REPO = os.getenv("SOM_REPO", "malvec/codebert_Malvec") # ✨ 補上 SOM_REPO,避免 NameError
SOM_AVAILABLE = False
if SOM_FILE_AVAILABLE: # 檢查 'som_analyzer.py' 是否 import 成功
try:
# ✅ 直接使用 repo 內的本地檔案
# (假設 app.py 和 .npy/.pkl 檔案在同一層級)
print(" Loading SOM files from local repository...")
som_weights_path = "som_weights.npy"
background_data_path = "som_background_data.pkl"
# 檢查檔案是否存在
if not os.path.exists(som_weights_path):
raise FileNotFoundError(f"{som_weights_path} not found in this repo.")
if not os.path.exists(background_data_path):
raise FileNotFoundError(f"{background_data_path} not found in this repo.")
print(" Local files found.")
som_analyzer = SOMAnalyzer(
som_weights_path=som_weights_path,
background_data_path=background_data_path
)
print("✅ SOM Analyzer initialized successfully!")
SOM_AVAILABLE = True
except Exception as e:
print(f"⚠️ SOM Analyzer initialization failed: {e}")
print(" SOM analysis will be disabled")
else:
print(" SOM analysis disabled because 'som_analyzer.py' is missing.")
# ----------------------------------------------------------
# ROUTES
# ----------------------------------------------------------
@app.get("/")
def home():
return {
"message": "Malware Classifier API (Space A) with SOM", # ✨
"model": MODEL_REPO,
"space_b_url": SPACE_B_URL,
"som_status": "Available" if SOM_AVAILABLE else "Disabled", # ✨
"endpoints": {
"/predict": "POST - Upload TXT files for prediction (with SOM)",
"/predict-batch": "POST - Simplified batch prediction (from app.py)",
"/model-info": "GET - Get model information",
"/attention-heatmap": "POST - Generate attention heatmap (with CLIP)",
"/check-new-samples": "POST - Trigger Space B Active Learning",
"/performance": "GET - Simple runtime performance stats" # ✨ 新增說明
}
}
@app.get("/model-info")
def get_model_info():
"""取得模型資訊"""
id2label_sample = {}
if hasattr(model.config, 'id2label'):
sample_keys = list(model.config.id2label.keys())[:3]
id2label_sample = {
k: {"type": str(type(k).__name__), "value": model.config.id2label[k]}
for k in sample_keys
}
return {
"model_name": MODEL_REPO,
"current_tag": CURRENT_TAG, # 👈 回報目前版本
"num_labels": model.config.num_labels,
"labels": list(model.config.id2label.values())
if hasattr(model.config, 'id2label') else None,
"device": str(DEVICE),
"id2label_sample": id2label_sample,
"som_model_repo": SOM_REPO, # ✨
"som_available": SOM_AVAILABLE # ✨
}
HF_DATASET_REPO = "lyi029/malvec-embeddings-new"
def upload_embeddings_to_hub(local_path: str):
"""自動建立 Dataset 並分批上傳 embeddings_log.jsonl"""
api = HfApi()
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
remote_path = f"logs/embeddings_{timestamp}.jsonl"
try:
# 確認 Dataset 存在
try:
api.dataset_info(repo_id=HF_DATASET_REPO, token=HF_TOKEN)
print(f"📂 Dataset {HF_DATASET_REPO} 已存在。")
except Exception as e:
if e.response is not None and e.response.status_code == 404:
print(f"🆕 Dataset 不存在,建立中...")
api.create_repo(repo_id=HF_DATASET_REPO, repo_type="dataset", token=HF_TOKEN)
print(f"✅ 已建立 Dataset: {HF_DATASET_REPO}")
else:
raise
print(f"🚀 上傳 {local_path} → {HF_DATASET_REPO}/{remote_path}")
api.upload_file(
path_or_fileobj=local_path,
path_in_repo=remote_path,
repo_id=HF_DATASET_REPO,
repo_type="dataset",
token=HF_TOKEN,
)
print(f"☁️ 已上傳 embeddings 至 {HF_DATASET_REPO}/{remote_path}")
# 上傳後清空本地檔案(避免爆 container)
open(local_path, "w").close()
print(f"🧹 已清空本地 {local_path}")
return True
except Exception as e:
print(f"❌ HF API HTTP error: {e.response.status_code} - {e.response.text}")
return False
except Exception as e:
import traceback
print("❌ Upload failed:", e)
traceback.print_exc()
return False
# ----------------------------------------------------------
# 新增:SOM 輔助函數 (from app.py)
# ----------------------------------------------------------
async def get_embeddings_from_hf_dataset(filename: str) -> Optional[List[np.ndarray]]:
""" (from app.py) """
try:
base_name = filename.rsplit('.', 1)[0].lower()
print(f"\n📦 Fetching embeddings from HF dataset for base name: {base_name}")
dataset = load_dataset("lyi029/malvec-embeddings-new", split="train", streaming=True)
embeddings = []
count = 0
for sample in dataset:
sample_filename = sample.get('source', '') or sample.get('filename', '')
# ✅ 2. 檢查 dataset source (例如 "unpacked_myfile_67.txt")
# 是否 *包含* 這個基礎檔名 (例如 "myfile_67")
if base_name in sample_filename.lower():
emb = sample.get('embedding') or sample.get('emb')
if emb is not None:
embeddings.append(np.array(emb, dtype=np.float32))
count += 1
if count >= 1000: break # 保留限制
if embeddings:
print(f"✅ Found {len(embeddings)} embeddings for base name {base_name}")
return embeddings
else:
print(f"⚠️ No embeddings found for base name {base_name} in dataset")
return None
except Exception as e:
print(f"❌ Error fetching from HF dataset: {e}")
return None
def analyze_som_region_probability(
som_analyzer: SOMAnalyzer,
center_row: int,
center_col: int,
embeddings: List[np.ndarray],
radius: int = 2
) -> Dict[str, float]:
""" (from app.py) """
print(f" 🔍 Analyzing region around ({center_row}, {center_col}) with radius={radius}")
region_samples = []
for emb in embeddings:
sample_row, sample_col = som_analyzer.som.winner(emb) #
if abs(sample_row - center_row) <= radius and abs(sample_col - center_col) <= radius:
region_samples.append(emb)
print(f" Found {len(region_samples)} samples in region")
if len(region_samples) == 0:
return {"dropper": 0.0, "APT30": 0.0}
feature_counts = {"dropper": [], "spreader": [], "APT30": [], "Codoso_Gh0st_1": []}
if hasattr(som_analyzer, 'background_embeddings') and hasattr(som_analyzer, 'background_labels'):
for i, bg_emb in enumerate(som_analyzer.background_embeddings):
bg_row, bg_col = som_analyzer.som.winner(bg_emb) #
if abs(bg_row - center_row) <= radius and abs(bg_col - center_col) <= radius:
for feature_name in feature_counts.keys():
if feature_name in som_analyzer.background_labels:
feature_counts[feature_name].append(
som_analyzer.background_labels[feature_name][i]
)
probabilities = {}
for feature_name, values in feature_counts.items():
if len(values) > 0:
prob = sum(values) / len(values)
probabilities[feature_name] = float(prob)
else:
probabilities[feature_name] = 0.0
return probabilities
async def analyze_with_som(embedding, predicted_family, filename):
"""
(from app.py)
✨ 修改後的 SOM 分析邏輯:
1. 優先從 HF Dataset 抓取 embeddings。
2. 如果找到,用它們的「平均值」來決定座標。
3. 如果沒找到,才用模型即時產生的 embedding。
"""
if not SOM_AVAILABLE:
print("⚠️ SOM analysis disabled")
return None
try:
print("\n🗺️ Performing SOM analysis (New Logic)...")
if isinstance(embedding, list):
embedding_to_use = np.array(embedding, dtype=np.float32)
else:
embedding_to_use = embedding
winner_row, winner_col = som_analyzer.find_winner_neuron(embedding_to_use)
print(f" 📍 Winner neuron: ({winner_row}, {winner_col}) (Source: high-attention segment)")
hf_embeddings = await get_embeddings_from_hf_dataset(filename)
data_source = "high-attention (pos) + "
if hf_embeddings and len(hf_embeddings) > 0:
print(f" Analysing region using {len(hf_embeddings)} HF embeddings...")
features_prob = analyze_som_region_probability(
som_analyzer, winner_row, winner_col, hf_embeddings, radius=2
)
data_source += "hf_dataset (prob)"
else:
print(f"⚠️ No HF data for prob, using background data")
features_dict = som_analyzer.predict_features_from_position(
winner_row, winner_col, radius=1
)
features_prob = {k: float(v) for k, v in features_dict.items()}
data_source += "background_data (prob)"
features_binary = {
feature: 1 if prob > 0.2 else 0
for feature, prob in features_prob.items()
}
print(f" ✅ Features detected: {features_binary}")
result = {
"winner_position": {"row": int(winner_row), "col": int(winner_col)},
"features": features_binary,
"features_probability": features_prob,
"data_source": data_source
}
print(f"✅ SOM analysis complete!")
return result
except Exception as e:
print(f"❌ SOM analysis error: {e}")
import traceback
traceback.print_exc()
return None
@app.post("/predict")
async def predict_malware(files: List[UploadFile] = File(...), original_filename: Optional[str] = None):
"""
批次預測惡意軟體家族(維持原回傳格式)
並自動寫入 embeddings_log.jsonl、上傳到 Hugging Face Dataset
"""
if not files:
raise HTTPException(status_code=400, detail="No files provided")
start_time = time.time() # ✨ 開始量測時間
print(f"\n{'='*60}")
print(f"📥 Received {len(files)} files")
print(f"{'='*60}")
predictions = []
all_embeddings = []
try:
with torch.no_grad():
for idx, file in enumerate(files, 1):
try:
content = await file.read()
asm_code = content.decode('utf-8').strip()
if not asm_code:
print(f"⚠️ Skip empty file: {file.filename}")
continue
print(f"📄 [{idx}/{len(files)}] Processing: {file.filename}")
# === Tokenize ===
inputs = tokenizer(
asm_code,
return_tensors="pt",
max_length=512,
truncation=True,
padding=True
)
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
# === Forward ===
outputs = model(**inputs)
logits = outputs.logits
# === Softmax 機率 ===
probs = torch.nn.functional.softmax(logits, dim=-1)
prob_list = probs.squeeze().cpu().tolist()
# === 取得預測結果 ===
confidence, predicted_class = torch.max(probs, dim=-1)
predicted_id = predicted_class.item()
label_name = (
model.config.id2label[predicted_id]
if hasattr(model.config, "id2label") and predicted_id in model.config.id2label
else f"class_{predicted_id}"
)
print(f" 🔍 Predicted ID: {predicted_id}, Label: {label_name}")
# === Embedding ===
if hasattr(outputs, "hidden_states") and outputs.hidden_states is not None:
last_hidden = outputs.hidden_states[-1]
cls_embedding = last_hidden[:, 0, :].cpu().numpy()[0]
else:
cls_embedding = logits.cpu().numpy()[0]
# === Attention ===
max_attention_score = 0.0
if hasattr(outputs, "attentions") and outputs.attentions is not None:
last_attention = outputs.attentions[-1]
avg_attention = last_attention.mean(dim=1)
cls_attention = avg_attention[0, 0, :].cpu().numpy()
max_attention_score = float(cls_attention.max())
# === Collect Results ===
predictions.append({
"filename": file.filename,
"predicted_label": label_name,
"confidence": float(confidence.item()),
"attention_score": max_attention_score
})
all_embeddings.append({
"source": file.filename,
"label": label_name,
"embedding": cls_embedding.tolist(),
"attention_score": max_attention_score,
"text_excerpt": asm_code,
"probs": prob_list # ✅ 新增:完整 softmax 機率
})
print(f" ✅ Predicted: {label_name} (confidence: {confidence.item():.3f})")
except Exception as e:
print(f" ❌ Error processing {file.filename}: {e}")
continue
if not predictions:
raise HTTPException(status_code=400, detail="No valid files processed")
# === 多數投票 ===
label_votes = [p["predicted_label"] for p in predictions]
vote_counts = Counter(label_votes)
final_label, final_count = vote_counts.most_common(1)[0]
print(f"\n📊 Vote distribution: {dict(vote_counts)}")
print(f"🏆 Final prediction: {final_label} ({final_count}/{len(predictions)} votes)")
# === 選最高注意力權重的 embedding ===
same_label_embeddings = [emb for emb in all_embeddings if emb["label"] == final_label]
best_embedding = (
max(same_label_embeddings, key=lambda x: x["attention_score"])
if same_label_embeddings else
max(all_embeddings, key=lambda x: x["attention_score"])
)
print(f"🎯 Selected embedding from: {best_embedding['source']}")
print(f" Attention score: {best_embedding['attention_score']:.4f}")
# === 回傳結果 ===
result = {
"final_label": final_label,
"vote_count": final_count,
"total_segments": len(predictions),
"confidence": sum(p["confidence"] for p in predictions) / len(predictions),
"vote_distribution": dict(vote_counts),
"embedding": {
"values": best_embedding["embedding"],
"source_file": best_embedding["source"],
"attention_score": best_embedding["attention_score"],
"dimension": len(best_embedding["embedding"])
},
"segment_predictions": predictions
}
os.environ["CURRENT_LABEL"] = final_label
print(f"\n✅ Prediction complete!\n")
# === 寫入本地 embeddings_log.jsonl ===
log_path = os.path.join("results", "embeddings_log.jsonl")
with open(log_path, "a") as f:
for emb in all_embeddings:
f.write(json.dumps(emb) + "\n")
print(f"📝 Logged {len(all_embeddings)} embeddings locally.")
# === 上傳到 Hugging Face Dataset ===
repo_id = "lyi029/malvec-embeddings-new" # ✅ 你的新 dataset
api = HfApi()
try:
old_data = []
try:
old_path = hf_hub_download(
repo_id=repo_id,
filename="embeddings_log.jsonl",
repo_type="dataset",
token=HF_TOKEN
)
with open(old_path, "r") as f:
old_data = [json.loads(l) for l in f if l.strip()]
except Exception:
print("ℹ️ No previous embeddings found in dataset.")
with open(log_path, "r") as f:
new_data = [json.loads(l) for l in f if l.strip()]
# 合併去重
merged_dict = {(d["source"]): d for d in (old_data + new_data)}
merged = list(merged_dict.values())
with open(log_path, "w") as f:
for item in merged:
f.write(json.dumps(item) + "\n")
api.upload_file(
path_or_fileobj=log_path,
path_in_repo="embeddings_log.jsonl",
repo_id=repo_id,
repo_type="dataset",
token=HF_TOKEN,
)
print(f"☁️ Uploaded {len(merged)} merged embeddings to dataset: {repo_id}")
except Exception as e:
print(f"⚠️ Dataset upload failed: {e}")
# ===== 新增:執行 SOM 分析 (from app.py) =====
som_analysis = None
final_embedding_values = result.get("embedding", {}).get("values")
if SOM_AVAILABLE and final_embedding_values:
print("\n🗺️ Performing SOM analysis...")
try:
filename_for_som = original_filename if original_filename else files[0].filename
print(f" Using filename for SOM lookup: {filename_for_som}")
som_analysis = await analyze_with_som(
embedding=final_embedding_values,
predicted_family=result.get("final_label", "Unknown"),
filename=filename_for_som
)
except Exception as e:
print(f"❌ SOM analysis error: {e}")
# 將 SOM 結果附加到最終回傳
result["som_analysis"] = som_analysis
print(f"✅ SOM analysis complete.")
# ✨ 更新 performance 統計
elapsed = time.time() - start_time
PERF_STATS["predict_calls"] += 1
PERF_STATS["predict_total_seconds"] += elapsed
PERF_STATS["predict_last_ms"] = elapsed * 1000.0
PERF_STATS["predict_last_files"] = len(files)
PERF_STATS["last_updated"] = datetime.datetime.utcnow().isoformat()
if len(files) > 0:
files_per_sec = len(files) / elapsed
else:
files_per_sec = 0.0
print("\n===== 🔬 Inference Performance (this request) =====")
print(f" Files processed : {len(files)}")
print(f" Elapsed time : {elapsed:.3f} s")
print(f" Avg per file : {elapsed/len(files):.3f} s/file" if len(files) > 0 else " Avg per file : N/A")
print(f" Throughput : {files_per_sec:.2f} files/s")
print(" Global stats :")
print(f" Total calls : {PERF_STATS['predict_calls']}")
print(f" Total seconds : {PERF_STATS['predict_total_seconds']:.3f} s")
if PERF_STATS["predict_calls"] > 0:
avg = PERF_STATS["predict_total_seconds"] / PERF_STATS["predict_calls"]
print(f" Avg per call : {avg:.3f} s/call")
print("===================================================\n")
return result
except Exception as e:
print(f"\n❌ Error in predict_malware: {e}")
import traceback
traceback.print_exc()
raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")
# ===== 新增:/predict-batch 路由 (from app.py) =====
@app.post("/predict-batch")
async def predict_batch(files: List[UploadFile] = File(...)):
"""
(from app.py)
簡化版: 只返回 label 和 embedding,不包含詳細資訊
"""
result = await predict_malware(files)
return {
"final_label": result["final_label"],
"embedding": result["embedding"]["values"]
# SOM results are not included here, matching app.py's behavior
}
csv.field_size_limit(sys.maxsize)
JUMP_MNEMONICS = {"jmp", "je", "jne", "jl", "jg", "jle", "jge", "call", "ret"}
def _split_into_basic_blocks(tokens):
"""把指令 tokens 拆成 basic blocks(遇到跳轉/ret 就斷)"""
blocks, cur = [], []
for tok in tokens:
cur.append(tok)
if tok.lower() in JUMP_MNEMONICS:
blocks.append(cur)
cur = []
if cur:
blocks.append(cur)
return blocks
def _block_attention_score(tokens, chunk_size=512):
"""
對單一 block 計算注意力:
- 以 512 token 為單位分塊
- 取最後一層 attention → head 平均 → 整體平均
- 多個 chunk 取平均
"""
scores = []
for i in range(0, len(tokens), chunk_size):
chunk = tokens[i:i+chunk_size]
inputs = tokenizer(
chunk,
return_tensors="pt",
is_split_into_words=True,
truncation=True,
max_length=chunk_size,
padding=False
)
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
with torch.no_grad():
out = model(**inputs, output_attentions=True)
last_attn = out.attentions[-1] # (1, heads, seq, seq)
mean_attn = last_attn.mean(dim=1).mean() # scalar
scores.append(mean_attn.item())
return float(np.mean(scores)) if scores else 0.0
@app.post("/attention-heatmap")
async def attention_heatmap(file: UploadFile = File(...)):
"""
1️⃣ 從 disasm token 生成 block-level attention heatmap
2️⃣ 將 heatmap 轉成 base64 圖
3️⃣ 用 CLIP 將 heatmap 轉成 embedding
4️⃣ 上傳至 dataset 並在同 label 裡找出最相似的 heatmap
"""
import io, base64, matplotlib.pyplot as plt, numpy as np, datetime, json
from PIL import Image
from transformers import CLIPProcessor, CLIPModel
from sklearn.metrics.pairwise import cosine_similarity
from huggingface_hub import HfApi, hf_hub_download
HF_HEATMAP_REPO = "lyi029/malvec-heatmap"
os.makedirs("results", exist_ok=True)
try:
# === Step 1. 讀檔 ===
content = await file.read()
text = content.decode("utf-8", errors="ignore")
# === Step 2. 解析 disasm token ===
tokens = []
for line in text.replace("\n", " ").split("</s>"):
toks = [t.strip() for t in line.split() if t.strip()]
if toks:
tokens.extend(toks)
print(f"📦 Total tokens parsed: {len(tokens)}")
# === Step 3. 拆 basic blocks ===
blocks = _split_into_basic_blocks(tokens)[:1000]
print(f"📊 Total blocks: {len(blocks)}")
# === Step 4. 計算 block-level attention ===
scores = [_block_attention_score(blk) for blk in blocks]
if not scores:
return {"error": "No valid blocks parsed"}
# === Step 5. 畫出 heatmap 圖像 ===
fig, ax = plt.subplots(figsize=(10, 2))
heatmap_data = np.expand_dims(scores, axis=0)
im = ax.imshow(heatmap_data, cmap="viridis", aspect="auto")
plt.colorbar(im, ax=ax, orientation="vertical", label="Attention Score")
ax.set_title("Attention Heatmap")
ax.set_xlabel("Block Index")
ax.set_yticks([])
plt.tight_layout()
buf = io.BytesIO()
plt.savefig(buf, format="png", dpi=200)
buf.seek(0)
img_base64 = base64.b64encode(buf.read()).decode("utf-8")
plt.close(fig)
b64_uri = f"data:image/png;base64,{img_base64}"
# === Step 6. 用 CLIP 轉成 embedding ===
clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
clip_proc = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
img = Image.open(io.BytesIO(base64.b64decode(img_base64))).convert("RGB")
inputs = clip_proc(images=img, return_tensors="pt")
with torch.no_grad():
emb = clip_model.get_image_features(**inputs)
emb = emb / emb.norm(p=2, dim=-1, keepdim=True)
emb_vec = emb.squeeze().cpu().numpy().tolist()
# === Step 7. 取得當前 label ===
current_label = os.getenv("CURRENT_LABEL", "unknown").strip()
print(f"[heatmap] 🏷️ Current label: {current_label}")
# === Step 8. 讀取舊 heatmap dataset ===
api = HfApi()
old_records = []
try:
old_path = hf_hub_download(
repo_id=HF_HEATMAP_REPO,
filename="heatmaps_log.jsonl",
repo_type="dataset",
token=HF_TOKEN
)
with open(old_path, "r") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
record = json.loads(line)
if isinstance(record, dict):
old_records.append(record)
except json.JSONDecodeError:
print(f"[heatmap-load] ⚠️ Skip invalid line.")
except Exception:
print("ℹ️ No previous dataset found, will create new.")
# === Step 9. 找同 label 最相似的 heatmap ===
most_similar_id, most_similar_score, most_similar_img = None, -1, None
if old_records:
same_label = [
rec for rec in old_records
if rec.get("label") == current_label
and rec.get("embedding")
and rec.get("source") != file.filename
]
print(f"[heatmap-match] Found {len(same_label)} old heatmaps under label '{current_label}'")
if same_label:
X = np.array([rec["embedding"] for rec in same_label if rec.get("embedding")])
if X.size > 0:
sim_scores = cosine_similarity([emb_vec], X)[0]
max_idx = int(np.argmax(sim_scores))
best_sim = float(sim_scores[max_idx])
best_rec = same_label[max_idx]
if best_sim < 2: # 排除完全相同
most_similar_id = best_rec.get("source")
most_similar_score = best_sim
most_similar_img = best_rec.get("image_base64")
print(f"[heatmap-match] ✅ Best match: {most_similar_id}, sim={best_sim:.4f}")
else:
print(f"[heatmap-match] ⚠️ No sufficiently different heatmaps found under label '{current_label}'")
else:
print(f"[heatmap-match] ⚠️ No existing heatmaps for label '{current_label}' yet")
# === Step 10. 儲存新紀錄並上傳 ===
new_record = {
"timestamp": datetime.datetime.now().isoformat(),
"label": current_label,
"embedding": emb_vec,
"source": file.filename,
"image_base64": b64_uri,
}
merged_dict = {rec["source"]: rec for rec in (old_records + [new_record])}
merged_list = list(merged_dict.values())
local_path = os.path.join("results", "heatmaps_log.jsonl")
with open(local_path, "w") as f:
for rec in merged_list:
f.write(json.dumps(rec) + "\n")
try:
api.upload_file(
path_or_fileobj=local_path,
path_in_repo="heatmaps_log.jsonl",
repo_id=HF_HEATMAP_REPO,
repo_type="dataset",
token=HF_TOKEN,
)
print(f"☁️ Uploaded {len(merged_list)} heatmaps to dataset: {HF_HEATMAP_REPO}")
except Exception as e:
print(f"⚠️ Upload failed: {e}")
# === Step 11. 回傳結果 ===
return {
"label": current_label,
"attention_heatmap": b64_uri,
"embedding_dim": len(emb_vec),
"most_similar_in_label": most_similar_id,
"similarity_score": most_similar_score,
"similar_heatmap_image": most_similar_img,
}
except Exception as e:
print(f"❌ attention_heatmap error: {e}")
import traceback
traceback.print_exc()
return {"error": str(e)}
@app.post("/check-new-samples")
async def check_new_samples():
"""
觸發 Space B 的 Active Learning 探測與 LoRA 訓練流程
並將 Space B 的回傳結果原樣傳回前端
"""
if not SPACE_B_URL:
raise HTTPException(status_code=400, detail="SPACE_B_URL not set")
try:
async with httpx.AsyncClient(timeout=600.0) as client:
params = {"batch_size": 1000, "mmd_threshold": 0.2, "entropy_threshold": 1.1}
resp = await client.post(f"{SPACE_B_URL}/check-new-samples", params=params)
print(f"🚀 Space B /check-new-samples → HTTP {resp.status_code}")
# 嘗試解析回傳 JSON
try:
data = resp.json()
print(f"📦 Space B response: {data}")
return data # ✅ 原樣回傳給前端
except Exception as e:
print(f"⚠️ Failed to parse Space B JSON: {e}")
return {
"status": "error",
"message": "Invalid JSON from Space B",
"raw_text": resp.text[:500]
}
except Exception as e:
print("❌ Failed to contact Space B:", e)
raise HTTPException(status_code=500, detail=f"Failed to contact Space B: {str(e)}")
def _reload_model_by_tag(tag: str):
global tokenizer, model, CURRENT_TAG
print(f"♻️ Reloading model: {MODEL_REPO}@{tag}")
tok = AutoTokenizer.from_pretrained(MODEL_REPO, token=HF_TOKEN, revision=tag)
mdl = AutoModelForSequenceClassification.from_pretrained(
MODEL_REPO, token=HF_TOKEN, revision=tag,
output_attentions=True, output_hidden_states=True
)
mdl.to(DEVICE).eval()
tokenizer = tok
model = mdl
CURRENT_TAG = tag
print("✅ Reloaded.")
@app.post("/api/update-model")
async def update_model(payload: dict):
tag = payload.get("tag")
if not tag:
raise HTTPException(400, "missing 'tag'")
try:
_reload_model_by_tag(tag)
return {"status":"ok", "tag": tag}
except Exception as e:
raise HTTPException(500, f"reload failed: {e}")
@app.get("/performance")
async def performance():
"""
回傳推論 performance + 系統資源使用狀況
"""
# === 計算平均推論時間 ===
avg_sec = (
PERF_STATS["predict_total_seconds"] / PERF_STATS["predict_calls"]
if PERF_STATS["predict_calls"] > 0 else 0.0
)
# === 系統資訊 ===
cpu_percent = psutil.cpu_percent(interval=0.2)
cpu_cores = psutil.cpu_count(logical=True)
cpu_model = platform.processor() or "Unknown CPU"
# === 記憶體資訊 ===
mem = psutil.virtual_memory()
memory_info = {
"total_gb": round(mem.total / 1024**3, 2),
"used_gb": round(mem.used / 1024**3, 2),
"free_gb": round(mem.available / 1024**3, 2),
"percent": mem.percent
}
# === Python Process 記憶體使用 ===
proc = psutil.Process(os.getpid())
proc_mem = proc.memory_info()
process_memory = {
"rss_mb": round(proc_mem.rss / 1024**2, 2),
"vms_mb": round(proc_mem.vms / 1024**2, 2),
}
# === 磁碟空間 ===
disk = shutil.disk_usage("/")
disk_info = {
"total_gb": round(disk.total / 1024**3, 2),
"used_gb": round(disk.used / 1024**3, 2),
"free_gb": round(disk.free / 1024**3, 2),
}
base_info = {
"model_name": MODEL_REPO,
"current_tag": CURRENT_TAG,
"device": str(DEVICE),
"som_available": SOM_AVAILABLE,
"space_b_url": SPACE_B_URL,
}
perf_info = {
"predict_calls": PERF_STATS["predict_calls"],
"predict_total_seconds": PERF_STATS["predict_total_seconds"],
"predict_avg_seconds": avg_sec,
"predict_last_ms": PERF_STATS["predict_last_ms"],
"predict_last_files": PERF_STATS["predict_last_files"],
"last_updated": PERF_STATS["last_updated"],
}
resource_info = {
"cpu": {
"model": cpu_model,
"cores": cpu_cores,
"usage_percent": cpu_percent,
},
"memory": memory_info,
"process_memory": process_memory,
"disk": disk_info,
}
# 嘗試從 Space B 取得 performance
space_b_perf = None
if SPACE_B_URL:
try:
async with httpx.AsyncClient(timeout=5.0) as client:
r = await client.get(f"{SPACE_B_URL}/performance")
if r.status_code == 200:
space_b_perf = r.json()
except Exception:
space_b_perf = None
return {
"base": base_info,
"space_a_performance": perf_info,
"system_resources": resource_info,
"space_b_performance": space_b_perf,
}
# ----------------------------------------------------------
# 健康檢查 & Performance
# ----------------------------------------------------------
@app.get("/health")
def health():
return {"status": "ok", "space_b_url": SPACE_B_URL, "model": MODEL_REPO}
# @app.get("/performance")
# async def performance():
# """
# 簡單回報目前的推論 performance 統計
# (目前只統計 /predict 的執行時間與呼叫次數)
# """
# avg_sec = (
# PERF_STATS["predict_total_seconds"] / PERF_STATS["predict_calls"]
# if PERF_STATS["predict_calls"] > 0 else 0.0
# )
# base_info = {
# "model_name": MODEL_REPO,
# "current_tag": CURRENT_TAG,
# "device": str(DEVICE),
# "som_available": SOM_AVAILABLE,
# "space_b_url": SPACE_B_URL,
# }
# perf_info = {
# "predict_calls": PERF_STATS["predict_calls"],
# "predict_total_seconds": PERF_STATS["predict_total_seconds"],
# "predict_avg_seconds": avg_sec,
# "predict_last_ms": PERF_STATS["predict_last_ms"],
# "predict_last_files": PERF_STATS["predict_last_files"],
# "last_updated": PERF_STATS["last_updated"],
# }
# # (可選)試著從 Space B 拿 performance(如果那邊有 /performance 的話)
# space_b_perf = None
# if SPACE_B_URL:
# try:
# async with httpx.AsyncClient(timeout=5.0) as client:
# r = await client.get(f"{SPACE_B_URL}/performance")
# if r.status_code == 200:
# space_b_perf = r.json()
# except Exception:
# space_b_perf = None
# return {
# "base": base_info,
# "space_a_performance": perf_info,
# "space_b_performance": space_b_perf,
# }
# ===== Hugging Face Space 啟動 =====
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", 7860))
uvicorn.run(app, host="0.0.0.0", port=port)
import os
import json
import httpx
import torch
from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from typing import List, Optional, Dict
from collections import Counter
from fastapi.staticfiles import StaticFiles
from huggingface_hub import HfApi,hf_hub_download
import datetime
import csv, sys
import io
import numpy as np
from datasets import load_dataset
import time # ✨ 新增:用來量測 performance
import psutil
import shutil
import platform
# ⚠️ 注意: som_analyzer.py 必須存在於同一目錄
try:
from som_analyzer import SOMAnalyzer
SOM_FILE_AVAILABLE = True
except ImportError:
print("⚠️ WARNING: 'som_analyzer.py' not found. SOM features will be disabled.")
SOM_FILE_AVAILABLE = False
CURRENT_TAG = os.getenv("MODEL_TAG", "main")
# ====== FastAPI 初始化 ======
app = FastAPI(
title="Malvec Prediction Space (A)",
description="Handles inference and optionally triggers LoRA fine-tuning (Space B).",
version="1.3"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ====== 模型設定 ======
MODEL_REPO = os.getenv("MODEL_REPO", "malvec/Malvec_predict")
HF_TOKEN = os.getenv("HF_TOKEN")
DEVICE = torch.device("cpu")
HF_DATASET_REPO = "lyi029/malvec-embeddings-new"
# ====== 連接 Space B ======
SPACE_B_URL = os.getenv("SPACE_B_URL", "https://malvec-model-update-test.hf.space")
# ====== Cache & 目錄 ======
CACHE_DIR = "/tmp/hf_cache"
os.environ.update({
"HF_HOME": CACHE_DIR,
"TRANSFORMERS_CACHE": CACHE_DIR,
"HUGGINGFACE_HUB_CACHE": CACHE_DIR
})
os.makedirs(CACHE_DIR, exist_ok=True)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
RESULT_DIR = os.path.join(BASE_DIR, "results")
os.makedirs("results", exist_ok=True)
app.mount("/results", StaticFiles(directory=RESULT_DIR), name="results")
# ====== 簡單 Performance 統計 ======
PERF_STATS = {
"predict_calls": 0,
"predict_total_seconds": 0.0,
"predict_last_ms": 0.0,
"predict_last_files": 0,
"last_updated": None,
}
# ====== 載入模型 ======
print("🤗 Loading model from:", MODEL_REPO)
tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, token=HF_TOKEN)
model = AutoModelForSequenceClassification.from_pretrained(
MODEL_REPO,
token=HF_TOKEN,
output_attentions=True,
output_hidden_states=True
)
model.to(DEVICE).eval()
print("✅ Model loaded successfully")
# ===== 新增:載入 SOM 模型 (from app.py) =====
print("🧠 Initializing SOM Analyzer...")
SOM_REPO = os.getenv("SOM_REPO", "malvec/codebert_Malvec") # ✨ 補上 SOM_REPO,避免 NameError
SOM_AVAILABLE = False
if SOM_FILE_AVAILABLE: # 檢查 'som_analyzer.py' 是否 import 成功
try:
# ✅ 直接使用 repo 內的本地檔案
# (假設 app.py 和 .npy/.pkl 檔案在同一層級)
print(" Loading SOM files from local repository...")