Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,7 +2,6 @@ from fastapi import FastAPI, HTTPException
|
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
import requests
|
| 4 |
from bs4 import BeautifulSoup
|
| 5 |
-
import json
|
| 6 |
from pydantic import BaseModel
|
| 7 |
from urllib.parse import urljoin
|
| 8 |
import logging
|
|
@@ -93,7 +92,7 @@ async def extract_website(website_url: WebsiteURL):
|
|
| 93 |
def safe_int(value, default=100):
|
| 94 |
if not value:
|
| 95 |
return default
|
| 96 |
-
value = re.sub(r'[^\d]', '', value)
|
| 97 |
try:
|
| 98 |
return int(value) if value else default
|
| 99 |
except ValueError:
|
|
@@ -121,13 +120,13 @@ async def extract_website(website_url: WebsiteURL):
|
|
| 121 |
logger.info(f"Processing tag: {tag.name}, text: {tag.get_text(strip=True)[:50]}")
|
| 122 |
element = {
|
| 123 |
'id': f'element-{element_index}',
|
| 124 |
-
'x': safe_int(styles.get('left', styles.get('margin-left', '0px')), 20 + depth *
|
| 125 |
-
'y': safe_int(styles.get('top', styles.get('margin-top', '0px')), y_offset),
|
| 126 |
'parentId': parent_id
|
| 127 |
}
|
| 128 |
element_index += 1
|
| 129 |
|
| 130 |
-
if tag.name in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button']:
|
| 131 |
text = tag.get_text(strip=True)
|
| 132 |
if text:
|
| 133 |
font_size = safe_int(styles.get('font-size', '16px'), 16)
|
|
@@ -170,250 +169,72 @@ async def extract_website(website_url: WebsiteURL):
|
|
| 170 |
'height': max(height, 20),
|
| 171 |
'backgroundColor': parse_color(styles.get('background-color', '#FFFFFF')),
|
| 172 |
'borderWidth': safe_int(styles.get('border-width', '0px'), 0),
|
| 173 |
-
'borderColor':
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
const data = await response.json();
|
| 211 |
-
console.log('Received data:', data);
|
| 212 |
-
|
| 213 |
-
if (!data.elements || data.elements.length === 0) {
|
| 214 |
-
figma.ui.postMessage({
|
| 215 |
-
type: 'conversion-error',
|
| 216 |
-
error: 'No elements found. The site may rely on JavaScript.'
|
| 217 |
-
});
|
| 218 |
-
return;
|
| 219 |
-
}
|
| 220 |
-
|
| 221 |
-
const page = figma.createPage();
|
| 222 |
-
page.name = `Web Import: ${new URL(msg.url).hostname}`;
|
| 223 |
-
figma.currentPage = page;
|
| 224 |
-
|
| 225 |
-
const frame = figma.createFrame();
|
| 226 |
-
frame.name = "Website Frame";
|
| 227 |
-
frame.resize(1440, 900);
|
| 228 |
-
frame.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1 } }];
|
| 229 |
-
|
| 230 |
-
const nodeMap = new Map();
|
| 231 |
-
|
| 232 |
-
for (const element of data.elements) {
|
| 233 |
-
let parentNode = element.parentId ? nodeMap.get(element.parentId) : frame;
|
| 234 |
-
|
| 235 |
-
if (!parentNode) {
|
| 236 |
-
console.log('Parent not found for:', element.id, 'using main frame');
|
| 237 |
-
parentNode = frame;
|
| 238 |
}
|
| 239 |
|
| 240 |
-
if
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
case 'h4': textNode.fontSize = 20; break;
|
| 260 |
-
case 'h5': textNode.fontSize = 18; break;
|
| 261 |
-
case 'h6': textNode.fontSize = 16; break;
|
| 262 |
-
case 'a': textNode.fills = [{ type: 'SOLID', color: { r: 0, g: 0.439, b: 0.866 } }]; break;
|
| 263 |
-
case 'button':
|
| 264 |
-
const buttonRect = figma.createRectangle();
|
| 265 |
-
buttonRect.resize(textNode.width + 40, textNode.height + 20);
|
| 266 |
-
buttonRect.x = textNode.x;
|
| 267 |
-
buttonRect.y = textNode.y;
|
| 268 |
-
buttonRect.cornerRadius = 8;
|
| 269 |
-
buttonRect.fills = [{ type: 'SOLID', color: { r: 0.094, g: 0.627, b: 0.984 } }];
|
| 270 |
-
textNode.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1 } }];
|
| 271 |
-
textNode.x += 20;
|
| 272 |
-
textNode.y += 10;
|
| 273 |
-
parentNode.appendChild(buttonRect);
|
| 274 |
-
break;
|
| 275 |
-
}
|
| 276 |
-
|
| 277 |
-
parentNode.appendChild(textNode);
|
| 278 |
-
nodeMap.set(element.id, textNode);
|
| 279 |
-
console.log('Added text:', element.content);
|
| 280 |
-
} catch (error) {
|
| 281 |
-
console.error('Error creating text:', error);
|
| 282 |
-
}
|
| 283 |
-
} else if (element.type === 'image') {
|
| 284 |
-
try {
|
| 285 |
-
const rect = figma.createRectangle();
|
| 286 |
-
rect.name = `Image: ${element.alt || 'Untitled'}`;
|
| 287 |
-
rect.resize(element.width || 300, element.height || 200);
|
| 288 |
-
rect.x = element.x || 100;
|
| 289 |
-
rect.y = element.y || 100;
|
| 290 |
-
|
| 291 |
-
if (element.src) {
|
| 292 |
-
try {
|
| 293 |
-
const imageData = await fetchImage(element.src);
|
| 294 |
-
const figmaImage = figma.createImage(imageData);
|
| 295 |
-
rect.fills = [{ type: 'IMAGE', imageHash: figmaImage.hash, scaleMode: 'FILL' }];
|
| 296 |
-
} catch (e) {
|
| 297 |
-
console.error('Failed to load image:', element.src, e);
|
| 298 |
-
rect.fills = [{ type: 'SOLID', color: { r: 0.9, g: 0.9, b: 0.9 } }];
|
| 299 |
-
const label = figma.createText();
|
| 300 |
-
await figma.loadFontAsync({ family: 'Inter', style: 'Regular' });
|
| 301 |
-
label.characters = `[Image: ${element.alt || element.src.split('/').pop()}]`;
|
| 302 |
-
label.fontSize = 12;
|
| 303 |
-
label.x = rect.x + rect.width / 2 - label.width / 2;
|
| 304 |
-
label.y = rect.y + rect.height / 2 - label.height / 2;
|
| 305 |
-
parentNode.appendChild(label);
|
| 306 |
-
}
|
| 307 |
-
}
|
| 308 |
-
|
| 309 |
-
parentNode.appendChild(rect);
|
| 310 |
-
nodeMap.set(element.id, rect);
|
| 311 |
-
console.log('Added image:', element.src);
|
| 312 |
-
} catch (error) {
|
| 313 |
-
console.error('Error creating image:', error);
|
| 314 |
-
}
|
| 315 |
-
} else if (element.type === 'div') {
|
| 316 |
-
try {
|
| 317 |
-
const group = figma.createFrame();
|
| 318 |
-
group.name = 'Div';
|
| 319 |
-
group.resize(element.width || 300, element.height || 100);
|
| 320 |
-
group.x = element.x || 100;
|
| 321 |
-
group.y = element.y || 100;
|
| 322 |
-
group.fills = [{ type: 'SOLID', color: hexToRgb(element.backgroundColor || '#FFFFFF') }];
|
| 323 |
-
if (element.borderWidth > 0) {
|
| 324 |
-
group.strokes = [{ type: 'SOLID', color: hexToRgb(element.borderColor || '#000000') }];
|
| 325 |
-
group.strokeWeight = element.borderWidth;
|
| 326 |
-
}
|
| 327 |
-
parentNode.appendChild(group);
|
| 328 |
-
nodeMap.set(element.id, group);
|
| 329 |
-
console.log('Added div:', element.width, element.height);
|
| 330 |
-
} catch (error) {
|
| 331 |
-
console.error('Error creating div:', error);
|
| 332 |
-
}
|
| 333 |
-
}
|
| 334 |
-
}
|
| 335 |
-
|
| 336 |
-
if (data.colors && data.colors.length > 0) {
|
| 337 |
-
const colorSection = figma.createFrame();
|
| 338 |
-
colorSection.name = "Color Palette";
|
| 339 |
-
colorSection.resize(300, 50 + data.colors.length * 50);
|
| 340 |
-
colorSection.x = frame.width - 400;
|
| 341 |
-
colorSection.y = 100;
|
| 342 |
-
|
| 343 |
-
const colorTitle = figma.createText();
|
| 344 |
-
await figma.loadFontAsync({ family: "Inter", style: "Medium" });
|
| 345 |
-
colorTitle.fontName = { family: "Inter", style: "Medium" };
|
| 346 |
-
colorTitle.characters = "Color Palette";
|
| 347 |
-
colorTitle.fontSize = 16;
|
| 348 |
-
colorTitle.x = 20;
|
| 349 |
-
colorTitle.y = 20;
|
| 350 |
-
colorSection.appendChild(colorTitle);
|
| 351 |
-
|
| 352 |
-
let colorY = 60;
|
| 353 |
-
for (const colorStr of data.colors) {
|
| 354 |
-
try {
|
| 355 |
-
const { r, g, b } = hexToRgb(colorStr);
|
| 356 |
-
const colorRect = figma.createRectangle();
|
| 357 |
-
colorRect.resize(30, 30);
|
| 358 |
-
colorRect.x = 20;
|
| 359 |
-
colorRect.y = colorY;
|
| 360 |
-
colorRect.fills = [{ type: 'SOLID', color: { r, g, b } }];
|
| 361 |
-
|
| 362 |
-
const colorLabel = figma.createText();
|
| 363 |
-
await figma.loadFontAsync({ family: "Inter", style: "Regular" });
|
| 364 |
-
colorLabel.fontName = { family: "Inter", style: "Regular" };
|
| 365 |
-
colorLabel.characters = colorStr;
|
| 366 |
-
colorLabel.fontSize = 12;
|
| 367 |
-
colorLabel.x = 60;
|
| 368 |
-
colorLabel.y = colorY + 8;
|
| 369 |
-
|
| 370 |
-
colorSection.appendChild(colorRect);
|
| 371 |
-
colorSection.appendChild(colorLabel);
|
| 372 |
-
colorY += 40;
|
| 373 |
-
} catch (error) {
|
| 374 |
-
console.error("Error creating color swatch:", error);
|
| 375 |
-
}
|
| 376 |
}
|
| 377 |
-
frame.appendChild(colorSection);
|
| 378 |
-
}
|
| 379 |
-
|
| 380 |
-
const bounds = frame.children.reduce(
|
| 381 |
-
(acc, node) => ({
|
| 382 |
-
width: Math.max(acc.width, node.x + node.width),
|
| 383 |
-
height: Math.max(acc.height, node.y + node.height)
|
| 384 |
-
}),
|
| 385 |
-
{ width: 1440, height: 900 }
|
| 386 |
-
);
|
| 387 |
-
frame.resize(bounds.width + 20, bounds.height + 20);
|
| 388 |
-
figma.viewport.scrollAndZoomIntoView([frame]);
|
| 389 |
-
|
| 390 |
-
figma.ui.postMessage({ type: 'conversion-complete' });
|
| 391 |
-
} catch (error) {
|
| 392 |
-
console.error("Conversion error:", error);
|
| 393 |
-
figma.ui.postMessage({
|
| 394 |
-
type: 'conversion-error',
|
| 395 |
-
error: error.message
|
| 396 |
-
});
|
| 397 |
-
}
|
| 398 |
-
}
|
| 399 |
-
};
|
| 400 |
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
}
|
| 408 |
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
if (!response.ok) throw new Error(`Failed to fetch image: ${response.status}`);
|
| 413 |
-
const arrayBuffer = await response.arrayBuffer();
|
| 414 |
-
return new Uint8Array(arrayBuffer);
|
| 415 |
-
} catch (e) {
|
| 416 |
-
console.error('Image fetch error:', e);
|
| 417 |
-
throw e;
|
| 418 |
-
}
|
| 419 |
-
}
|
|
|
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
import requests
|
| 4 |
from bs4 import BeautifulSoup
|
|
|
|
| 5 |
from pydantic import BaseModel
|
| 6 |
from urllib.parse import urljoin
|
| 7 |
import logging
|
|
|
|
| 92 |
def safe_int(value, default=100):
|
| 93 |
if not value:
|
| 94 |
return default
|
| 95 |
+
value = re.sub(r'[^\d]', '', str(value))
|
| 96 |
try:
|
| 97 |
return int(value) if value else default
|
| 98 |
except ValueError:
|
|
|
|
| 120 |
logger.info(f"Processing tag: {tag.name}, text: {tag.get_text(strip=True)[:50]}")
|
| 121 |
element = {
|
| 122 |
'id': f'element-{element_index}',
|
| 123 |
+
'x': safe_int(styles.get('left', styles.get('margin-left', '0px')), 20 + depth * 20),
|
| 124 |
+
'y': safe_int(styles.get('top', styles.get('margin-top', '0px')), y_offset + depth * 20),
|
| 125 |
'parentId': parent_id
|
| 126 |
}
|
| 127 |
element_index += 1
|
| 128 |
|
| 129 |
+
if tag.name in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button', 'li', 'strong', 'em']:
|
| 130 |
text = tag.get_text(strip=True)
|
| 131 |
if text:
|
| 132 |
font_size = safe_int(styles.get('font-size', '16px'), 16)
|
|
|
|
| 169 |
'height': max(height, 20),
|
| 170 |
'backgroundColor': parse_color(styles.get('background-color', '#FFFFFF')),
|
| 171 |
'borderWidth': safe_int(styles.get('border-width', '0px'), 0),
|
| 172 |
+
'borderColor': parse_color(styles.get('border-color', '#000000'))
|
| 173 |
+
})
|
| 174 |
+
y_offset += height + 20
|
| 175 |
+
elements.append(element)
|
| 176 |
+
logger.info(f"Added div element: {width}x{height}")
|
| 177 |
+
|
| 178 |
+
# Process child elements
|
| 179 |
+
for child in tag.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button', 'li', 'strong', 'em', 'img', 'div'], recursive=False):
|
| 180 |
+
process_element(child, element['id'], depth + 1)
|
| 181 |
+
|
| 182 |
+
# Process body elements
|
| 183 |
+
body = soup.find('body')
|
| 184 |
+
if body:
|
| 185 |
+
for tag in body.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button', 'li', 'strong', 'em', 'img', 'div'], recursive=False):
|
| 186 |
+
process_element(tag)
|
| 187 |
+
else:
|
| 188 |
+
logger.warning("No <body> tag found, processing all elements")
|
| 189 |
+
for tag in soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button', 'li', 'strong', 'em', 'img', 'div']):
|
| 190 |
+
process_element(tag)
|
| 191 |
+
|
| 192 |
+
# Extract color palette
|
| 193 |
+
colors = set()
|
| 194 |
+
for element in soup.find_all(style=True):
|
| 195 |
+
style = element.get('style')
|
| 196 |
+
if 'color' in style:
|
| 197 |
+
color_part = style.split('color:')[1].split(';')[0].strip()
|
| 198 |
+
colors.add(parse_color(color_part))
|
| 199 |
+
if 'background-color' in style:
|
| 200 |
+
bg_color = style.split('background-color:')[1].split(';')[0].strip()
|
| 201 |
+
colors.add(parse_color(bg_color))
|
| 202 |
+
|
| 203 |
+
# Extract basic layout
|
| 204 |
+
layout = {
|
| 205 |
+
'title': soup.title.string if soup.title else '',
|
| 206 |
+
'bodyWidth': '100%',
|
| 207 |
+
'bodyHeight': '100%'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
}
|
| 209 |
|
| 210 |
+
if not elements:
|
| 211 |
+
logger.warning("No elements found, adding fallback")
|
| 212 |
+
elements.append({
|
| 213 |
+
'id': 'element-0',
|
| 214 |
+
'type': 'text',
|
| 215 |
+
'x': 20,
|
| 216 |
+
'y': 20,
|
| 217 |
+
'content': 'Unable to parse dynamic content. This site may rely on JavaScript.',
|
| 218 |
+
'fontSize': 16,
|
| 219 |
+
'color': '#FF0000',
|
| 220 |
+
'fontFamily': 'Inter',
|
| 221 |
+
'fontWeight': '400'
|
| 222 |
+
})
|
| 223 |
+
|
| 224 |
+
logger.info(f"Returning {len(elements)} elements")
|
| 225 |
+
return {
|
| 226 |
+
"elements": elements,
|
| 227 |
+
"colors": list(colors),
|
| 228 |
+
"layout": layout
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
+
except requests.RequestException as e:
|
| 232 |
+
logger.error(f"Error fetching website: {str(e)}")
|
| 233 |
+
raise HTTPException(status_code=400, detail=f"Error fetching website: {str(e)}")
|
| 234 |
+
except Exception as e:
|
| 235 |
+
logger.error(f"Error processing website: {str(e)}")
|
| 236 |
+
raise HTTPException(status_code=500, detail=f"Error processing website: {str(e)}")
|
|
|
|
| 237 |
|
| 238 |
+
@app.get("/")
|
| 239 |
+
async def root():
|
| 240 |
+
return {"message": "Web to Figma Converter API is running"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|