File size: 1,830 Bytes
5237bb2 b36a521 5237bb2 b36a521 5237bb2 b36a521 5237bb2 b36a521 5237bb2 b36a521 5237bb2 b36a521 5237bb2 b36a521 5237bb2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# app.py
import os
import joblib
import torch
from transformers import BertTokenizer, BertForSequenceClassification
from torch.nn.functional import softmax
# Load the tokenizer and model
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
# Check if CUDA is available, otherwise use CPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load the saved model
model = joblib.load('model.joblib')
model.to(device)
model.eval()
# Class names
class_names = ["JAILBREAK", "INJECTION", "PHISHING", "SAFE"]
def preprocess(text):
# Tokenize the input text
encoding = tokenizer(
text,
truncation=True,
padding=True,
max_length=128,
return_tensors='pt'
)
return encoding
def inference(model_inputs):
"""
This function will be called for every inference request.
"""
try:
# Get the text input
text = model_inputs.get('text', None)
if text is None:
return {'message': 'No text provided for inference.'}
# Preprocess the text
encoding = preprocess(text)
input_ids = encoding['input_ids'].to(device)
attention_mask = encoding['attention_mask'].to(device)
# Perform inference
with torch.no_grad():
outputs = model(input_ids, attention_mask=attention_mask)
logits = outputs.logits
probabilities = softmax(logits, dim=-1)
confidence, predicted_class = torch.max(probabilities, dim=-1)
# Prepare the response
predicted_label = class_names[predicted_class.item()]
confidence_score = confidence.item()
return {
'classification': predicted_label,
'confidence': confidence_score
}
except Exception as e:
return {'error': str(e)}
|