dungeon29 commited on
Commit
3797dd4
·
verified ·
1 Parent(s): c7a84e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -55
app.py CHANGED
@@ -9,9 +9,6 @@ from urllib.parse import urlparse
9
  import time
10
  import os
11
 
12
- from safetensors.torch import load_file
13
- import json
14
-
15
  # --- import your architecture ---
16
  # Make sure this file is in the repo (e.g., models/deberta_lstm_classifier.py)
17
  # and update the import path accordingly.
@@ -23,71 +20,36 @@ from llm_client import LLMClient
23
 
24
  # --------- Config ----------
25
  REPO_ID = "dungeon29/deberta-lstm-detect-phishing" # HF repo that holds the checkpoint
26
- CKPT_NAME = "model.safetensors" # the .safetensors file name
27
  MODEL_NAME = "microsoft/deberta-base" # base tokenizer/backbone
28
  LABELS = ["benign", "phishing"] # adjust to your classes
29
 
 
 
 
 
30
  # --------- Load model/tokenizer once (global) ----------
31
  device = "cuda" if torch.cuda.is_available() else "cpu"
32
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
33
 
34
- # Check if checkpoint exists locally, otherwise download from HF
35
- if os.path.exists(CKPT_NAME):
36
- print(f"📂 Found local checkpoint: {CKPT_NAME}")
37
- ckpt_path = CKPT_NAME
38
- else:
39
- print(f"⬇️ Downloading checkpoint {CKPT_NAME} from HF Hub...")
40
- try:
41
- ckpt_path = hf_hub_download(repo_id=REPO_ID, filename=CKPT_NAME)
42
- except Exception as e:
43
- print(f"⚠️ Could not download from HF: {e}")
44
- # Fallback to pytorch_model.bin if the new name fails
45
- print("🔄 Trying fallback to pytorch_model.bin...")
46
- ckpt_path = hf_hub_download(repo_id=REPO_ID, filename="pytorch_model.bin")
47
-
48
- # Load weights based on file extension
49
- if ckpt_path.endswith(".safetensors"):
50
- print("📦 Loading weights from safetensors...")
51
- state_dict = load_file(ckpt_path, device=device)
52
-
53
- # Try to load config.json for model_args
54
- try:
55
- if os.path.exists("config.json"):
56
- config_path = "config.json"
57
- else:
58
- config_path = hf_hub_download(repo_id=REPO_ID, filename="config.json")
59
-
60
- with open(config_path, "r") as f:
61
- config = json.load(f)
62
- # Extract model_args from config if they exist, otherwise use defaults
63
- # Assuming config might have custom keys or we just use defaults
64
- model_args = config.get("model_args", {})
65
- except Exception as e:
66
- print(f"⚠️ Could not load config.json: {e}. Using default model args.")
67
- model_args = {}
68
-
69
- else:
70
- # Legacy loading for .bin/.pt
71
- print("📦 Loading weights from torch checkpoint...")
72
- checkpoint = torch.load(ckpt_path, map_location=device)
73
- if isinstance(checkpoint, dict) and "model_state_dict" in checkpoint:
74
- state_dict = checkpoint["model_state_dict"]
75
- model_args = checkpoint.get("model_args", {})
76
- elif isinstance(checkpoint, dict):
77
- state_dict = checkpoint
78
- model_args = checkpoint.get("model_args", {})
79
- else:
80
- state_dict = checkpoint
81
- model_args = {}
82
 
83
- # Initialize model
 
84
  model = DeBERTaLSTMClassifier(**model_args)
85
 
86
- # Load state dict
87
  try:
 
 
 
 
 
 
88
  model.load_state_dict(state_dict, strict=False)
89
 
90
- # Check attention layer
91
  if hasattr(model, 'attention') and 'attention.weight' not in state_dict:
92
  print("⚠️ Loaded model without attention layer, using newly initialized attention weights")
93
  else:
 
9
  import time
10
  import os
11
 
 
 
 
12
  # --- import your architecture ---
13
  # Make sure this file is in the repo (e.g., models/deberta_lstm_classifier.py)
14
  # and update the import path accordingly.
 
20
 
21
  # --------- Config ----------
22
  REPO_ID = "dungeon29/deberta-lstm-detect-phishing" # HF repo that holds the checkpoint
23
+ CKPT_NAME = "pytorch_model.bin" # the .pt file name
24
  MODEL_NAME = "microsoft/deberta-base" # base tokenizer/backbone
25
  LABELS = ["benign", "phishing"] # adjust to your classes
26
 
27
+ # If your checkpoint contains hyperparams, you can fetch them like:
28
+ # checkpoint.get("config") or checkpoint.get("model_args")
29
+ # and pass into DeBERTaLSTMClassifier(**model_args)
30
+
31
  # --------- Load model/tokenizer once (global) ----------
32
  device = "cuda" if torch.cuda.is_available() else "cpu"
33
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
34
 
35
+ ckpt_path = hf_hub_download(repo_id=REPO_ID, filename=CKPT_NAME)
36
+ checkpoint = torch.load(ckpt_path, map_location=device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ # If you saved hyperparams in the checkpoint, use them:
39
+ model_args = checkpoint.get("model_args", {}) # e.g., {"lstm_hidden":256, "num_labels":2, ...}
40
  model = DeBERTaLSTMClassifier(**model_args)
41
 
42
+ # Load weights
43
  try:
44
+ state_dict = torch.load(ckpt_path, map_location=device)
45
+
46
+ # Xử lý nếu file lưu dạng checkpoint đầy đủ (có key "model_state_dict")
47
+ if "model_state_dict" in state_dict:
48
+ state_dict = state_dict["model_state_dict"]
49
+
50
  model.load_state_dict(state_dict, strict=False)
51
 
52
+ # Kiểm tra layer attention
53
  if hasattr(model, 'attention') and 'attention.weight' not in state_dict:
54
  print("⚠️ Loaded model without attention layer, using newly initialized attention weights")
55
  else: