abhidgp1978 commited on
Commit
0600e1f
·
verified ·
1 Parent(s): 873ecf1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -577
app.py CHANGED
@@ -1,585 +1,103 @@
1
  import gradio as gr
2
- import json
3
- import os
4
- import io
5
- import zipfile
6
- from datetime import datetime
7
  from PIL import Image, ImageDraw, ImageFont
8
- from typing import Dict, List, Any
9
-
10
- # -----------------------------
11
- # Utility: Safe optional imports for AI
12
- # -----------------------------
13
- TEXT_MODEL_AVAILABLE = False
14
- IMG_MODEL_AVAILABLE = False
15
-
16
- try:
17
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
18
- # A tiny chat model that can run CPU-only in Spaces (slow but works)
19
- _TXT_MODEL_ID = os.getenv("TEXT_MODEL_ID", "TinyLlama/TinyLlama-1.1B-Chat-v1.0")
20
- _tokenizer = AutoTokenizer.from_pretrained(_TXT_MODEL_ID)
21
- _model = AutoModelForCausalLM.from_pretrained(_TXT_MODEL_ID)
22
- text_gen = pipeline("text-generation", model=_model, tokenizer=_tokenizer, device=-1)
23
- TEXT_MODEL_AVAILABLE = True
24
- except Exception:
25
- TEXT_MODEL_AVAILABLE = False
26
-
27
- try:
28
- # We avoid heavy diffusers import by default; only if env permits
29
- if os.getenv("ENABLE_DIFFUSERS", "0") == "1":
30
- from diffusers import AutoPipelineForText2Image
31
- import torch
32
- _IMG_MODEL_ID = os.getenv("IMAGE_MODEL_ID", "stabilityai/sd-turbo")
33
- dtype = torch.float16 if torch.cuda.is_available() else torch.float32
34
- pipe = AutoPipelineForText2Image.from_pretrained(_IMG_MODEL_ID, torch_dtype=dtype)
35
- if torch.cuda.is_available():
36
- pipe = pipe.to("cuda")
37
- IMG_MODEL_AVAILABLE = True
38
- except Exception:
39
- IMG_MODEL_AVAILABLE = False
40
-
41
- # -----------------------------
42
- # In-memory page state (a JSON schema)
43
- # -----------------------------
44
- # Structure:
45
- # {
46
- # "header": [component, ...],
47
- # "body": {
48
- # "subsections": [
49
- # {"id": "sub-1", "name": "Hero Row", "columns": [
50
- # {"width": 100, "components": [ ... ]}
51
- # ]}
52
- # ]
53
- # },
54
- # "footer": [component, ...]
55
- # }
56
- # Component schema: {"type": str, "props": {...}}
57
-
58
- DEFAULT_PAGE = {
59
- "header": [],
60
- "body": {"subsections": []},
61
- "footer": []
62
- }
63
-
64
- # -----------------------------
65
- # Component Catalog
66
- # -----------------------------
67
- COMPONENTS_CATALOG = {
68
- "header": [
69
- {"value": "navbar", "label": "Navigation Bar"},
70
- {"value": "hero", "label": "Hero Section"}
71
- ],
72
- "body": [
73
- {"value": "features", "label": "Features / Services"},
74
- {"value": "testimonials", "label": "Testimonials"},
75
- {"value": "cta", "label": "Call To Action"},
76
- {"value": "contact", "label": "Contact Form"},
77
- {"value": "blog_cards", "label": "Blog / Article Cards"},
78
- # Good-to-have
79
- {"value": "team", "label": "Team / About Us"},
80
- {"value": "faq", "label": "FAQ"},
81
- {"value": "map", "label": "Interactive Map"},
82
- {"value": "portfolio", "label": "Case Studies / Portfolio"},
83
- {"value": "pricing", "label": "Pricing Table"},
84
- {"value": "logos", "label": "Partners / Client Logos"},
85
- {"value": "gallery", "label": "Image Gallery / Carousel"}
86
- ],
87
- "footer": [
88
- {"value": "footer", "label": "Footer"},
89
- {"value": "newsletter", "label": "Newsletter Signup (Footer)"}
90
- ]
91
- }
92
-
93
- # -----------------------------
94
- # AI helpers
95
- # -----------------------------
96
-
97
- def ai_generate_text(prompt: str, tone: str = "neutral", words: int = 40) -> str:
98
- if not prompt.strip():
99
- return ""
100
- system_hint = (
101
- f"Write in a {tone} marketing tone. Keep it concise, scannable, and conversion-focused."
102
- )
103
- target_len = max(20, min(200, words))
104
- if TEXT_MODEL_AVAILABLE:
105
- try:
106
- full_prompt = (
107
- f"[System]: {system_hint}\n[User]: {prompt}\n[Assistant]:"
108
- )
109
- out = text_gen(full_prompt, max_new_tokens=target_len, do_sample=True, temperature=0.8)
110
- return out[0]["generated_text"].split("[Assistant]:")[-1].strip()
111
- except Exception:
112
- pass
113
- # Fallback: simple template
114
- return (
115
- f"{prompt.strip()} — {tone.title()} messaging. "
116
- f"This is placeholder copy intended to be replaced when the AI model is available."
117
- )
118
-
119
-
120
- def ai_generate_image(prompt: str, width: int = 1024, height: int = 576) -> Image.Image:
121
- prompt = prompt.strip() or "Abstract gradient background with soft shapes"
122
- if IMG_MODEL_AVAILABLE:
123
- try:
124
- image = pipe(prompt=prompt, width=width, height=height, num_inference_steps=4).images[0]
125
- return image
126
- except Exception:
127
- pass
128
- # Fallback: generate a placeholder with text
129
- img = Image.new("RGB", (width, height), color=(240, 244, 248))
130
- draw = ImageDraw.Draw(img)
131
- text = f"Placeholder\n{prompt[:60]}..."
132
- try:
133
- font = ImageFont.truetype("DejaVuSans.ttf", 24)
134
- except Exception:
135
- font = ImageFont.load_default()
136
- w, h = draw.multiline_textbbox((0, 0), text, font=font)[2:]
137
- draw.multiline_text(((width - w) / 2, (height - h) / 2), text, fill=(60, 72, 88), font=font, align="center")
138
- return img
139
-
140
- # -----------------------------
141
- # Component factory (props collectors)
142
- # -----------------------------
143
-
144
- def build_component(component_type: str, props: Dict[str, Any]) -> Dict[str, Any]:
145
- return {"type": component_type, "props": props}
146
-
147
- # -----------------------------
148
- # HTML Renderer
149
- # -----------------------------
150
-
151
- BASE_CSS = """
152
- :root{--bg:#ffffff;--fg:#0f172a;--muted:#475569;--brand:#2563eb;--brand-contrast:#ffffff;--card:#f8fafc}
153
- *{box-sizing:border-box}
154
- body{margin:0;background:var(--bg);color:var(--fg);font-family:ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial}
155
- .container{max-width:1120px;margin:0 auto;padding:16px}
156
- .btn{display:inline-block;background:var(--brand);color:var(--brand-contrast);padding:12px 18px;border-radius:12px;text-decoration:none;font-weight:600}
157
- .btn.secondary{background:#111827;color:#fff}
158
- .grid{display:grid;gap:16px}
159
- .card{background:var(--card);border:1px solid #e2e8f0;border-radius:16px;padding:16px}
160
- .navbar{position:sticky;top:0;background:rgba(255,255,255,.9);backdrop-filter:saturate(180%) blur(10px);border-bottom:1px solid #e5e7eb;z-index:50}
161
- .navbar-inner{display:flex;align-items:center;justify-content:space-between;padding:12px 16px}
162
- .nav-links{display:flex;gap:16px;align-items:center}
163
- .hamburger{display:none}
164
- .hero{padding:64px 0}
165
- .hero-grid{display:grid;grid-template-columns:1.2fr 1fr;gap:24px;align-items:center}
166
- .hero h1{font-size:40px;line-height:1.1;margin:0 0 12px}
167
- .hero p{color:var(--muted);font-size:18px;margin:0 0 20px}
168
- .features{padding:40px 0}
169
- .features h2{margin:0 0 16px}
170
- .feature-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
171
- .testimonials{padding:40px 0}
172
- .testimonial-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
173
- .cta{padding:36px;border-radius:16px;background:linear-gradient(135deg,#dbeafe,#eff6ff)}
174
- .blog-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
175
- .footer{padding:32px 0;border-top:1px solid #e5e7eb;font-size:14px;color:var(--muted)}
176
- .section{padding:32px 0}
177
- .map-embed iframe{width:100%;height:320px;border:0;border-radius:12px}
178
- .gallery{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}
179
- .pricing{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
180
- @media (max-width:1024px){.hero-grid{grid-template-columns:1fr}.feature-grid,.testimonial-grid,.blog-grid,.pricing{grid-template-columns:repeat(2,1fr)}}
181
- @media (max-width:640px){.nav-links{display:none}.hamburger{display:block}.feature-grid,.testimonial-grid,.blog-grid,.gallery,.pricing{grid-template-columns:1fr}}
182
- """
183
-
184
-
185
- def esc(t: Any) -> str:
186
- return (str(t) if t is not None else "").replace("<", "&lt;").replace(">", "&gt;")
187
-
188
-
189
- def render_component(c: Dict[str, Any]) -> str:
190
- t = c.get("type")
191
- p = c.get("props", {})
192
- if t == "navbar":
193
- logo = esc(p.get("logo_text", "Brand"))
194
- links = p.get("links", ["Home", "About", "Services", "Contact"]) or []
195
- cta_label = esc(p.get("cta_label", "Get Started"))
196
- cta_href = esc(p.get("cta_href", "#"))
197
- nav_links = "".join([f'<a href="#" aria-label="{esc(l)}">{esc(l)}</a>' for l in links])
198
- return (
199
- f"<nav class='navbar'><div class='container navbar-inner'>"
200
- f"<a href='/' aria-label='Go to homepage' style='font-weight:800'>{logo}</a>"
201
- f"<div class='nav-links'>{nav_links}<a class='btn' href='{cta_href}'>{cta_label}</a></div>"
202
- f"<button aria-label='Open menu' class='hamburger'>☰</button>"
203
- f"</div></nav>"
204
- )
205
- if t == "hero":
206
- h = esc(p.get("headline", "Build websites faster with AI"))
207
- sub = esc(p.get("subheadline", "Drag-and-drop sections, AI copy & images."))
208
- cta = esc(p.get("cta_label", "Start Free"))
209
- cta_href = esc(p.get("cta_href", "#"))
210
- img_src = esc(p.get("image_src", ""))
211
- img_html = f"<img src='{img_src}' alt='Hero image' style='width:100%;border-radius:16px'/>" if img_src else ""
212
- return (
213
- f"<section class='hero'><div class='container hero-grid'>"
214
- f"<div><h1>{h}</h1><p>{sub}</p><a class='btn' href='{cta_href}'>{cta}</a></div>"
215
- f"<div>{img_html}</div></div></section>"
216
- )
217
- if t == "features":
218
- title = esc(p.get("title", "What you get"))
219
- items = p.get("items", [])
220
- cards = []
221
- for it in items[:9]:
222
- cards.append(
223
- f"<div class='card'><div style='font-size:24px'>{esc(it.get('icon','✨'))}</div>"
224
- f"<h3 style='margin:8px 0'>{esc(it.get('title','Feature'))}</h3>"
225
- f"<p style='color:var(--muted)'>{esc(it.get('desc',''))}</p></div>"
226
- )
227
- return f"<section class='features section'><div class='container'><h2>{title}</h2><div class='feature-grid'>{''.join(cards)}</div></div></section>"
228
- if t == "testimonials":
229
- title = esc(p.get("title", "What our customers say"))
230
- items = p.get("items", [])
231
- cards = []
232
- for it in items[:6]:
233
- headshot = esc(it.get("img", ""))
234
- img_html = f"<img src='{headshot}' alt='Headshot of {esc(it.get('name',''))}' style='width:48px;height:48px;border-radius:9999px;object-fit:cover'/>" if headshot else ""
235
- stars = "★" * int(it.get("rating", 5))
236
- cards.append(
237
- f"<div class='card'><div style='display:flex;gap:12px;align-items:center'>{img_html}<div><strong>{esc(it.get('name',''))}</strong><div style='color:var(--muted);font-size:12px'>{esc(it.get('title',''))} · {esc(it.get('company',''))}</div></div></div>"
238
- f"<div style='margin-top:8px;color:#f59e0b'>{stars}</div>"
239
- f"<blockquote style='margin-top:8px'>&ldquo;{esc(it.get('quote',''))}&rdquo;</blockquote></div>"
240
- )
241
- return f"<section class='testimonials section'><div class='container'><h2>{title}</h2><div class='testimonial-grid'>{''.join(cards)}</div></div></section>"
242
- if t == "cta":
243
- title = esc(p.get("title", "Ready to launch?"))
244
- body = esc(p.get("body", "Build a production-grade site in minutes."))
245
- label = esc(p.get("cta_label", "Get Started"))
246
- href = esc(p.get("cta_href", "#"))
247
- return f"<section class='section'><div class='container'><div class='cta'><h3 style='margin:0 0 8px'>{title}</h3><p style='margin:0 0 16px;color:var(--muted)'>{body}</p><a class='btn' href='{href}'>{label}</a></div></div></section>"
248
- if t == "contact":
249
- title = esc(p.get("title", "Contact us"))
250
- subtitle = esc(p.get("subtitle", "We usually respond within a day."))
251
- return (
252
- f"<section class='section'><div class='container'><h2>{title}</h2><p style='color:var(--muted)'>{subtitle}</p>"
253
- f"<form onsubmit=\"event.preventDefault();alert('Thanks! We\'ll be in touch.');\" aria-label='Contact form' class='card' style='display:grid;gap:12px'>"
254
- f"<label>Name<input name='name' required aria-label='Your name' style='width:100%;padding:10px;border:1px solid #e5e7eb;border-radius:8px'/></label>"
255
- f"<label>Email<input type='email' name='email' required aria-label='Your email' style='width:100%;padding:10px;border:1px solid #e5e7eb;border-radius:8px'/></label>"
256
- f"<label>Message<textarea name='message' rows='4' required aria-label='Your message' style='width:100%;padding:10px;border:1px solid #e5e7eb;border-radius:8px'></textarea></label>"
257
- f"<button class='btn' type='submit'>Submit</button></form></div></section>"
258
- )
259
- if t == "blog_cards":
260
- title = esc(p.get("title", "Latest articles"))
261
- items = p.get("items", [])
262
- cards = []
263
- for it in items[:6]:
264
- img = esc(it.get("img", ""))
265
- img_html = f"<img src='{img}' alt='' style='width:100%;height:160px;object-fit:cover;border-radius:12px'/>" if img else ""
266
- cards.append(
267
- f"<article class='card'>{img_html}<h3 style='margin:8px 0'>{esc(it.get('title','Article'))}</h3>"
268
- f"<div style='color:var(--muted);font-size:12px'>{esc(it.get('date',''))}</div>"
269
- f"<p style='color:var(--muted)'>{esc(it.get('excerpt',''))}</p></article>"
270
- )
271
- return f"<section class='section'><div class='container'><h2>{title}</h2><div class='blog-grid'>{''.join(cards)}</div></div></section>"
272
- if t == "team":
273
- title = esc(p.get("title", "Meet the team"))
274
- items = p.get("items", [])
275
- cards = []
276
- for it in items[:8]:
277
- img = esc(it.get("img", ""))
278
- img_html = f"<img src='{img}' alt='Headshot of {esc(it.get('name',''))}' style='width:100%;height:220px;object-fit:cover;border-radius:12px'/>" if img else ""
279
- cards.append(
280
- f"<div class='card'>{img_html}<h3 style='margin:8px 0'>{esc(it.get('name',''))}</h3><div style='color:var(--muted)'>{esc(it.get('role',''))}</div><p style='color:var(--muted)'>{esc(it.get('bio',''))}</p></div>"
281
- )
282
- return f"<section class='section'><div class='container'><h2>{title}</h2><div class='feature-grid'>{''.join(cards)}</div></div></section>"
283
- if t == "faq":
284
- title = esc(p.get("title", "Frequently asked questions"))
285
- items = p.get("items", [])
286
- qa = []
287
- for it in items[:10]:
288
- qa.append(
289
- f"<details class='card'><summary><strong>{esc(it.get('q','Question'))}</strong></summary><div style='margin-top:8px;color:var(--muted)'>{esc(it.get('a','Answer'))}</div></details>"
290
- )
291
- return f"<section class='section'><div class='container'><h2>{title}</h2><div class='grid'>{''.join(qa)}</div></div></section>"
292
- if t == "map":
293
- title = esc(p.get("title", "Our location"))
294
- iframe = esc(p.get("iframe", ""))
295
- iframe_html = iframe if "<iframe" in iframe else "<div class='card'>Add a Google Maps embed iframe in settings</div>"
296
- return f"<section class='section map-embed'><div class='container'><h2>{title}</h2>{iframe_html}</div></section>"
297
- if t == "portfolio":
298
- title = esc(p.get("title", "Case studies"))
299
- items = p.get("items", [])
300
- cards = []
301
- for it in items[:6]:
302
- img = esc(it.get("img", ""))
303
- img_html = f"<img src='{img}' alt='' style='width:100%;height:160px;object-fit:cover;border-radius:12px'/>" if img else ""
304
- cards.append(
305
- f"<article class='card'>{img_html}<h3 style='margin:8px 0'>{esc(it.get('title','Project'))}</h3><p style='color:var(--muted)'>{esc(it.get('summary',''))}</p><a class='btn secondary' href='{esc(it.get('href','#'))}'>Read Case Study</a></article>"
306
- )
307
- return f"<section class='section'><div class='container'><h2>{title}</h2><div class='blog-grid'>{''.join(cards)}</div></div></section>"
308
- if t == "pricing":
309
- title = esc(p.get("title", "Pricing"))
310
- plans = p.get("plans", [])
311
- cards = []
312
- for pl in plans[:3]:
313
- features = "".join([f"<li>✓ {esc(f)}</li>" for f in pl.get("features", [])])
314
- cards.append(
315
- f"<div class='card'><h3 style='margin:8px 0'>{esc(pl.get('name','Plan'))}</h3><div style='font-size:28px;font-weight:800'>{esc(pl.get('price','$9'))}</div>"
316
- f"<ul style='color:var(--muted);padding-left:20px'>{features}</ul><a class='btn' href='{esc(pl.get('href','#'))}'>Choose</a></div>"
317
- )
318
- return f"<section class='section'><div class='container'><h2>{title}</h2><div class='pricing'>{''.join(cards)}</div></div></section>"
319
- if t == "logos":
320
- title = esc(p.get("title", "Trusted by great teams"))
321
- items = p.get("items", [])
322
- logos = []
323
- for it in items[:8]:
324
- img = esc(it.get("img", ""))
325
- alt = esc(it.get("alt", "Client logo"))
326
- if img:
327
- logos.append(f"<img src='{img}' alt='{alt}' style='max-height:40px;object-fit:contain'/>")
328
- return f"<section class='section'><div class='container'><h2>{title}</h2><div class='gallery'>{''.join(logos)}</div></div></section>"
329
- if t == "gallery":
330
- title = esc(p.get("title", "Gallery"))
331
- imgs = p.get("imgs", [])
332
- grid = []
333
- for src in imgs[:12]:
334
- src = esc(src)
335
- grid.append(f"<img src='{src}' alt='' style='width:100%;height:160px;object-fit:cover;border-radius:12px' />")
336
- return f"<section class='section'><div class='container'><h2>{title}</h2><div class='gallery'>{''.join(grid)}</div></div></section>"
337
- if t == "footer":
338
- about = esc(p.get("about", "We build things with care."))
339
- links = p.get("links", ["Home", "About", "Contact"]) or []
340
- contact = p.get("contact", {"email": "hello@example.com"})
341
- social = p.get("social", [])
342
- links_html = "".join([f"<a href='#' style='margin-right:12px'>{esc(l)}</a>" for l in links])
343
- social_html = "".join([f"<a href='{esc(s.get('href','#'))}' aria-label='{esc(s.get('label',''))}' style='margin-right:8px'>{esc(s.get('label',''))}</a>" for s in social])
344
- year = datetime.now().year
345
- return (
346
- f"<footer class='footer'><div class='container' style='display:grid;gap:16px'>"
347
- f"<div>{about}</div><div>{links_html}</div><div>{esc(contact.get('email',''))}</div>"
348
- f"<div>{social_html}</div><div>© {year} Your Company</div></div></footer>"
349
- )
350
- if t == "newsletter":
351
- title = esc(p.get("title", "Stay in the loop"))
352
- return (
353
- f"<section class='section'><div class='container card'><h3 style='margin:0 0 8px'>{title}</h3>"
354
- f"<form onsubmit=\"event.preventDefault();alert('Subscribed!');\" style='display:flex;gap:8px;flex-wrap:wrap'>"
355
- f"<input aria-label='Your email' type='email' required placeholder='you@company.com' style='flex:1;min-width:240px;padding:10px;border:1px solid #e5e7eb;border-radius:8px'/>"
356
- f"<button class='btn' type='submit'>Subscribe</button></form></div></section>"
357
- )
358
  return ""
