SpamShield is a production-grade machine learning model for accurate spam detection and intelligent categorization across multiple languages. It uses a dual-model architecture:
1import numpy as np
2import onnxruntime as ort
34# Load ONNX models5binary_model = ort.InferenceSession('binary_model.onnx',6 providers=['CPUExecutionProvider'])7category_model = ort.InferenceSession('category_model.onnx',8 providers=['CPUExecutionProvider'])910# Classify a message11text ="Congratulations! You've won a free iPhone. Click here to claim!"1213# For simplicity, assume text is vectorized to numpy array14# In production, use the vectorizer to prepare input15# This example shows the inference pattern16input_array = np.array([[text]], dtype=object)1718# Binary prediction (spam or not)19binary_output = binary_model.run(None,{'input': input_array})20is_spam = binary_output[0][0]# 0 or 121confidence =float(binary_output[1][0].get(1,0.0))2223if is_spam:24# Category prediction25 category_output = category_model.run(None,{'input': input_array})26 category = category_output[0][0]27else:28 category ="normal"2930print(f"🚨 SPAM: {is_spam} | Category: {category} | Confidence: {confidence:.2f}")
1// iOS with Core ML (converted from ONNX)2importCoreML34let model =try!BinaryModel_onnx(configuration:MLModelConfiguration())5let input =BinaryModel_onnxInput(input:"message text here")6let output =try! model.prediction(input: input)7let isSpam = output.output0 ==1
📊 Datasets
Data Composition
Training data combines curated open-source datasets with synthetic augmentation for comprehensive coverage:
Dataset Statistics
Language
Total Messages
Normal (Ham)
Spam
Spam %
English
119,105
59,903
59,202
49.7%
Spanish
16,595
7,683
8,912
53.7%
Chinese
13,442
7,549
5,893
43.8%
Arabic
2,642
993
1,649
62.4%
Hinglish
2,385
1,368
1,017
42.6%
German
2,115
928
1,187
56.1%
Russian
1,235
635
600
48.6%
French
1,116
550
566
50.7%
🎯 TOTAL
158,635
79,609
79,026
49.8%
Data Sources & Attribution
Primary Open-Source Datasets
The model is trained on carefully curated data from multiple open-source datasets combined with extensive synthetic augmentation:
Open-Source Components:
Multiple public spam/ham message datasets
Community-contributed multilingual spam corpora
Research-backed offensive language and spam detection datasets
Email and SMS spam classification datasets
Synthetic Data Generation (35-40% of Training Set):
Extensive synthetic data was generated to ensure:
Balanced category representation: All 6 spam types equally represented
Comprehensive coverage: Edge cases, variations, and emerging spam patterns
Privacy compliance: No real personal data in synthetic samples
Realistic patterns: Generated data follows observed spam tactics
Synthesis Techniques:
Paraphrasing & variation of base patterns
Contextual generation based on category-specific tactics
1import numpy as np
2import onnxruntime as ort
3from sklearn.feature_extraction.text import TfidfVectorizer
4import pickle
56# Load models7binary_model = ort.InferenceSession('binary_model.onnx')8category_model = ort.InferenceSession('category_model.onnx')910# Load vectorizer (trained during model creation)11withopen('vectorizer.pkl','rb')as f:12 vectorizer = pickle.load(f)1314defdetect_spam(text, threshold=0.49):15"""Complete spam detection with category"""1617# Preprocess and vectorize18 X = vectorizer.transform([text]).astype(np.float32)1920# Binary prediction21 binary_inputs ={binary_model.get_inputs()[0].name: X.toarray()}22 binary_outputs = binary_model.run(None, binary_inputs)2324 spam_prob =float(binary_outputs[1][0].get(1,0.0))25 is_spam = spam_prob >= threshold
2627 result ={28'text': text,29'is_spam': is_spam,30'confidence':round(spam_prob,4),31}3233# Category prediction (if spam)34if is_spam:35 category_inputs ={category_model.get_inputs()[0].name: X.toarray()}36 category_outputs = category_model.run(None, category_inputs)37 result['category']= category_outputs[0][0]38else:39 result['category']='normal'4041return result
4243# Test44messages =[45"Hey, how are you doing?",46"Congratulations! You won a free iPhone!",47"Click here to verify your account",48"Work from home and earn $5000/week",49]5051for msg in messages:52 result = detect_spam(msg)53print(f"{msg:<45} => {result['is_spam']:>5} | {result['category']:<12} ({result['confidence']:.2f})")
Output:
Hey, how are you doing? => False | normal (0.12)
Congratulations! You won a free iPhone! => True | giveaway (0.94)
Click here to verify your account => True | phishing (0.91)
Work from home and earn $5000/week => True | job_scam (0.88)
Batch Processing with Pandas
python
1import pandas as pd
2import numpy as np
3import onnxruntime as ort
4import pickle
56# Load models and vectorizer7binary_model = ort.InferenceSession('binary_model.onnx')8category_model = ort.InferenceSession('category_model.onnx')910withopen('vectorizer.pkl','rb')as f:11 vectorizer = pickle.load(f)1213# Load data14df = pd.read_csv('messages.csv')# columns: 'text'1516# Vectorize all messages17X = vectorizer.transform(df['text']).astype(np.float32)1819# Binary predictions20binary_inputs ={binary_model.get_inputs()[0].name: X.toarray()}21binary_outputs = binary_model.run(None, binary_inputs)2223df['spam_prob']=[float(p.get(1,0.0))for p in binary_outputs[1]]24df['is_spam']= df['spam_prob']>=0.492526# Category predictions (for spam messages only)27spam_mask = df['is_spam']28df['category']='normal'2930category_inputs ={category_model.get_inputs()[0].name: X[spam_mask].toarray()}31category_outputs = category_model.run(None, category_inputs)32df.loc[spam_mask,'category']= category_outputs[0]3334# Save results35df.to_csv('messages_classified.csv', index=False)36print(df.head())
1{2"input_type":"string",3"input_shape":[null,1],4"output_format":"int64 label + probability dictionary",5"vectorization":"embedded in ONNX graph",6"conversion_method":"skl2onnx pipeline",7"providers":["CPUExecutionProvider"]8}
⚠️ Limitations
Known Constraints
Language Coverage: Best on English; varies for low-resource languages
Context: Cannot understand sarcasm, humor, or cultural references
Domain Shift: Performance degrades on completely unseen domains
Adversarial: Vulnerable to intentional obfuscation and adversarial text
False Positives: Legitimate promotional messages may be flagged
False Negatives: Sophisticated spam may evade detection
Temporal Drift: Spam patterns evolve; retraining recommended every 3-6 months
Ethical Usage Guidelines
SpamShield should be used responsibly:
⚠️ Human Review Required: Never use for autonomous enforcement without human review
⚠️ Monitor for Bias: Regularly audit predictions across user groups
⚠️ Transparency: Inform users that automated moderation is active
⚠️ Appeal Mechanism: Provide clear paths for users to contest decisions
⚠️ Compliance: Ensure usage complies with GDPR, CCPA, and local laws
⚠️ No Autonomous Banning: Always maintain human-in-the-loop for enforcement
Recommended Safeguards
python
1# For production: High confidence threshold + human review2ENFORCEMENT_THRESHOLD =0.7534if spam_confidence >= ENFORCEMENT_THRESHOLD:5# Flag for human moderator review6 flag_for_review(message, category, confidence)7else:8# For borderline cases, always require human review9if0.5<= spam_confidence < ENFORCEMENT_THRESHOLD:10 flag_for_review(message, category, confidence)
🏆 Attribution & Credits
Development & Maintenance
Arjun-M (@Arjun-M) - Model development, optimization, and maintenance
Dataset Sources & Acknowledgments
We gratefully acknowledge:
Academic Institutions
University of Colorado Boulder - OLID dataset (Offensive Language Identification)
ONNX Project - Model standardization and cross-platform deployment
Scikit-learn - Machine learning framework
NumPy - Scientific computing
ONNX Runtime - Inference engine
Language & Domain Specialists
Chinese NLP research community
Hindi/Hinglish language researchers
Multilingual offensive language identification teams
Spam detection research community
Special Thanks
This project builds upon decades of NLP and spam detection research. We thank all dataset creators, researchers, and the open-source community for making this work possible.
Free for use, modification, and distribution in open-source and commercial projects.
text
1MIT License
23Copyright (c) 2026 Arjun-M
45Permission is hereby granted, free of charge, to any person obtaining a copy
6of this software and associated documentation files (the "Software"), to deal
7in the Software without restriction, including without limitation the rights
8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9copies of the Software, and to permit persons to whom the Software is
10furnished to do so, subject to the following conditions:
1112The above copyright notice and this permission notice shall be included in all
13copies or substantial portions of the Software.
1415THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.