Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,259 +1,71 @@
|
|
| 1 |
-
from
|
| 2 |
-
from
|
| 3 |
-
from
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
app = FastAPI()
|
| 13 |
-
|
| 14 |
-
# Enable CORS
|
| 15 |
-
app.add_middleware(
|
| 16 |
-
CORSMiddleware,
|
| 17 |
-
allow_origins=["*"],
|
| 18 |
-
allow_credentials=True,
|
| 19 |
-
allow_methods=["*"],
|
| 20 |
-
allow_headers=["*"],
|
| 21 |
-
)
|
| 22 |
-
|
| 23 |
-
# Configure logging
|
| 24 |
-
logging.basicConfig(level=logging.INFO)
|
| 25 |
-
logger = logging.getLogger(__name__)
|
| 26 |
-
|
| 27 |
-
class WebsiteURL(BaseModel):
|
| 28 |
-
url: str
|
| 29 |
-
|
| 30 |
-
@app.post("/extract")
|
| 31 |
-
async def extract_website(website_url: WebsiteURL):
|
| 32 |
-
logger.info(f"Extract endpoint called with URL: {website_url.url}")
|
| 33 |
try:
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
css_response.raise_for_status()
|
| 57 |
-
css_soup = BeautifulSoup(f"<style>{css_response.text}</style>", 'html.parser')
|
| 58 |
-
soup.append(css_soup)
|
| 59 |
-
logger.info(f"Fetched stylesheet: {css_url}")
|
| 60 |
-
except requests.RequestException as e:
|
| 61 |
-
logger.warning(f"Failed to fetch stylesheet {css_url}: {e}")
|
| 62 |
-
|
| 63 |
-
elements = []
|
| 64 |
-
y_offset = 20
|
| 65 |
-
element_index = 0
|
| 66 |
-
|
| 67 |
-
def parse_styles(style_text):
|
| 68 |
-
styles = {}
|
| 69 |
-
try:
|
| 70 |
-
for style_item in style_text.split(';'):
|
| 71 |
-
if ':' in style_item:
|
| 72 |
-
prop, val = style_item.split(':', 1)
|
| 73 |
-
styles[prop.strip()] = val.strip()
|
| 74 |
-
except Exception as e:
|
| 75 |
-
logger.warning(f"Error parsing styles: {e}")
|
| 76 |
-
return styles
|
| 77 |
-
|
| 78 |
-
def get_styles(element):
|
| 79 |
-
styles = parse_styles(element.get('style', ''))
|
| 80 |
-
for style_tag in soup.find_all('style'):
|
| 81 |
-
try:
|
| 82 |
-
css = style_tag.string or ''
|
| 83 |
-
for rule in css.split('}'):
|
| 84 |
-
if '{' in rule:
|
| 85 |
-
selector, props = rule.split('{', 1)
|
| 86 |
-
selector = selector.strip()
|
| 87 |
-
if selector.startswith('.') and 'class' in element.attrs:
|
| 88 |
-
classes = element.get('class', [])
|
| 89 |
-
if selector[1:] in classes:
|
| 90 |
-
styles.update(parse_styles(props))
|
| 91 |
-
elif selector.startswith('#') and element.get('id') == selector[1:]:
|
| 92 |
-
styles.update(parse_styles(props))
|
| 93 |
-
elif selector.lower() == element.name:
|
| 94 |
-
styles.update(parse_styles(props))
|
| 95 |
-
except Exception as e:
|
| 96 |
-
logger.warning(f"Error parsing <style> tag: {e}")
|
| 97 |
-
return styles
|
| 98 |
-
|
| 99 |
-
def safe_int(value, default=100):
|
| 100 |
-
if not value:
|
| 101 |
-
return default
|
| 102 |
-
value = re.sub(r'[^\d]', '', str(value))
|
| 103 |
-
try:
|
| 104 |
-
return int(value) if value else default
|
| 105 |
-
except ValueError:
|
| 106 |
-
logger.warning(f"Invalid value for int conversion: {value}")
|
| 107 |
-
return default
|
| 108 |
-
|
| 109 |
-
def parse_color(color):
|
| 110 |
-
if not color:
|
| 111 |
-
return '#FFFFFF'
|
| 112 |
-
color = color.lower()
|
| 113 |
-
if color.startswith('#'):
|
| 114 |
-
return color
|
| 115 |
-
if color.startswith('rgb'):
|
| 116 |
-
try:
|
| 117 |
-
nums = re.findall(r'\d+', color)
|
| 118 |
-
r, g, b = map(int, nums[:3])
|
| 119 |
-
return f'#{r:02x}{g:02x}{b:02x}'
|
| 120 |
-
except:
|
| 121 |
-
return '#FFFFFF'
|
| 122 |
-
return '#FFFFFF'
|
| 123 |
-
|
| 124 |
-
def process_element(tag, parent_id=None, depth=0):
|
| 125 |
-
nonlocal elements, y_offset, element_index
|
| 126 |
-
styles = get_styles(tag)
|
| 127 |
-
logger.info(f"Processing tag: {tag.name}, text: {tag.get_text(strip=True)[:50]}, classes: {tag.get('class', [])}")
|
| 128 |
-
element = {
|
| 129 |
-
'id': f'element-{element_index}',
|
| 130 |
-
'x': safe_int(styles.get('left', styles.get('margin-left', '0px')), 50 + depth * 40),
|
| 131 |
-
'y': safe_int(styles.get('top', styles.get('margin-top', '0px')), y_offset + depth * 40),
|
| 132 |
-
'parentId': parent_id
|
| 133 |
-
}
|
| 134 |
-
element_index += 1
|
| 135 |
-
|
| 136 |
-
if tag.name in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button', 'li', 'strong', 'em', 'input', 'label']:
|
| 137 |
-
text = tag.get_text(strip=True)
|
| 138 |
-
if text:
|
| 139 |
-
font_size = safe_int(styles.get('font-size', '16px'), 16)
|
| 140 |
-
element.update({
|
| 141 |
-
'type': 'text',
|
| 142 |
-
'tag': tag.name,
|
| 143 |
-
'content': text[:1000] or 'Text Placeholder',
|
| 144 |
-
'fontSize': font_size,
|
| 145 |
-
'color': parse_color(styles.get('color', '#000000')),
|
| 146 |
-
'fontFamily': styles.get('font-family', 'Inter'),
|
| 147 |
-
'fontWeight': styles.get('font-weight', '400')
|
| 148 |
-
})
|
| 149 |
-
y_offset += font_size + 20
|
| 150 |
-
elements.append(element)
|
| 151 |
-
logger.info(f"Added text element: {text[:50]}")
|
| 152 |
|
| 153 |
-
elif tag.name == 'img':
|
| 154 |
-
src = tag.get('src', '')
|
| 155 |
-
if src:
|
| 156 |
-
src = urljoin(website_url.url, src)
|
| 157 |
-
width = safe_int(tag.get('width', styles.get('width', '200px')), 200)
|
| 158 |
-
height = safe_int(tag.get('height', styles.get('height', '200px')), 200)
|
| 159 |
-
element.update({
|
| 160 |
-
'type': 'image',
|
| 161 |
-
'src': src,
|
| 162 |
-
'alt': tag.get('alt', ''),
|
| 163 |
-
'width': max(width, 20),
|
| 164 |
-
'height': max(height, 20)
|
| 165 |
-
})
|
| 166 |
-
y_offset += height + 20
|
| 167 |
-
elements.append(element)
|
| 168 |
-
logger.info(f"Added image element: {src[:50]}")
|
| 169 |
-
|
| 170 |
-
elif tag.name == 'div':
|
| 171 |
-
width = safe_int(styles.get('width', '300px'), 300)
|
| 172 |
-
height = safe_int(styles.get('height', '100px'), 100)
|
| 173 |
-
element.update({
|
| 174 |
-
'type': 'div',
|
| 175 |
-
'width': max(width, 20),
|
| 176 |
-
'height': max(height, 20),
|
| 177 |
-
'backgroundColor': parse_color(styles.get('background-color', '#FFFFFF')),
|
| 178 |
-
'borderWidth': safe_int(styles.get('border-width', '0px'), 0),
|
| 179 |
-
'borderColor': parse_color(styles.get('border-color', '#000000'))
|
| 180 |
-
})
|
| 181 |
-
y_offset += height + 20
|
| 182 |
-
elements.append(element)
|
| 183 |
-
logger.info(f"Added div element: {width}x{height}")
|
| 184 |
-
|
| 185 |
-
for child in tag.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button', 'li', 'strong', 'em', 'input', 'label', 'img', 'div'], recursive=False):
|
| 186 |
-
process_element(child, element['id'], depth + 1)
|
| 187 |
-
|
| 188 |
-
body = soup.find('body')
|
| 189 |
-
if body:
|
| 190 |
-
logger.info("Found body tag, processing children")
|
| 191 |
-
for tag in body.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button', 'li', 'strong', 'em', 'input', 'label', 'img', 'div'], recursive=False):
|
| 192 |
-
process_element(tag)
|
| 193 |
-
else:
|
| 194 |
-
logger.warning("No <body> tag found, processing all elements")
|
| 195 |
-
for tag in soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'a', 'button', 'li', 'strong', 'em', 'input', 'label', 'img', 'div']):
|
| 196 |
-
process_element(tag)
|
| 197 |
-
|
| 198 |
-
colors = set()
|
| 199 |
-
for element in soup.find_all(style=True):
|
| 200 |
-
style = element.get('style')
|
| 201 |
-
if 'color' in style:
|
| 202 |
-
color_part = style.split('color:')[1].split(';')[0].strip()
|
| 203 |
-
colors.add(parse_color(color_part))
|
| 204 |
-
if 'background-color' in style:
|
| 205 |
-
bg_color = style.split('background-color:')[1].split(';')[0].strip()
|
| 206 |
-
colors.add(parse_color(bg_color))
|
| 207 |
-
|
| 208 |
-
layout = {
|
| 209 |
-
'title': soup.title.string if soup.title else '',
|
| 210 |
-
'bodyWidth': '100%',
|
| 211 |
-
'bodyHeight': '100%'
|
| 212 |
-
}
|
| 213 |
-
|
| 214 |
-
if not elements:
|
| 215 |
-
logger.warning("No elements found, adding fallback")
|
| 216 |
-
elements.append({
|
| 217 |
-
'id': 'element-0',
|
| 218 |
-
'type': 'text',
|
| 219 |
-
'x': 20,
|
| 220 |
-
'y': 20,
|
| 221 |
-
'content': 'Unable to parse content. Try a static website like https://example.com.',
|
| 222 |
-
'fontSize': 16,
|
| 223 |
-
'color': '#FF0000',
|
| 224 |
-
'fontFamily': 'Inter',
|
| 225 |
-
'fontWeight': '400'
|
| 226 |
-
})
|
| 227 |
-
|
| 228 |
-
logger.info(f"Returning {len(elements)} elements: {elements[:2]}")
|
| 229 |
-
return {
|
| 230 |
-
"elements": elements,
|
| 231 |
-
"colors": list(colors),
|
| 232 |
-
"layout": layout
|
| 233 |
-
}
|
| 234 |
-
|
| 235 |
-
except requests.RequestException as e:
|
| 236 |
-
logger.error(f"Error fetching website: {str(e)}")
|
| 237 |
-
raise HTTPException(status_code=400, detail=f"Error fetching website: {str(e)}")
|
| 238 |
except Exception as e:
|
| 239 |
-
|
| 240 |
-
raise HTTPException(status_code=500, detail=f"Error processing website: {str(e)}")
|
| 241 |
-
|
| 242 |
-
@app.get("/proxy-image")
|
| 243 |
-
async def proxy_image(url: str):
|
| 244 |
-
logger.info(f"Proxying image: {url}")
|
| 245 |
-
try:
|
| 246 |
-
response = requests.get(url, stream=True)
|
| 247 |
-
response.raise_for_status()
|
| 248 |
-
return Response(content=response.content, media_type=response.headers['content-type'])
|
| 249 |
-
except requests.RequestException as e:
|
| 250 |
-
logger.error(f"Error fetching image: {str(e)}")
|
| 251 |
-
raise HTTPException(status_code=400, detail=f"Error fetching image: {str(e)}")
|
| 252 |
|
| 253 |
-
@app.
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
return {"
|
| 257 |
|
| 258 |
if __name__ == "__main__":
|
| 259 |
-
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
+
from gradio_client import Client, handle_file
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import io
|
| 6 |
+
import base64
|
| 7 |
+
import tempfile
|
| 8 |
+
|
| 9 |
+
app = Flask(__name__)
|
| 10 |
+
CORS(app) # Enable CORS for Figma plugin requests
|
| 11 |
+
|
| 12 |
+
# Initialize Gradio Client for the background removal model
|
| 13 |
+
client = Client("ECCV2022/dis-background-removal")
|
| 14 |
+
|
| 15 |
+
def image_to_data_url(img: Image.Image) -> str:
|
| 16 |
+
"""Convert a PIL Image to a base64-encoded data URL."""
|
| 17 |
+
buffered = io.BytesIO()
|
| 18 |
+
img.save(buffered, format="PNG")
|
| 19 |
+
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 20 |
+
return f"data:image/png;base64,{img_str}"
|
| 21 |
+
|
| 22 |
+
def base64_to_image(data_url):
|
| 23 |
+
"""Convert a base64-encoded data URL to a PIL Image."""
|
| 24 |
+
header, encoded = data_url.split(",", 1)
|
| 25 |
+
binary_data = base64.b64decode(encoded)
|
| 26 |
+
image = Image.open(io.BytesIO(binary_data))
|
| 27 |
+
return image
|
| 28 |
+
|
| 29 |
+
@app.route("/remove_background", methods=["POST"])
|
| 30 |
+
def remove_background():
|
| 31 |
+
"""Remove background from an image using the Hugging Face model."""
|
| 32 |
+
data = request.json
|
| 33 |
+
data_url = data.get("image_url")
|
| 34 |
+
|
| 35 |
+
if not data_url:
|
| 36 |
+
return jsonify({"error": "image_url is required"}), 400
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
try:
|
| 39 |
+
# Convert base64 data URL to image and save to temporary file
|
| 40 |
+
input_image = base64_to_image(data_url).convert("RGB")
|
| 41 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
| 42 |
+
input_image.save(tmp, format="PNG")
|
| 43 |
+
temp_path = tmp.name
|
| 44 |
+
|
| 45 |
+
# Call the Gradio model to remove background
|
| 46 |
+
result = client.predict(
|
| 47 |
+
image=handle_file(temp_path),
|
| 48 |
+
api_name="/predict"
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Process the two output images
|
| 52 |
+
image_path1, image_path2 = result
|
| 53 |
+
depth_image = Image.open(image_path2)
|
| 54 |
+
processed_image = Image.open(image_path1)
|
| 55 |
+
|
| 56 |
+
# Return base64-encoded images
|
| 57 |
+
return jsonify({
|
| 58 |
+
"depth_image": image_to_data_url(depth_image),
|
| 59 |
+
"semi_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
except Exception as e:
|
| 63 |
+
return jsonify({"error": str(e)}), 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
+
@app.route("/", methods=["GET"])
|
| 66 |
+
def health_check():
|
| 67 |
+
"""Health check endpoint for Hugging Face Spaces."""
|
| 68 |
+
return jsonify({"status": "ok"}), 200
|
| 69 |
|
| 70 |
if __name__ == "__main__":
|
| 71 |
+
app.run(host="0.0.0.0", port=7860) # Required for Hugging Face Spaces
|