martynattakit commited on
Commit
8a621d3
·
verified ·
1 Parent(s): a0046fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -60
app.py CHANGED
@@ -1,17 +1,16 @@
1
  import torch
2
  from transformers import RobertaTokenizer, RobertaModel
3
- from huggingface_hub import hf_hub_download # <--- NEW IMPORT
4
  import numpy as np
5
  from scipy.special import softmax
6
  import gradio as gr
7
  import re
8
- import os # <--- NEW IMPORT
9
 
10
  # Define the model class with dimension reduction
11
  class CodeClassifier(torch.nn.Module):
12
  def __init__(self, base_model, num_labels=6):
13
  super(CodeClassifier, self).__init__()
14
- self.base = base_model # This will be the microsoft/codebert-base model
15
  self.reduction = torch.nn.Linear(768, 512)
16
  self.classifier = torch.nn.Linear(512, num_labels)
17
 
@@ -20,62 +19,21 @@ class CodeClassifier(torch.nn.Module):
20
  reduced = self.reduction(outputs.pooler_output)
21
  return self.classifier(reduced)
22
 
23
- # --- START OF MODIFIED LOADING LOGIC ---
24
-
25
- # Hugging Face Model ID where your .pt file is located
26
- HF_MODEL_REPO_ID = 'martynattakit/CodeSentinel-Model'
27
- # The exact filename of your .pt file in that repository
28
- HF_MODEL_FILENAME = 'best_model.pt' # <--- CONFIRM THIS IS THE EXACT FILENAME YOU UPLOADED
29
-
30
- # Load the base tokenizer (from Hugging Face Hub as before)
31
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
32
  tokenizer = RobertaTokenizer.from_pretrained('microsoft/codebert-base')
33
-
34
- # Initialize the base CodeBERT model from Hugging Face (standard download)
35
- base_codebert_model = RobertaModel.from_pretrained('microsoft/codebert-base')
36
-
37
- # Instantiate your custom CodeClassifier model
38
- model = CodeClassifier(base_codebert_model, num_labels=6)
39
-
40
- # Download the .pt file from Hugging Face Hub
41
- print(f"Attempting to download {HF_MODEL_FILENAME} from {HF_MODEL_REPO_ID}...")
42
- try:
43
- # hf_hub_download will download the file and return its local path (which might be in cache)
44
- downloaded_model_path = hf_hub_download(
45
- repo_id=HF_MODEL_REPO_ID,
46
- filename=HF_MODEL_FILENAME,
47
- # If your model repo is private, you might need to ensure
48
- # that huggingface-cli login has been run in your environment.
49
- )
50
- print(f"Model downloaded to: {downloaded_model_path}")
51
-
52
- # Load the state dictionary from the downloaded .pt file
53
- state_dict = torch.load(downloaded_model_path, map_location=device)
54
-
55
- # Handle 'module.' prefix if the model was saved with DataParallel
56
- new_state_dict = {}
57
- for k, v in state_dict.items():
58
- if k.startswith('module.'):
59
- new_state_dict[k[7:]] = v # remove 'module.' prefix
60
- else:
61
- new_state_dict[k] = v
62
- model.load_state_dict(new_state_dict)
63
- print(f"Successfully loaded model state into CodeClassifier.")
64
-
65
- except Exception as e:
66
- print(f"Error during model download or loading: {e}")
67
- print("Please ensure:")
68
- print(f"1. The repository '{HF_MODEL_REPO_ID}' exists and is public (or you're logged in with `huggingface-cli login`).")
69
- print(f"2. The file '{HF_MODEL_FILENAME}' exists within that repository on Hugging Face and is spelled exactly correctly.")
70
- # Exiting here is good for deployment environments like Hugging Face Spaces,
71
- # as it makes the error clear early on.
72
- exit()
73
-
74
- # --- END OF MODIFIED LOADING LOGIC ---
75
-
76
-
77
- print("Loaded state dict keys (after loading .pt):", model.state_dict().keys())
78
- print("Classifier weight shape (after loading .pt):", model.classifier.weight.shape)
79
  model.eval()
80
  model.to(device)
81
 
@@ -109,11 +67,11 @@ def evaluate_code(code):
109
  try:
110
  if len(code) >= 1500000:
111
  return "Code too large"
112
-
113
  cleaned_code = clean_code(code)
114
  inputs = tokenizer(cleaned_code, return_tensors="pt", truncation=True, padding=True, max_length=256).to(device)
115
  print("Input shape:", inputs['input_ids'].shape)
116
-
117
  with torch.no_grad():
118
  outputs = model(**inputs)
119
  print("Raw logits:", outputs.cpu().numpy())
@@ -121,7 +79,7 @@ def evaluate_code(code):
121
  pred = np.argmax(probs, axis=1)[0]
122
  cwe, description = label_map[pred]
123
  return f"{cwe} {description}"
124
-
125
  except Exception as e:
126
  return f"Error during prediction: {str(e)}"
127
 
 
1
  import torch
2
  from transformers import RobertaTokenizer, RobertaModel
 
3
  import numpy as np
4
  from scipy.special import softmax
5
  import gradio as gr
6
  import re
7
+ from huggingface_hub import hf_hub_download
8
 
9
  # Define the model class with dimension reduction
10
  class CodeClassifier(torch.nn.Module):
11
  def __init__(self, base_model, num_labels=6):
12
  super(CodeClassifier, self).__init__()
13
+ self.base = base_model
14
  self.reduction = torch.nn.Linear(768, 512)
15
  self.classifier = torch.nn.Linear(512, num_labels)
16
 
 
19
  reduced = self.reduction(outputs.pooler_output)
20
  return self.classifier(reduced)
21
 
22
+ # Load base model and tokenizer from Hugging Face Model Hub
 
 
 
 
 
 
 
23
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
24
  tokenizer = RobertaTokenizer.from_pretrained('microsoft/codebert-base')
25
+ base_model = RobertaModel.from_pretrained('microsoft/codebert-base')
26
+ # Initialize the CodeClassifier with the base model
27
+ model = CodeClassifier(base_model)
28
+ # Load the checkpoint from Hugginface Model Hub
29
+ checkpoint_path = hf_hub_download(repo_id="martynattakit/CodeSentinel-Model", filename="best_model.pt")
30
+ checkpoint = torch.load(checkpoint_path, map_location=device)
31
+
32
+ # Load the state dict, focusing on classifier weights
33
+ model_state = checkpoint.get('model_state_dict', checkpoint)
34
+ model.load_state_dict(model_state, strict=False)
35
+ print("Loaded state dict keys:", model.state_dict().keys())
36
+ print("Classifier weight shape:", model.classifier.weight.shape)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  model.eval()
38
  model.to(device)
39
 
 
67
  try:
68
  if len(code) >= 1500000:
69
  return "Code too large"
70
+
71
  cleaned_code = clean_code(code)
72
  inputs = tokenizer(cleaned_code, return_tensors="pt", truncation=True, padding=True, max_length=256).to(device)
73
  print("Input shape:", inputs['input_ids'].shape)
74
+
75
  with torch.no_grad():
76
  outputs = model(**inputs)
77
  print("Raw logits:", outputs.cpu().numpy())
 
79
  pred = np.argmax(probs, axis=1)[0]
80
  cwe, description = label_map[pred]
81
  return f"{cwe} {description}"
82
+
83
  except Exception as e:
84
  return f"Error during prediction: {str(e)}"
85