hackerbyhobby commited on
Commit
c0d4e9e
·
unverified ·
1 Parent(s): 8b4d92e

working good1

Browse files
Files changed (2) hide show
  1. app.py +8 -88
  2. app.py.jan27 +245 -0
app.py CHANGED
@@ -5,22 +5,6 @@ from transformers import pipeline
5
  import re
6
  from langdetect import detect
7
  from deep_translator import GoogleTranslator
8
- import shap
9
- import requests
10
- import json
11
- import os
12
- import numpy as np
13
- from shap.maskers import Text
14
-
15
- # Patch SHAP to replace np.bool with np.bool_ dynamically
16
- if hasattr(shap.maskers._text.Text, "invariants"):
17
- original_invariants = shap.maskers._text.Text.invariants
18
-
19
- def patched_invariants(self, *args):
20
- # Use np.bool_ instead of the deprecated np.bool
21
- return np.zeros(len(self._tokenized_s), dtype=np.bool_)
22
-
23
- shap.maskers._text.Text.invariants = patched_invariants
24
 
25
  # Translator instance
26
  translator = GoogleTranslator(source="auto", target="es")
@@ -37,49 +21,6 @@ model_name = "joeddav/xlm-roberta-large-xnli"
37
  classifier = pipeline("zero-shot-classification", model=model_name)
38
  CANDIDATE_LABELS = ["SMiShing", "Other Scam", "Legitimate"]
39
 
40
- # 3. SHAP Explainer Setup
41
- explainer = shap.Explainer(classifier, masker=Text(tokenizer=classifier.tokenizer))
42
-
43
- # Retrieve the Google Safe Browsing API key from the environment
44
- SAFE_BROWSING_API_KEY = os.getenv("SAFE_BROWSING_API_KEY")
45
-
46
- if not SAFE_BROWSING_API_KEY:
47
- raise ValueError("Google Safe Browsing API key not found. Please set it as an environment variable in your Hugging Face Space.")
48
-
49
- SAFE_BROWSING_URL = "https://safebrowsing.googleapis.com/v4/threatMatches:find"
50
-
51
- def check_url_with_google_safebrowsing(url):
52
- """
53
- Check a URL against Google's Safe Browsing API.
54
- """
55
- payload = {
56
- "client": {
57
- "clientId": "your-client-id",
58
- "clientVersion": "1.0"
59
- },
60
- "threatInfo": {
61
- "threatTypes": ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"],
62
- "platformTypes": ["ANY_PLATFORM"],
63
- "threatEntryTypes": ["URL"],
64
- "threatEntries": [
65
- {"url": url}
66
- ]
67
- }
68
- }
69
- try:
70
- response = requests.post(
71
- SAFE_BROWSING_URL,
72
- params={"key": SAFE_BROWSING_API_KEY},
73
- json=payload
74
- )
75
- response_data = response.json()
76
- if "matches" in response_data:
77
- return True # URL is flagged as malicious
78
- return False # URL is safe
79
- except Exception as e:
80
- print(f"Error checking URL with Safe Browsing API: {e}")
81
- return False
82
-
83
  def get_keywords_by_language(text: str):
84
  """
85
  Detect language using `langdetect` and translate keywords if needed.
@@ -142,21 +83,9 @@ def boost_probabilities(probabilities: dict, text: str):
142
  "SMiShing": p_smishing,
143
  "Other Scam": p_other_scam,
144
  "Legitimate": p_legit,
145
- "detected_lang": detected_lang,
146
  }
147
 
148
- def explain_classification(text):
149
- """
150
- Generate SHAP explanations for the classification.
151
- """
152
- if not text.strip():
153
- raise ValueError("Cannot generate SHAP explanations for empty text.")
154
-
155
- shap_values = explainer([text])
156
- shap.force_plot(
157
- explainer.expected_value[0], shap_values[0].values[0], shap_values[0].data
158
- )
159
-
160
  def smishing_detector(text, image):
161
  """
162
  Main detection function combining text and OCR.
@@ -173,8 +102,7 @@ def smishing_detector(text, image):
173
  "label": "No text provided",
174
  "confidence": 0.0,
175
  "keywords_found": [],
176
- "urls_found": [],
177
- "threat_analysis": "No URLs to analyze",
178
  }
179
 
