csjhonathan commited on
Commit
045bec2
·
1 Parent(s): 713fb63

ajusta moderador para aceitar base64

Browse files
Files changed (1) hide show
  1. app.py +48 -10
app.py CHANGED
@@ -5,6 +5,8 @@ import torch
5
  import timm
6
  from PIL import Image
7
  import numpy as np
 
 
8
 
9
  try:
10
  eva02_model = timm.create_model('hf_hub:SmilingWolf/wd-eva02-large-tagger-v3', pretrained=True)
@@ -24,6 +26,18 @@ except Exception as e:
24
  content_model = pipeline("image-classification", model="facebook/convnext-base-224")
25
  nsfw_model = pipeline("image-classification", model="Falconsai/nsfw_image_detection")
26
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def analyze_with_eva02(image):
28
  if eva02_model is None:
29
  return [], []
@@ -50,7 +64,33 @@ def analyze_with_eva02(image):
50
 
51
  return detected_tags, tag_scores
52
 
53
- def analyze_image(image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  if eva02_model is not None:
55
  eva02_tags_detected, eva02_scores = analyze_with_eva02(image)
56
  combined_labels = " ".join(eva02_tags_detected).lower()
@@ -131,14 +171,12 @@ def analyze_image(image):
131
  "grave", "tombstone", "funeral", "coffin", "burial"
132
  ]
133
 
134
- # Palavras-chave para comportamento SUSPEITO (não normal)
135
  suspicious_keywords = [
136
  "unconscious", "motionless", "lifeless", "rigid", "cold", "pale",
137
  "injured", "wounded", "bleeding", "hurt", "pain", "distress",
138
  "abandoned", "neglected", "starving", "malnourished", "chained", "caged"
139
  ]
140
 
141
- # Palavras-chave para comportamento NORMAL de cachorros (não suspeito)
142
  normal_dog_behavior = [
143
  "sleeping", "resting", "lying", "sitting", "playing", "running", "walking",
144
  "happy", "excited", "alert", "awake", "active", "energetic", "playful"
@@ -155,14 +193,10 @@ def analyze_image(image):
155
  abuse = any(keyword in combined_labels for keyword in abuse_keywords)
156
  death = any(keyword in combined_labels for keyword in death_keywords)
157
 
158
- # Detecção mais inteligente para cachorros
159
  has_suspicious_behavior = any(keyword in combined_labels for keyword in suspicious_keywords)
160
  has_normal_behavior = any(keyword in combined_labels for keyword in normal_dog_behavior)
161
  has_death_indicators = any(keyword in combined_labels for keyword in death_keywords)
162
-
163
- # Se é um cachorro, só marcar como suspeito se:
164
- # 1. Tem indicadores de morte OU
165
- # 2. Tem comportamento suspeito E NÃO tem comportamento normal
166
  if is_dog:
167
  suspicious_animal = has_death_indicators or (has_suspicious_behavior and not has_normal_behavior)
168
  dead_dog = has_death_indicators
@@ -228,9 +262,13 @@ def analyze_image(image):
228
 
229
  demo = gr.Interface(
230
  fn=analyze_image,
231
- inputs=gr.Image(type="pil"),
 
 
 
232
  outputs="json",
233
- title="Dog / Human Safety Detector"
 
234
  )
235
 
236
  if __name__ == "__main__":
 
5
  import timm
6
  from PIL import Image
7
  import numpy as np
8
+ import base64
9
+ from io import BytesIO
10
 
11
  try:
12
  eva02_model = timm.create_model('hf_hub:SmilingWolf/wd-eva02-large-tagger-v3', pretrained=True)
 
26
  content_model = pipeline("image-classification", model="facebook/convnext-base-224")
27
  nsfw_model = pipeline("image-classification", model="Falconsai/nsfw_image_detection")
28
 
29
+ def decode_base64_image(base64_string):
30
+ if ',' in base64_string:
31
+ base64_string = base64_string.split(',')[1]
32
+
33
+ try:
34
+ image_data = base64.b64decode(base64_string)
35
+ image = Image.open(BytesIO(image_data))
36
+ return image
37
+ except Exception as e:
38
+ print(f"Erro ao decodificar base64: {e}")
39
+ return None
40
+
41
  def analyze_with_eva02(image):
42
  if eva02_model is None:
43
  return [], []
 
64
 
65
  return detected_tags, tag_scores
66
 
67
+ def analyze_image(image_input, base64_input=None):
68
+ image = None
69
+
70
+ if base64_input and isinstance(base64_input, str) and base64_input.strip():
71
+ image = decode_base64_image(base64_input)
72
+ if image is None:
73
+ return {
74
+ "content": "unknown",
75
+ "adult_content": False,
76
+ "violence": False,
77
+ "sensitive_content": False,
78
+ "content_description": "Erro ao processar imagem base64."
79
+ }
80
+ elif image_input is not None:
81
+ image = image_input
82
+ else:
83
+ return {
84
+ "content": "unknown",
85
+ "adult_content": False,
86
+ "violence": False,
87
+ "sensitive_content": False,
88
+ "content_description": "Nenhuma imagem fornecida."
89
+ }
90
+
91
+ if isinstance(image, np.ndarray):
92
+ image = Image.fromarray(image)
93
+
94
  if eva02_model is not None:
95
  eva02_tags_detected, eva02_scores = analyze_with_eva02(image)
96
  combined_labels = " ".join(eva02_tags_detected).lower()
 
171
  "grave", "tombstone", "funeral", "coffin", "burial"
172
  ]
173
 
 
174
  suspicious_keywords = [
175
  "unconscious", "motionless", "lifeless", "rigid", "cold", "pale",
176
  "injured", "wounded", "bleeding", "hurt", "pain", "distress",
177
  "abandoned", "neglected", "starving", "malnourished", "chained", "caged"
178
  ]
179
 
 
180
  normal_dog_behavior = [
181
  "sleeping", "resting", "lying", "sitting", "playing", "running", "walking",
182
  "happy", "excited", "alert", "awake", "active", "energetic", "playful"
 
193
  abuse = any(keyword in combined_labels for keyword in abuse_keywords)
194
  death = any(keyword in combined_labels for keyword in death_keywords)
195
 
 
196
  has_suspicious_behavior = any(keyword in combined_labels for keyword in suspicious_keywords)
197
  has_normal_behavior = any(keyword in combined_labels for keyword in normal_dog_behavior)
198
  has_death_indicators = any(keyword in combined_labels for keyword in death_keywords)
199
+
 
 
 
200
  if is_dog:
201
  suspicious_animal = has_death_indicators or (has_suspicious_behavior and not has_normal_behavior)
202
  dead_dog = has_death_indicators
 
262
 
263
  demo = gr.Interface(
264
  fn=analyze_image,
265
+ inputs=[
266
+ gr.Image(type="pil", label="Upload de Imagem ou Cole Base64"),
267
+ gr.Textbox(label="Ou Cole String Base64 Aqui", lines=3, placeholder="data:image/jpeg;base64,/9j/4AAQ...")
268
+ ],
269
  outputs="json",
270
+ title="Dog / Human Safety Detector",
271
+ description="Envie uma imagem ou cole uma string base64 para análise de moderação"
272
  )
273
 
274
  if __name__ == "__main__":