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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -9
app.py CHANGED
@@ -23,7 +23,7 @@ from llm_client import LLMClient
23
 
24
  # --------- Config ----------
25
  REPO_ID = "dungeon29/deberta-lstm-detect-phishing" # HF repo that holds the checkpoint
26
- FILE_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
 
@@ -31,26 +31,73 @@ LABELS = ["benign", "phishing"] # adjust to your classes
31
  device = "cuda" if torch.cuda.is_available() else "cpu"
32
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  # Initialize model
36
- model = DeBERTaLSTMClassifier()
37
- model.to(device)
38
 
39
  # Load state dict
40
  try:
41
- model_path = hf_hub_download(repo_id=REPO_ID, filename=FILE_NAME)
42
-
43
- state_dict = load_file(model_path)
44
-
45
  model.load_state_dict(state_dict, strict=False)
46
 
47
- print("✅ Load weights successfully!")
 
 
 
 
48
 
49
  except Exception as e:
50
  print(f"❌ Error when loading weights: {e}")
51
  raise e
52
 
53
- model.eval()
54
 
55
  # --------- Initialize RAG & LLM ----------
56
  print("Initializing RAG Engine (LangChain)...")
 
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
 
 
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:
94
+ print("✅ Load weights successfully!")
95
 
96
  except Exception as e:
97
  print(f"❌ Error when loading weights: {e}")
98
  raise e
99
 
100
+ model.to(device).eval()
101
 
102
  # --------- Initialize RAG & LLM ----------
103
  print("Initializing RAG Engine (LangChain)...")