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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import joblib
|
| 3 |
+
import os
|
| 4 |
+
import logging
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
|
| 7 |
+
# Configure logging
|
| 8 |
+
logging.basicConfig(level=logging.INFO)
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
class SMSScamDetector:
|
| 12 |
+
"""Enhanced SMS Scam Detection System"""
|
| 13 |
+
|
| 14 |
+
def __init__(self):
|
| 15 |
+
self.model = None
|
| 16 |
+
self.vectorizer = None
|
| 17 |
+
self.load_models()
|
| 18 |
+
|
| 19 |
+
def load_models(self):
|
| 20 |
+
"""Load machine learning models with error handling"""
|
| 21 |
+
try:
|
| 22 |
+
if os.path.exists("scam_classifier_model.joblib"):
|
| 23 |
+
self.model = joblib.load("scam_classifier_model.joblib")
|
| 24 |
+
logger.info("Model loaded successfully")
|
| 25 |
+
else:
|
| 26 |
+
logger.error("Model file not found")
|
| 27 |
+
|
| 28 |
+
if os.path.exists("tfidf_vectorizer.joblib"):
|
| 29 |
+
self.vectorizer = joblib.load("tfidf_vectorizer.joblib")
|
| 30 |
+
logger.info("Vectorizer loaded successfully")
|
| 31 |
+
else:
|
| 32 |
+
logger.error("Vectorizer file not found")
|
| 33 |
+
|
| 34 |
+
except Exception as e:
|
| 35 |
+
logger.error(f"Error loading models: {str(e)}")
|
| 36 |
+
self.model = None
|
| 37 |
+
self.vectorizer = None
|
| 38 |
+
|
| 39 |
+
def preprocess_text(self, text):
|
| 40 |
+
"""Clean and preprocess input text"""
|
| 41 |
+
if not text or not isinstance(text, str):
|
| 42 |
+
return ""
|
| 43 |
+
|
| 44 |
+
# Basic cleaning
|
| 45 |
+
text = text.strip()
|
| 46 |
+
text = ' '.join(text.split()) # Remove extra whitespace
|
| 47 |
+
return text
|
| 48 |
+
|
| 49 |
+
def get_confidence_level(self, prediction_proba):
|
| 50 |
+
"""Determine confidence level based on prediction probability"""
|
| 51 |
+
max_prob = max(prediction_proba)
|
| 52 |
+
if max_prob >= 0.8:
|
| 53 |
+
return "Imara sana (Very High)", "π΄"
|
| 54 |
+
elif max_prob >= 0.65:
|
| 55 |
+
return "Imara (High)", "π "
|
| 56 |
+
elif max_prob >= 0.5:
|
| 57 |
+
return "Wastani (Medium)", "π‘"
|
| 58 |
+
else:
|
| 59 |
+
return "Haba (Low)", "π’"
|
| 60 |
+
|
| 61 |
+
def predict_sms(self, text):
|
| 62 |
+
"""Enhanced prediction function with detailed output"""
|
| 63 |
+
# Input validation
|
| 64 |
+
if not text or len(text.strip()) == 0:
|
| 65 |
+
return "β **Kosa**: Tafadhali ingiza ujumbe wa SMS"
|
| 66 |
+
|
| 67 |
+
if len(text.strip()) < 5:
|
| 68 |
+
return "β οΈ **Onyo**: Ujumbe mfupi sana. Ingiza ujumbe kamili."
|
| 69 |
+
|
| 70 |
+
# Check if models are loaded
|
| 71 |
+
if self.model is None or self.vectorizer is None:
|
| 72 |
+
return "β **Kosa la Mfumo**: Mifumo ya AI haijapakiwa vizuri. Tafadhali rudia tena."
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
# Preprocess text
|
| 76 |
+
cleaned_text = self.preprocess_text(text)
|
| 77 |
+
|
| 78 |
+
# Vectorize text
|
| 79 |
+
text_vector = self.vectorizer.transform([cleaned_text])
|
| 80 |
+
|
| 81 |
+
# Make prediction
|
| 82 |
+
prediction = self.model.predict(text_vector)[0]
|
| 83 |
+
prediction_proba = self.model.predict_proba(text_vector)[0]
|
| 84 |
+
|
| 85 |
+
# Get confidence level
|
| 86 |
+
confidence, emoji = self.get_confidence_level(prediction_proba)
|
| 87 |
+
|
| 88 |
+
# Format prediction
|
| 89 |
+
if prediction.lower() == 'scam':
|
| 90 |
+
result_text = "**SCAM** π¨"
|
| 91 |
+
result_color = "danger"
|
| 92 |
+
advice = "**Onyo**: Ujumbe huu unaweza kuwa wa udanganyifu. Usijibu au kutoa taarifa za kibinafsi."
|
| 93 |
+
else:
|
| 94 |
+
result_text = "**TRUST** β
"
|
| 95 |
+
result_color = "success"
|
| 96 |
+
advice = "Ujumbe huu unaonekana kuwa wa kawaida, lakini bado kuwa makini."
|
| 97 |
+
|
| 98 |
+
# Create detailed output
|
| 99 |
+
output = f"""
|
| 100 |
+
## Matokeo ya Uchunguzi {emoji}
|
| 101 |
+
|
| 102 |
+
**Ujumbe**: "{text[:100]}{'...' if len(text) > 100 else ''}"
|
| 103 |
+
|
| 104 |
+
**Utabiri**: {result_text}
|
| 105 |
+
|
| 106 |
+
**Kiwango cha Uhakika**: {confidence}
|
| 107 |
+
|
| 108 |
+
**Maoni**: {advice}
|
| 109 |
+
|
| 110 |
+
---
|
| 111 |
+
*Tarehe*: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
| 112 |
+
*Urefu wa ujumbe*: {len(text)} herufi
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
return output
|
| 116 |
+
|
| 117 |
+
except Exception as e:
|
| 118 |
+
logger.error(f"Prediction error: {str(e)}")
|
| 119 |
+
return f"β **Kosa la Kihesabu**: {str(e)}"
|
| 120 |
+
|
| 121 |
+
# Initialize detector
|
| 122 |
+
detector = SMSScamDetector()
|
| 123 |
+
|
| 124 |
+
# Sample SMS messages for testing
|
| 125 |
+
sample_messages = [
|
| 126 |
+
"Hongera! Umeshinda Tsh 1,000,000. Piga *123# ili kupokea zawadi yako sasa hivi!",
|
| 127 |
+
"Habari za leo? Tutaonana kesho uwandani kama tulivyopanga.",
|
| 128 |
+
"URGENT: Your account will be closed. Click link to verify: http://fake-bank.com",
|
| 129 |
+
"Mama, nimepoteza simu yangu. Hii ni nambari yangu mpya. Nitakuja nyumbani jioni."
|
| 130 |
+
]
|
| 131 |
+
|
| 132 |
+
def load_sample(sample_text):
|
| 133 |
+
"""Load sample message into the textbox"""
|
| 134 |
+
return sample_text
|
| 135 |
+
|
| 136 |
+
# Create enhanced Gradio interface
|
| 137 |
+
with gr.Blocks(
|
| 138 |
+
theme=gr.themes.Soft(),
|
| 139 |
+
title="Bongo SMS Scam Detector",
|
| 140 |
+
css="""
|
| 141 |
+
.gradio-container {
|
| 142 |
+
max-width: 800px !important;
|
| 143 |
+
margin: auto !important;
|
| 144 |
+
}
|
| 145 |
+
.warning {
|
| 146 |
+
background: linear-gradient(45deg, #ff6b6b, #feca57);
|
| 147 |
+
padding: 15px;
|
| 148 |
+
border-radius: 10px;
|
| 149 |
+
margin: 10px 0;
|
| 150 |
+
}
|
| 151 |
+
"""
|
| 152 |
+
) as demo:
|
| 153 |
+
|
| 154 |
+
gr.Markdown("""
|
| 155 |
+
# π‘οΈ Bongo SMS Scam Detector
|
| 156 |
+
|
| 157 |
+
**Kiunga cha Usalama wa SMS** - Chunguza ujumbe wa SMS ili kujua kama ni wa udanganyifu
|
| 158 |
+
|
| 159 |
+
β‘ Ingiza ujumbe wa SMS hapo chini na upate matokeo ya haraka
|
| 160 |
+
""")
|
| 161 |
+
|
| 162 |
+
with gr.Row():
|
| 163 |
+
with gr.Column(scale=2):
|
| 164 |
+
# Main input
|
| 165 |
+
sms_input = gr.Textbox(
|
| 166 |
+
lines=6,
|
| 167 |
+
placeholder="Nakili na ubandike ujumbe wa SMS hapa...\n\nMfano: 'Hongera! Umeshinda Tsh 500,000. Piga *150# ili kupokea pesa zako!'",
|
| 168 |
+
label="π± Ujumbe wa SMS",
|
| 169 |
+
info="Ingiza ujumbe wowote wa SMS unaodai kushinda zawadi, pesa, au kutaka taarifa za kibinafsi"
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
with gr.Row():
|
| 173 |
+
predict_btn = gr.Button("π Chunguza SMS", variant="primary", size="lg")
|
| 174 |
+
clear_btn = gr.Button("ποΈ Futa", variant="secondary")
|
| 175 |
+
|
| 176 |
+
with gr.Column(scale=1):
|
| 177 |
+
gr.Markdown("### π Mifano ya SMS")
|
| 178 |
+
|
| 179 |
+
# Sample buttons
|
| 180 |
+
for i, sample in enumerate(sample_messages, 1):
|
| 181 |
+
sample_btn = gr.Button(
|
| 182 |
+
f"Mfano {i}",
|
| 183 |
+
variant="outline",
|
| 184 |
+
size="sm"
|
| 185 |
+
)
|
| 186 |
+
sample_btn.click(
|
| 187 |
+
fn=lambda x=sample: x,
|
| 188 |
+
outputs=sms_input
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# Output section
|
| 192 |
+
output_result = gr.Markdown(
|
| 193 |
+
label="π Matokeo",
|
| 194 |
+
value="Matokeo yataonyeshwa hapa baada ya kuchunguza ujumbe..."
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
# Information section
|
| 198 |
+
with gr.Accordion("βΉοΈ Maelezo ya Ziada", open=False):
|
| 199 |
+
gr.Markdown("""
|
| 200 |
+
### Jinsi ya Kutumia:
|
| 201 |
+
1. **Nakili ujumbe** wa SMS kutoka kwa simu yako
|
| 202 |
+
2. **Ubandike hapa** kwenye kisanduku cha maandishi
|
| 203 |
+
3. **Bonyeza kitufe** cha "Chunguza SMS"
|
| 204 |
+
4. **Soma matokeo** na ufuate mapendekezo
|
| 205 |
+
|
| 206 |
+
### Dalili za SMS za Udanganyifu:
|
| 207 |
+
- π Inadai umeshinda zawadi kubwa
|
| 208 |
+
- π° Inahitaji malipo ya haraka
|
| 209 |
+
- π Ina viungo vya kugusia (links)
|
| 210 |
+
- β‘ Inadai ni ya dharura
|
| 211 |
+
- π Inaomba taarifa za kibinafsi
|
| 212 |
+
|
| 213 |
+
### Onyo Muhimu:
|
| 214 |
+
Mfumo huu ni wa kusaidia tu. Daima tumia busara zako na usijibu SMS zisizoeleweka.
|
| 215 |
+
""")
|
| 216 |
+
|
| 217 |
+
# Event handlers
|
| 218 |
+
predict_btn.click(
|
| 219 |
+
fn=detector.predict_sms,
|
| 220 |
+
inputs=sms_input,
|
| 221 |
+
outputs=output_result
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
clear_btn.click(
|
| 225 |
+
fn=lambda: ("", "Matokeo yataonyeshwa hapa baada ya kuchunguza ujumbe..."),
|
| 226 |
+
outputs=[sms_input, output_result]
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
sms_input.submit(
|
| 230 |
+
fn=detector.predict_sms,
|
| 231 |
+
inputs=sms_input,
|
| 232 |
+
outputs=output_result
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
# Launch configuration
|
| 236 |
+
if __name__ == "__main__":
|
| 237 |
+
demo.launch(
|
| 238 |
+
share=False,
|
| 239 |
+
server_name="0.0.0.0",
|
| 240 |
+
server_port=7860,
|
| 241 |
+
show_error=True,
|
| 242 |
+
favicon_path=None,
|
| 243 |
+
inbrowser=True
|
| 244 |
+
)
|