Update routers/profanity.py
Browse files- routers/profanity.py +30 -82
routers/profanity.py
CHANGED
@@ -3,96 +3,44 @@ from fastapi.responses import StreamingResponse
|
|
3 |
from PIL import Image
|
4 |
import requests
|
5 |
from io import BytesIO
|
|
|
6 |
|
7 |
router = APIRouter()
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
# ENCODE
|
29 |
-
@router.get("/image/encode/")
|
30 |
-
def encode_custom(url: str = Query(...), width: int = 2, height: int = 2):
|
31 |
try:
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
# Montar paleta e mapa de índices
|
37 |
-
palette = []
|
38 |
-
index_map = []
|
39 |
-
for pixel in pixels:
|
40 |
-
if pixel not in palette:
|
41 |
-
if len(palette) >= len(palette_charset):
|
42 |
-
raise HTTPException(status_code=400, detail="Too many unique colors for encoding.")
|
43 |
-
palette.append(pixel)
|
44 |
-
index = palette.index(pixel)
|
45 |
-
index_map.append(color_to_char(index))
|
46 |
-
|
47 |
-
# Codificar string compactada
|
48 |
-
palette_str = ",".join([f"#{r:02X}{g:02X}{b:02X}" for r, g, b in palette])
|
49 |
-
data_str = "".join(index_map)
|
50 |
-
code = f"W{width}H{height}|{palette_str}|{data_str}"
|
51 |
-
compact_code = f"W{width}H{height}|{''.join([color_to_char(i) for i in range(len(palette))])}|{data_str}"
|
52 |
-
return {
|
53 |
-
"code": code, # Humano-legível
|
54 |
-
"compact_code": compact_code # Super comprimido
|
55 |
-
}
|
56 |
except Exception as e:
|
57 |
-
raise HTTPException(status_code=
|
58 |
|
59 |
-
|
60 |
-
|
61 |
-
def decode_custom(code: str = Query(...)):
|
62 |
try:
|
63 |
-
|
64 |
-
if len(parts) != 3:
|
65 |
-
raise HTTPException(status_code=400, detail="Invalid code format.")
|
66 |
-
|
67 |
-
size = parts[0]
|
68 |
-
palette_keys = parts[1]
|
69 |
-
pixel_indices = parts[2]
|
70 |
-
|
71 |
-
width = int(size.split("H")[0][1:])
|
72 |
-
height = int(size.split("H")[1])
|
73 |
-
|
74 |
-
# Montar paleta de cores (dummy, associar cores fictícias ou embutidas na versão full)
|
75 |
-
# Aqui está usando uma tabela temporária pra leitura de paleta real
|
76 |
-
# Mas se quiser usar as cores reais na string (como na versão anterior), é só trocar aqui
|
77 |
-
palette = []
|
78 |
-
if "," in palette_keys:
|
79 |
-
# Caso legacy (com hex)
|
80 |
-
palette = [hex_to_color(c) for c in palette_keys.split(",")]
|
81 |
-
else:
|
82 |
-
# Compacto: gerar paleta fictícia baseada nos índices (para testes visuais)
|
83 |
-
base_colors = [(255, 0, 0), (0, 0, 255), (0, 255, 0), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
|
84 |
-
for i in range(len(palette_keys)):
|
85 |
-
palette.append(base_colors[i % len(base_colors)])
|
86 |
-
|
87 |
-
# Montar imagem
|
88 |
-
pixels = [palette[char_to_index(c)] for c in pixel_indices]
|
89 |
-
img = Image.new("RGB", (width, height))
|
90 |
-
img.putdata(pixels)
|
91 |
-
|
92 |
buffer = BytesIO()
|
93 |
-
|
94 |
buffer.seek(0)
|
95 |
return StreamingResponse(buffer, media_type="image/png")
|
96 |
-
|
97 |
except Exception as e:
|
98 |
-
raise HTTPException(status_code=
|
|
|
3 |
from PIL import Image
|
4 |
import requests
|
5 |
from io import BytesIO
|
6 |
+
import base64
|
7 |
|
8 |
router = APIRouter()
|
9 |
|
10 |
+
def image_to_custom_string(img: Image.Image) -> str:
|
11 |
+
img = img.convert("RGB").resize((32, 32)) # Reduz pra facilitar
|
12 |
+
pixels = list(img.getdata())
|
13 |
+
|
14 |
+
# Representa cada pixel como R,G,B separado por vírgula e ponto-e-vírgula por pixel
|
15 |
+
pixel_data = ";".join([f"{r},{g},{b}" for r, g, b in pixels])
|
16 |
+
return pixel_data
|
17 |
+
|
18 |
+
def custom_string_to_image(data: str, size=(32, 32)) -> Image.Image:
|
19 |
+
pixels = [
|
20 |
+
tuple(map(int, pixel.split(",")))
|
21 |
+
for pixel in data.strip().split(";") if pixel
|
22 |
+
]
|
23 |
+
img = Image.new("RGB", size)
|
24 |
+
img.putdata(pixels)
|
25 |
+
return img
|
26 |
+
|
27 |
+
@router.get("/encode")
|
28 |
+
def encode_image(url: str = Query(..., description="URL da imagem")):
|
|
|
|
|
|
|
29 |
try:
|
30 |
+
response = requests.get(url)
|
31 |
+
image = Image.open(BytesIO(response.content))
|
32 |
+
encoded_string = image_to_custom_string(image)
|
33 |
+
return {"encoded": encoded_string}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
except Exception as e:
|
35 |
+
raise HTTPException(status_code=400, detail=f"Erro ao processar imagem: {e}")
|
36 |
|
37 |
+
@router.get("/decode")
|
38 |
+
def decode_image(encoded: str = Query(..., description="String da imagem codificada")):
|
|
|
39 |
try:
|
40 |
+
image = custom_string_to_image(encoded)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
buffer = BytesIO()
|
42 |
+
image.save(buffer, format="PNG")
|
43 |
buffer.seek(0)
|
44 |
return StreamingResponse(buffer, media_type="image/png")
|
|
|
45 |
except Exception as e:
|
46 |
+
raise HTTPException(status_code=400, detail=f"Erro ao decodificar imagem: {e}")
|