项目简介
Screenshot-to-Code 利用 AI 模型将截图、设计稿和录屏转换为可运行的代码,支持 HTML、React、Vue 等前端框架。可从截图中提取真实素材,并支持多种模型提供商。项目包含 React 前端和 FastAPI 后端,可本地部署或使用官方托管服务。
README 预览
# screenshot-to-code\n\nConvert screenshots, mockups, Figma designs, and screen recordings into clean, functional code using AI. The easiest way to try this is using the official, hosted product at screenshottocode.com →\n\n\nhttps://github.com/user-attachments/assets/ec08a5e6-9606-41c5-b03a-1bf47dfeba75\n\n\nSupported stacks:\n\n- HTML + Tailwind\n- HTML + CSS\n- React + Tailwind\n- Vue + Tailwind\n- Bootstrap\n- Ionic + Tailwind\n\nDefault AI models:\n\n- Gemini 3 Flash Preview and Gemini 3.1 Pro Preview - the best models\n- GPT-5.5 and GPT-5.4 Mini\n- Claude Opus 4.6, Claude Opus 4.8\n- z-image-turbo (using Replicate) for image generation\n\nSee the [Examples](#-examples) section below for more demos.\n\nScreenshot to Code also supports taking a screen recording of a website in action and turning that into a functional prototype.\n\n\n\n## 🛠 Getting Started\n\nChoose the path that fits what you want to do:\n\n- **Run locally:** best if you want to customize, self-host, or contribute.\n- **Use the hosted app:** the fastest way to try Screenshot to Code with no local setup. Open the hosted app →\n\nRunning locally requires API keys and a backend/frontend setup. The app has a React/Vite frontend and a FastAPI backend.\n\n### API keys\n\nYou need **at least one** model provider key (OpenAI, Anthropic, or Gemini).\n**Gemini and Replicate are strongly recommended for the best quality of\nscreenshot-to-code accuracy** — Gemini powers asset extraction (reusing the\nreal logos/images from your screenshot) and Replicate powers image\ngeneration, background removal, and image editing. Adding all four keys gives\nthe best results and lets you compare multiple models per generation.\n\n| Key | Required? | What it unlocks |\n|-----|-----------|-----------------|\n| `OPENAI_API_KEY` | One of these three | GPT code-gen variants (GPT-5.5, GPT-5.4 Mini) |\n| `ANTHROPIC_API_KEY` | One of these three | Claude code-gen variants (Opus 5, Opus 4.8, Fable 5, Sonnet 4.6) |\n| `GEMINI_AP
常见问题 (5)
故障排除如何修复 Starlette WebSocket 崩溃:异常关闭代码 1006 之后出现 RuntimeError "Unexpected ASGI message 'websocket.close'"?
升级到包含 issue #599 修复的最新版本。作为临时变通方案,可降级到上一个主版本。要修补代码,请从 Starlette 导入 WebSocketDisconnect,并让 WebSocketCommunicator.close() 和 throw_error() 处理连接已关闭的状态,例如:
from starlette.websockets import WebSocketDisconnect
try:
await ws_comm.close()
except (
ConnectionClosedOK,
ConnectionClosedError,
WebSocketDisconnect,
RuntimeError,
):
pass
在 throw_error() 中应用相同的异常处理。这样可以防止在 uvicorn 已经关闭连接之后,finally 代码块再次发送 websocket.close ASGI 消息。该崩溃是在 Python 3.11、uvicorn 0.25.0、Starlette 0.41.3 和 websockets 14.1 环境下观察到的。
故障排除如何修复流式传输抛出异常时 AsyncAnthropic 连接池耗尽或连接泄漏的问题?
将客户端生命周期包裹在 try/finally 中,这样即使流式传输或会话初始化失败,close() 也会执行:
client = AsyncAnthropic(api_key=api_key)
try:
# streaming / session logic
...
finally:
await client.close()
或者,将客户端用作异步上下文管理器:
async with AsyncAnthropic(api_key=api_key) as client:
# streaming logic
...
将同样的模式应用于 AsyncOpenAI,以及 stream_claude_response 和 stream_claude_response_native 这两个函数。如果不进行清理,异常会使 HTTP 连接保持打开状态,这可能会在长时间运行的服务中耗尽连接池。
故障排除如何修复 screenshot-to-code 代码生成失败并提示 OpenAI model not found、invalid API key 或 rate limit 错误的问题?
首先检查后端日志以确定具体的 OpenAI 错误:
docker compose logs backend --tail=100
# 或
docker logs <container_id>
常见修复方法:
1. **API 密钥无效或缺失:** 确保 OPENAI_API_KEY 已在您的环境或 .env 文件中正确设置,然后重启容器。
2. **模型未找到或不可用:** 如果 generate_code.py 固定使用了带日期的模型(如 gpt-4o-2024-11-20),请将其更改为您的 OpenAI 账户可用的模型,如 gpt-4o 或 gpt-4。
3. **速率限制或账户限制:** 检查您的 OpenAI 账单/用量控制面板,降低请求频率,或等待速率限制重置。
4. **配置更改后重启:** 运行 docker compose down && docker compose up --build。
要彻底解决问题,请在 generate_code.py 中添加显式的 OpenAI API 错误处理,以便将身份验证、速率限制和模型未找到等错误暴露出来,而不是静默失败。
故障排除为什么 Poetry 安装 typing-extensions 4.12.2 时失败,报错 "All attempts to connect to pypi.org failed"?
这是网络/DNS/代理问题,而不是 typing-extensions 包的问题。在 PowerShell 中,首先测试连接性:
Resolve-DnsName pypi.org
Invoke-WebRequest https://pypi.org/simple/ -UseBasicParsing
poetry install -v
如果您在本地代理之后,请在运行 Poetry 之前设置代理(将端口替换为您的代理端口):
$env:HTTP_PROXY = "http://127.0.0.1:7890"
$env:HTTPS_PROXY = "http://127.0.0.1:7890"
poetry install
如果 PyPI 在您的网络上被屏蔽,请临时使用镜像:
$env:POETRY_PYPI_MIRROR_URL = "https://pypi.tuna.tsinghua.edu.cn/simple/"
poetry install
还可以尝试禁用或重新配置 VPN/防火墙软件,然后重新运行 poetry install。
故障排除如何修复在使用 OpenAI SDK 时出现的 DeepSeek API 错误 "Failed to deserialize the JSON body into target type: messages[1] ... ChatCompletionRequestContent"?
这个 422 错误表示 messages[1].content 使用了 DeepSeek 不接受的格式。尽管 DeepSeek 与 OpenAI 兼容,但它可能不接受 OpenAI 的多模态 content-part 数组。请将消息的 content 以纯文本字符串的形式发送。
检查出错的消息:
import json
print(json.dumps(params["messages"][1], ensure_ascii=False, indent=2))
在调用 API 之前,将 content 数组转换为文本:
def normalize_deepseek_messages(messages):
for message in messages:
content = message.get("content")
if isinstance(content, list):
message["content"] = "".join(
part.get("text", "")
for part in content
if isinstance(part, dict) and part.get("type") == "text"
)
elif content is None:
message["content"] = ""
return messages
params["messages"] = normalize_deepseek_messages(params["messages"])
stream = await client.chat.completions.create(**params)
同时移除不支持的部分,例如 image_url 或 input_audio;仅使用 DeepSeek 的文本/聊天格式。如果使用 agent 框架,请禁用视觉/多模态消息格式化,或强制使用纯文本的 OpenAI 兼容消息。