Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import torchfrom transformers import DistilBertTokenizer, DistilBertForSequenceClassificationimport gradio as grimport reimport nltkfrom nltk.tokenize import word_tokenizefrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizer# Download NLTK resources (optional if already available)nltk.download('punkt_tab')nltk.download('stopwords')nltk.download('wordnet')# Preprocessing setupstop_words = set(stopwords.words('english'))lemmatizer = WordNetLemmatizer()def preprocess_text(text):# Remove non-alphabetic characterstext = re.sub(r'[^A-Za-z\s]', '', text)# Remove URLstext = re.sub(r'http\S+|www\S+|https\S+', '', text)# Remove extra spacestext = re.sub(r'\s+', ' ', text).strip()# Lowercasetext = text.lower()# Tokenizetokens = word_tokenize(text)# Remove stopwordstokens = [word for word in tokens if word not in stop_words]# Lemmatizetokens = [lemmatizer.lemmatize(word) for word in tokens]return ' '.join(tokens)# Load tokenizer and modeltokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)# Load trained phishing detection modelmodel.load_state_dict(torch.load("phishing_model.pth", map_location=torch.device("cpu")))model.eval()# Label mappingidx2label = {0: "phishing", 1: "legitimate"}# Prediction functiondef predict(text):clean_text = preprocess_text(text)inputs = tokenizer(clean_text, return_tensors="pt", truncation=True, padding=True, max_length=128)with torch.no_grad():outputs = model(**inputs)probs = torch.nn.functional.softmax(outputs.logits, dim=1)[0].numpy()return {idx2label[i]: float(round(probs[i], 4)) for i in range(2)}# Gradio UIinterface = gr.Interface(fn=predict,inputs=gr.Textbox(lines=4, placeholder="Enter a suspicious message or account description..."),outputs=gr.Label(num_top_classes=2),title="🛡️ Phishing Account Detector",description="Detects whether an account or message is likely phishing or legitimate using a custom DistilBERT model.")if __name__ == "__main__":interface.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import torchfrom transformers import DistilBertTokenizer, DistilBertForSequenceClassificationimport gradio as grimport reimport nltkfrom nltk.tokenize import word_tokenizefrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizer# Download NLTK resources (optional if already available)nltk.download('punkt_tab')nltk.download('stopwords')nltk.download('wordnet')# Preprocessing setupstop_words = set(stopwords.words('english'))lemmatizer = WordNetLemmatizer()def preprocess_text(text):# Remove non-alphabetic characterstext = re.sub(r'[^A-Za-z\s]', '', text)# Remove URLstext = re.sub(r'http\S+|www\S+|https\S+', '', text)# Remove extra spacestext = re.sub(r'\s+', ' ', text).strip()# Lowercasetext = text.lower()# Tokenizetokens = word_tokenize(text)# Remove stopwordstokens = [word for word in tokens if word not in stop_words]# Lemmatizetokens = [lemmatizer.lemmatize(word) for word in tokens]return ' '.join(tokens)# Load tokenizer and modeltokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)# Load trained phishing detection modelmodel.load_state_dict(torch.load("best_model.pth", map_location=torch.device("cpu")))model.eval()# Label mappingidx2label = {0: "phishing", 1: "legitimate"}# Prediction functiondef predict(text):clean_text = preprocess_text(text)inputs = tokenizer(clean_text, return_tensors="pt", truncation=True, padding=True, max_length=128)with torch.no_grad():outputs = model(**inputs)probs = torch.nn.functional.softmax(outputs.logits, dim=1)[0].numpy()return {idx2label[i]: float(round(probs[i], 4)) for i in range(2)}# Gradio UIinterface = gr.Interface(fn=predict,inputs=gr.Textbox(lines=4, placeholder="Enter a suspicious message or account description..."),outputs=gr.Label(num_top_classes=2),title="🛡️ Phishing Account Detector",description="Detects whether an account or message is likely phishing or legitimate using a custom DistilBERT model.")if __name__ == "__main__":interface.launch()
app.py+67-67