Spaces:
Sleeping
Sleeping
File size: 10,261 Bytes
7d5b9d2 49febd2 7d5b9d2 b8ac356 7d5b9d2 7569b80 7d5b9d2 49febd2 4f554c5 49febd2 7d5b9d2 7569b80 7d5b9d2 7569b80 b8ac356 7569b80 b8ac356 7569b80 b8ac356 7d5b9d2 7569b80 7d5b9d2 7569b80 7d5b9d2 7569b80 b8ac356 7569b80 7d5b9d2 7569b80 7d5b9d2 7569b80 7d5b9d2 7569b80 7d5b9d2 7569b80 7d5b9d2 7569b80 7d5b9d2 7569b80 7d5b9d2 7569b80 7d5b9d2 7569b80 7d5b9d2 7569b80 7d5b9d2 9817019 7d5b9d2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 |
import gradio as gr
from playwright.async_api import async_playwright, Page
from PIL import Image
from io import BytesIO
from anthropic import Anthropic, APIStatusError
from dotenv import load_dotenv
import os
from typing import Literal
import time
from base64 import b64encode
from contextlib import asynccontextmanager
load_dotenv()
# check for ANTHROPIC_API_KEY
if os.getenv("ANTHROPIC_API_KEY") is None:
raise ValueError(
"ANTHROPIC_API_KEY is not set, set it in .env or export it in your environment"
)
anthropic = Anthropic()
model = "claude-3-5-sonnet-20240620"
def prepare_playwright_if_needed():
# hopefully, we already installed the deps with dependencies.txt
os.system("playwright install chromium")
def apply_tailwind(content):
return f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
{content}
</body>
</html>
"""
system_prompt = f"""
You are a helpful assistant that generates HTML and CSS.
You directly output HTML with tailwind css classes, and nothing else (no markdown, no other text, etc).
You are not able to insert images from the internet, but you can still generate an <img> tag with an appropriate alt tag (leave out the src, we will provide that).
Assume that the content is being inserted into a template like this:
{apply_tailwind("your html here")}
"""
def messages_text_to_web(prompt):
return [
{"role": "user", "content": prompt},
]
class MaxRetriesExceeded(Exception):
pass
# returns the full text of the response each time
def stream_claude(
messages,
system=system_prompt,
max_tokens=2000,
max_retries=3,
wait_seconds=1,
wait_exponential=1.5,
):
text = ""
for _ in range(max_retries):
try:
with anthropic.messages.stream(
model=model,
max_tokens=max_tokens,
system=system,
messages=messages,
) as stream:
for chunk in stream.text_stream:
text += chunk
yield text
return
except APIStatusError as e:
# anthropic.APIStatusError: {'type': 'error', 'error': {'details': None, 'type': 'overloaded_error', 'message': 'Overloaded'}}
print(
f"Error from Claude: {e}, will wait {wait_seconds} seconds before retrying"
)
wait_seconds *= wait_exponential
raise MaxRetriesExceeded
def format_image(image: bytes, media_type: Literal["image/png", "image/jpeg"]):
image_base64 = b64encode(image).decode("utf-8")
return {
"type": "image",
"source": {
"type": "base64",
"media_type": media_type,
"data": image_base64,
},
}
def visual_feedback_messages(prompt, history: list[tuple[str, bytes]]):
"""
history is a list of tuples of (content, image) corresponding to iterations of generation and rendering
"""
improve_prompt = """
Given the current draft of the webpage you generated for me as HTML and the screenshot of it rendered, improve the HTML to look nicer.
"""
return [
{"role": "user", "content": prompt},
*[
item
for content, image_bytes in history
for item in [
{
"role": "assistant",
"content": content,
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "Here is a screenshot of the above HTML code rendered in a browser:",
},
format_image(image_bytes, "image/png"),
{
"type": "text",
"text": improve_prompt,
},
],
},
]
],
]
def match_image_messages(image_bytes: bytes, history: list[tuple[bytes, bytes]]):
improve_prompt = """
Given the current draft of the webpage you generated for me as HTML and the original screenshot, improve the HTML to match closer to the original screenshot. Remember not to output any commentary, just the HTML.
"""
return [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Please generate a webpage that matches the image below as closely as possible:",
},
format_image(image_bytes, "image/png"),
],
},
*[
item
for content, image_bytes in history
for item in [
{
"role": "assistant",
"content": content,
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "Here is a screenshot of the above HTML code rendered in a browser:",
},
format_image(image_bytes, "image/png"),
{
"type": "text",
"text": improve_prompt,
},
],
},
]
],
]
async def render_html(page: Page, content: str):
start_time = time.perf_counter()
await page.set_content(content)
# weird, can we set scale to 2.0 directly instead of "device", ie whatever server this is running on?
image_bytes = await page.screenshot(type="png", scale="device", full_page=True)
dt = time.perf_counter() - start_time
return image_bytes, dt
def apply_template(content, template):
if template == "tailwind":
return apply_tailwind(content)
return content
def to_pil(image_bytes: bytes):
return Image.open(BytesIO(image_bytes))
@asynccontextmanager
async def browser(width, height):
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page(viewport={"width": width, "height": height})
try:
yield page
finally:
await browser.close()
async def throttle(generator, every=0.25):
last_emit_time = 0
for item in generator:
current_time = time.perf_counter()
if current_time - last_emit_time >= every:
yield item
last_emit_time = current_time
# always emit the last item
yield item
async def generate_with_visual_feedback(
prompt,
template,
resolution: str = "512",
num_iterations: int = 1,
):
width = {"512": 512, "1024": 1024}[resolution]
async with browser(width, width) as page:
history = []
for i in range(num_iterations):
messages = (
messages_text_to_web(prompt)
if i == 0
else visual_feedback_messages(prompt, history)
)
content = ""
async for content in throttle(stream_claude(messages), every=0.25):
image_bytes, render_time = await render_html(
page, apply_template(content, template)
)
yield to_pil(image_bytes), content, render_time
history.append((content, image_bytes))
def to_image_bytes(image: Image.Image) -> bytes:
buffer = BytesIO()
image.save(buffer, format="PNG")
return buffer.getvalue()
async def match_image_with_visual_feedback(image, template, resolution, num_iterations):
width = {"512": 512, "1024": 1024}[resolution]
async with browser(width, width) as page:
history = []
for i in range(num_iterations):
image.thumbnail((width, width), Image.Resampling.LANCZOS)
messages = match_image_messages(to_image_bytes(image), history)
async for content in throttle(stream_claude(messages), 0.25):
image_bytes, render_time = await render_html(
page, apply_template(content, template)
)
yield to_pil(image_bytes), content, render_time
# always render the final image of each iteration
image_bytes, render_time = await render_html(
page, apply_template(content, template)
)
history.append((content, image_bytes))
demo_generate = gr.Interface(
generate_with_visual_feedback,
inputs=[
gr.Textbox(
lines=5,
label="Prompt",
placeholder="Prompt to generate HTML",
value="Generate a beautiful webpage for a cat cafe",
),
gr.Dropdown(choices=["tailwind"], label="Template", value="tailwind"),
gr.Dropdown(choices=["512", "1024"], label="Page Width", value="512"),
gr.Slider(1, 10, 1, step=1, label="Iterations"),
],
outputs=[
gr.Image(type="pil", label="Rendered HTML", image_mode="RGB", format="png"),
gr.Textbox(lines=5, label="Code"),
gr.Number(label="Render Time", precision=2),
],
)
demo_match_image = gr.Interface(
match_image_with_visual_feedback,
inputs=[
gr.Image(type="pil", label="Original Image", image_mode="RGB", format="png"),
gr.Dropdown(choices=["tailwind"], label="Template", value="tailwind"),
gr.Dropdown(choices=["512", "1024"], label="Page Width", value="512"),
gr.Slider(1, 10, 3, step=1, label="Iterations"),
],
outputs=[
gr.Image(type="pil", label="Rendered HTML", image_mode="RGB", format="png"),
gr.Textbox(lines=5, label="Code"),
gr.Number(label="Render Time", precision=2),
],
)
demo = gr.TabbedInterface(
[demo_match_image, demo_generate],
["Match Image", "Generate"],
)
if __name__ == "__main__":
prepare_playwright_if_needed()
demo.launch()
|