Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,17 @@
|
|
| 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 |
|
| 8 |
# Define the model class with dimension reduction
|
| 9 |
class CodeClassifier(torch.nn.Module):
|
| 10 |
def __init__(self, base_model, num_labels=6):
|
| 11 |
super(CodeClassifier, self).__init__()
|
| 12 |
-
self.base = base_model
|
| 13 |
self.reduction = torch.nn.Linear(768, 512)
|
| 14 |
self.classifier = torch.nn.Linear(512, num_labels)
|
| 15 |
|
|
@@ -18,13 +20,62 @@ class CodeClassifier(torch.nn.Module):
|
|
| 18 |
reduced = self.reduction(outputs.pooler_output)
|
| 19 |
return self.classifier(reduced)
|
| 20 |
|
| 21 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 23 |
tokenizer = RobertaTokenizer.from_pretrained('microsoft/codebert-base')
|
| 24 |
-
|
| 25 |
-
model
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
model.eval()
|
| 29 |
model.to(device)
|
| 30 |
|
|
@@ -58,11 +109,11 @@ def evaluate_code(code):
|
|
| 58 |
try:
|
| 59 |
if len(code) >= 1500000:
|
| 60 |
return "Code too large"
|
| 61 |
-
|
| 62 |
cleaned_code = clean_code(code)
|
| 63 |
inputs = tokenizer(cleaned_code, return_tensors="pt", truncation=True, padding=True, max_length=256).to(device)
|
| 64 |
print("Input shape:", inputs['input_ids'].shape)
|
| 65 |
-
|
| 66 |
with torch.no_grad():
|
| 67 |
outputs = model(**inputs)
|
| 68 |
print("Raw logits:", outputs.cpu().numpy())
|
|
@@ -70,7 +121,7 @@ def evaluate_code(code):
|
|
| 70 |
pred = np.argmax(probs, axis=1)[0]
|
| 71 |
cwe, description = label_map[pred]
|
| 72 |
return f"{cwe} {description}"
|
| 73 |
-
|
| 74 |
except Exception as e:
|
| 75 |
return f"Error during prediction: {str(e)}"
|
| 76 |
|
|
|
|
| 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 |
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 |
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 |
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 |
|