File size: 5,537 Bytes
431a0a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import re

import gradio as gr
import spaces
import torch
from transformers import AutoProcessor, Qwen3VLForConditionalGeneration

MODEL_ID = os.environ.get("MODEL_ID", "Qwen/Qwen3-VL-8B-Instruct")

processor = AutoProcessor.from_pretrained(MODEL_ID)
model = Qwen3VLForConditionalGeneration.from_pretrained(
    MODEL_ID,
    dtype=torch.bfloat16,
    device_map="cuda",
)

NEXTJS_PROMPT = """You are a senior front-end engineer. Convert this UI design into production React.

Rules:
- Output ONE complete .tsx file. A single default-exported component.
- Tailwind CSS utility classes only. No styled-components, no CSS modules, no <style> tags.
- Prefer Tailwind's scale (p-4, gap-6, text-sm). Use arbitrary values like w-[327px] only when the design clearly demands an off-scale value.
- Server component by default. Add "use client" at the top ONLY if it uses state, effects, or event handlers.
- Semantic HTML: header, nav, main, section, footer, button, ul/li. Not a pile of divs.
- Responsive. Read the design as the desktop breakpoint and make sensible sm:/md:/lg: choices.
- Images: next/image with a /placeholder.svg src and explicit width/height.
- Icons: inline SVG. Do not import an icon library.
- Transcribe the real text from the design. Do not substitute lorem ipsum.
- No commentary before or after. Code only, in one ```tsx fence.
"""

FRAMER_PROMPT = """You are converting this UI design into a Framer code component.

Framer has NO Tailwind build step, so Tailwind class names would render as unstyled boxes. Obey these rules exactly:

- Output ONE complete .tsx file. A single default-exported React component.
- NEVER use className. Every style is an inline `style={{ ... }}` object.
- Use flexbox layout with explicit gap, padding, borderRadius, backgroundColor, color, fontSize, fontWeight, lineHeight values in px or standard CSS units.
- Start the file with these Framer layout annotations above the component:
  /**
   * @framerSupportedLayoutWidth any
   * @framerSupportedLayoutHeight auto
   */
- Expose the editable text, colors, and image sources as component props with sensible defaults, then register them with addPropertyControls so they are editable on the Framer canvas.
- Import exactly: import { addPropertyControls, ControlType } from "framer"
- Use plain <img> for images, not next/image. Framer has no next/image.
- Icons: inline SVG.
- Transcribe the real text from the design. Do not substitute lorem ipsum.
- No commentary before or after. Code only, in one ```tsx fence.
"""

PROMPTS = {"Next.js + Tailwind": NEXTJS_PROMPT, "Framer code component": FRAMER_PROMPT}


def _extract_code(text: str) -> str:
    """Pull the fenced block out, but fall back to raw text if the model skipped the fence."""
    match = re.search(r"```(?:tsx|jsx|typescript|javascript)?\s*\n(.*?)```", text, re.DOTALL)
    return match.group(1).strip() if match else text.strip()


@spaces.GPU(duration=240)
def generate(image, target, notes, max_new_tokens, temperature):
    if image is None:
        raise gr.Error("Upload a screenshot of the design first.")

    instruction = PROMPTS[target]
    if notes and notes.strip():
        instruction += f"\nAdditional requirements from the designer:\n{notes.strip()}\n"

    messages = [
        {
            "role": "user",
            "content": [
                {"type": "image", "image": image},
                {"type": "text", "text": instruction},
            ],
        }
    ]

    inputs = processor.apply_chat_template(
        messages,
        tokenize=True,
        add_generation_prompt=True,
        return_dict=True,
        return_tensors="pt",
    ).to(model.device)

    generated = model.generate(
        **inputs,
        max_new_tokens=int(max_new_tokens),
        do_sample=temperature > 0,
        temperature=float(temperature) if temperature > 0 else None,
        top_p=0.8,
        top_k=20,
        repetition_penalty=1.0,
    )

    trimmed = [out[len(inp):] for inp, out in zip(inputs.input_ids, generated)]
    decoded = processor.batch_decode(trimmed, skip_special_tokens=True)[0]
    return _extract_code(decoded)


with gr.Blocks(title="Design → Code") as demo:
    gr.Markdown(
        "# Design → Code\n"
        "Upload a design screenshot. Get a Next.js + Tailwind component, or a "
        "Framer code component with inline styles (Framer cannot compile Tailwind classes)."
    )

    with gr.Row():
        with gr.Column(scale=1):
            image = gr.Image(type="pil", label="Design screenshot")
            target = gr.Radio(
                choices=list(PROMPTS.keys()),
                value="Next.js + Tailwind",
                label="Output target",
            )
            notes = gr.Textbox(
                label="Notes (optional)",
                placeholder="e.g. use our brand color #0F172A, make the nav sticky",
                lines=3,
            )
            with gr.Accordion("Generation settings", open=False):
                max_new_tokens = gr.Slider(512, 8192, value=4096, step=256, label="Max new tokens")
                temperature = gr.Slider(0.0, 1.0, value=0.2, step=0.05, label="Temperature")
            run = gr.Button("Generate", variant="primary")

        with gr.Column(scale=1):
            code = gr.Code(label="Generated component", language="typescript", lines=34)

    run.click(
        generate,
        inputs=[image, target, notes, max_new_tokens, temperature],
        outputs=code,
    )

if __name__ == "__main__":
    demo.queue(max_size=20).launch()