Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

Support script image URLs in export

Abi Rajad74c466f6fc9
diff --git a/backend/routes/export.py b/backend/routes/export.py
index 802f8a9d..8399d221 100644
--- a/backend/routes/export.py
+++ b/backend/routes/export.py
@@ -51,6 +51,7 @@ MIME_EXTENSION_MAP = {
}
CSS_URL_RE = re.compile(r"url\(\s*(['\"]?)(.*?)\1\s*\)", re.IGNORECASE)
+RAW_URL_RE = re.compile(r"https?://[^\s'\"<>\\)]+")
MAX_ASSETS = 50
MAX_ASSET_BYTES = 20 * 1024 * 1024
MAX_REDIRECTS = 5
@@ -133,6 +134,16 @@ def add_candidate(candidates: dict[str, AssetCandidate], raw_url: str) -> None:
candidates[url] = AssetCandidate(url=url, extension_hint=extension_from_url(url))
+def add_script_url_candidate(
+ candidates: dict[str, AssetCandidate], raw_url: str
+) -> None:
+ url = raw_url.rstrip(".,;:")
+ parsed = urlparse(url)
+ if parsed.hostname != "replicate.delivery" and extension_from_url(url) == "bin":
+ return
+ add_candidate(candidates, url)
+
+
def display_asset_url(url: str) -> str:
parsed = urlparse(url)
if not parsed.netloc:
@@ -172,6 +183,13 @@ def collect_asset_candidates(soup: BeautifulSoup) -> list[AssetCandidate]:
for url in extract_css_urls(style):
add_candidate(candidates, url)
+ for script_element in soup.select("script"):
+ script_text = script_element.string
+ if not isinstance(script_text, str):
+ continue
+ for match in RAW_URL_RE.finditer(script_text):
+ add_script_url_candidate(candidates, match.group(0))
+
return list(candidates.values())[:MAX_ASSETS]
@@ -412,6 +430,13 @@ def rewrite_html_assets(soup: BeautifulSoup, asset_path_by_url: dict[str, str])
element["style"] = rewrite_css_urls(style, asset_path_by_url)
+def rewrite_raw_asset_urls(index_html: str, asset_path_by_url: dict[str, str]) -> str:
+ for original_url, asset_path in asset_path_by_url.items():
+ index_html = index_html.replace(original_url, asset_path)
+ index_html = index_html.replace(original_url.replace("/", "\\/"), asset_path)
+ return index_html
+
+
def create_project_zip(index_html: str, assets: Iterable[ExportedAsset]) -> bytes:
buffer = BytesIO()
with ZipFile(buffer, "w", ZIP_DEFLATED) as zip_file:
@@ -448,7 +473,8 @@ async def export_code(request: ExportRequest) -> Response:
if asset_path_by_url:
rewrite_html_assets(soup, asset_path_by_url)
- zip_content = create_project_zip(str(soup), assets)
+ index_html = rewrite_raw_asset_urls(str(soup), asset_path_by_url)
+ zip_content = create_project_zip(index_html, assets)
print(
"Export complete: "
f"candidates={len(candidates)} assets={len(assets)} "
diff --git a/backend/tests/test_export.py b/backend/tests/test_export.py
index ccd310eb..74538b7a 100644
--- a/backend/tests/test_export.py
+++ b/backend/tests/test_export.py
@@ -1,6 +1,7 @@
from io import BytesIO
from zipfile import ZipFile
+import httpx
import pytest
from routes.export import ExportRequest, export_code
@@ -37,6 +38,43 @@ async def test_export_code_rewrites_data_url_images_into_zip_assets() -> None:
assert archive.read("assets/image-2.svg").startswith(b"<svg")
+async def test_export_code_rewrites_script_image_urls_into_zip_assets(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ image_url = "https://replicate.delivery/example/output.png"
+ code = f"""
+ <html>
+ <body>
+ <div id="root"></div>
+ <script type="text/babel">
+ function App() {{
+ return <img src="{image_url}" />;
+ }}
+ </script>
+ </body>
+ </html>
+ """
+
+ async def mock_fetch_remote_asset(
+ _client: httpx.AsyncClient, fetch_url: str, extension_hint: str
+ ) -> tuple[bytes, str] | None:
+ assert fetch_url == image_url
+ assert extension_hint == "png"
+ return b"\x89PNG\r\n\x1a\n", "png"
+
+ monkeypatch.setattr("routes.export.fetch_remote_asset", mock_fetch_remote_asset)
+
+ response = await export_code(ExportRequest(code=code))
+
+ with ZipFile(BytesIO(response.body)) as archive:
+ assert sorted(archive.namelist()) == ["assets/image-1.png", "index.html"]
+ index_html = archive.read("index.html").decode("utf-8")
+ assert image_url not in index_html
+ assert 'src="assets/image-1.png"' in index_html
+ assert archive.read("assets/image-1.png") == b"\x89PNG\r\n\x1a\n"
+
+
@pytest.mark.asyncio
async def test_export_code_returns_zip_with_index_when_no_assets() -> None:
response = await export_code(ExportRequest(code="<html><body>Hello</body></html>"))