Azzan Dwi Riski commited on
Commit
2f33391
·
1 Parent(s): 68e7bab

initial commit

Browse files
Files changed (2) hide show
  1. app.py +394 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # def unwrap_dataparallel(model):
79
+ # """Recursively unwrap all DataParallel layers inside a model."""
80
+ # if isinstance(model, torch.nn.DataParallel):
81
+ # model = model.module
82
+ # for name, module in model.named_children():
83
+ # setattr(model, name, unwrap_dataparallel(module))
84
+ # return model
85
+
86
+ # Load model
87
+ model_path = "models/best_fusion_model.pt"
88
+ if os.path.exists(model_path):
89
+ fusion_model = torch.load(model_path, map_location=device, weights_only=False)
90
+ else:
91
+ model_path = hf_hub_download(repo_id="azzandr/gambling-fusion-model", filename="best_fusion_model.pt")
92
+ fusion_model = torch.load(model_path, map_location=device, weights_only=False)
93
+
94
+ # fusion_model = unwrap_dataparallel(fusion_model)
95
+ fusion_model.to(device)
96
+ fusion_model.eval()
97
+ print("Fusion model loaded successfully!")
98
+
99
+ # Load Image-Only Model
100
+ # Load image model from state_dict
101
+ image_model_path = "models/best_image_model_Adam_lr0.0001_bs32_state_dict.pt"
102
+ if os.path.exists(image_model_path):
103
+ image_only_model = models.efficientnet_b3(weights=models.EfficientNet_B3_Weights.DEFAULT)
104
+ num_features = image_only_model.classifier[1].in_features
105
+ image_only_model.classifier = nn.Linear(num_features, 1)
106
+ image_only_model.load_state_dict(torch.load(image_model_path, map_location=device))
107
+ image_only_model.to(device)
108
+ image_only_model.eval()
109
+ print("Image-only model loaded from state_dict successfully!")
110
+ else:
111
+ raise FileNotFoundError("Image-only model not found in models/ folder.")
112
+
113
+
114
+ # --- Functions ---
115
+ def clean_text(text):
116
+ # text = re.sub(r"http\S+", "", text)
117
+ # text = re.sub('\n', '', text)
118
+ # text = re.sub("[^a-zA-Z^']", " ", text)
119
+ # text = re.sub(" {2,}", " ", text)
120
+ # text = text.strip()
121
+ # text = re.sub(r'\s+', ' ', text)
122
+ # text = re.sub(r'\b\w{1,2}\b', '', text)
123
+ # text = re.sub(r'\b\w{20,}\b', '', text)
124
+ # text = text.lower()
125
+ # Kata 1–2 huruf yang penting dan tidak boleh dihapus
126
+ exceptions = {
127
+ "di", "ke", "ya"
128
+ }
129
+ # ----- BASIC CLEANING -----
130
+ text = re.sub(r"http\S+", "", text) # Hapus URL
131
+ text = re.sub(r"\n", " ", text) # Ganti newline dengan spasi
132
+ text = re.sub(r"[^a-zA-Z']", " ", text) # Hanya sisakan huruf dan apostrof
133
+ text = re.sub(r"\s{2,}", " ", text).strip().lower() # Hapus spasi ganda, ubah ke lowercase
134
+
135
+ # ----- FILTERING -----
136
+ words = text.split()
137
+ filtered_words = [
138
+ w for w in words
139
+ if (len(w) > 2 or w in exceptions) # Simpan kata >2 huruf atau ada di exceptions
140
+ ]
141
+ text = ' '.join(filtered_words)
142
+
143
+ # ----- REMOVE UNWANTED PATTERNS -----
144
+ text = re.sub(r'\b[aeiou]+\b', '', text) # Hapus kata semua vokal (panjang berapa pun)
145
+ text = re.sub(r'\b[^aeiou\s]+\b', '', text) # Hapus kata semua konsonan (panjang berapa pun)
146
+ text = re.sub(r'\b\w{20,}\b', '', text) # Hapus kata sangat panjang (≥20 huruf)
147
+ text = re.sub(r'\s+', ' ', text).strip() # Bersihkan spasi ekstra
148
+
149
+ # check words number
150
+ if len(text.split()) < 5:
151
+ print(f"Cleaned text too short ({len(text.split())} words). Ignoring text.")
152
+ return "" # empty return to use image-only
153
+ return text
154
+
155
+ # Your API key
156
+ SCREENSHOT_API_KEY = os.getenv("SCREENSHOT_API_KEY") # Ambil dari environment variable
157
+
158
+ def take_screenshot(url):
159
+ filename = url.replace('https://', '').replace('http://', '').replace('/', '_').replace('.', '_') + '.png'
160
+ filepath = os.path.join(SCREENSHOT_DIR, filename)
161
+
162
+ try:
163
+ if not SCREENSHOT_API_KEY:
164
+ print("SCREENSHOT_API_KEY not found in environment.")
165
+ return None
166
+
167
+ api_url = "https://api.apiflash.com/v1/urltoimage"
168
+
169
+ # Try with different configurations for problematic URLs
170
+ configs = [
171
+ # Configuration 1: Standard with redirect handling
172
+ {
173
+ "access_key": SCREENSHOT_API_KEY,
174
+ "url": url,
175
+ "format": "png",
176
+ "wait_until": "network_idle",
177
+ "delay": 3,
178
+ "timeout": 30,
179
+ "follow_redirect": "true"
180
+ },
181
+ # Configuration 2: Simplified for redirect issues
182
+ {
183
+ "access_key": SCREENSHOT_API_KEY,
184
+ "url": url,
185
+ "format": "png",
186
+ "delay": 5,
187
+ "timeout": 20,
188
+ "follow_redirect": "false"
189
+ },
190
+ # Configuration 3: Basic fallback
191
+ {
192
+ "access_key": SCREENSHOT_API_KEY,
193
+ "url": url,
194
+ "format": "png"
195
+ }
196
+ ]
197
+
198
+ for i, params in enumerate(configs):
199
+ print(f"Attempting screenshot with configuration {i+1} for: {url}")
200
+ response = requests.get(api_url, params=params)
201
+
202
+ if response.status_code == 200:
203
+ # Check if response is actually an image
204
+ if response.headers.get('content-type', '').startswith('image'):
205
+ with open(filepath, 'wb') as f:
206
+ f.write(response.content)
207
+ print(f"Screenshot taken successfully for URL: {url}")
208
+ return filepath
209
+ else:
210
+ print(f"Configuration {i+1} returned non-image content")
211
+ continue
212
+ else:
213
+ error_msg = response.text
214
+ print(f"Configuration {i+1} failed: {error_msg}")
215
+
216
+ # Check for specific redirect error
217
+ if "ERR_TOO_MANY_REDIRECTS" in error_msg:
218
+ print(f"Redirect issue detected for {url}, trying next configuration...")
219
+ continue
220
+ elif i == len(configs) - 1: # Last configuration failed
221
+ print(f"All configurations failed for {url}")
222
+ return None
223
+
224
+ return None
225
+
226
+ except Exception as e:
227
+ print(f"Error taking screenshot: {e}")
228
+ return None
229
+
230
+ def resize_if_needed(image_path, max_mb=1, target_height=720):
231
+ file_size = os.path.getsize(image_path) / (1024 * 1024) # dalam MB
232
+ if file_size > max_mb:
233
+ try:
234
+ with Image.open(image_path) as img:
235
+ width, height = img.size
236
+ if height > target_height:
237
+ ratio = target_height / float(height)
238
+ new_width = int(float(width) * ratio)
239
+ img = img.resize((new_width, target_height), Image.Resampling.LANCZOS)
240
+ img.save(image_path, optimize=True, quality=85)
241
+ print(f"Image resized to {new_width}x{target_height}")
242
+ except Exception as e:
243
+ print(f"Resize error: {e}")
244
+
245
+ def easyocr_extract(image_path):
246
+ try:
247
+ results = reader.readtext(image_path, detail=0)
248
+ text = " ".join(results)
249
+ print(f"OCR text extracted from EasyOCR: {len(text)} characters")
250
+ return text.strip()
251
+ except Exception as e:
252
+ print(f"EasyOCR error: {e}")
253
+ return ""
254
+
255
+ # def extract_text_from_image(image_path):
256
+ # print("Skipping OCR. Forcing Image-Only prediction.")
257
+ # return ""
258
+
259
+ def extract_text_from_image(image_path):
260
+ try:
261
+ resize_if_needed(image_path, max_mb=1, target_height=720) # Tambahkan ini di awal
262
+ file_size = os.path.getsize(image_path) / (1024 * 1024) # ukuran MB
263
+
264
+ if file_size < 1:
265
+ print(f"Using OCR.Space API for image ({file_size:.2f} MB)")
266
+ api_key = os.getenv("OCR_SPACE_API_KEY")
267
+ if not api_key:
268
+ print("OCR_SPACE_API_KEY not found in environment. Using EasyOCR as fallback.")
269
+ return easyocr_extract(image_path)
270
+
271
+ with open(image_path, 'rb') as f:
272
+ payload = {
273
+ 'isOverlayRequired': False,
274
+ 'apikey': api_key,
275
+ 'language': 'eng'
276
+ }
277
+ r = requests.post('https://api.ocr.space/parse/image',
278
+ files={'filename': f},
279
+ data=payload)
280
+ result = r.json()
281
+ if result.get('IsErroredOnProcessing', False):
282
+ print(f"OCR.Space API Error: {result.get('ErrorMessage')}")
283
+ return easyocr_extract(image_path)
284
+ text = result['ParsedResults'][0]['ParsedText']
285
+ print(f"OCR text extracted from OCR.Space: {len(text)} characters")
286
+ return text.strip()
287
+ else:
288
+ print(f"Using EasyOCR for image ({file_size:.2f} MB)")
289
+ return easyocr_extract(image_path)
290
+ except Exception as e:
291
+ print(f"OCR error: {e}")
292
+ return ""
293
+
294
+ def prepare_data_for_model(image_path, text):
295
+ image = Image.open(image_path)
296
+ image_tensor = transform(image).unsqueeze(0).to(device)
297
+
298
+ clean_text_data = clean_text(text)
299
+ encoding = tokenizer.encode_plus(
300
+ clean_text_data,
301
+ add_special_tokens=True,
302
+ max_length=128,
303
+ padding='max_length',
304
+ truncation=True,
305
+ return_tensors='pt'
306
+ )
307
+
308
+ input_ids = encoding['input_ids'].to(device)
309
+ attention_mask = encoding['attention_mask'].to(device)
310
+
311
+ return image_tensor, input_ids, attention_mask
312
+
313
+ def predict_single_url(url):
314
+ print(f"Processing URL: {url}")
315
+ screenshot_path = take_screenshot(url)
316
+ if not screenshot_path:
317
+ 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"
318
+
319
+ text = extract_text_from_image(screenshot_path)
320
+
321
+ if not text.strip(): # Jika text kosong
322
+ print(f"No OCR text found for {url}. Using Image-Only Model.")
323
+ image = Image.open(screenshot_path)
324
+ image_tensor = transform(image).unsqueeze(0).to(device)
325
+
326
+ with torch.no_grad():
327
+ image_logits = image_only_model(image_tensor).squeeze(1)
328
+ image_probs = torch.sigmoid(image_logits)
329
+
330
+ threshold = 0.6
331
+ is_gambling = image_probs[0] > threshold
332
+
333
+ label = "Gambling" if is_gambling else "Non-Gambling"
334
+ confidence = image_probs[0].item() if is_gambling else 1 - image_probs[0].item()
335
+ print(f"[Image-Only] URL: {url}")
336
+ print(f"Prediction: {label} | Confidence: {confidence:.2f}\n")
337
+ return label, f"Confidence: {confidence:.2f} (Image-Only Model)"
338
+
339
+ else:
340
+ image_tensor, input_ids, attention_mask = prepare_data_for_model(screenshot_path, text)
341
+
342
+ with torch.no_grad():
343
+ fused_logits, image_logits, text_logits, weights = fusion_model(image_tensor, input_ids, attention_mask)
344
+ fused_probs = torch.sigmoid(fused_logits)
345
+ image_probs = torch.sigmoid(image_logits)
346
+ text_probs = torch.sigmoid(text_logits)
347
+
348
+ threshold = 0.6
349
+ is_gambling = fused_probs[0] > threshold
350
+
351
+ label = "Gambling" if is_gambling else "Non-Gambling"
352
+ confidence = fused_probs[0].item() if is_gambling else 1 - fused_probs[0].item()
353
+
354
+ # ✨ Log detail
355
+ print(f"[Fusion Model] URL: {url}")
356
+ print(f"Image Model Prediction Probability: {image_probs[0]:.2f}")
357
+ print(f"Text Model Prediction Probability: {text_probs[0]:.2f}")
358
+ print(f"Fusion Final Prediction: {label} | Confidence: {confidence:.2f}\n")
359
+
360
+ return label, f"Confidence: {confidence:.2f} (Fusion Model)"
361
+
362
+ def predict_batch_urls(file_obj):
363
+ results = []
364
+ content = file_obj.read().decode('utf-8')
365
+ urls = [line.strip() for line in content.splitlines() if line.strip()]
366
+ for url in urls:
367
+ label, confidence = predict_single_url(url)
368
+ results.append({"url": url, "label": label, "confidence": confidence})
369
+
370
+ df = pd.DataFrame(results)
371
+ print(f"Batch prediction completed for {len(urls)} URLs.")
372
+ return df
373
+
374
+ # --- Gradio App ---
375
+
376
+ with gr.Blocks() as app:
377
+ gr.Markdown("# 🕵️ Gambling Website Detection (URL Based)")
378
+
379
+ with gr.Tab("Single URL"):
380
+ url_input = gr.Textbox(label="Enter Website URL")
381
+ predict_button = gr.Button("Predict")
382
+ label_output = gr.Label()
383
+ confidence_output = gr.Textbox(label="Confidence", interactive=False)
384
+
385
+ predict_button.click(fn=predict_single_url, inputs=url_input, outputs=[label_output, confidence_output])
386
+
387
+ with gr.Tab("Batch URLs"):
388
+ file_input = gr.File(label="Upload .txt file with URLs (one per line)")
389
+ batch_predict_button = gr.Button("Batch Predict")
390
+ batch_output = gr.DataFrame()
391
+
392
+ batch_predict_button.click(fn=predict_batch_urls, inputs=file_input, outputs=batch_output)
393
+
394
+ app.launch()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ easyocr
4
+ gradio
5
+ torchvision
6
+ pandas
7
+ Pillow
8
+ requests