359
 
360
 
361
- def render_page(page: Dict[str, Any]) -> str:
362
- html = ["<style>" + BASE_CSS + "</style>"]
363
- # header
364
- for c in page.get("header", []):
365
- html.append(render_component(c))
366
- # body subsections
367
- for sub in page.get("body", {}).get("subsections", []):
368
- cols = sub.get("columns", [])
369
- # columns container
370
- html.append("<section class='section'><div class='container'>")
371
- if sub.get("name"):
372
- html.append(f"<h2 style='margin-top:0'>{esc(sub.get('name'))}</h2>")
373
- html.append("<div class='grid' style='grid-template-columns:" + " ".join([f"{col.get('width',100)}%" for col in cols]).replace(" ", " ") + ";gap:16px'>")
374
- for col in cols:
375
- html.append("<div>")
376
- for comp in col.get("components", []):
377
- html.append(render_component(comp))
378
- html.append("</div>")
379
- html.append("</div></div></section>")
380
- # footer
381
- for c in page.get("footer", []):
382
- html.append(render_component(c))
383
- return "".join(html)
384
-
385
- # -----------------------------
386
- # Mutations
387
- # -----------------------------
388
-
389
- import uuid
390
-
391
- def add_subsection(state_json: str, name: str, columns: int, widths_csv: str):
392
- page = json.loads(state_json) if state_json else json.loads(json.dumps(DEFAULT_PAGE))
393
- columns = max(1, min(4, int(columns)))
394
- widths = []
395
- try:
396
- widths = [float(x.strip()) for x in widths_csv.split(',') if x.strip()]
397
- except Exception:
398
- widths = []
399
- if len(widths) != columns:
400
- widths = [round(100/columns, 3)] * columns
401
- subsection = {"id": f"sub-{uuid.uuid4().hex[:6]}", "name": name or "Section", "columns": [{"width": widths[i], "components": []} for i in range(columns)]}
402
- page.setdefault("body", {}).setdefault("subsections", []).append(subsection)
403
- return json.dumps(page, indent=2), gr.update(choices=[s["id"] for s in page["body"]["subsections"]], value=subsection["id"]), render_page(page)
404
-
405
-
406
- def add_component(state_json: str, section: str, component_type: str, props_json: str, target_sub_id: str, target_col_idx: int):
407
- page = json.loads(state_json) if state_json else json.loads(json.dumps(DEFAULT_PAGE))
408
- try:
409
- props = json.loads(props_json) if props_json.strip() else {}
410
- except Exception as e:
411
- props = {"_error": f"Invalid JSON props: {e}"}
412
- comp = build_component(component_type, props)
413
- if section == "header":
414
- page.setdefault("header", []).append(comp)
415
- elif section == "footer":
416
- page.setdefault("footer", []).append(comp)
417
- else: # body
418
- subs = page.setdefault("body", {}).setdefault("subsections", [])
419
- if not subs:
420
- # create default one-col subsection if absent
421
- page, _, _ = add_subsection(json.dumps(page), "Main", 1, "100")
422
- page = json.loads(page)
423
- subs = page["body"]["subsections"]
424
- # find target subsection
425
- sub = next((s for s in subs if s["id"] == target_sub_id), subs[-1])
426
- cols = sub.get("columns", [])
427
- if not cols:
428
- sub["columns"] = [{"width": 100, "components": []}]
429
- cols = sub["columns"]
430
- idx = max(0, min(len(cols)-1, int(target_col_idx)))
431
- cols[idx].setdefault("components", []).append(comp)
432
- return json.dumps(page, indent=2), render_page(page)
433
-
434
-
435
- def remove_last(state_json: str, section: str, target_sub_id: str, target_col_idx: int):
436
- page = json.loads(state_json) if state_json else json.loads(json.dumps(DEFAULT_PAGE))
437
- if section == "header":
438
- if page.get("header"): page["header"].pop()
439
- elif section == "footer":
440
- if page.get("footer"): page["footer"].pop()
441
- else:
442
- subs = page.get("body", {}).get("subsections", [])
443
- if subs:
444
- sub = next((s for s in subs if s["id"] == target_sub_id), subs[-1])
445
- cols = sub.get("columns", [])
446
- if cols:
447
- idx = max(0, min(len(cols)-1, int(target_col_idx)))
448
- if cols[idx].get("components"): cols[idx]["components"].pop()
449
- return json.dumps(page, indent=2), render_page(page)
450
-
451
-
452
- def reset_page():
453
- return json.dumps(DEFAULT_PAGE, indent=2), render_page(DEFAULT_PAGE)
454
-
455
- # -----------------------------
456
- # Exporter
457
- # -----------------------------
458
-
459
- def export_zip(state_json: str):
460
- page = json.loads(state_json) if state_json else DEFAULT_PAGE
461
- html = render_page(page)
462
- base_html = f"""<!doctype html>
463
- <html lang=\"en\"><head><meta charset=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>
464
- <title>AI Site</title>
465
- </head><body>{html}</body></html>"""
466
- b = io.BytesIO()
467
- with zipfile.ZipFile(b, 'w', zipfile.ZIP_DEFLATED) as z:
468
- z.writestr('index.html', base_html)
469
- # assets could be added here if needed
470
- b.seek(0)
471
- return b, "website.zip"
472
-
473
- # -----------------------------
474
  # Gradio UI
