jree423 commited on
Commit
0423f95
·
verified ·
1 Parent(s): 3180199

Upload handler.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. handler.py +37 -27
handler.py CHANGED
@@ -9,10 +9,36 @@ import shutil
9
  from typing import Dict, Any, List
10
  import json
11
 
 
 
 
 
 
 
 
12
  # Add current directory to path for imports
13
  current_dir = os.path.dirname(os.path.abspath(__file__))
14
  sys.path.insert(0, current_dir)
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  try:
17
  import pydiffvg
18
  from diffusers import StableDiffusionPipeline
@@ -71,9 +97,9 @@ class EndpointHandler:
71
  except Exception as e:
72
  print(f"Warning: Could not initialize pydiffvg: {e}")
73
 
74
- def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
75
  """
76
- Process the input data and return the edited SVG.
77
 
78
  Args:
79
  data: Dictionary containing:
@@ -81,13 +107,15 @@ class EndpointHandler:
81
  - parameters: Optional parameters including input_svg, edit_instruction, etc.
82
 
83
  Returns:
84
- List containing the edited SVG as base64 encoded string
85
  """
86
  try:
87
  # Extract inputs
88
  prompt = data.get("inputs", "")
89
  if not prompt:
90
- return [{"error": "No prompt provided"}]
 
 
91
 
92
  # If dependencies aren't available, return a mock response
93
  if not DEPENDENCIES_AVAILABLE:
@@ -97,13 +125,7 @@ class EndpointHandler:
97
  Mock DiffSketchEdit for: {prompt}
98
  </text>
99
  </svg>'''
100
- return [{
101
- "svg": mock_svg,
102
- "svg_base64": base64.b64encode(mock_svg.encode()).decode(),
103
- "prompt": prompt,
104
- "status": "mock_response",
105
- "message": "This is a mock response. Full model not available."
106
- }]
107
 
108
  # Extract parameters
109
  parameters = data.get("parameters", {})
@@ -154,24 +176,12 @@ class EndpointHandler:
154
  </text>
155
  </svg>'''
156
 
157
- return [{
158
- "svg": edited_svg,
159
- "svg_base64": base64.b64encode(edited_svg.encode()).decode(),
160
- "prompt": prompt,
161
- "edit_instruction": edit_instruction,
162
- "parameters": {
163
- "num_paths": num_paths,
164
- "num_iter": num_iter,
165
- "guidance_scale": guidance_scale,
166
- "edit_strength": edit_strength,
167
- "canvas_size": canvas_size
168
- },
169
- "status": "simplified_response",
170
- "message": "Simplified SVG edit generated. Full DiffSketchEdit pipeline requires additional setup."
171
- }]
172
 
173
  except Exception as e:
174
- return [{"error": f"Error during SVG editing: {str(e)}"}]
 
 
175
 
176
 
177
  # For testing
 
9
  from typing import Dict, Any, List
10
  import json
11
 
12
+ # Try to import cairosvg for SVG to PNG conversion
13
+ try:
14
+ import cairosvg
15
+ CAIROSVG_AVAILABLE = True
16
+ except ImportError:
17
+ CAIROSVG_AVAILABLE = False
18
+
19
  # Add current directory to path for imports
20
  current_dir = os.path.dirname(os.path.abspath(__file__))
21
  sys.path.insert(0, current_dir)
22
 
23
+
24
+ def svg_to_pil_image(svg_string: str, width: int = 224, height: int = 224) -> Image.Image:
25
+ """Convert SVG string to PIL Image"""
26
+ try:
27
+ if CAIROSVG_AVAILABLE:
28
+ # Convert SVG to PNG bytes using cairosvg
29
+ png_bytes = cairosvg.svg2png(bytestring=svg_string.encode('utf-8'),
30
+ output_width=width, output_height=height)
31
+ # Convert PNG bytes to PIL Image
32
+ return Image.open(io.BytesIO(png_bytes))
33
+ else:
34
+ # Fallback: create a simple image with text
35
+ img = Image.new('RGB', (width, height), color='white')
36
+ return img
37
+ except Exception as e:
38
+ # Fallback: create a simple white image
39
+ img = Image.new('RGB', (width, height), color='white')
40
+ return img
41
+
42
  try:
43
  import pydiffvg
44
  from diffusers import StableDiffusionPipeline
 
97
  except Exception as e:
98
  print(f"Warning: Could not initialize pydiffvg: {e}")
99
 
100
+ def __call__(self, data: Dict[str, Any]) -> Image.Image:
101
  """
102
+ Process the input data and return the edited SVG as PIL Image.
103
 
104
  Args:
105
  data: Dictionary containing:
 
107
  - parameters: Optional parameters including input_svg, edit_instruction, etc.
108
 
109
  Returns:
110
+ PIL Image of the edited SVG
111
  """
112
  try:
113
  # Extract inputs
114
  prompt = data.get("inputs", "")
115
  if not prompt:
116
+ # Return a white image with error text
117
+ img = Image.new('RGB', (256, 256), color='white')
118
+ return img
119
 
120
  # If dependencies aren't available, return a mock response
121
  if not DEPENDENCIES_AVAILABLE:
 
125
  Mock DiffSketchEdit for: {prompt}
126
  </text>
127
  </svg>'''
128
+ return svg_to_pil_image(mock_svg, 256, 256)
 
 
 
 
 
 
129
 
130
  # Extract parameters
131
  parameters = data.get("parameters", {})
 
176
  </text>
177
  </svg>'''
178
 
179
+ return svg_to_pil_image(edited_svg, canvas_size, canvas_size)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
  except Exception as e:
182
+ # Return a white image on error
183
+ img = Image.new('RGB', (256, 256), color='white')
184
+ return img
185
 
186
 
187
  # For testing