180
  result = classifier(
@@ -197,14 +125,6 @@ def smishing_detector(text, image):
197
  found_smishing = [kw for kw in smishing_keys if kw in lower_text]
198
  found_other_scam = [kw for kw in scam_keys if kw in lower_text]
199
 
200
- # Analyze URLs using Google's Safe Browsing API
201
- threat_analysis = {
202
- url: check_url_with_google_safebrowsing(url) for url in found_urls
203
- }
204
-
205
- # SHAP Explanation (optional for user insights)
206
- explain_classification(combined_text)
207
-
208
  return {
209
  "detected_language": detected_lang,
210
  "text_used_for_classification": combined_text,
@@ -215,7 +135,6 @@ def smishing_detector(text, image):
215
  "smishing_keywords_found": found_smishing,
216
  "other_scam_keywords_found": found_other_scam,
217
  "urls_found": found_urls,
218
- "threat_analysis": threat_analysis,
219
  }
220
 
221
  demo = gr.Interface(
@@ -232,14 +151,15 @@ demo = gr.Interface(
232
  )
233
  ],
234
  outputs="json",
235
- title="SMiShing & Scam Detector with Safe Browsing",
236
  description="""
237
  This tool classifies messages as SMiShing, Other Scam, or Legitimate using a zero-shot model
238
  (joeddav/xlm-roberta-large-xnli). It automatically detects if the text is Spanish or English.
239
- It uses SHAP for explainability and checks URLs against Google's Safe Browsing API for enhanced analysis.
240
- """,
241
- flagging_mode="never"
 
242
  )
243
 
244
  if __name__ == "__main__":
245
- demo.launch()
 
5
  import re
6
  from langdetect import detect
7
  from deep_translator import GoogleTranslator
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  # Translator instance
10
  translator = GoogleTranslator(source="auto", target="es")
 
21
  classifier = pipeline("zero-shot-classification", model=model_name)
22
  CANDIDATE_LABELS = ["SMiShing", "Other Scam", "Legitimate"]
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  def get_keywords_by_language(text: str):
25
  """
26
  Detect language using `langdetect` and translate keywords if needed.
 
83
  "SMiShing": p_smishing,
84
  "Other Scam": p_other_scam,
85
  "Legitimate": p_legit,
86
+ "detected_lang": detected_lang
87
  }
88
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  def smishing_detector(text, image):
90
  """
91
  Main detection function combining text and OCR.
 
102
  "label": "No text provided",
103
  "confidence": 0.0,
104
  "keywords_found": [],
105
+ "urls_found": []
 
106
  }
107
 
108
  result = classifier(
 
125
  found_smishing = [kw for kw in smishing_keys if kw in lower_text]
126
  found_other_scam = [kw for kw in scam_keys if kw in lower_text]
127
 
 
 
 
 
 
 
 
 
128
  return {
129
  "detected_language": detected_lang,
130
  "text_used_for_classification": combined_text,
 
135
  "smishing_keywords_found": found_smishing,
136
  "other_scam_keywords_found": found_other_scam,
137
  "urls_found": found_urls,
 
138
  }
139
 
140
  demo = gr.Interface(
 
151
  )
152
  ],
153
  outputs="json",
154
+ title="SMiShing & Scam Detector (Language Detection + Keyword Translation)",
155
  description="""
156
  This tool classifies messages as SMiShing, Other Scam, or Legitimate using a zero-shot model
157
  (joeddav/xlm-roberta-large-xnli). It automatically detects if the text is Spanish or English.
158
+ If Spanish, it translates the English-based keyword lists to Spanish before boosting the scores.
159
+ Any URL found further boosts SMiShing specifically.
160
+ """,
161
+ allow_flagging="never"
162
  )
163
 
164
  if __name__ == "__main__":