475
- # -----------------------------
476
-
477
- with gr.Blocks(css="footer{display:none}") as demo:
478
- gr.Markdown("# 🧱 AI Website Builder — Drag & Drop (Hugging Face Space)\nDesign responsive, accessible marketing pages. Use AI to generate copy & images.")
479
- state = gr.State(json.dumps(DEFAULT_PAGE, indent=2))
480
-
481
- with gr.Tabs():
482
- # ------------------- Components Tab -------------------
483
- with gr.Tab("Components"):
484
  with gr.Row():
485
- with gr.Column(scale=1):
486
- gr.Markdown("### Sections")
487
- section = gr.Radio(["header", "body", "footer"], label="Select section", value="body")
488
-
489
- gr.Markdown("#### Body subsections")
490
- sub_name = gr.Textbox(label="Subsection name", value="Main Section")
491
- sub_cols = gr.Slider(1, 4, step=1, value=2, label="Columns")
492
- sub_widths = gr.Textbox(label="Column widths (%, CSV)", value="50,50", info="If blank or invalid, equal widths are used.")
493
- add_sub_btn = gr.Button("➕ Add subsection")
494
- current_sub_choices = gr.Dropdown(choices=[], label="Target subsection for new components")
495
-
496
- add_sub_btn.click(add_subsection, [state, sub_name, sub_cols, sub_widths], [state, current_sub_choices,])
497
-
498
- gr.Markdown("### Add component")
499
- comp_section = gr.Dropdown(["header", "body", "footer"], value="body", label="Component section")
500
- comp_type = gr.Dropdown(choices=[c["value"] for c in COMPONENTS_CATALOG["body"]], label="Component type")
501
-
502
- def update_comp_choices(sec):
503
- return gr.update(choices=[c["value"] for c in COMPONENTS_CATALOG[sec]], value=(COMPONENTS_CATALOG[sec][0]["value"]))
504
-
505
- comp_section.change(update_comp_choices, comp_section, comp_type)
506
-
507
- props = gr.Code(label="Component props (JSON)", language="json", value=json.dumps({
508
- "headline": "Grow faster with AI",
509
- "subheadline": "Launch a site in minutes.",
510
- "cta_label": "Start Free",
511
- "cta_href": "#"
512
- }, indent=2))
513
-
514
- target_sub = current_sub_choices
515
- target_col = gr.Slider(0, 3, step=1, value=0, label="Target column index")
516
-
517
- add_btn = gr.Button("Add component to page")
518
- remove_btn = gr.Button("Undo: remove last in target")
519
-
520
- with gr.Column(scale=1):
521
- gr.Markdown("### AI Tools")
522
- with gr.Tab("AI Text"):
523
- t_prompt = gr.Textbox(label="Prompt", value="Write a compelling hero headline for an AI website builder")
524
- t_tone = gr.Dropdown(["neutral","friendly","professional","bold","playful"], value="friendly", label="Tone")
525
- t_words = gr.Slider(20, 200, value=40, step=5, label="Approx. words")
526
- t_btn = gr.Button("Generate text")
527
- t_out = gr.Textbox(label="AI output")
528
- t_btn.click(lambda p, tone, n: ai_generate_text(p, tone, int(n)), [t_prompt, t_tone, t_words], t_out)
529
-
530
- with gr.Tab("AI Image"):
531
- i_prompt = gr.Textbox(label="Prompt", value="Minimal hero illustration of marketers building a website, soft gradients")
532
- i_w = gr.Slider(512, 1280, step=64, value=1024, label="Width")
533
- i_h = gr.Slider(320, 1024, step=32, value=576, label="Height")
534
- i_btn = gr.Button("Generate image")
535
- i_img = gr.Image(label="Result", type="pil")
536
- i_btn.click(lambda p,w,h: ai_generate_image(p, int(w), int(h)), [i_prompt, i_w, i_h], i_img)
537
-
538
- gr.Markdown("### Page JSON")
539
- page_json = gr.Code(label="Page schema", language="json")
540
- reset = gr.Button("Reset page")
541
-
542
  with gr.Row():
