Spaces:
Runtime error
Runtime error
File size: 8,013 Bytes
0875567 3a052d8 fe4a64d 0875567 6f1c7e3 3466d4c bc6423e 6f1c7e3 3466d4c bc6423e 0875567 6f1c7e3 0875567 6f1c7e3 0875567 6f1c7e3 0875567 bc6423e 6f1c7e3 3466d4c 6f1c7e3 bc6423e 6f1c7e3 bc6423e 6f1c7e3 bc6423e 6f1c7e3 bc6423e 6f1c7e3 bc6423e 6f1c7e3 9e085a0 | 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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | import os
CACHE_DIR = "/tmp/hf_cache"
os.environ["HF_HOME"] = CACHE_DIR
os.environ["TRANSFORMERS_CACHE"] = CACHE_DIR
os.environ["HUGGINGFACE_HUB_CACHE"] = CACHE_DIR
os.makedirs(CACHE_DIR, exist_ok=True)
import torch
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from typing import List
from collections import Counter
import json
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ===== 模型設定 =====
MODEL_REPO = "raxhel/Malvec_predict"
HF_TOKEN = os.environ.get("hf_token")
DEVICE = torch.device("cpu")
# ===== 載入模型 =====
print("🤗 Loading model...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, token=HF_TOKEN)
model = AutoModelForSequenceClassification.from_pretrained(
MODEL_REPO,
token=HF_TOKEN,
output_attentions=True # 🔸 關鍵: 輸出注意力權重
)
model.to(DEVICE)
model.eval()
print("✅ Model loaded successfully")
@app.get("/")
def home():
return {
"message": "Malware Classifier API",
"model": MODEL_REPO,
"endpoints": {
"/predict": "POST - Upload TXT files for prediction",
"/model-info": "GET - Get model information"
}
}
@app.get("/model-info")
def get_model_info():
"""取得模型資訊"""
return {
"model_name": MODEL_REPO,
"num_labels": model.config.num_labels,
"labels": list(model.config.id2label.values()) if hasattr(model.config, 'id2label') else None,
"device": str(DEVICE),
"max_length": 512
}
@app.post("/predict")
async def predict_malware(files: List[UploadFile] = File(...)):
"""
批次預測惡意軟體家族
接收多個 TXT 檔案 (來自同一個執行檔的分段)
返回:
- final_label: 多數投票的家族標籤
- embeddings: 最高注意力權重的 embedding
"""
if not files:
raise HTTPException(status_code=400, detail="No files provided")
print(f"\n{'='*60}")
print(f"📥 Received {len(files)} files")
print(f"{'='*60}")
predictions = []
all_embeddings = []
all_attentions = []
with torch.no_grad():
for idx, file in enumerate(files, 1):
# 讀取檔案內容
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()}
# 模型預測
outputs = model(**inputs)
# 取得預測結果
logits = outputs.logits
probs = torch.nn.functional.softmax(logits, dim=-1)
confidence, predicted_class = torch.max(probs, dim=-1)
# 取得 label
if hasattr(model.config, 'id2label'):
label_name = model.config.id2label[str(predicted_class.item())]
else:
label_name = f"class_{predicted_class.item()}"
# 取得最後一層的 hidden states (作為 embedding)
# 注意: 需要模型支援 output_hidden_states
if hasattr(outputs, 'hidden_states') and outputs.hidden_states is not None:
# 取最後一層的 [CLS] token embedding
last_hidden = outputs.hidden_states[-1] # (batch, seq_len, hidden_size)
cls_embedding = last_hidden[:, 0, :].cpu().numpy() # (1, 768)
else:
# 如果沒有 hidden_states,用 logits 作為替代
cls_embedding = logits.cpu().numpy()
# 取得注意力權重
if hasattr(outputs, 'attentions') and outputs.attentions is not None:
# attentions: tuple of (batch, num_heads, seq_len, seq_len)
# 取最後一層的注意力,平均所有 head
last_attention = outputs.attentions[-1] # (1, num_heads, seq_len, seq_len)
avg_attention = last_attention.mean(dim=1) # (1, seq_len, seq_len)
# 取 [CLS] token 對所有 token 的注意力
cls_attention = avg_attention[0, 0, :].cpu().numpy() # (seq_len,)
max_attention_score = cls_attention.max()
else:
cls_attention = None
max_attention_score = 0.0
# 儲存結果
predictions.append({
"filename": file.filename,
"predicted_label": label_name,
"confidence": confidence.item(),
"attention_score": float(max_attention_score)
})
all_embeddings.append({
"filename": file.filename,
"label": label_name,
"embedding": cls_embedding.tolist()[0], # 轉成 list
"attention_score": float(max_attention_score)
})
print(f" ✅ Predicted: {label_name} (confidence: {confidence.item():.3f})")
if not predictions:
raise HTTPException(status_code=400, detail="No valid files processed")
# ===== 多數投票 (Majority Voting) =====
label_votes = [p["predicted_label"] for p in predictions]
vote_counts = Counter(label_votes)
final_label = vote_counts.most_common(1)[0][0]
final_count = vote_counts[final_label]
print(f"\n📊 Vote distribution: {dict(vote_counts)}")
print(f"🏆 Final prediction: {final_label} ({final_count}/{len(predictions)} votes)")
# ===== 選擇最高注意力權重的 embedding (且屬於最終預測的 label) =====
# 過濾出預測為 final_label 的 embeddings
same_label_embeddings = [
emb for emb in all_embeddings
if emb["label"] == final_label
]
if same_label_embeddings:
# 選擇注意力權重最高的
best_embedding = max(same_label_embeddings, key=lambda x: x["attention_score"])
else:
# 如果沒有,就選所有裡面注意力最高的
best_embedding = max(all_embeddings, key=lambda x: x["attention_score"])
print(f"🎯 Selected embedding from: {best_embedding['filename']}")
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["filename"],
"attention_score": best_embedding["attention_score"],
"dimension": len(best_embedding["embedding"])
},
"segment_predictions": predictions
}
print(f"\n✅ Prediction complete!\n")
return result
@app.post("/predict-batch")
async def predict_batch(files: List[UploadFile] = File(...)):
"""
簡化版: 只返回 label 和 embedding,不包含詳細資訊
"""
result = await predict_malware(files)
return {
"final_label": result["final_label"],
"embedding": result["embedding"]["values"]
}
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("PORT", 7860))
uvicorn.run(app, host="0.0.0.0", port=port) |