rdsarjito commited on
Commit
f4a6c1a
·
1 Parent(s): ff3ee13
.DS_Store ADDED
Binary file (6.15 kB). View file
 
README.md DELETED
@@ -1,12 +0,0 @@
1
- ---
2
- title: Gambling Detector
3
- emoji: 👁
4
- colorFrom: purple
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import re
4
+ import time
5
+ import torch
6
+ import torch.nn as nn
7
+ from PIL import Image
8
+ import requests
9
+ import easyocr
10
+ from transformers import AutoTokenizer
11
+ from torchvision import transforms
12
+ from torchvision import models
13
+ from torchvision.transforms import functional as F
14
+ import pandas as pd
15
+ from huggingface_hub import hf_hub_download
16
+ import warnings
17
+ warnings.filterwarnings("ignore")
18
+
19
+ # --- Setup ---
20
+
21
+ # Device setup
22
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
+ print(f"Using device: {device}")
24
+
25
+ # Load tokenizer
26
+ tokenizer = AutoTokenizer.from_pretrained('indobenchmark/indobert-base-p1')
27
+
28
+ # Image transformation
29
+ class ResizePadToSquare:
30
+ def __init__(self, target_size=300):
31
+ self.target_size = target_size
32
+
33
+ def __call__(self, img):
34
+ img = img.convert("RGB")
35
+ img.thumbnail((self.target_size, self.target_size), Image.BILINEAR)
36
+ delta_w = self.target_size - img.size[0]
37
+ delta_h = self.target_size - img.size[1]
38
+ padding = (delta_w // 2, delta_h // 2, delta_w - delta_w // 2, delta_h - delta_h // 2)
39
+ img = F.pad(img, padding, fill=0, padding_mode='constant')
40
+ return img
41
+
42
+ transform = transforms.Compose([
43
+ ResizePadToSquare(300),
44
+ transforms.ToTensor(),
45
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
46
+ std=[0.229, 0.224, 0.225]),
47
+ ])
48
+
49
+
50
+ # Screenshot folder
51
+ SCREENSHOT_DIR = "screenshots"
52
+ os.makedirs(SCREENSHOT_DIR, exist_ok=True)
53
+
54
+ # Create OCR reader
55
+ reader = easyocr.Reader(['id']) # Indonesia language
56
+ print("OCR reader initialized.")
57
+
58
+ # --- Model ---
59
+
60
+ class LateFusionModel(nn.Module):
61
+ def __init__(self, image_model, text_model):
62
+ super(LateFusionModel, self).__init__()
63
+ self.image_model = image_model
64
+ self.text_model = text_model
65
+ self.image_weight = nn.Parameter(torch.tensor(0.5))
66
+ self.text_weight = nn.Parameter(torch.tensor(0.5))
67
+
68
+ def forward(self, images, input_ids, attention_mask):
69
+ with torch.no_grad():
70
+ image_logits = self.image_model(images).squeeze(1)
71
+ text_logits = self.text_model(input_ids=input_ids, attention_mask=attention_mask).logits.squeeze(1)
72
+
73
+ weights = torch.softmax(torch.stack([self.image_weight, self.text_weight]), dim=0)
74
+ fused_logits = weights[0] * image_logits + weights[1] * text_logits
75
+
76
+ return fused_logits, image_logits, text_logits, weights
77
+
78
+ # Load model
79
+ fusion_model = torch.load("best_mlp_fusion_model_state_dict.pt", map_location=device, weights_only=False)
80
+
81
+ # fusion_model = unwrap_dataparallel(fusion_model)
82
+ fusion_model.to(device)
83
+ fusion_model.eval()
84
+ print("Fusion model loaded successfully!")
85
+
86
+ # Load Image-Only Model
87
+ # Load image model from state_dict
88
+ image_model_path = "models/best_image_model_Adam_lr0.0001_bs32_state_dict.pt"
89
+ if os.path.exists(image_model_path):
90
+ image_only_model = models.efficientnet_b3(weights=models.EfficientNet_B3_Weights.DEFAULT)
91
+ num_features = image_only_model.classifier[1].in_features
92
+ image_only_model.classifier = nn.Linear(num_features, 1)
93
+ image_only_model.load_state_dict(torch.load(image_model_path, map_location=device))
94
+ image_only_model.to(device)
95
+ image_only_model.eval()
96
+ print("Image-only model loaded from state_dict successfully!")
97
+ else:
98
+ print("Image-only model not found locally. Downloading from Hugging Face Hub...")
99
+ image_model_path = hf_hub_download(repo_id="azzandr/gambling-image-model", filename="best_image_model_Adam_lr0.0001_bs32_state_dict.pt")
100
+ image_only_model = models.efficientnet_b3(weights=models.EfficientNet_B3_Weights.DEFAULT)
101
+ num_features = image_only_model.classifier[1].in_features
102
+ image_only_model.classifier = nn.Linear(num_features, 1)
103
+ image_only_model.load_state_dict(torch.load(image_model_path, map_location=device))
104
+ image_only_model.to(device)
105
+ image_only_model.eval()
106
+ print("Image-only model downloaded and loaded successfully!")
107
+
108
+
109
+ # --- Functions ---
110
+ def clean_text(text):
111
+ exceptions = {
112
+ "di", "ke", "ya"
113
+ }
114
+ # ----- BASIC CLEANING -----
115
+ text = re.sub(r"http\S+", "", text) # Hapus URL
116
+ text = re.sub(r"\n", " ", text) # Ganti newline dengan spasi
117
+ text = re.sub(r"[^a-zA-Z']", " ", text) # Hanya sisakan huruf dan apostrof
118
+ text = re.sub(r"\s{2,}", " ", text).strip().lower() # Hapus spasi ganda, ubah ke lowercase
119
+
120
+ # ----- FILTERING -----
121
+ words = text.split()
122
+ filtered_words = [
123
+ w for w in words
124
+ if (len(w) > 2 or w in exceptions) # Simpan kata >2 huruf atau ada di exceptions
125
+ ]
126
+ text = ' '.join(filtered_words)
127
+
128
+ # ----- REMOVE UNWANTED PATTERNS -----
129
+ text = re.sub(r'\b[aeiou]+\b', '', text) # Hapus kata semua vokal (panjang berapa pun)
130
+ text = re.sub(r'\b[^aeiou\s]+\b', '', text) # Hapus kata semua konsonan (panjang berapa pun)
131
+ text = re.sub(r'\b\w{20,}\b', '', text) # Hapus kata sangat panjang (≥20 huruf)
132
+ text = re.sub(r'\s+', ' ', text).strip() # Bersihkan spasi ekstra
133
+
134
+ # check words number
135
+ if len(text.split()) < 5:
136
+ print(f"Cleaned text too short ({len(text.split())} words). Ignoring text.")
137
+ return "" # empty return to use image-only
138
+ return text
139
+
140
+ # Your API key
141
+ SCREENSHOT_API_KEY = os.getenv("SCREENSHOT_API_KEY") # Ambil dari environment variable
142
+
143
+ # Constants for screenshot configuration
144
+ CLOUDFLARE_CHECK_KEYWORDS = ["Checking your browser", "Just a moment", "Cloudflare"]
145
+
146
+ def ensure_http(url):
147
+ if not url.startswith(('http://', 'https://')):
148
+ return 'http://' + url
149
+ return url
150
+
151
+ def sanitize_filename(url):
152
+ return re.sub(r'[^\w\-_\. ]', '_', url)
153
+
154
+ def take_screenshot(url):
155
+ url = ensure_http(url)
156
+ filename = sanitize_filename(url) + '.png'
157
+ filepath = os.path.join(SCREENSHOT_DIR, filename)
158
+
159
+ try:
160
+ if not SCREENSHOT_API_KEY:
161
+ print("SCREENSHOT_API_KEY not found in environment.")
162
+ return None
163
+
164
+ api_url = "https://api.apiflash.com/v1/urltoimage"
165
+
166
+ # Base parameters - only using supported parameters
167
+ params = {
168
+ "access_key": SCREENSHOT_API_KEY,
169
+ "url": url,
170
+ "format": "png",
171
+ "wait_until": "network_idle",
172
+ "delay": 2,
173
+ "fail_on_status": "400,401,402,403,404,500,502,503,504",
174
+ "fresh": "true", # Don't use cached version
175
+ "response_type": "image",
176
+ "wait_for": "body" # Wait for body to be present
177
+ }
178
+
179
+ print(f"Taking screenshot of: {url}")
180
+ response = requests.get(api_url, params=params)
181
+
182
+ if response.status_code == 200:
183
+ # Check if response is actually an image
184
+ if response.headers.get('content-type', '').startswith('image'):
185
+ with open(filepath, 'wb') as f:
186
+ f.write(response.content)
187
+ print(f"Screenshot taken successfully for URL: {url}")
188
+ return filepath
189
+ else:
190
+ print(f"API returned non-image content")
191
+ return None
192
+ else:
193
+ error_msg = response.text
194
+ print(f"Screenshot failed: {error_msg}")
195
+
196
+ # Check for Cloudflare detection
197
+ if any(keyword.lower() in error_msg.lower() for keyword in CLOUDFLARE_CHECK_KEYWORDS):
198
+ print("Cloudflare challenge detected, retrying with different parameters...")
199
+ # Retry with different parameters for Cloudflare
200
+ params.update({
201
+ "wait_until": "load",
202
+ "delay": 5
203
+ })
204
+ response = requests.get(api_url, params=params)
205
+
206
+ if response.status_code == 200 and response.headers.get('content-type', '').startswith('image'):
207
+ with open(filepath, 'wb') as f:
208
+ f.write(response.content)
209
+ print(f"Screenshot taken successfully after Cloudflare retry")
210
+ return filepath
211
+
212
+ return None
213
+
214
+ except Exception as e:
215
+ print(f"Error taking screenshot: {e}")
216
+ return None
217
+
218
+ def resize_if_needed(image_path, max_mb=1, target_height=720):
219
+ file_size = os.path.getsize(image_path) / (1024 * 1024) # dalam MB
220
+ if file_size > max_mb:
221
+ try:
222
+ with Image.open(image_path) as img:
223
+ width, height = img.size
224
+ if height > target_height:
225
+ ratio = target_height / float(height)
226
+ new_width = int(float(width) * ratio)
227
+ img = img.resize((new_width, target_height), Image.Resampling.LANCZOS)
228
+ img.save(image_path, optimize=True, quality=85)
229
+ print(f"Image resized to {new_width}x{target_height}")
230
+ except Exception as e:
231
+ print(f"Resize error: {e}")
232
+
233
+ def easyocr_extract(image_path):
234
+ try:
235
+ results = reader.readtext(image_path, detail=0)
236
+ text = " ".join(results)
237
+ print(f"OCR text extracted from EasyOCR: {len(text)} characters")
238
+ return text.strip()
239
+ except Exception as e:
240
+ print(f"EasyOCR error: {e}")
241
+ return ""
242
+
243
+ # def extract_text_from_image(image_path):
244
+ # print("Skipping OCR. Forcing Image-Only prediction.")
245
+ # return ""
246
+
247
+ def extract_text_from_image(image_path):
248
+ try:
249
+ resize_if_needed(image_path, max_mb=1, target_height=720) # Tambahkan ini di awal
250
+ file_size = os.path.getsize(image_path) / (1024 * 1024) # ukuran MB
251
+
252
+ if file_size < 1:
253
+ print(f"Using OCR.Space API for image ({file_size:.2f} MB)")
254
+ api_key = os.getenv("OCR_SPACE_API_KEY")
255
+ if not api_key:
256
+ print("OCR_SPACE_API_KEY not found in environment. Using EasyOCR as fallback.")
257
+ return easyocr_extract(image_path)
258
+
259
+ with open(image_path, 'rb') as f:
260
+ payload = {
261
+ 'isOverlayRequired': False,
262
+ 'apikey': api_key,
263
+ 'language': 'eng'
264
+ }
265
+ r = requests.post('https://api.ocr.space/parse/image',
266
+ files={'filename': f},
267
+ data=payload)
268
+ result = r.json()
269
+ if result.get('IsErroredOnProcessing', False):
270
+ print(f"OCR.Space API Error: {result.get('ErrorMessage')}")
271
+ return easyocr_extract(image_path)
272
+ text = result['ParsedResults'][0]['ParsedText']
273
+ print(f"OCR text extracted from OCR.Space: {len(text)} characters")
274
+ return text.strip()
275
+ else:
276
+ print(f"Using EasyOCR for image ({file_size:.2f} MB)")
277
+ return easyocr_extract(image_path)
278
+ except Exception as e:
279
+ print(f"OCR error: {e}")
280
+ return ""
281
+
282
+ def prepare_data_for_model(image_path, text):
283
+ image = Image.open(image_path)
284
+ image_tensor = transform(image).unsqueeze(0).to(device)
285
+
286
+ clean_text_data = clean_text(text)
287
+ encoding = tokenizer.encode_plus(
288
+ clean_text_data,
289
+ add_special_tokens=True,
290
+ max_length=128,
291
+ padding='max_length',
292
+ truncation=True,
293
+ return_tensors='pt'
294
+ )
295
+
296
+ input_ids = encoding['input_ids'].to(device)
297
+ attention_mask = encoding['attention_mask'].to(device)
298
+
299
+ return image_tensor, input_ids, attention_mask
300
+
301
+ def predict_single_url(url):
302
+ print(f"Processing URL: {url}")
303
+ screenshot_path = take_screenshot(url)
304
+ if not screenshot_path:
305
+ return f"❌ Error: Unable to capture screenshot for {url}. This may be due to:\n• Too many redirects\n• Website blocking automated access\n• Network connectivity issues\n• Invalid URL", "Screenshot capture failed", None, "", ""
306
+
307
+ text = extract_text_from_image(screenshot_path)
308
+ raw_text = text # Store raw text before cleaning
309
+
310
+ if not text.strip(): # Jika text kosong
311
+ print(f"No OCR text found for {url}. Using Image-Only Model.")
312
+ image = Image.open(screenshot_path)
313
+ image_tensor = transform(image).unsqueeze(0).to(device)
314
+
315
+ with torch.no_grad():
316
+ image_logits = image_only_model(image_tensor).squeeze(1)
317
+ image_probs = torch.sigmoid(image_logits)
318
+
319
+ threshold = 0.6
320
+ is_gambling = image_probs[0] > threshold
321
+
322
+ label = "Gambling" if is_gambling else "Non-Gambling"
323
+ confidence = image_probs[0].item() if is_gambling else 1 - image_probs[0].item()
324
+ print(f"[Image-Only] URL: {url}")
325
+ print(f"Prediction: {label} | Confidence: {confidence:.2f}\n")
326
+ return label, f"Confidence: {confidence:.2f} (Image-Only Model)", screenshot_path, raw_text, ""
327
+
328
+ else:
329
+ clean_text_data = clean_text(text)
330
+ image_tensor, input_ids, attention_mask = prepare_data_for_model(screenshot_path, text)
331
+
332
+ with torch.no_grad():
333
+ fused_logits, image_logits, text_logits, weights = fusion_model(image_tensor, input_ids, attention_mask)
334
+ fused_probs = torch.sigmoid(fused_logits)
335
+ image_probs = torch.sigmoid(image_logits)
336
+ text_probs = torch.sigmoid(text_logits)
337
+
338
+ threshold = 0.6
339
+ is_gambling = fused_probs[0] > threshold
340
+
341
+ label = "Gambling" if is_gambling else "Non-Gambling"
342
+ confidence = fused_probs[0].item() if is_gambling else 1 - fused_probs[0].item()
343
+
344
+ # ✨ Log detail
345
+ print(f"[Fusion Model] URL: {url}")
346
+ print(f"Image Model Prediction Probability: {image_probs[0]:.2f}")
347
+ print(f"Text Model Prediction Probability: {text_probs[0]:.2f}")
348
+ print(f"Fusion Final Prediction: {label} | Confidence: {confidence:.2f}\n")
349
+
350
+ return label, f"Confidence: {confidence:.2f} (Fusion Model)", screenshot_path, raw_text, clean_text_data
351
+
352
+ def predict_batch_urls(file_obj):
353
+ results = []
354
+ content = file_obj.read().decode('utf-8')
355
+ urls = [line.strip() for line in content.splitlines() if line.strip()]
356
+ for url in urls:
357
+ label, confidence, screenshot_path, raw_text, cleaned_text = predict_single_url(url)
358
+ results.append({
359
+ "url": url,
360
+ "label": label,
361
+ "confidence": confidence,
362
+ "screenshot_path": screenshot_path,
363
+ "raw_text": raw_text,
364
+ "cleaned_text": cleaned_text
365
+ })
366
+
367
+ df = pd.DataFrame(results)
368
+ print(f"Batch prediction completed for {len(urls)} URLs.")
369
+ return df
370
+
371
+ # --- Gradio App ---
372
+
373
+ with gr.Blocks() as app:
374
+ gr.Markdown("# 🕵️ Gambling Website Detection (URL Based)")
375
+
376
+ with gr.Tab("Single URL"):
377
+ url_input = gr.Textbox(label="Enter Website URL")
378
+ predict_button = gr.Button("Predict")
379
+
380
+ with gr.Row():
381
+ with gr.Column():
382
+ label_output = gr.Label()
383
+ confidence_output = gr.Textbox(label="Confidence", interactive=False)
384
+
385
+ with gr.Column():
386
+ screenshot_output = gr.Image(label="Screenshot", type="filepath")
387
+
388
+ with gr.Row():
389
+ with gr.Column():
390
+ raw_text_output = gr.Textbox(label="Raw OCR Text", lines=5)
391
+ with gr.Column():
392
+ cleaned_text_output = gr.Textbox(label="Cleaned Text", lines=5)
393
+
394
+ predict_button.click(
395
+ fn=predict_single_url,
396
+ inputs=url_input,
397
+ outputs=[
398
+ label_output,
399
+ confidence_output,
400
+ screenshot_output,
401
+ raw_text_output,
402
+ cleaned_text_output
403
+ ]
404
+ )
405
+
406
+ with gr.Tab("Batch URLs"):
407
+ file_input = gr.File(label="Upload .txt file with URLs (one per line)")
408
+ batch_predict_button = gr.Button("Batch Predict")
409
+ batch_output = gr.DataFrame()
410
+
411
+ batch_predict_button.click(fn=predict_batch_urls, inputs=file_input, outputs=batch_output)
412
+
413
+ app.launch()
models/best_image_model_Adam_lr0.0001_bs32_state_dict.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:08b358e4e32596d3e479fa56dff0f2870704b99a4213095ffd947ab4e7a82d90
3
+ size 43374276
models/best_mlp_fusion_model_state_dict.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b1821489df51bf17812f02483921f5495fe39f21b3e7b817de4f2aae3c77fec
3
+ size 541236115
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ easyocr
4
+ gradio
5
+ torchvision
6
+ pandas
7
+ Pillow
8
+ requests