165
+ demo.launch()
app.py.jan27 ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pytesseract
3
+ from PIL import Image
4
+ from transformers import pipeline
5
+ import re
6
+ from langdetect import detect
7
+ from deep_translator import GoogleTranslator
8
+ import shap
9
+ import requests
10
+ import json
11
+ import os
12
+ import numpy as np
13
+ from shap.maskers import Text
14
+
15
+ # Patch SHAP to replace np.bool with np.bool_ dynamically
16
+ if hasattr(shap.maskers._text.Text, "invariants"):
17
+ original_invariants = shap.maskers._text.Text.invariants
18
+
19
+ def patched_invariants(self, *args):
20
+ # Use np.bool_ instead of the deprecated np.bool
21
+ return np.zeros(len(self._tokenized_s), dtype=np.bool_)
22
+
23
+ shap.maskers._text.Text.invariants = patched_invariants
24
+
25
+ # Translator instance
26
+ translator = GoogleTranslator(source="auto", target="es")
27
+
28
+ # 1. Load separate keywords for SMiShing and Other Scam (assumed in English)
29
+ with open("smishing_keywords.txt", "r", encoding="utf-8") as f:
30
+ SMISHING_KEYWORDS = [line.strip().lower() for line in f if line.strip()]
31
+
32
+ with open("other_scam_keywords.txt", "r", encoding="utf-8") as f:
33
+ OTHER_SCAM_KEYWORDS = [line.strip().lower() for line in f if line.strip()]
34
+
35
+ # 2. Zero-Shot Classification Pipeline
36
+ model_name = "joeddav/xlm-roberta-large-xnli"
37
+ classifier = pipeline("zero-shot-classification", model=model_name)
38
+ CANDIDATE_LABELS = ["SMiShing", "Other Scam", "Legitimate"]
39
+
40
+ # 3. SHAP Explainer Setup
41
+ explainer = shap.Explainer(classifier, masker=Text(tokenizer=classifier.tokenizer))
42
+
43
+ # Retrieve the Google Safe Browsing API key from the environment
44
+ SAFE_BROWSING_API_KEY = os.getenv("SAFE_BROWSING_API_KEY")
45
+
46
+ if not SAFE_BROWSING_API_KEY:
47
+ raise ValueError("Google Safe Browsing API key not found. Please set it as an environment variable in your Hugging Face Space.")
48
+
49
+ SAFE_BROWSING_URL = "https://safebrowsing.googleapis.com/v4/threatMatches:find"
50
+
51
+ def check_url_with_google_safebrowsing(url):
52
+ """
53
+ Check a URL against Google's Safe Browsing API.
54
+ """
55
+ payload = {
56
+ "client": {
57
+ "clientId": "your-client-id",
58
+ "clientVersion": "1.0"
59
+ },
60
+ "threatInfo": {
61
+ "threatTypes": ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"],
62
+ "platformTypes": ["ANY_PLATFORM"],
63
+ "threatEntryTypes": ["URL"],
64
+ "threatEntries": [
65
+ {"url": url}
66
+ ]
67
+ }
68
+ }
69
+ try:
70
+ response = requests.post(
71
+ SAFE_BROWSING_URL,
72
+ params={"key": SAFE_BROWSING_API_KEY},
73
+ json=payload
74
+ )
75
+ response_data = response.json()
76
+ if "matches" in response_data:
77
+ return True # URL is flagged as malicious
78
+ return False # URL is safe
79
+ except Exception as e:
80
+ print(f"Error checking URL with Safe Browsing API: {e}")
81
+ return False
82
+
83
+ def get_keywords_by_language(text: str):
84
+ """
85
+ Detect language using `langdetect` and translate keywords if needed.
86
+ """
87
+ snippet = text[:200] # Use a snippet for detection
88
+ try:
89
+ detected_lang = detect(snippet)
90
+ except Exception:
91
+ detected_lang = "en" # Default to English if detection fails
92
+
93
+ if detected_lang == "es":
94
+ smishing_in_spanish = [
95
+ translator.translate(kw).lower() for kw in SMISHING_KEYWORDS
96
+ ]
97
+ other_scam_in_spanish = [
98
+ translator.translate(kw).lower() for kw in OTHER_SCAM_KEYWORDS
99
+ ]
100
+ return smishing_in_spanish, other_scam_in_spanish, "es"
101
+ else:
102
+ return SMISHING_KEYWORDS, OTHER_SCAM_KEYWORDS, "en"
103
+
104
+ def boost_probabilities(probabilities: dict, text: str):
105
+ """
106
+ Boost probabilities based on keyword matches and presence of URLs.
107
+ """
108
+ lower_text = text.lower()
109
+ smishing_keywords, other_scam_keywords, detected_lang = get_keywords_by_language(text)
110
+
111
+ smishing_count = sum(1 for kw in smishing_keywords if kw in lower_text)
112
+ other_scam_count = sum(1 for kw in other_scam_keywords if kw in lower_text)
113
+
114
+ smishing_boost = 0.30 * smishing_count
115
+ other_scam_boost = 0.30 * other_scam_count
116
+
117
+ found_urls = re.findall(r"(https?://[^\s]+)", lower_text)
118
+ if found_urls:
119
+ smishing_boost += 0.35
120
+
121
+ p_smishing = probabilities.get("SMiShing", 0.0)
122
+ p_other_scam = probabilities.get("Other Scam", 0.0)
123
+ p_legit = probabilities.get("Legitimate", 1.0)
124
+
125
+ p_smishing += smishing_boost
126
+ p_other_scam += other_scam_boost
127
+ p_legit -= (smishing_boost + other_scam_boost)
128
+
129
+ p_smishing = max(p_smishing, 0.0)
130
+ p_other_scam = max(p_other_scam, 0.0)
131
+ p_legit = max(p_legit, 0.0)
132
+
133
+ total = p_smishing + p_other_scam + p_legit
134
+ if total > 0:
135
+ p_smishing /= total
136
+ p_other_scam /= total
137
+ p_legit /= total
138
+ else:
139
+ p_smishing, p_other_scam, p_legit = 0.0, 0.0, 1.0
140
+
141
+ return {
142
+ "SMiShing": p_smishing,
143
+ "Other Scam": p_other_scam,
144
+ "Legitimate": p_legit,
145
+ "detected_lang": detected_lang,
146
+ }
147
+
148
+ def explain_classification(text):
149
+ """
150
+ Generate SHAP explanations for the classification.
151
+ """
152
+ if not text.strip():
153
+ raise ValueError("Cannot generate SHAP explanations for empty text.")
154
+
155
+ shap_values = explainer([text])
156
+ shap.force_plot(
157
+ explainer.expected_value[0], shap_values[0].values[0], shap_values[0].data
158
+ )
159
+
160
+ def smishing_detector(text, image):
161
+ """
162
+ Main detection function combining text and OCR.
163
+ """
164
+ combined_text = text or ""
165
+ if image is not None:
166
+ ocr_text = pytesseract.image_to_string(image, lang="spa+eng")
167
+ combined_text += " " + ocr_text
168
+ combined_text = combined_text.strip()
169
+
170
+ if not combined_text:
171
+ return {
172
+ "text_used_for_classification": "(none)",
173
+ "label": "No text provided",
174
+ "confidence": 0.0,
175
+ "keywords_found": [],
176
+ "urls_found": [],
177
+ "threat_analysis": "No URLs to analyze",
178
+ }
179
+
180
+ result = classifier(
181
+ sequences=combined_text,
182
+ candidate_labels=CANDIDATE_LABELS,
183
+ hypothesis_template="This message is {}."
184
+ )
185
+ original_probs = {k: float(v) for k, v in zip(result["labels"], result["scores"])}
186
+ boosted = boost_probabilities(original_probs, combined_text)
187
+
188
+ boosted = {k: float(v) for k, v in boosted.items() if isinstance(v, (int, float))}
189
+ detected_lang = boosted.pop("detected_lang", "en")
190
+ final_label = max(boosted, key=boosted.get)
191
+ final_confidence = round(boosted[final_label], 3)
192
+
193
+ lower_text = combined_text.lower()
194
+ smishing_keys, scam_keys, _ = get_keywords_by_language(combined_text)
195
+
196
+ found_urls = re.findall(r"(https?://[^\s]+)", lower_text)
197
+ found_smishing = [kw for kw in smishing_keys if kw in lower_text]
198
+ found_other_scam = [kw for kw in scam_keys if kw in lower_text]
199
+
200
+ # Analyze URLs using Google's Safe Browsing API
201
+ threat_analysis = {
202
+ url: check_url_with_google_safebrowsing(url) for url in found_urls
203
+ }
204
+
205
+ # SHAP Explanation (optional for user insights)
206
+ explain_classification(combined_text)
207
+
208
+ return {
209
+ "detected_language": detected_lang,
210
+ "text_used_for_classification": combined_text,
211
+ "original_probabilities": {k: round(v, 3) for k, v in original_probs.items()},
212
+ "boosted_probabilities": {k: round(v, 3) for k, v in boosted.items()},
213
+ "label": final_label,
214
+ "confidence": final_confidence,
215
+ "smishing_keywords_found": found_smishing,
216
+ "other_scam_keywords_found": found_other_scam,
217
+ "urls_found": found_urls,
218
+ "threat_analysis": threat_analysis,
219
+ }
220
+
221
+ demo = gr.Interface(
222
+ fn=smishing_detector,
223
+ inputs=[
224
+ gr.Textbox(
225
+ lines=3,
226
+ label="Paste Suspicious SMS Text (English/Spanish)",
227
+ placeholder="Type or paste the message here..."
228
+ ),
229
+ gr.Image(
230
+ type="pil",
231
+ label="Or Upload a Screenshot (Optional)"
232
+ )
233
+ ],
234
+ outputs="json",
235
+ title="SMiShing & Scam Detector with Safe Browsing",
236
+ description="""
237
+ This tool classifies messages as SMiShing, Other Scam, or Legitimate using a zero-shot model
238
+ (joeddav/xlm-roberta-large-xnli). It automatically detects if the text is Spanish or English.
239
+ It uses SHAP for explainability and checks URLs against Google's Safe Browsing API for enhanced analysis.
240
+ """,
241
+ flagging_mode="never"
242
+ )
243
+
244
+ if __name__ == "__main__":
245
+ demo.launch()