-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathawswaf_classification.py
More file actions
106 lines (83 loc) · 3.36 KB
/
awswaf_classification.py
File metadata and controls
106 lines (83 loc) · 3.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import os
import base64
import requests
from dotenv import load_dotenv
# Cargar variables de entorno desde el archivo .env
load_dotenv()
# Configuracion de la API de CapSolver
CAPSOLVER_API_KEY = os.getenv("CAPSOLVER_API_KEY")
CREATE_TASK_URL = "https://api.capsolver.com/createTask"
# Tipos de preguntas para clasificacion AWS WAF
# Preguntas tipo cuadricula (soporta hasta 9 imagenes)
GRID_QUESTIONS = [
"aws:grid:bed", # cama
"aws:grid:bag", # bolsa
"aws:grid:hat", # sombrero
"aws:grid:chair", # silla
"aws:grid:bucket", # cubo
"aws:grid:curtain", # cortina
"aws:grid:mop", # fregona
"aws:grid:clock", # reloj
"aws:grid:suitcase", # maleta
"aws:grid:binocular", # binoculares
"aws:grid:cooking pot" # olla
]
# Tipo ciudad de coche de juguete (soporta 1 imagen, marca el punto final del camino del coche)
TOYCARCITY_QUESTIONS = [
"aws:toycarcity:carcity"
]
def solve_awswaf_classification(images, question):
"""
Clasificar desafios de imagenes de AWS WAF.
Args:
images: Lista de imagenes codificadas en base64 (hasta 9 para cuadricula, 1 para toycarcity)
question: Tipo de pregunta (ver GRID_QUESTIONS o TOYCARCITY_QUESTIONS)
Returns:
Solucion conteniendo objetos (cuadricula) o coordenadas de caja (toycarcity)
"""
if not images:
raise ValueError("Se debe proporcionar al menos una imagen")
payload = {
"clientKey": CAPSOLVER_API_KEY,
"task": {
"type": "AwsWafClassification",
"images": images if isinstance(images, list) else [images],
"question": question
}
}
# AwsWafClassification devuelve resultado directamente (no necesita polling)
response = requests.post(CREATE_TASK_URL, json=payload)
result = response.json()
if result.get("errorId") != 0:
raise Exception(f"Error al resolver: {result.get('errorDescription')}")
return result.get("solution", {})
def load_images_as_base64(image_paths):
"""Funcion auxiliar para cargar multiples imagenes como base64."""
images = []
for path in image_paths:
with open(path, "rb") as f:
images.append(base64.b64encode(f.read()).decode("utf-8"))
return images
def main():
if not CAPSOLVER_API_KEY:
print("Error: CAPSOLVER_API_KEY no encontrada en el archivo .env")
print("Por favor, crea un archivo .env con tu clave API:")
print("CAPSOLVER_API_KEY=tu_clave_api_aqui")
return
print("Clasificacion de Imagenes AWS WAF")
print("\nPreguntas de Cuadricula (soporta hasta 9 imagenes):")
for q in GRID_QUESTIONS:
print(f" {q}")
print("\nPreguntas de Ciudad de Coche de Juguete (1 imagen):")
for q in TOYCARCITY_QUESTIONS:
print(f" {q}")
print("\nEjemplo de uso:")
print(" # Para desafios de cuadricula:")
print(' images = load_images_as_base64(["img1.png", "img2.png", ...])')
print(' solution = solve_awswaf_classification(images, "aws:grid:chair")')
print(" # Devuelve: {'objects': [0, 2, 5]} # indices de imagenes coincidentes")
print("\n # Para ciudad de coche de juguete:")
print(' solution = solve_awswaf_classification([imagen_base64], "aws:toycarcity:carcity")')
print(" # Devuelve: {'box': [x, y]} # coordenadas del punto final")
if __name__ == "__main__":
main()