ExistedYear commited on
Commit
7d945cb
·
1 Parent(s): fa9bd1a

flask design ported to gradio: verdict cards, confidence bar, url blocks, shap bars, phone-framed mobile tab

Browse files
Files changed (1) hide show
  1. app.py +440 -150
app.py CHANGED
@@ -26,105 +26,389 @@ print("Loading SHAP explainer...")
26
  explainer = SmishingExplainer(predictor)
27
  print("Model loaded. Ready.")
28
 
 
29
  CSS = """
30
  @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
31
- .gradio-container { font-family: 'Plus Jakarta Sans', sans-serif !important; max-width: 920px !important; margin: 0 auto !important; }
32
- .ss-hero { text-align: center; padding: 2rem 0 1.2rem; }
33
- .ss-hero h1 { font-size: 2.3rem; font-weight: 800; letter-spacing: -0.5px; margin: 0; }
34
- .ss-hero h1 span { color: #3b82f6; }
35
- .ss-hero p { opacity: 0.65; font-size: 0.92rem; margin-top: 0.4rem; }
36
- .ss-badge { display: inline-flex; align-items: center; gap: 0.35rem; background: rgba(59,130,246,.12);
37
- border: 1px solid rgba(59,130,246,.35); color: #3b82f6; font-size: 0.72rem; font-weight: 700;
38
- padding: 0.25rem 0.7rem; border-radius: 20px; margin-bottom: 0.8rem; }
39
- .phone-frame { max-width: 392px !important; margin: 0 auto !important; border: 10px solid #0b0e13;
40
- border-radius: 34px; padding: 1rem 0.9rem 1.3rem !important; box-shadow: 0 14px 44px rgba(0,0,0,.35); }
41
- .phone-notch { width: 120px; height: 22px; background: #0b0e13; border-radius: 0 0 12px 12px; margin: -1rem auto 0.7rem; }
42
- .phone-title { text-align: center; font-weight: 800; font-size: 1rem; margin-bottom: 0.2rem; }
43
- .phone-sub { text-align: center; font-size: 0.72rem; opacity: 0.6; margin-bottom: 0.8rem; }
44
- .ss-footer { text-align: center; font-size: 0.75rem; opacity: 0.6; margin-top: 1.6rem; line-height: 1.7; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  """
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- @spaces.GPU(duration=120)
49
- def analyze(message):
50
- if not message or not message.strip():
51
- return "⚠️ Please enter a message.", None, None, None
52
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  result = predictor.predict(message)
 
 
 
 
 
 
54
 
55
- label = result["label"]
56
- risk = result["risk_level"]
57
- conf = result["confidence"]
58
- lang = result.get("language", "?")
59
- gc = result.get("green_channel", False)
60
- gc_reason = result.get("green_reason", "")
61
-
62
- # --- Verdict ---
63
- if label == "safe":
64
- verdict = f"## ✅ Safe\nGreen Channel cleared: {gc_reason}"
65
- elif label == "spam":
66
- emoji = "🔴" if risk == "high" else "🟠"
67
- verdict = f"## {emoji} {label.upper()} — {risk.upper()} RISK"
68
- else:
69
- verdict = f"## 🟢 {label.upper()} — LOW RISK"
70
-
71
- verdict += f"\nConfidence: **{conf:.1%}** | Threshold: {predictor.threshold} | Language: {lang}"
72
-
73
- if gc:
74
- verdict += f"\n\n🛡️ Green Channel: {gc_reason}"
75
-
76
- # --- URL signals ---
77
- urls = result.get("url_signals", {})
78
- url_text = ""
79
- if urls.get("has_url"):
80
- url_text = "### 🔗 URL Analysis\n"
81
- flags = []
82
- if urls.get("has_ip_url"): flags.append("🔴 IP address instead of domain")
83
- if urls.get("has_shortened_url"): flags.append("🔴 URL shortener — hides real destination")
84
- if urls.get("suspicious_tld"): flags.append("🟠 Suspicious TLD (.xyz, .tk, .top etc.)")
85
- if urls.get("has_http") and not urls.get("has_https"):
86
- flags.append("🟠 HTTP (not encrypted)")
87
- if urls.get("has_legit_domain"): flags.append("🟢 Legitimate domain detected")
88
- url_text += "\n".join(f"- {f}" for f in flags) if flags else "- No obvious threats"
89
- url_text += f"\nLinks found: {urls.get('num_urls', 0)}"
90
-
91
- # --- Text signals ---
92
- text = result.get("text_signals", {})
93
- text_info = "### 📝 Text Signals\n"
94
- text_info += f"- Chars: {text.get('num_chars', 0)} | Words: {text.get('num_words', 0)}\n"
95
- text_info += f"- Uppercase: {text.get('pct_upper', 0)*100:.0f}% | Digits: {text.get('pct_digits', 0)*100:.0f}%\n"
96
- text_info += f"- Urgency keywords: {text.get('urgency_count', 0)}\n"
97
- text_info += f"- Phone number: {'Yes' if text.get('has_phone') else 'No'} | Currency symbol: {'Yes' if text.get('has_currency') else 'No'}"
98
-
99
- # --- Internal scores ---
100
- scores = "### ⚙️ Scores\n"
101
- scores += f"Neural: {result.get('_neural_score', 0):.3f} | Rule: {result.get('_rule_score', 0):.3f} | Ham: {result.get('_ham_rule_score', 0):.3f}"
102
-
103
- # --- SHAP explanation ---
104
- shap_text = "### 🔬 SHAP Explainability\n"
105
  try:
