Azzan Dwi Riski commited on
Commit
04a36d6
·
1 Parent(s): 305197f

initial commit

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,13 +1,53 @@
1
  ---
2
- title: Indonesian Gambling Site Detector
3
- emoji: 🔥
4
- colorFrom: purple
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 5.29.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Gambling Site Detector
3
+ emoji: 🐢
4
+ colorFrom: gray
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 5.27.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ short_description: Detects whether a website is related to gambling or not
12
  ---
13
 
14
+ # 🕵️ Indonesian Gambling Website Detection - Huggingface Space
15
+
16
+ This Space detects whether a website is related to gambling based on its screenshot and OCR text.
17
+
18
+ ## Features
19
+ - Single URL Prediction
20
+ - Batch URLs Prediction
21
+ - Screenshot capture using external API (apiflash)
22
+ - OCR extraction using a hybrid approach (OCR.Space API + EasyOCR fallback)
23
+ - Multimodal model (image + text fusion)
24
+
25
+ ## Instructions
26
+ 1. Enter a website URL or upload a `.txt` file containing multiple URLs (one URL per line).
27
+ 2. The system will:
28
+ - Take a screenshot of the website.
29
+ - Extract text using Tesseract OCR.
30
+ - Predict if it is a Gambling or Non-Gambling site.
31
+
32
+ ## Model
33
+ - Fusion model (`best_fusion_model.pth`) trained with EfficientNet + IndoBERT.
34
+ <!-- - Hosted at: [HuggingFace Model Hub](https://huggingface.co/azzandr/gambling-fusion-model) -->
35
+
36
+ ## Deployment
37
+ This Space requires:
38
+ - Gradio
39
+ - Torch
40
+ - Transformers
41
+ - EasyOCR
42
+ - Pillow
43
+ - Pandas
44
+ - Requests
45
+
46
+ ## Important Notes
47
+ ⚡ **Inference may take longer than expected** because this Space runs on **CPU-only hardware**.
48
+ Performance is significantly slower compared to GPU-enabled environments like Google Colab.
49
+ Each prediction can take several minutes due to the complexity of multimodal fusion models (image + text processing).
50
+
51
+ For faster performance, consider running the model locally with a GPU, or upgrading to a GPU-enabled Huggingface Space.
52
+
53
+
app.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ params = {
169
+ "access_key": SCREENSHOT_API_KEY,
170
+ "url": url,
171
+ "full_page": "true",
172
+ "format": "png"
173
+ }
174
+ response = requests.get(api_url, params=params)
175
+
176
+ if response.status_code == 200:
177
+ with open(filepath, 'wb') as f:
178
+ f.write(response.content)
179
+ print(f"Screenshot taken for URL: {url}")
180
+ return filepath
181
+ else:
182
+ print(f"Error in screenshot API: {response.text}")
183
+ return None
184
+ except Exception as e:
185
+ print(f"Error taking screenshot: {e}")
186
+ return None
187
+
188
+ def easyocr_extract(image_path):
189
+ try:
190
+ results = reader.readtext(image_path, detail=0)
191
+ text = " ".join(results)
192
+ print(f"OCR text extracted from EasyOCR: {len(text)} characters")
193
+ return text.strip()
194
+ except Exception as e:
195
+ print(f"EasyOCR error: {e}")
196
+ return ""
197
+
198
+ # def extract_text_from_image(image_path):
199
+ # print("Skipping OCR. Forcing Image-Only prediction.")
200
+ # return ""
201
+
202
+ def extract_text_from_image(image_path):
203
+ try:
204
+ file_size = os.path.getsize(image_path) / (1024 * 1024) # ukuran MB
205
+ if file_size < 1:
206
+ print(f"Using OCR.Space API for image ({file_size:.2f} MB)")
207
+ api_key = os.getenv("OCR_SPACE_API_KEY") # Ambil dari environment variable
208
+ if not api_key:
209
+ print("OCR_SPACE_API_KEY not found in environment. Using EasyOCR as fallback.")
210
+ return easyocr_extract(image_path)
211
+
212
+ with open(image_path, 'rb') as f:
213
+ payload = {
214
+ 'isOverlayRequired': False,
215
+ 'apikey': api_key,
216
+ 'language': 'eng'
217
+ }
218
+ r = requests.post('https://api.ocr.space/parse/image',
219
+ files={'filename': f},
220
+ data=payload)
221
+ result = r.json()
222
+ if result.get('IsErroredOnProcessing', False):
223
+ print(f"OCR.Space API Error: {result.get('ErrorMessage')}")
224
+ return easyocr_extract(image_path)
225
+ text = result['ParsedResults'][0]['ParsedText']
226
+ print(f"OCR text extracted from OCR.Space: {len(text)} characters")
227
+ return text.strip()
228
+ else:
229
+ print(f"Using EasyOCR for image ({file_size:.2f} MB)")
230
+ return easyocr_extract(image_path)
231
+ except Exception as e:
232
+ print(f"OCR error: {e}")
233
+ return ""
234
+
235
+ def prepare_data_for_model(image_path, text):
236
+ image = Image.open(image_path)
237
+ image_tensor = transform(image).unsqueeze(0).to(device)
238
+
239
+ clean_text_data = clean_text(text)
240
+ encoding = tokenizer.encode_plus(
241
+ clean_text_data,
242
+ add_special_tokens=True,
243
+ max_length=128,
244
+ padding='max_length',
245
+ truncation=True,
246
+ return_tensors='pt'
247
+ )
248
+
249
+ input_ids = encoding['input_ids'].to(device)
250
+ attention_mask = encoding['attention_mask'].to(device)
251
+
252
+ return image_tensor, input_ids, attention_mask
253
+
254
+ def predict_single_url(url):
255
+ screenshot_path = take_screenshot(url)
256
+ if not screenshot_path:
257
+ return f"Error: Failed to take screenshot for {url}", None
258
+
259
+ text = extract_text_from_image(screenshot_path)
260
+
261
+ if not text.strip(): # Jika text kosong
262
+ print(f"No OCR text found for {url}. Using Image-Only Model.")
263
+ image = Image.open(screenshot_path)
264
+ image_tensor = transform(image).unsqueeze(0).to(device)
265
+
266
+ with torch.no_grad():
267
+ image_logits = image_only_model(image_tensor).squeeze(1)
268
+ image_probs = torch.sigmoid(image_logits)
269
+
270
+ threshold = 0.8
271
+ is_gambling = image_probs[0] > threshold
272
+
273
+ label = "Gambling" if is_gambling else "Non-Gambling"
274
+ confidence = image_probs[0].item() if is_gambling else 1 - image_probs[0].item()
275
+ print(f"[Image-Only] URL: {url}")
276
+ print(f"Prediction: {label} | Confidence: {confidence:.2f}\n")
277
+ return label, f"Confidence: {confidence:.2f}"
278
+
279
+ else:
280
+ image_tensor, input_ids, attention_mask = prepare_data_for_model(screenshot_path, text)
281
+
282
+ with torch.no_grad():
283
+ fused_logits, image_logits, text_logits, weights = fusion_model(image_tensor, input_ids, attention_mask)
284
+ fused_probs = torch.sigmoid(fused_logits)
285
+ image_probs = torch.sigmoid(image_logits)
286
+ text_probs = torch.sigmoid(text_logits)
287
+
288
+ threshold = 0.8
289
+ is_gambling = fused_probs[0] > threshold
290
+
291
+ label = "Gambling" if is_gambling else "Non-Gambling"
292
+ confidence = fused_probs[0].item() if is_gambling else 1 - fused_probs[0].item()
293
+
294
+ # ✨ Log detail
295
+ print(f"[Fusion Model] URL: {url}")
296
+ print(f"Image Model Prediction Probability: {image_probs[0]:.2f}")
297
+ print(f"Text Model Prediction Probability: {text_probs[0]:.2f}")
298
+ print(f"Fusion Final Prediction: {label} | Confidence: {confidence:.2f}\n")
299
+
300
+ return label, f"Confidence: {confidence:.2f}"
301
+
302
+ def predict_batch_urls(file_obj):
303
+ results = []
304
+ content = file_obj.read().decode('utf-8')
305
+ urls = [line.strip() for line in content.splitlines() if line.strip()]
306
+ for url in urls:
307
+ label, confidence = predict_single_url(url)
308
+ results.append({"url": url, "label": label, "confidence": confidence})
309
+
310
+ df = pd.DataFrame(results)
311
+ print(f"Batch prediction completed for {len(urls)} URLs.")
312
+ return df
313
+
314
+ # --- Gradio App ---
315
+
316
+ with gr.Blocks() as app:
317
+ gr.Markdown("# 🕵️ Gambling Website Detection (URL Based)")
318
+
319
+ with gr.Tab("Single URL"):
320
+ url_input = gr.Textbox(label="Enter Website URL")
321
+ predict_button = gr.Button("Predict")
322
+ label_output = gr.Label()
323
+ confidence_output = gr.Textbox(label="Confidence", interactive=False)
324
+
325
+ predict_button.click(fn=predict_single_url, inputs=url_input, outputs=[label_output, confidence_output])
326
+
327
+ with gr.Tab("Batch URLs"):
328
+ file_input = gr.File(label="Upload .txt file with URLs (one per line)")
329
+ batch_predict_button = gr.Button("Batch Predict")
330
+ batch_output = gr.DataFrame()
331
+
332
+ batch_predict_button.click(fn=predict_batch_urls, inputs=file_input, outputs=batch_output)
333
+
334
+ 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
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ easyocr
4
+ gradio
5
+ torchvision
6
+ pandas
7
+ Pillow
8
+ requests
screenshots/02.infoshiba2.fun.png ADDED

Git LFS Details

  • SHA256: ae3b7ad32fa98d5473d168f3fc7f3a00f56cd363cc01735f836116ac7ee5ae7b
  • Pointer size: 131 Bytes
  • Size of remote file: 425 kB