File size: 2,376 Bytes
3c849b2
4fbe353
a31d9c3
61fa9dd
 
3c849b2
a31d9c3
3c849b2
 
61fa9dd
3c849b2
61fa9dd
 
 
 
4fbe353
61fa9dd
 
3c849b2
61fa9dd
a31d9c3
4fbe353
3c849b2
 
 
61fa9dd
3c849b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a31d9c3
 
 
 
4fbe353
 
 
a31d9c3
3c849b2
 
 
 
4fbe353
3c849b2
a31d9c3
4fbe353
a31d9c3
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
# Updated UI Generator with Better Open-Source Model and DartPad/Expo Preview Support

import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM, TextGenerationPipeline
import torch
import re

# Use a smaller model for CPU support
model_id = "deepseek-ai/deepseek-coder-1.3b-instruct"

# Use CPU or GPU if available
device = 0 if torch.cuda.is_available() else -1

# Load tokenizer and model
print("Loading model...")
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32)

# Build the generation pipeline
generator = TextGenerationPipeline(model=model, tokenizer=tokenizer, device=device)

def generate_ui(platform, framework, ui_prompt):
    prompt_template = f"""
You are a professional mobile developer.
Create a full {framework} UI code for {platform} based on this request:
"""
    full_prompt = prompt_template + f"\n{ui_prompt}\n" + "\nEnsure to include imports, widgets, and app structure."
    response = generator(full_prompt, max_new_tokens=512, do_sample=True, temperature=0.7)[0]['generated_text']

    # Extract only code block (removes echoed prompt if needed)
    code_match = re.search(r"(?s)(import .*?)$", response)
    code = code_match.group(1).strip() if code_match else response.strip()
    return code, generate_preview_link(code, framework)

def generate_preview_link(code, framework):
    if framework == "Flutter":
        return f"https://dartpad.dev/?id=custom&code={gr.utils.sanitize_html(code)[:1500]}"
    elif framework == "React Native":
        return f"https://snack.expo.dev/?code={gr.utils.sanitize_html(code)[:1500]}"
    else:
        return "Preview not available for this framework."

interface = gr.Interface(
    fn=generate_ui,
    inputs=[
        gr.Dropdown(["Android", "iOS"], label="Platform"),
        gr.Dropdown(["Flutter", "Kotlin XML", "SwiftUI", "React Native"], label="Framework"),
        gr.Textbox(lines=4, label="UI Prompt", placeholder="e.g. Login screen with email & password, dark theme")
    ],
    outputs=[
        gr.Code(label="Generated UI Code"),
        gr.Textbox(label="Preview Link")
    ],
    title="Prompt-to-UI Code Generator",
    description="Describe your screen and get UI code + preview for Flutter/React Native apps."
)

interface.launch()