106
- explanation = explainer.explain_text(message, num_features=8)
107
- if explanation["top_spam_words"]:
108
- shap_text += "*Spam indicators:*\n"
109
- for word, val in explanation["top_spam_words"]:
110
- shap_text += f"- `{word}` +{val:.3f}\n"
111
- if explanation["top_ham_words"]:
112
- shap_text += "*Ham indicators:*\n"
113
- for word, val in explanation["top_ham_words"]:
114
- shap_text += f"- `{word}` {val:.3f}\n"
115
- if not explanation["top_spam_words"] and not explanation["top_ham_words"]:
116
- shap_text += "No strong word-level signals found."
117
  except Exception:
118
- shap_text += "SHAP explanation unavailable for this message."
119
 
120
- return verdict, url_text if url_text else "No URLs found", text_info + "\n\n" + scores, shap_text
121
 
122
-
123
- examples = [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  "URGENT: Your SBI account has been suspended. Verify KYC now at http://sbi-kyc-verify.xyz or funds frozen.",
125
  "HDFC Bank: Rs.25,000 credited to a/c XX4521. Avl bal: Rs.1,42,356. -HDFC Bank",
126
  "Aapka bijli connection aaj raat 9:30 baje band ho jayega. Turant call karein: 9876543210",
127
- "Airtel: Your recharge of Rs.239 is successful. Validity 28 days. -Airtel",
128
  "CBI notice: Aapke khilaf money laundering case darj. Digital arrest warrant. Call 9911000000.",
129
  "PhonePe: Rs.500 received from Rahul Kumar. UPI Ref: 4893721019.",
130
  "बधाई हो! आपको KBC लॉटरी में ₹25,00,000 का इनाम मिला। http://kbc-lottery.ml/win",
@@ -133,81 +417,87 @@ examples = [
133
  "Mom, I landed safely. Will call from the hotel in an hour.",
134
  ]
135
 
136
- seed_labels = ["Seed 1 · EN spam (KYC)", "Seed 2 · EN ham (bank)", "Seed 3 · Hinglish spam (bijli)",
137
- "Seed 4 · EN ham (recharge)", "Seed 5 · Hinglish spam (CBI)", "Seed 6 · EN ham (UPI)",
138
- "Seed 7 · Hindi spam (lottery)", "Seed 8 · EN ham (OTP)", "Seed 9 · EN spam (UPI)",
139
- "Seed 10 · EN ham (personal)"]
140
-
141
-
142
- def _pick_seed(choice):
143
- try:
144
- idx = seed_labels.index(choice)
145
- except ValueError:
146
- idx = 0
147
- return examples[idx]
148
-
149
 
150
  with gr.Blocks(title="ScamShield — Smishing Detector", css=CSS,
151
- theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate")) as demo:
152
- gr.HTML("""<div class="ss-hero">
153
- <div class="ss-badge">🛡️ AI · Cybersecurity — Smishing Detection</div>
154
- <h1>Detect <span>Scams</span> Before They Strike</h1>
155
- <p>XLM-RoBERTa + URL fusion + SHAP · English · Hindi · Hinglish · Threshold 0.55</p>
156
- </div>""")
157
 
158
  with gr.Tabs():
159
- with gr.TabItem("Desktop"):
160
  with gr.Row():
161
- with gr.Column(scale=2):
162
- inp = gr.Textbox(label="SMS Message", placeholder="Paste the SMS message here...",
163
- lines=4, max_lines=10)
164
- btn = gr.Button("🔍 Analyze", variant="primary", size="lg")
165
- gr.Examples(examples=examples, inputs=inp, label="Try these examples")
166
-
167
  with gr.Column(scale=3):
168
- verdict = gr.Markdown(label="Verdict")
169
  with gr.Tabs():
170
  with gr.TabItem("URL Analysis"):
171
- url_box = gr.Markdown()
172
  with gr.TabItem("Text Signals"):
173
- text_box = gr.Markdown()
174
  with gr.TabItem("SHAP Explainability"):
175
- shap_box = gr.Markdown()
176
-
177
- btn.click(fn=analyze, inputs=inp,
178
- outputs=[verdict, url_box, text_box, shap_box], api_name="predict")
179
- inp.submit(fn=analyze, inputs=inp,
180
- outputs=[verdict, url_box, text_box, shap_box])
181
-
182
- with gr.TabItem("Mobile"):
183
- gr.Markdown("Phone-style scanner — same live model. Full app adds the 100-message seeded inbox + Scan All; "
184
- "pick a seed below or paste any SMS.")
185
- with gr.Column(elem_classes="phone-frame"):
186
- gr.HTML('<div class="phone-notch"></div><div class="phone-title">🛡️ ScamShield</div>'
187
- '<div class="phone-sub">Seeded inbox preview · live analysis</div>')
188
- seed = gr.Dropdown(choices=seed_labels, value=seed_labels[0], label="Seeded message")
189
- minp = gr.Textbox(label="SMS Message", lines=3, max_lines=6)
190
- mbtn = gr.Button("🔍 Scan", variant="primary")
191
- mverdict = gr.Markdown(label="Verdict")
192
- with gr.Tabs():
193
- with gr.TabItem("URLs"):
194
- murl = gr.Markdown()
195
- with gr.TabItem("Signals"):
196
- mtext = gr.Markdown()
197
- with gr.TabItem("SHAP"):
198
- mshap = gr.Markdown()
199
-
200
- seed.change(fn=_pick_seed, inputs=seed, outputs=minp, api_name=False)
201
- mbtn.click(fn=analyze, inputs=minp,
202
- outputs=[mverdict, murl, mtext, mshap], api_name="predict_mobile")
203
-
204
- gr.HTML("""<div class="ss-footer">
205
- <b>Model:</b> XLM-RoBERTa (xlm-roberta-base) · <b>Threshold:</b> 0.55 ·
206
- <b>Languages:</b> English · Hindi · Hinglish · <b>Features:</b> 9 URL + 8 text signals · <b>Spam F1:</b> 0.94<br/>
207
- Full Android app (.apk) via EAS build — same API underneath.
208
- </div>""")
 
 
 
 
 
 
 
 
 
209
 
210
 
211
  if __name__ == "__main__":
212
- demo.queue(default_concurrency_limit=1)
213
- demo.launch()
 
26
  explainer = SmishingExplainer(predictor)
27
  print("Model loaded. Ready.")
28
 
29
+ # ── Design tokens (ported from the Flask dashboard) ───────────────────────────
30
  CSS = """
31
  @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
32
+ :root, .dark, .light, .gradio-container {
33
+ --bg:#0d1117; --surface:#1c2333; --surface2:#21293d; --border:#2d3748;
34
+ --red:#ef4444; --red-soft:rgba(239,68,68,.12); --red-border:rgba(239,68,68,.32);
35
+ --green:#22c55e; --green-soft:rgba(22,197,94,.12); --green-border:rgba(22,197,94,.32);
36
+ --amber:#f59e0b; --amber-soft:rgba(245,158,11,.12); --amber-border:rgba(245,158,11,.32);
37
+ --accent:#3b82f6; --accent-soft:rgba(59,130,246,.12); --accent-border:rgba(59,130,246,.34);
38
+ --text:#f0f6fc; --text2:#8b949e; --text3:#5b6472;
39
+ }
40
+ body, .gradio-container, input, textarea, button {
41
+ font-family:'Plus Jakarta Sans',sans-serif !important;
42
+ }
43
+ .dark body, .dark .gradio-container { background:var(--bg) !important; color:var(--text) !important; }
44
+ .gradio-container { max-width:960px !important; margin:0 auto !important; }
45
+ footer, .gradio-container > footer { display:none !important; }
46
+
47
+ /* header */
48
+ .ss-hero{text-align:center;padding:1.6rem 0 .6rem}
49
+ .ss-hero h1{font-size:2.2rem;font-weight:800;letter-spacing:-.6px;margin:0;line-height:1.2}
50
+ .ss-hero h1 span{color:var(--accent)}
51
+ .ss-hero p{color:var(--text2);font-size:.9rem;margin-top:.35rem}
52
+ .ss-tag{display:inline-block;background:var(--accent-soft);border:1px solid var(--accent-border);
53
+ color:var(--accent);font-size:.7rem;font-weight:700;padding:.22rem .7rem;border-radius:20px;
54
+ margin-bottom:.7rem}
55
+ .ss-foot{text-align:center;color:var(--text3);font-size:.74rem;margin:1.2rem 0 .4rem;line-height:1.8}
56
+
57
+ /* cards */
58
+ .ss-card{background:var(--surface);border:1px solid var(--border);border-radius:14px;
59
+ padding:1.1rem 1.2rem}
60
+ .ss-card.r-high{border-color:var(--red-border);box-shadow:0 0 0 1px var(--red-border)}
61
+ .ss-card.r-med{border-color:var(--amber-border);box-shadow:0 0 0 1px var(--amber-border)}
62
+ .ss-card.r-low{border-color:var(--green-border);box-shadow:0 0 0 1px var(--green-border)}
63
+
64
+ /* verdict */
65
+ .ss-v{display:flex;align-items:center;gap:.9rem}
66
+ .ss-vb{width:54px;height:54px;border-radius:13px;display:flex;align-items:center;
67
+ justify-content:center;font-size:1.4rem;flex-shrink:0}
68
+ .vb-r{background:var(--red-soft);border:1.5px solid var(--red-border);color:var(--red)}
69
+ .vb-a{background:var(--amber-soft);border:1.5px solid var(--amber-border);color:var(--amber)}
70
+ .vb-g{background:var(--green-soft);border:1.5px solid var(--green-border);color:var(--green)}
71
+ .ss-vt{font-size:1.02rem;font-weight:800}
72
+ .ss-vr{font-size:.78rem;color:var(--text2);display:flex;align-items:center;gap:.35rem}
73
+ .ss-dot{width:7px;height:7px;border-radius:50%;display:inline-block}
74
+
75
+ /* confidence */
76
+ .ss-cl{font-size:.76rem;font-weight:600;color:var(--text2);margin-bottom:.35rem}
77
+ .ss-track{height:9px;border-radius:5px;background:var(--surface2);border:1px solid var(--border);
78
+ overflow:hidden}
79
+ .ss-fill{height:100%;border-radius:5px;transition:width .9s cubic-bezier(.23,1,.32,1)}
80
+ .ss-ticks{display:flex;justify-content:space-between;margin-top:.22rem;font-size:.64rem;
81
+ color:var(--text3)}
82
+
83
+ /* labels + rows */
84
+ .ss-lbl{font-size:.66rem;font-weight:800;color:var(--text3);letter-spacing:.8px;
85
+ text-transform:uppercase;margin:.9rem 0 .35rem}
86
+ .ss-box{background:var(--bg);border:1px solid var(--border);border-left:3px solid var(--accent);
87
+ border-radius:0 9px 9px 0;padding:.65rem .85rem;color:var(--text2);font-size:.8rem;
88
+ line-height:1.6;word-break:break-word}
89
+ .ss-url{border:1px solid var(--border);border-radius:10px;padding:.55rem .8rem;
90
+ background:var(--surface2);font-size:.76rem}
91
+ .ss-flag{color:var(--text2);font-size:.74rem;line-height:1.7}
92
+ .ss-kw{display:inline-block;background:var(--accent-soft);border:1px solid var(--accent-border);
93
+ border-radius:6px;color:var(--accent);font-size:.69rem;font-weight:700;padding:.12rem .42rem;
94
+ margin:.1rem}
95
+ .ss-alert{border-radius:10px;padding:.8rem .95rem;margin-top:.9rem;font-size:.78rem;
96
+ line-height:1.7;color:var(--text2)}
97
+ .al-red{background:var(--red-soft);border:1px solid var(--red-border)}
98
+ .al-inf{background:var(--accent-soft);border:1px solid var(--accent-border)}
99
+ .al-green{background:var(--green-soft);border:1px solid var(--green-border)}
100
+ .ss-alert b{color:var(--text)}
101
+ .ss-alert code{background:var(--surface2);border:1px solid var(--border);border-radius:4px;
102
+ padding:.02rem .3rem;font-family:monospace;font-size:.74rem;color:var(--text)}
103
+ .ss-scoreline{font-size:.76rem;color:var(--text3);font-family:monospace}
104
+
105
+ /* shap */
106
+ .shap-chart{display:flex;flex-direction:column;gap:.4rem;margin-top:.2rem}
107
+ .shap-row{display:flex;align-items:center;gap:.5rem}
108
+ .shap-word{width:104px;text-align:right;font-weight:600;font-size:.72rem;color:var(--text2);
109
+ white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
110
+ .shap-bc{flex:1;position:relative;height:16px}
111
+ .shap-bc::before{content:'';position:absolute;left:50%;top:-2px;bottom:-2px;width:1px;
112
+ background:var(--border)}
113
+ .shap-val{width:48px;font-size:.68rem;color:var(--text3)}
114
+
115
+ /* phone frame */
116
+ .phone{max-width:392px;margin:0 auto;background:var(--surface);border:10px solid #0b0e13;
117
+ border-radius:34px;padding:.9rem .8rem 1.2rem;box-shadow:0 14px 44px rgba(0,0,0,.35)}
118
+ .phone-notch{width:120px;height:18px;background:#0b0e13;border-radius:0 0 12px 12px;
119
+ margin:0 auto .7rem}
120
+ .phone-brand{text-align:center;font-weight:800;font-size:.94rem;margin-bottom:.6rem}
121
+ .phone-brand span{color:var(--accent)}
122
+ .p-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:.4rem;margin:.6rem 0 .8rem}
123
+ .p-stat{background:var(--surface2);border:1px solid var(--border);border-radius:10px;
124
+ padding:.45rem .2rem;text-align:center}
125
+ .p-stat b{display:block;font-size:1.1rem;font-weight:800}
126
+ .p-stat span{font-size:.6rem;color:var(--text3);text-transform:uppercase;letter-spacing:.5px}
127
+ .p-list{border:1px solid var(--border);border-radius:10px;overflow:hidden;max-height:300px;
128
+ overflow-y:auto}
129
+ .p-item{display:flex;gap:.5rem;align-items:flex-start;padding:.5rem .6rem;
130
+ border-bottom:1px solid var(--border);font-size:.74rem;cursor:pointer}
131
+ .p-item:last-child{border-bottom:none}
132
+ .p-item:hover{background:var(--surface2)}
133
+ .p-dot{width:8px;height:8px;border-radius:50%;margin-top:.35rem;flex-shrink:0;background:var(--text3)}
134
+ .p-sender{font-size:.66rem;color:var(--text3);font-weight:700}
135
+ .p-body{color:var(--text2);line-height:1.45;overflow:hidden}
136
+ .p-lab{font-size:.58rem;font-weight:800;padding:.08rem .36rem;border-radius:20px;
137
+ flex-shrink:0;margin-top:.15rem}
138
+ .p-note{font-size:.73rem;color:var(--text3);line-height:1.6;margin:.8rem 0 .2rem}
139
+ .mob-col{display:grid;grid-template-columns:392px 1fr;gap:1.3rem;align-items:start}
140
+ @media(max-width:880px){.mob-col{grid-template-columns:1fr}}
141
+
142
+ /* gradio bits */
143
+ .ss-msg textarea{background:var(--bg)!important;border:1.5px solid var(--border)!important;
144
+ border-radius:10px!important;color:var(--text)!important}
145
+ .ss-msg textarea:focus{border-color:var(--accent)!important}
146
+ .ss-btn button{background:var(--accent)!important;border:none!important;font-weight:800!important;
147
+ border-radius:10px!important}
148
+ .ss-sel .wrap, .gradio-container .wrap{border-color:var(--border)!important}
149
+ footer{display:none!important}
150
  """
151
 
152
+ SEED_SMS = [
153
+ {"s": "+91-SBI-ALERT", "b": "URGENT: Your SBI account has been suspended. Verify KYC now at http://sbi-kyc-verify.xyz or funds will be frozen.", "e": "spam"},
154
+ {"s": "+91-LOTTERY", "b": "CONGRATULATIONS! You have been selected as the lucky winner of Rs.5,00,000. Claim before it expires: http://prize-winner.xyz/claim", "e": "spam"},
155
+ {"s": "+91-DHL", "b": "Your package could not be delivered. Pay Rs.2.99 customs fee at http://dhl-fee.net/track or it will be returned.", "e": "spam"},
156
+ {"s": "+91-CBI", "b": "CBI notice: Aapke khilaf money laundering case darj. Digital arrest warrant. Call 9911000000.", "e": "spam"},
157
+ {"s": "+91-BIJLI", "b": "Aapka bijli connection aaj raat 9:30 baje band ho jayega. Turant call karein: 9876543210", "e": "spam"},
158
+ {"s": "+91-UPI", "b": "Dear user, your UPI ID expires in 24h. Renew at http://upi-renew.club/verify", "e": "spam"},
159
+ {"s": "+91-IPURL", "b": "Your account is compromised. Verify immediately at http://192.168.44.12/secure-login", "e": "spam"},
160
+ {"s": "लोटरी", "b": "बधाई हो! आपको KBC लॉटरी में ₹25,00,000 का इनाम मिला। http://kbc-lottery.ml/win", "e": "spam"},
161
+ {"s": "बिजली", "b": "प्रिय ग्राहक, आपका बिजली कनेक्शन आज रात 9:30 बजे क��ट दिया जाएगा। अभी कॉल करें: 9876543210", "e": "spam"},
162
+ {"s": "+91-HDFC", "b": "HDFC Bank: Rs.25,000 credited to a/c XX4521 on 02-May. Avl bal: Rs.1,42,356. -HDFC Bank", "e": "ham"},
163
+ {"s": "+91-SBI", "b": "Your OTP for SBI Net Banking login is 483921. Valid for 10 minutes. Do not share. -SBI", "e": "ham"},
164
+ {"s": "+91-AIRTEL", "b": "Airtel Thanks! Your recharge of Rs.239 is successful. Validity: 28 days. Data: 1.5GB/day. -Airtel", "e": "ham"},
165
+ {"s": "+91-PHONEPE", "b": "PhonePe: Rs.500 received from Rahul Kumar. UPI Ref: 4893721019.", "e": "ham"},
166
+ {"s": "+91-AMAZON", "b": "Your Amazon order #402-9876543 is out for delivery today. Track: amzn.in/track -Amazon", "e": "ham"},
167
+ {"s": "+91-IRCTC", "b": "Your IRCTC ticket PNR 4567891230 is confirmed. Train 12345 on 05-May. Seat: S4/32. -IRCTC", "e": "ham"},
168
+ {"s": "Mum", "b": "Mom, I landed safely. Will call from the hotel in an hour.", "e": "ham"},
169
+ ]
170
 
171
+ SEED_LABELS = [f"{m['s']}" for m in SEED_SMS]
172
+
173
+
174
+ def esc(s):
175
+ return (str(s).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))
176
+
177
+
178
+ def risk_of(p, risk_level=""):
179
+ if p >= 75 or risk_level == "high":
180
+ return "r", "var(--red)", "vb-r", "High Risk", "🔴"
181
+ if p >= 55 or risk_level == "medium":
182
+ return "a", "var(--amber)", "vb-a", "Medium Risk", "🟠"
183
+ return "g", "var(--green)", "vb-g", "Low Risk", "🟢"
184
+
185
+
186
+ def verdict_html(result, msg=""):
187
+ conf = result.get("confidence", 0)
188
+ p = max(0, min(99, round(conf * 100)))
189
+ lvl, colour, badge, label, icon = risk_of(p, result.get("risk_level", ""))
190
+ spam = result.get("label") == "spam"
191
+ title = "Threat Detected" if spam else ("Safe" if result.get("label") == "safe" else "Appears Legitimate")
192
+
193
+ out = [f'<div class="ss-card r-{"high" if lvl=="r" else ("med" if lvl=="a" else "low")}">']
194
+ out.append(
195
+ f'<div class="ss-v"><div class="ss-vb {badge}">{icon}</div><div>'
196
+ f'<div class="ss-vt">{title}</div>'
197
+ f'<div class="ss-vr"><span class="ss-dot" style="background:{colour}"></span>'
198
+ f'{label} · {result.get("language","?")} · threshold {predictor.threshold}</div></div></div>'
199
+ )
200
+
201
+ if msg:
202
+ out.append('<div class="ss-lbl">Scanned input</div>')
203
+ out.append(f'<div class="ss-box">{esc(msg)}</div>')
204
+
205
+ out.append('<div class="ss-lbl">Threat confidence score</div>')
206
+ out.append(
207
+ f'<div class="ss-cl">{p}% probability of smishing</div>'
208
+ f'<div class="ss-track"><div class="ss-fill" style="width:{p}%;background:{colour}"></div></div>'
209
+ f'<div class="ss-ticks"><span>Safe 0%</span><span>Threshold 55%</span><span>High 75%+</span></div>'
210
+ )
211
+
212
+ if result.get("green_channel"):
213
+ out.append(
214
+ f'<div class="ss-alert al-green"><b>🛡 Green Channel cleared:</b> '
215
+ f'{esc(result.get("green_reason",""))}</div>'
216
+ )
217
+
218
+ out.append("</div>")
219
+ return "".join(out)
220
+
221
+
222
+ def url_html(result):
223
+ u = result.get("url_signals", {})
224
+ if not u.get("has_url"):
225
+ return '<div class="ss-card"><div class="ss-flag">No URLs found in this message.</div></div>'
226
+
227
+ rows = []
228
+ if u.get("has_ip_url"): rows.append(("🔴", "IP address used instead of a domain"))
229
+ if u.get("has_shortened_url"): rows.append(("🔴", "URL shortener — hides the real destination"))
230
+ if u.get("suspicious_tld"): rows.append(("🟠", "Suspicious TLD (.xyz, .tk, .top …)"))
231
+ if u.get("has_http") and not u.get("has_https"): rows.append(("🟠", "HTTP — connection not encrypted"))
232
+ if u.get("has_legit_domain"): rows.append(("🟢", "Legitimate domain detected"))
233
+
234
+ flags = "".join(f"<div>{i} {t}</div>" for i, t in rows) or "<div>No obvious threats</div>"
235
+ return (
236
+ f'<div class="ss-card"><div class="ss-lbl" style="margin-top:0">URL analysis</div>'
237
+ f'<div class="ss-url">{flags}</div>'
238
+ f'<div class="ss-flag" style="margin-top:.45rem">Links found: {u.get("num_urls",0)}</div></div>'
239
+ )
240
+
241
+
242
+ def signals_html(result):
243
+ t = result.get("text_signals", {})
244
+ line1 = f'Chars {t.get("num_chars",0)} · Words {t.get("num_words",0)} · Upper {round(t.get("pct_upper",0)*100)}% · Digits {round(t.get("pct_digits",0)*100)}%'
245
+ line2 = (f'Urgency keywords {t.get("urgency_count",0)} · '
246
+ f'Phone number {"Yes" if t.get("has_phone") else "No"} · '
247
+ f'Currency symbol {"Yes" if t.get("has_currency") else "No"}')
248
+ kws = [w for w in result.get("_tokens", [])][:12]
249
+ kw_html = ""
250
+ if kws:
251
+ kw_html = ('<div class="ss-lbl">Trigger tokens</div>' +
252
+ "".join(f'<span class="ss-kw">{esc(w)}</span>' for w in kws))
253
+
254
+ scores = (
255
+ f'Neural {result.get("_neural_score",0):.3f} · '
256
+ f'Rule {result.get("_rule_score",0):.3f} · '
257
+ f'Ham {result.get("_ham_rule_score",0):.3f}'
258
+ )
259
+ return (
260
+ f'<div class="ss-card"><div class="ss-lbl" style="margin-top:0">Text signals</div>'
261
+ f'<div class="ss-box">{esc(line1)}<br>{esc(line2)}</div>'
262
+ f'<div class="ss-lbl">Scores</div><div class="ss-scoreline">{esc(scores)}</div>{kw_html}</div>'
263
+ )
264
+
265
+
266
+ def shap_html(words, note=""):
267
+ if not words:
268
+ return f'<div class="ss-card"><div class="ss-flag">{esc(note or "No strong word-level signals found.")}</div></div>'
269
+ rows = sorted(words, key=lambda w: -abs(w[1]))[:10]
270
+ mx = max(abs(w[1]) for w in rows) or 1
271
+ bars = []
272
+ for word, val in rows:
273
+ pct = (abs(val) / mx) * 45
274
+ style = (f"left:50%;width:{pct}%;background:var(--red)" if val > 0
275
+ else f"right:50%;width:{pct}%;background:var(--green)")
276
+ bars.append(
277
+ f'<div class="shap-row"><div class="shap-word">{esc(word)}</div>'
278
+ f'<div class="shap-bc"><div style="position:absolute;height:10px;border-radius:2px;top:3px;{style}"></div></div>'
279
+ f'<div class="shap-val">{val:+.3f}</div></div>'
280
+ )
281
+ return f'<div class="ss-card"><div class="shap-chart">{"".join(bars)}</div></div>'
282
+
283
+
284
+ def warn_html(result):
285
+ if result.get("label") != "spam":
286
+ return ""
287
+ return (
288
+ '<div class="ss-alert al-red"><b>⚠ Early Warning — do not act on this message.</b><br>'
289
+ 'Do <b>NOT</b> click links or share your OTP, Aadhaar or bank details.<br>'
290
+ '▸ Block the sender · ▸ Report at <code>cybercrime.gov.in</code> · Helpline <code>1930</code></div>'
291
+ )
292
+
293
+
294
+ def _run(message):
295
  result = predictor.predict(message)
296
+ result["_tokens"] = sorted(
297
+ w for w in str(message).lower().split()
298
+ if w.isalpha() and len(w) > 2
299
+ )
300
+ return result
301
+
302
 
303
+ def _explain(message):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  try:
305
+ return explainer.explain_text(message, num_features=10)
 
 
 
 
 
 
 
 
 
 
306
  except Exception:
307
+ return {"top_spam_words": [], "top_ham_words": []}
308
 
 
309
 
310
+ # ── Tab 1: text scanner ────────────────────────────────────────────────────────
311
+ @spaces.GPU(duration=90)
312
+ def scan(message):
313
+ if not message or not message.strip():
314
+ blank = '<div class="ss-card"><div class="ss-flag">Please enter a message to analyse.</div></div>'
315
+ return blank, blank, blank, blank, ""
316
+
317
+ result = _run(message)
318
+ ex = _explain(message)
319
+ words = list(ex.get("top_spam_words", [])) + list(ex.get("top_ham_words", []))
320
+ return (
321
+ verdict_html(result, message),
322
+ url_html(result),
323
+ signals_html(result),
324
+ shap_html(words),
325
+ warn_html(result),
326
+ )
327
+
328
+
329
+ # ── Tab 2: mobile view ─────────────────────────────────────────────────────────
330
+ @spaces.GPU
331
+ def mobile_detail(seed_choice, custom=""):
332
+ idx = SEED_LABELS.index(seed_choice) if seed_choice in SEED_LABELS else 0
333
+ message = custom.strip() if custom.strip() else SEED_SMS[idx]["b"]
334
+ result = _run(message)
335
+ ex = _explain(message)
336
+ words = list(ex.get("top_spam_words", [])) + list(ex.get("top_ham_words", []))
337
+ body = verdict_html(result, message) + url_html(result) + signals_html(result)
338
+ body += shap_html(words, "Scan a message to see word-level SHAP impact.")
339
+ body += warn_html(result)
340
+ return body
341
+
342
+
343
+ @spaces.GPU
344
+ def mobile_scan_all(progress=gr.Progress()):
345
+ rows, threats, safe = [], 0, 0
346
+ for i, seed in enumerate(SEED_SMS):
347
+ progress(i / len(SEED_SMS), desc=f"Scanning {i+1}/{len(SEED_SMS)} · {seed['s']}")
348
+ try:
349
+ r = _run(seed["b"])
350
+ is_spam = r.get("label") == "spam"
351
+ except Exception:
352
+ r = {"label": "ham"}
353
+ is_spam = False
354
+ threats += is_spam
355
+ safe += (not is_spam)
356
+ rows.append(
357
+ f'<div class="p-item"><span class="p-dot" style="background:'
358
+ f'{"var(--red)" if is_spam else "var(--green)"}"></span>'
359
+ f'<div style="flex:1;min-width:0"><div class="p-sender">{esc(seed["s"])}</div>'
360
+ f'<div class="p-body">{esc(seed["b"][:96])}{"…" if len(seed["b"])>96 else ""}</div></div>'
361
+ f'<span class="p-lab" style="background:{"var(--red-soft)" if is_spam else "var(--green-soft)"};'
362
+ f'color:{"var(--red)" if is_spam else "var(--green)"};'
363
+ f'border:1px solid {"var(--red-border)" if is_spam else "var(--green-border)"}">'
364
+ f'{"RISK" if is_spam else "SAFE"}</span></div>'
365
+ )
366
+
367
+ progress(1, desc="done")
368
+ stats = (
369
+ '<div class="p-stats">'
370
+ f'<div class="p-stat"><b>{len(SEED_SMS)}</b><span>Scanned</span></div>'
371
+ f'<div class="p-stat"><b style="color:var(--red)">{threats}</b><span>Threats</span></div>'
372
+ f'<div class="p-stat"><b style="color:var(--green)">{safe}</b><span>Safe</span></div>'
373
+ f'</div>'
374
+ )
375
+ return stats + f'<div class="p-list">{"".join(rows)}</div>'
376
+
377
+
378
+ # ── JSON API (used by the mobile app and any external client) ─────────────────
379
+ @spaces.GPU(duration=60)
380
+ def predict_api(message: str) -> dict:
381
+ return _run(message)
382
+
383
+
384
+ @spaces.GPU
385
+ def explain_api(message: str) -> dict:
386
+ result = _run(message)
387
+ ex = _explain(message)
388
+ return {
389
+ "label": result["label"],
390
+ "confidence": result["confidence"],
391
+ "top_spam_words": ex.get("top_spam_words", []),
392
+ "top_ham_words": ex.get("top_ham_words", []),
393
+ }
394
+
395
+
396
+ def check_domain_api(domain: str) -> dict:
397
+ from utils.safe_browsing import check_domain_status
398
+
399
+ status = check_domain_status(domain)
400
+ return {
401
+ "domain": domain,
402
+ "status": status,
403
+ "is_legitimate": status == "known_safe",
404
+ "is_malicious": status == "known_malicious",
405
+ }
406
+
407
+
408
+ EXAMPLES = [
409
  "URGENT: Your SBI account has been suspended. Verify KYC now at http://sbi-kyc-verify.xyz or funds frozen.",
410
  "HDFC Bank: Rs.25,000 credited to a/c XX4521. Avl bal: Rs.1,42,356. -HDFC Bank",
411
  "Aapka bijli connection aaj raat 9:30 baje band ho jayega. Turant call karein: 9876543210",
 
412
  "CBI notice: Aapke khilaf money laundering case darj. Digital arrest warrant. Call 9911000000.",
413
  "PhonePe: Rs.500 received from Rahul Kumar. UPI Ref: 4893721019.",
414
  "बधाई हो! आपको KBC लॉटरी में ₹25,00,000 का इनाम मिला। http://kbc-lottery.ml/win",
 
417
  "Mom, I landed safely. Will call from the hotel in an hour.",
418
  ]
419
 
420
+ HERO = (
421
+ '<div class="ss-hero">'
422
+ '<span class="ss-tag">🛡 AI · Cybersecurity — Smishing Detection</span>'
423
+ '<h1>Detect <span>Scams</span> Before They Strike</h1>'
424
+ '<p>XLM-RoBERTa + URL fusion + SHAP · English · Hindi · Hinglish</p>'
425
+ "</div>"
426
+ )
427
+ FOOT = (
428
+ '<div class="ss-foot">'
429
+ "XLM-RoBERTa (xlm-roberta-base) · threshold 0.55 · 9 URL + 8 text signals · spam F1 0.94<br/>"
430
+ "Android app (.apk) runs this identical API · messages are analysed on the GPU"
431
+ "</div>"
432
+ )
433
 
434
  with gr.Blocks(title="ScamShield — Smishing Detector", css=CSS,
435
+ theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"),
436
+ fill_height=False) as demo:
437
+ gr.HTML(HERO)
 
 
 
438
 
439
  with gr.Tabs():
440
+ with gr.TabItem("Text & Link Scanner"):
441
  with gr.Row():
442
+ with gr.Column(scale=2, elem_classes="ss-msg"):
443
+ inp = gr.Textbox(label="SMS message", lines=5, max_lines=10,
444
+ placeholder="Paste the SMS message here…\nCtrl+Enter to scan.")
445
+ btn = gr.Button("🔍 Run Threat Analysis", variant="primary", size="lg",
446
+ elem_classes="ss-btn")
447
+ gr.Examples(examples=EXAMPLES, inputs=inp, label="Try these examples")
448
  with gr.Column(scale=3):
449
+ verdict = gr.HTML()
450
  with gr.Tabs():
451
  with gr.TabItem("URL Analysis"):
452
+ url_box = gr.HTML()
453
  with gr.TabItem("Text Signals"):
454
+ text_box = gr.HTML()
455
  with gr.TabItem("SHAP Explainability"):
456
+ shap_box = gr.HTML()
457
+ warn_box = gr.HTML()
458
+
459
+ for evt in (btn.click, inp.submit):
460
+ evt(fn=scan, inputs=inp,
461
+ outputs=[verdict, url_box, text_box, shap_box, warn_box],
462
+ api_name="scan", show_progress="hidden")
463
+
464
+ with gr.TabItem("Mobile App"):
465
+ with gr.Row():
466
+ with gr.Column(scale=2, elem_classes="phone"):
467
+ gr.HTML('<div class="phone-notch"></div>'
468
+ '<div class="phone-brand">🛡 <span>ScamShield</span></div>')
469
+ m_stats = gr.HTML()
470
+ m_seed = gr.Dropdown(choices=SEED_LABELS, value=SEED_LABELS[0],
471
+ label="Seeded inbox message", elem_classes="ss-sel")
472
+ m_custom = gr.Textbox(label="…or paste your own", lines=2, max_lines=4,
473
+ elem_classes="ss-msg")
474
+ with gr.Row():
475
+ m_scan = gr.Button("🔍 Scan this", variant="primary", elem_classes="ss-btn")
476
+ m_all = gr.Button("▶ Scan all 16", variant="secondary")
477
+ m_out = gr.HTML()
478
+ with gr.Column(scale=3):
479
+ gr.HTML(
480
+ '<div class="ss-card"><div class="ss-lbl" style="margin-top:0">'
481
+ "Live app, phone frame</div><div class=\"ss-flag\">"
482
+ "Same Space, same model, same SHAP — this is the mobile UI running the "
483
+ "identical analysis pipeline. The Android build adds real inbox polling "
484
+ "(<code>READ_SMS</code>), AES-256-CBC encrypted requests and background "
485
+ "threat notifications.</div></div>"
486
+ '<div class="ss-card"><div class="ss-lbl">Why a seeded inbox?</div>'
487
+ '<div class="ss-flag">Browsers and iOS cannot read an SMS inbox, so the '
488
+ "web demo ships a fixed set of English, Hindi and Hinglish messages. "
489
+ "<b>Scan all 16</b> walks the whole set through the model and tallies "
490
+ "threats vs safe.</div></div>"
491
+ )
492
+
493
+ m_scan.click(fn=mobile_detail, inputs=[m_seed, m_custom], outputs=m_out,
494
+ show_progress="hidden")
495
+ m_all.click(fn=mobile_scan_all, outputs=m_stats, show_progress="minimal")
496
+ m_stats.click(fn=mobile_scan_all, outputs=m_stats, show_progress="minimal")
497
+
498
+ gr.HTML(FOOT)
499
 
500
 
501
  if __name__ == "__main__":
502
+ demo.queue(default_concurrency_limit=2)
503
+ demo.launch()