111306047 commited on
Commit
6c9facf
·
1 Parent(s): 78ac2e4

fix id problem

Browse files
Files changed (1) hide show
  1. app.py +23 -3
app.py CHANGED
@@ -53,12 +53,25 @@ def home():
53
  @app.get("/model-info")
54
  def get_model_info():
55
  """取得模型資訊"""
 
 
 
 
 
 
 
 
 
 
 
 
56
  return {
57
  "model_name": MODEL_REPO,
58
  "num_labels": model.config.num_labels,
59
  "labels": list(model.config.id2label.values()) if hasattr(model.config, 'id2label') else None,
60
  "device": str(DEVICE),
61
- "max_length": 512
 
62
  }
63
 
64
  @app.post("/predict")
@@ -115,10 +128,17 @@ async def predict_malware(files: List[UploadFile] = File(...)):
115
  confidence, predicted_class = torch.max(probs, dim=-1)
116
 
117
  # 取得 label
 
118
  if hasattr(model.config, 'id2label'):
119
- label_name = model.config.id2label[str(predicted_class.item())]
 
 
 
 
 
 
120
  else:
121
- label_name = f"class_{predicted_class.item()}"
122
 
123
  # ✅ 取得 embedding (使用 hidden_states)
124
  if hasattr(outputs, 'hidden_states') and outputs.hidden_states is not None:
 
53
  @app.get("/model-info")
54
  def get_model_info():
55
  """取得模型資訊"""
56
+ # ✅ 檢查 id2label 的 key 類型
57
+ id2label_sample = {}
58
+ if hasattr(model.config, 'id2label'):
59
+ # 取前 3 個 key 作為範例
60
+ sample_keys = list(model.config.id2label.keys())[:3]
61
+ id2label_sample = {
62
+ k: {
63
+ "type": str(type(k).__name__),
64
+ "value": model.config.id2label[k]
65
+ } for k in sample_keys
66
+ }
67
+
68
  return {
69
  "model_name": MODEL_REPO,
70
  "num_labels": model.config.num_labels,
71
  "labels": list(model.config.id2label.values()) if hasattr(model.config, 'id2label') else None,
72
  "device": str(DEVICE),
73
+ "max_length": 512,
74
+ "id2label_sample": id2label_sample # ✅ 除錯用
75
  }
76
 
77
  @app.post("/predict")
 
128
  confidence, predicted_class = torch.max(probs, dim=-1)
129
 
130
  # 取得 label
131
+ predicted_id = predicted_class.item()
132
  if hasattr(model.config, 'id2label'):
133
+ # ✅ 嘗試整數 key,再嘗試字串 key
134
+ if predicted_id in model.config.id2label:
135
+ label_name = model.config.id2label[predicted_id]
136
+ elif str(predicted_id) in model.config.id2label:
137
+ label_name = model.config.id2label[str(predicted_id)]
138
+ else:
139
+ label_name = f"class_{predicted_id}"
140
  else:
141
+ label_name = f"class_{predicted_id}"
142
 
143
  # ✅ 取得 embedding (使用 hidden_states)
144
  if hasattr(outputs, 'hidden_states') and outputs.hidden_states is not None: