Spaces:
Sleeping
Sleeping
from fastapi import FastAPI, HTTPException | |
from pydantic import BaseModel | |
from fastapi.middleware.cors import CORSMiddleware | |
import zlib | |
app = FastAPI(title="API PlantUML Encoder") | |
# Habilitar CORS para todos los orígenes | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=["*"], # Permite todos los orígenes | |
allow_credentials=True, | |
allow_methods=["*"], # Permite todos los métodos HTTP (GET, POST, PUT, DELETE, etc.) | |
allow_headers=["*"], # Permite todos los encabezados | |
) | |
class PlantUMLRequest(BaseModel): | |
uml_code: str | |
def generate_plantuml_url(request: PlantUMLRequest): | |
try: | |
encoded = encode_plantuml(request.uml_code) | |
image_url = f"https://www.plantuml.com/plantuml/png/{encoded}" | |
return {"image_url": image_url} | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=str(e)) | |
def encode_plantuml(plantuml_text): | |
zlibbed_str = zlib.compress(plantuml_text.encode('utf-8')) | |
compressed_string = zlibbed_str[2:-4] # strip zlib headers | |
return encode_base64(compressed_string) | |
def encode_base64(data): | |
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_' | |
result = '' | |
data = bytearray(data) | |
i = 0 | |
while i < len(data): | |
b1 = data[i] | |
b2 = data[i + 1] if i + 1 < len(data) else 0 | |
b3 = data[i + 2] if i + 2 < len(data) else 0 | |
result += alphabet[b1 >> 2] | |
result += alphabet[((b1 & 0x3) << 4) | (b2 >> 4)] | |
result += alphabet[((b2 & 0xF) << 2) | (b3 >> 6)] | |
result += alphabet[b3 & 0x3F] | |
i += 3 | |
return result | |