NTThong0710 commited on
Commit
baa68e1
·
1 Parent(s): 71209d1

push speed

Browse files
Files changed (3) hide show
  1. app/gen_ai.py +1 -1
  2. app/safety_check.py +147 -95
  3. requirements.txt +1 -0
app/gen_ai.py CHANGED
@@ -11,5 +11,5 @@ from google import genai
11
  client = genai.Client(api_key="AIzaSyAYEaSiZq7lcT5eJaVwnZJJ_UMoUTtpjJk")
12
 
13
  def generate_response(prompt: str):
14
- result = client.models.generate_content(model="gemini-2.0-flash", contents="GEMINI")
15
  return result.text
 
11
  client = genai.Client(api_key="AIzaSyAYEaSiZq7lcT5eJaVwnZJJ_UMoUTtpjJk")
12
 
13
  def generate_response(prompt: str):
14
+ result = client.models.generate_content(model="gemini-2.0-flash", contents=prompt)
15
  return result.text
app/safety_check.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  from detoxify import Detoxify
2
  from transformers import (
3
  AutoProcessor, AutoModelForImageClassification,
@@ -6,30 +8,85 @@ from transformers import (
6
  )
7
  from PIL import Image
8
  import torch
9
-
10
  import re
11
  from urllib.parse import urlparse, unquote
12
 
13
- # Load model phát hiện URL độc hại
14
- classifier = pipeline("zero-shot-classification")
15
-
16
- # Load models
17
- detox_model = Detoxify('original')
18
-
19
- nsfw_model_id = "Falconsai/nsfw_image_detection"
20
- nsfw_processor = AutoProcessor.from_pretrained(nsfw_model_id)
21
- nsfw_model = AutoModelForImageClassification.from_pretrained(nsfw_model_id)
22
-
23
- violence_model_id = "jaranohaal/vit-base-violence-detection"
24
- violence_model = ViTForImageClassification.from_pretrained(violence_model_id)
25
- violence_processor = ViTFeatureExtractor.from_pretrained(violence_model_id)
26
-
27
- # Load BLIP cho caption của ảnh
28
- blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
29
- blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
30
-
31
-
32
- def is_prompt_safe(prompt: str):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  results = detox_model.predict(prompt)
34
  threshold = 0.5
35
  flagged = {label: score for label, score in results.items() if score > threshold}
@@ -37,17 +94,19 @@ def is_prompt_safe(prompt: str):
37
  return False, list(flagged.keys())
38
  return True, []
39
 
40
- def generate_caption(image: Image.Image):
41
- inputs = blip_processor(images=image, return_tensors="pt")
 
 
 
 
 
42
  with torch.no_grad():
43
  out = blip_model.generate(**inputs)
44
  caption = blip_processor.decode(out[0], skip_special_tokens=True)
45
- return caption
46
-
47
- def check_nsfw_image(image: Image.Image) -> str:
48
- """Kiểm tra và trả về kết quả NSFW của ảnh"""
49
  # Xử lý NSFW
50
- nsfw_inputs = nsfw_processor(images=image, return_tensors="pt")
51
  with torch.no_grad():
52
  nsfw_outputs = nsfw_model(**nsfw_inputs)
53
  nsfw_probs = torch.nn.functional.softmax(nsfw_outputs.logits, dim=1)[0]
@@ -57,10 +116,29 @@ def check_nsfw_image(image: Image.Image) -> str:
57
  nsfw_label = nsfw_labels[nsfw_pred]
58
  nsfw_score = nsfw_probs[nsfw_pred].item() * 100
59
 
60
- # Tạo caption
61
- caption = generate_caption(image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- # Đánh giá kết quả
64
  if nsfw_label.lower() in ["porn", "hentai", "sex", "nsfw"]:
65
  return f"""🚨 Ảnh KHÔNG an toàn (NSFW):
66
  - Loại: {nsfw_label}
@@ -74,26 +152,12 @@ def check_nsfw_image(image: Image.Image) -> str:
74
 
75
  def check_violence_image(image: Image.Image) -> str:
76
  """Kiểm tra và trả về kết quả bạo lực của ảnh"""
77
- # Xử lý bạo lực
78
- violence_inputs = violence_processor(images=image, return_tensors="pt")
79
- with torch.no_grad():
80
- violence_outputs = violence_model(**violence_inputs)
81
- violence_probs = torch.nn.functional.softmax(violence_outputs.logits, dim=1)[0]
82
-
83
- violence_labels = ["Non-Violent", "Violent"]
84
- violence_pred = violence_probs.argmax().item()
85
- violence_label = violence_labels[violence_pred]
86
- violence_score = violence_probs[violence_pred].item() * 100
87
 
88
- # Tạo caption
89
- caption = generate_caption(image)
90
-
91
- # Đánh giá kết quả
92
- is_violent = False
93
- if violence_label.lower() == "non-violent" and violence_score > 50:
94
- is_violent = True
95
- elif violence_label.lower() == "violent" and violence_score > 80:
96
- is_violent = True
97
 
98
  if is_violent:
99
  return f"""🚨 Ảnh KHÔNG an toàn (Bạo lực):
@@ -106,52 +170,41 @@ def check_violence_image(image: Image.Image) -> str:
106
  - Độ chính xác: {violence_score:.2f}%
107
  - Mô tả: {caption}"""
108
 
109
- # ===Hàm check url===
110
- def check_url(url: str):
 
111
  try:
112
- # Chuẩn hóa URL (decode các ký tự đặc biệt)
113
  decoded_url = unquote(url)
114
  parsed = urlparse(decoded_url)
115
-
116
- # Danh sách cảnh báo
117
  warnings = []
118
 
119
- # 1. Phát hiện IP thay domain (http://203.0.113.45/...)
120
  if re.match(r'^https?://\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', decoded_url):
121
- warnings.append("🚨 Nguy hiểm: Truy cập trực tiếp bằng IP (thường dùng cho tấn công)")
122
-
123
- # 2. Phát hiện file thực thi (gift-card.exe)
124
  if re.search(r'\.(exe|msi|bat|js|jar|apk|dmg)(\?|$)', parsed.path.lower()):
125
- warnings.append("🚨 Nguy hiểm: URL chứa file thực thi có thể độc hại")
126
-
127
- # 3. Phát hiện redirect độc hại (redirect?target=...)
128
  if 'redirect' in parsed.path.lower() or 'url=' in parsed.query.lower():
129
- warnings.append("⚠️ Cảnh báo: URL chứa chức năng redirect (có thể lừa đảo)")
130
-
131
- # 4. Phát hiện ký tự đặc biệt (/login%20%2F%00%3F%2F%2E%2E)
132
  if re.search(r'%[0-9a-f]{2}|[\x00-\x1f\x7f]', url):
133
- warnings.append("🚨 Nguy hiểm: URL chứa ký tự mã hóa đáng ngờ (có thể tấn công)")
134
-
135
- # 5. Phát hiện domain giả mạo (example.com@malicious-site.com)
136
  if '@' in parsed.netloc:
137
- warnings.append("🚨 Lừa đảo: URL chứa kỹ thuật giả mạo domain (user@fake-domain)")
138
-
139
- # 6. Phát hiện domain giả danh (secure.example-login.com)
140
- deceptive_domains = ['login', 'secure', 'account', 'verify', 'update']
141
- if any(keyword in parsed.netloc.lower() for keyword in deceptive_domains):
142
- warnings.append("⚠️ Cảnh báo: Domain có dấu hiệu giả mạo dịch vụ đăng nhập")
143
-
144
- # 7. Kiểm tra giao thức không mã hóa
145
  if parsed.scheme == 'http':
146
- warnings.append("⚠️ Cảnh báo: Kết nối không mã hóa (HTTP)")
147
 
148
- # Kết hợp với AI classifier
149
- ai_result = classifier(url, candidate_labels=["malicious", "safe"])
150
- ai_label = ai_result["labels"][0]
151
- ai_score = ai_result["scores"][0] * 100
152
-
153
- # Tạo báo cáo
154
- report = {
 
 
 
 
155
  "url": url,
156
  "decoded_url": decoded_url,
157
  "domain": parsed.netloc,
@@ -162,21 +215,20 @@ def check_url(url: str):
162
  "confidence": ai_score
163
  }
164
  }
165
-
166
- # Quyết định cuối cùng
167
- if warnings or ai_label == "malicious":
168
- return format_report(report, is_safe=False)
169
- else:
170
- return format_report(report, is_safe=True)
171
-
172
  except Exception as e:
173
- return f"⚠️ Lỗi khi phân tích URL: {str(e)}"
174
 
175
- def format_report(report: dict, is_safe: bool):
176
- """Định dạng báo cáo dễ đọc"""
 
 
 
 
 
 
177
  warning_text = "\n".join(f"- {w}" for w in report["warnings"]) if report["warnings"] else "- Không phát hiện cảnh báo"
178
 
179
- if not is_safe:
180
  return f"""🚨 URL KHÔNG AN TOÀN
181
  🔍 Phân tích chi tiết:
182
  • URL gốc: {report['url']}
 
1
+ from functools import lru_cache
2
+ from concurrent.futures import ThreadPoolExecutor
3
  from detoxify import Detoxify
4
  from transformers import (
5
  AutoProcessor, AutoModelForImageClassification,
 
8
  )
9
  from PIL import Image
10
  import torch
 
11
  import re
12
  from urllib.parse import urlparse, unquote
13
 
14
+ # Kiểm tra GPU thiết lập device
15
+ device = "cuda" if torch.cuda.is_available() else "cpu"
16
+ torch.set_num_threads(4 if device == "cpu" else 1)
17
+
18
+ # Load các model song song
19
+ def load_models():
20
+ with ThreadPoolExecutor() as executor:
21
+ # Model phát hiện URL độc hại
22
+ classifier_future = executor.submit(
23
+ pipeline,
24
+ "zero-shot-classification",
25
+ device=0 if device == "cuda" else -1
26
+ )
27
+
28
+ # Model detoxify
29
+ detox_future = executor.submit(Detoxify, 'original')
30
+
31
+ # Model NSFW
32
+ nsfw_model_id = "Falconsai/nsfw_image_detection"
33
+ nsfw_future = executor.submit(
34
+ AutoProcessor.from_pretrained,
35
+ nsfw_model_id
36
+ )
37
+ nsfw_model_future = executor.submit(
38
+ AutoModelForImageClassification.from_pretrained,
39
+ nsfw_model_id
40
+ )
41
+
42
+ # Model bạo lực
43
+ violence_model_id = "jaranohaal/vit-base-violence-detection"
44
+ violence_model_future = executor.submit(
45
+ ViTForImageClassification.from_pretrained,
46
+ violence_model_id
47
+ )
48
+ violence_processor_future = executor.submit(
49
+ ViTFeatureExtractor.from_pretrained,
50
+ violence_model_id
51
+ )
52
+
53
+ # Model BLIP
54
+ blip_processor_future = executor.submit(
55
+ BlipProcessor.from_pretrained,
56
+ "Salesforce/blip-image-captioning-base"
57
+ )
58
+ blip_model_future = executor.submit(
59
+ BlipForConditionalGeneration.from_pretrained,
60
+ "Salesforce/blip-image-captioning-base"
61
+ )
62
+
63
+ # Lấy kết quả
64
+ classifier = classifier_future.result()
65
+ detox_model = detox_future.result()
66
+ nsfw_processor = nsfw_future.result()
67
+ nsfw_model = nsfw_model_future.result().to(device)
68
+ violence_model = violence_model_future.result().to(device)
69
+ violence_processor = violence_processor_future.result()
70
+ blip_processor = blip_processor_future.result()
71
+ blip_model = blip_model_future.result().to(device)
72
+
73
+ return (
74
+ classifier, detox_model,
75
+ nsfw_processor, nsfw_model,
76
+ violence_processor, violence_model,
77
+ blip_processor, blip_model
78
+ )
79
+
80
+ (
81
+ classifier, detox_model,
82
+ nsfw_processor, nsfw_model,
83
+ violence_processor, violence_model,
84
+ blip_processor, blip_model
85
+ ) = load_models()
86
+
87
+ # Cache cho các hàm xử lý text
88
+ @lru_cache(maxsize=1000)
89
+ def is_prompt_safe_cached(prompt: str):
90
  results = detox_model.predict(prompt)
91
  threshold = 0.5
92
  flagged = {label: score for label, score in results.items() if score > threshold}
 
94
  return False, list(flagged.keys())
95
  return True, []
96
 
97
+ def is_prompt_safe(prompt: str):
98
+ return is_prompt_safe_cached(prompt[:500]) # Giới hạn độ dài để cache hiệu quả
99
+
100
+ # Tối ưu xử lý ảnh
101
+ def process_image(image: Image.Image):
102
+ # Tạo caption
103
+ inputs = blip_processor(images=image, return_tensors="pt").to(device)
104
  with torch.no_grad():
105
  out = blip_model.generate(**inputs)
106
  caption = blip_processor.decode(out[0], skip_special_tokens=True)
107
+
 
 
 
108
  # Xử lý NSFW
109
+ nsfw_inputs = nsfw_processor(images=image, return_tensors="pt").to(device)
110
  with torch.no_grad():
111
  nsfw_outputs = nsfw_model(**nsfw_inputs)
112
  nsfw_probs = torch.nn.functional.softmax(nsfw_outputs.logits, dim=1)[0]
 
116
  nsfw_label = nsfw_labels[nsfw_pred]
117
  nsfw_score = nsfw_probs[nsfw_pred].item() * 100
118
 
119
+ # Xử lý bạo lực
120
+ violence_inputs = violence_processor(images=image, return_tensors="pt").to(device)
121
+ with torch.no_grad():
122
+ violence_outputs = violence_model(**violence_inputs)
123
+ violence_probs = torch.nn.functional.softmax(violence_outputs.logits, dim=1)[0]
124
+
125
+ violence_labels = ["Non-Violent", "Violent"]
126
+ violence_pred = violence_probs.argmax().item()
127
+ violence_label = violence_labels[violence_pred]
128
+ violence_score = violence_probs[violence_pred].item() * 100
129
+
130
+ return {
131
+ "caption": caption,
132
+ "nsfw": (nsfw_label, nsfw_score),
133
+ "violence": (violence_label, violence_score)
134
+ }
135
+
136
+ def check_nsfw_image(image: Image.Image) -> str:
137
+ """Kiểm tra và trả về kết quả NSFW của ảnh"""
138
+ results = process_image(image)
139
+ nsfw_label, nsfw_score = results["nsfw"]
140
+ caption = results["caption"]
141
 
 
142
  if nsfw_label.lower() in ["porn", "hentai", "sex", "nsfw"]:
143
  return f"""🚨 Ảnh KHÔNG an toàn (NSFW):
144
  - Loại: {nsfw_label}
 
152
 
153
  def check_violence_image(image: Image.Image) -> str:
154
  """Kiểm tra và trả về kết quả bạo lực của ảnh"""
155
+ results = process_image(image)
156
+ violence_label, violence_score = results["violence"]
157
+ caption = results["caption"]
 
 
 
 
 
 
 
158
 
159
+ is_violent = (violence_label.lower() == "non-violent" and violence_score > 50) or \
160
+ (violence_label.lower() == "violent" and violence_score > 80)
 
 
 
 
 
 
 
161
 
162
  if is_violent:
163
  return f"""🚨 Ảnh KHÔNG an toàn (Bạo lực):
 
170
  - Độ chính xác: {violence_score:.2f}%
171
  - Mô tả: {caption}"""
172
 
173
+ # Cache cho URL check
174
+ @lru_cache(maxsize=1000)
175
+ def check_url_cached(url: str):
176
  try:
 
177
  decoded_url = unquote(url)
178
  parsed = urlparse(decoded_url)
 
 
179
  warnings = []
180
 
181
+ # Các rule kiểm tra URL (giữ nguyên như cũ)
182
  if re.match(r'^https?://\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', decoded_url):
183
+ warnings.append("🚨 Nguy hiểm: Truy cập trực tiếp bằng IP")
 
 
184
  if re.search(r'\.(exe|msi|bat|js|jar|apk|dmg)(\?|$)', parsed.path.lower()):
185
+ warnings.append("🚨 Nguy hiểm: URL chứa file thực thi")
 
 
186
  if 'redirect' in parsed.path.lower() or 'url=' in parsed.query.lower():
187
+ warnings.append("⚠️ Cảnh báo: URL chứa chức năng redirect")
 
 
188
  if re.search(r'%[0-9a-f]{2}|[\x00-\x1f\x7f]', url):
189
+ warnings.append("🚨 Nguy hiểm: URL chứa ký tự mã hóa đáng ngờ")
 
 
190
  if '@' in parsed.netloc:
191
+ warnings.append("🚨 Lừa đảo: URL chứa kỹ thuật giả mạo domain")
192
+ if any(keyword in parsed.netloc.lower() for keyword in ['login', 'secure', 'account', 'verify', 'update']):
193
+ warnings.append("⚠️ Cảnh báo: Domain dấu hiệu giả mạo")
 
 
 
 
 
194
  if parsed.scheme == 'http':
195
+ warnings.append("⚠️ Cảnh báo: Kết nối không mã hóa")
196
 
197
+ # AI classifier (chỉ chạy nếu có cảnh báo)
198
+ ai_result = None
199
+ if warnings:
200
+ ai_result = classifier(url, candidate_labels=["malicious", "safe"])
201
+ ai_label = ai_result["labels"][0]
202
+ ai_score = ai_result["scores"][0] * 100
203
+ else:
204
+ ai_label = "safe"
205
+ ai_score = 90.0 # Giả định an toàn nếu không có cảnh báo
206
+
207
+ return {
208
  "url": url,
209
  "decoded_url": decoded_url,
210
  "domain": parsed.netloc,
 
215
  "confidence": ai_score
216
  }
217
  }
 
 
 
 
 
 
 
218
  except Exception as e:
219
+ return {"error": str(e)}
220
 
221
+ def check_url(url: str):
222
+ # Giới hạn độ dài URL để cache hiệu quả
223
+ cache_key = url[:200] if len(url) > 200 else url
224
+ report = check_url_cached(cache_key)
225
+
226
+ if "error" in report:
227
+ return f"⚠️ Lỗi khi phân tích URL: {report['error']}"
228
+
229
  warning_text = "\n".join(f"- {w}" for w in report["warnings"]) if report["warnings"] else "- Không phát hiện cảnh báo"
230
 
231
+ if report["warnings"] or report["ai_analysis"]["label"] == "malicious":
232
  return f"""🚨 URL KHÔNG AN TOÀN
233
  🔍 Phân tích chi tiết:
234
  • URL gốc: {report['url']}
requirements.txt CHANGED
@@ -6,3 +6,4 @@ presidio-analyzer
6
  detoxify
7
  Pillow
8
  google-genai
 
 
6
  detoxify
7
  Pillow
8
  google-genai
9
+ concurrent-log-handler