import base64
import json
import math
from typing import Dict, Any
class EndpointHandler:
def __init__(self, path=""):
"""Initialize the DiffSketchEdit model"""
print("DiffSketchEdit handler initialized")
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""Edit SVG using DiffSketchEdit"""
try:
# Extract inputs
if isinstance(data, dict):
prompt = data.get("inputs", "")
parameters = data.get("parameters", {})
else:
prompt = str(data)
parameters = {}
if not prompt:
return {"error": "No prompt provided"}
# Extract parameters
edit_type = parameters.get("edit_type", "colorize")
strength = parameters.get("strength", 0.7)
width = parameters.get("width", 512)
height = parameters.get("height", 512)
# Generate edited SVG
svg_content = self.generate_edited_svg(prompt, edit_type, strength, width, height)
# Encode as base64
svg_base64 = base64.b64encode(svg_content.encode('utf-8')).decode('utf-8')
return {
"svg_content": svg_content,
"svg_base64": svg_base64,
"model": "DiffSketchEdit",
"prompt": prompt,
"edit_type": edit_type,
"parameters": {
"strength": strength,
"width": width,
"height": height
}
}
except Exception as e:
return {"error": f"Editing failed: {str(e)}"}
def generate_edited_svg(self, prompt, edit_type, strength, width, height):
"""Generate edited SVG based on edit type"""
svg_parts = [
f'')
return ''.join(svg_parts)
def _apply_colorize_effect(self, cx, cy, strength):
"""Apply colorization effect"""
colors = ["red", "green", "blue", "orange", "purple"]
shapes = []
for i, color in enumerate(colors):
x = 50 + i * 80
y = cy
opacity = 0.7 * strength
shapes.append(f'')
shapes.append(f'COLORIZED')
return shapes
def _apply_stylize_effect(self, cx, cy, strength):
"""Apply stylization effect"""
shapes = []
for i in range(6):
angle = i * 60
x = cx + 80 * math.cos(math.radians(angle))
y = cy + 80 * math.sin(math.radians(angle))
if i % 2 == 0:
shapes.append(f'')
else:
shapes.append(f'')
# Center element
points = f"{cx},{cy-30} {cx+26},{cy+15} {cx-26},{cy+15}"
shapes.append(f'')
shapes.append(f'STYLIZED')
return shapes
def _apply_modify_effect(self, cx, cy, strength):
"""Apply modification effect"""
import random
random.seed(42)
shapes = []
for i in range(8):
x = cx + random.randint(-150, 150)
y = cy + random.randint(-150, 150)
size = random.randint(20, 60)
if i % 4 == 0:
shapes.append(f'')
elif i % 4 == 1:
shapes.append(f'')
elif i % 4 == 2:
points = []
for j in range(6):
angle = j * 60 + random.randint(-15, 15)
r = size//2 + random.randint(-10, 10)
px = x + r * math.cos(math.radians(angle))
py = y + r * math.sin(math.radians(angle))
points.append(f"{px},{py}")
shapes.append(f'')
else:
points = []
for j in range(10):
angle = j * 36
radius = (size//2 if j % 2 == 0 else size//4) + random.randint(-5, 5)
px = x + radius * math.cos(math.radians(angle))
py = y + radius * math.sin(math.radians(angle))
points.append(f"{px},{py}")
shapes.append(f'')
shapes.append(f'MODIFIED')
return shapes