543
- with gr.Column(scale=2):
544
- preview_html = gr.HTML(render_page(DEFAULT_PAGE))
545
- with gr.Column(scale=1):
546
- gr.Markdown("### Export")
547
- dl_btn = gr.Button("📦 Export .zip")
548
- dl_file = gr.File()
549
-
550
- # Wire up add/remove
551
- add_btn.click(add_component, [state, comp_section, comp_type, props, target_sub, target_col], [state, preview_html])
552
- remove_btn.click(remove_last, [state, comp_section, target_sub, target_col], [state, preview_html])
553
- reset.click(lambda: reset_page(), None, [state, preview_html])
554
- # reflect state JSON in editor
555
- def reflect_state(s):
556
- return s
557
- state.change(reflect_state, state, page_json)
558
- # export
559
- dl_btn.click(export_zip, [state], dl_file)
560
-
561
- # ------------------- Preview Tab -------------------
562
- with gr.Tab("Preview"):
563
- live_html = gr.HTML(render_page(DEFAULT_PAGE))
564
- def sync_preview(s):
565
- return render_page(json.loads(s))
566
- state.change(sync_preview, state, live_html)
567
-
568
- # ------------------- Mobile Views Tab -------------------
569
- with gr.Tab("Mobile Views"):
570
- m_phone = gr.HTML("<div style='max-width:380px;margin:0 auto;border:12px solid #111;border-radius:32px;overflow:auto;height:700px'>" + render_page(DEFAULT_PAGE) + "</div>")
571
- m_tablet = gr.HTML("<div style='max-width:820px;margin:24px auto;border:12px solid #111;border-radius:24px;overflow:auto;height:700px'>" + render_page(DEFAULT_PAGE) + "</div>")
572
- m_laptop = gr.HTML("<div style='max-width:1060px;margin:24px auto;border:12px solid #111;border-radius:16px;overflow:auto;height:700px'>" + render_page(DEFAULT_PAGE) + "</div>")
573
-
574
- def sync_mobile(s):
575
- html = render_page(json.loads(s))
576
- wrap = lambda w: f"<div style='max-width:{w}px;margin:0 auto;border:12px solid #111;border-radius:24px;overflow:auto;height:700px'>{html}</div>"
577
- return wrap(380), wrap(820), wrap(1060)
578
-
579
- state.change(sync_mobile, state, [m_phone, m_tablet, m_laptop])
580
-
581
- # -----------------------------
582
- # Launch
583
- # -----------------------------
584
- if __name__ == "__main__":
585
- demo.launch()
 
1
  import gradio as gr
 
 
 
 
 
2
  from PIL import Image, ImageDraw, ImageFont
3
+ import io, base64
4
+
5
+ # ----------------------------
6
+ # State
7
+ # ----------------------------
8
+ SECTIONS = {"Header": [], "Body": [], "Footer": []}
9
+
10
+ # ----------------------------
11
+ # Utils
12
+ # ----------------------------
13
+ def render_component_html(comp):
14
+ ctype = comp["type"]
15
+ if ctype == "Navbar":
16
+ tabs_html = "".join([f'<a href="{u}">{n}</a>' for n, u in zip(comp["tabs"], comp["urls"])])
17
+ logo_html = f'<img src="{comp["logo"]}" style="height:{comp["logo_size"]}px; float:{comp["logo_align"]};">' if comp["logo"] else ""
18
+ return f"<nav style='position:sticky;top:0;'>{logo_html}{tabs_html}<button>{comp['cta']}</button></nav>"
19
+ elif ctype == "Hero":
20
+ img_html = f"<img src='{comp['image']}' style='width:100%;'>" if comp['image'] else ""
21
+ return f"<section style='text-align:center;'><h1 style='font-size:{comp['font_size']}px;color:{comp['font_color']};position:{comp['position']};'>{comp['desc']}</h1>{img_html}<button>{comp['cta']}</button></section>"
22
+ elif ctype == "Generic":
23
+ cols_html = "".join([f"<div style='flex:{w};font-size:{comp['font_size']}px;color:{comp['font_color']};text-align:{comp['align']};'>{c}</div>" for c, w in zip(comp["cols"], comp["widths"])])
24
+ return f"<section style='display:flex;'>{cols_html}</section>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  return ""
26
 
27
 
28
+ def render_page():
29
+ html = ""
30
+ for sec in ["Header", "Body", "Footer"]:
31
+ for comp in SECTIONS[sec]:
32
+ html += render_component_html(comp)
33
+ return f"<html><body>{html}</body></html>"
34
+
35
+ # ----------------------------
36
+ # Add component logic
37
+ # ----------------------------
38
+ def add_navbar(tabs, urls, cta, logo, logo_align, logo_size, logo_place):
39
+ comp = {"type":"Navbar", "tabs":tabs, "urls":urls, "cta":cta, "logo":logo, "logo_align":logo_align, "logo_size":logo_size, "logo_place":logo_place}
40
+ SECTIONS["Header"].append(comp)
41
+ return render_page()
42
+
43
+ def add_hero(desc, image, cta, position, font_color, font_size):
44
+ comp = {"type":"Hero", "desc":desc, "image":image, "cta":cta, "position":position, "font_color":font_color, "font_size":font_size}
45
+ SECTIONS["Header"].append(comp)
46
+ return render_page()
47
+
48
+ def add_generic(section, cols, widths, font_color, font_size, align):
49
+ comp = {"type":"Generic", "cols":cols, "widths":widths, "font_color":font_color, "font_size":font_size, "align":align}
50
+ SECTIONS[section].append(comp)
51
+ return render_page()
52
+
53
+ # ----------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  # Gradio UI
55
+ # ----------------------------
56
+ with gr.Blocks() as demo:
57
+ with gr.Tab("Components"):
58
+ with gr.Accordion("Header"):
 
 
 
 
 
59
  with gr.Row():
60
+ nav_tabs = gr.Textbox(label="Nav Tabs (comma)")
61
+ nav_urls = gr.Textbox(label="Nav URLs (comma)")
62
+ nav_cta = gr.Textbox(label="CTA Text")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  with gr.Row():
64
+ nav_logo = gr.Textbox(label="Logo URL")
65
+ nav_logo_align = gr.Dropdown(["left","center","right"], label="Logo Alignment")
66
+ nav_logo_size = gr.Number(label="Logo Size px", value=40)
67
+ nav_logo_place = gr.Dropdown(["above","inside"], label="Logo Placement")
68
+ nav_btn = gr.Button("Add Navbar")
69
+
70
+ hero_desc = gr.Textbox(label="Hero Description")
71
+ hero_image = gr.Textbox(label="Hero Image URL")
72
+ hero_cta = gr.Textbox(label="Hero CTA")
73
+ hero_position = gr.Dropdown(["top","center","bottom","top left","top right","center left","center right","center bottom"], label="Text Position", value="center")
74
+ hero_font_color = gr.ColorPicker(label="Font Color", value="#000000")
75
+ hero_font_size = gr.Number(label="Font Size", value=20)
76
+ hero_btn = gr.Button("Add Hero")
77
+
78
+ with gr.Accordion("Body"):
79
+ gr.Markdown("It is recommended to have Nav Bar ✖️")
80
+ body_cols = gr.Textbox(label="Columns Content (comma)")
81
+ body_widths = gr.Textbox(label="Widths (comma)", value="1")
82
+ body_font_color = gr.ColorPicker(label="Font Color", value="#000000")
83
+ body_font_size = gr.Number(label="Font Size", value=12)
84
+ body_align = gr.Dropdown(["left","center","right"], label="Align")
85
+ body_btn = gr.Button("Add Body Component")
86
+
87
+ with gr.Accordion("Footer"):
88
+ footer_cols = gr.Textbox(label="Columns Content (comma)")
89
+ footer_widths = gr.Textbox(label="Widths (comma)", value="1")
90
+ footer_font_color = gr.ColorPicker(label="Font Color", value="#000000")
91
+ footer_font_size = gr.Number(label="Font Size", value=12)
92
+ footer_align = gr.Dropdown(["left","center","right"], label="Align")
93
+ footer_btn = gr.Button("Add Footer Component")
94
+
95
+ with gr.Tab("Preview"):
96
+ preview_html = gr.HTML()
97
+
98
+ nav_btn.click(add_navbar, [nav_tabs, nav_urls, nav_cta, nav_logo, nav_logo_align, nav_logo_size, nav_logo_place], preview_html)
99
+ hero_btn.click(add_hero, [hero_desc, hero_image, hero_cta, hero_position, hero_font_color, hero_font_size], preview_html)
100
+ body_btn.click(lambda c,w,fc,fs,a: add_generic("Body", c.split(","), w.split(","), fc, fs, a), [body_cols, body_widths, body_font_color, body_font_size, body_align], preview_html)
101
+ footer_btn.click(lambda c,w,fc,fs,a: add_generic("Footer", c.split(","), w.split(","), fc, fs, a), [footer_cols, footer_widths, footer_font_color, footer_font_size, footer_align], preview_html)
102
+
103
+ demo.launch()