""" VectorForge ⚡ - Pro Max UI/UX Edition AI 2D Character Super-Resolution & Mathematical Vectorization Engine Designed with UI/UX Pro Max Intelligence: Tech Startup Typography, Dark Glassmorphism, Micro-Interactions """ import os import base64 from pathlib import Path import urllib.request import time from PIL import Image import gradio as gr # Ensure models exist BASE_DIR = Path(__file__).resolve().parent MODELS_DIR = BASE_DIR / "models" MODELS_DIR.mkdir(parents=True, exist_ok=True) MODEL_URLS = { MODELS_DIR / "waifu2x_art_scale2x.onnx": "https://huggingface.co/deepghs/waifu2x_onnx/resolve/main/20230131/onnx_models/cunet/art/scale2x.onnx", MODELS_DIR / "waifu2x_art_noise1_scale2x.onnx": "https://huggingface.co/deepghs/waifu2x_onnx/resolve/main/20230131/onnx_models/cunet/art/noise1_scale2x.onnx" } for path, url in MODEL_URLS.items(): if not path.exists(): print(f"Downloading {path.name}...") urllib.request.urlretrieve(url, path) from engine.upscaler import AI2DUpscaler from engine.vectorizer import Vectorizer upscaler = AI2DUpscaler(models_dir=MODELS_DIR) STORAGE_DIR = BASE_DIR / "storage" STORAGE_DIR.mkdir(exist_ok=True) # Safe ZeroGPU decorator support try: import spaces gpu_decorator = spaces.GPU except (ImportError, Exception): def gpu_decorator(fn): return fn def image_to_base64_data_uri(img: Image.Image) -> str: import io buffered = io.BytesIO() img.save(buffered, format="PNG") b64 = base64.b64encode(buffered.getvalue()).decode("utf-8") return f"data:image/png;base64,{b64}" @gpu_decorator def process_pipeline(input_img, mode, preset, scale, denoise): if input_img is None: empty_html = """
🎨

No Image Uploaded

Select an example below or upload a 2D character/icon to begin.

""" return None, None, None, empty_html, "", "Upload an image to start." t0 = time.time() timestamp = int(time.time() * 1000) # Save input temp temp_in = STORAGE_DIR / f"temp_{timestamp}.png" if isinstance(input_img, Image.Image): pil_in = input_img.convert("RGBA") else: pil_in = Image.fromarray(input_img).convert("RGBA") pil_in.save(temp_in, format="PNG") orig_w, orig_h = pil_in.size in_b64 = image_to_base64_data_uri(pil_in) out_png_path = None out_svg_path = None enhanced_pil = None preset_map = { "2D Character / Anime": "character", "Flat Color / Icon": "flat_icon", "Detailed Lineart": "detailed_lineart", "Monochrome / Ink": "monochrome", } v_preset = preset_map.get(preset, "character") scale_factor = int(scale.replace("x", "")) # Step 1: AI Super-Resolution (if selected) if "AI" in mode or "Hybrid" in mode: out_png_path = STORAGE_DIR / f"enhanced_{timestamp}.png" upscaler.upscale_file(temp_in, out_png_path, scale=scale_factor, denoise=denoise) enhanced_pil = Image.open(out_png_path) enhanced_w, enhanced_h = enhanced_pil.size else: enhanced_w, enhanced_h = orig_w, orig_h # Step 2: Vectorization (if selected) svg_code = "" if "Vector" in mode or "Hybrid" in mode: out_svg_path = STORAGE_DIR / f"vector_{timestamp}.svg" source_for_vector = out_png_path if (out_png_path and "Hybrid" in mode) else temp_in Vectorizer.vectorize_file(source_for_vector, out_svg_path, preset=v_preset) svg_code = out_svg_path.read_text(encoding="utf-8") elapsed = round(time.time() - t0, 2) after_b64 = image_to_base64_data_uri(enhanced_pil if enhanced_pil else pil_in) # UI/UX Pro Max Interactive Comparison Slider HTML Component slider_html = f"""
Enhanced Result
Original Low-Res
❮ ❯
ORIGINAL ({orig_w}×{orig_h}) ENHANCED 4× ({enhanced_w}×{enhanced_h})
""" # UI/UX Pro Max Metric Cards HTML svg_size_kb = round(out_svg_path.stat().st_size / 1024, 1) if out_svg_path else 0 png_size_kb = round(out_png_path.stat().st_size / 1024, 1) if out_png_path else 0 pixel_increase = round(((enhanced_w * enhanced_h) / (orig_w * orig_h) - 1) * 100) if (orig_w * orig_h) else 0 metrics_html = f"""
Resolution Boost {orig_w}×{orig_h} → {enhanced_w}×{enhanced_h} +{pixel_increase}% total pixel clarity
Inference Latency {elapsed}s ZeroGPU & CUNet acceleration
Scalable Vector {svg_size_kb} KB SVG Mathematical Bezier splines
Raster Master {png_size_kb} KB PNG Artifacts & noise removed
""" return ( enhanced_pil if enhanced_pil else pil_in, str(out_png_path) if out_png_path else None, str(out_svg_path) if out_svg_path else None, slider_html, svg_code, metrics_html ) # UI/UX Pro Max Custom CSS & Theme Styling CUSTOM_CSS = """ @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&family=JetBrains+Mono:wght@400;500;700&family=Space+Grotesk:wght@500;600;700&display=swap'); :root { --bg-obsidian: #090d16; --card-surface: rgba(17, 24, 39, 0.75); --border-glass: rgba(255, 255, 255, 0.08); --accent-indigo: #6366f1; --accent-emerald: #10b981; --accent-pink: #ec4899; } body, .gradio-container { background-color: var(--bg-obsidian) !important; font-family: 'DM Sans', -apple-system, sans-serif !important; color: #f1f5f9 !important; } h1, h2, h3, .pro-title { font-family: 'Space Grotesk', sans-serif !important; letter-spacing: -0.02em !important; } /* Glassmorphism Cards */ .glass-panel { background: var(--card-surface) !important; backdrop-filter: blur(16px) !important; -webkit-backdrop-filter: blur(16px) !important; border: 1px solid var(--border-glass) !important; border-radius: 16px !important; padding: 20px !important; box-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.5) !important; } /* Hero Badge */ .hero-badge { display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; border-radius: 9999px; background: rgba(99, 102, 241, 0.12); border: 1px solid rgba(99, 102, 241, 0.3); color: #a5b4fc; font-size: 12px; font-weight: 600; margin-bottom: 8px; } /* Interactive Split Comparison Slider */ .pro-slider-wrapper { width: 100%; margin: 8px 0; } .pro-slider-container { position: relative; width: 100%; height: 420px; border-radius: 14px; overflow: hidden; cursor: ew-resize; user-select: none; border: 1px solid rgba(255, 255, 255, 0.12); background-color: #0f172a; background-image: linear-gradient(45deg, #1e293b 25%, transparent 25%), linear-gradient(-45deg, #1e293b 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #1e293b 75%), linear-gradient(-45deg, transparent 75%, #1e293b 75%); background-size: 16px 16px; background-position: 0 0, 0 8px, 8px -8px, -8px 0px; } .slider-img-after { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: contain; pointer-events: none; } .slider-before-mask { position: absolute; top: 0; left: 0; width: 50%; height: 100%; overflow: hidden; border-right: 2px solid var(--accent-indigo); pointer-events: none; } .slider-img-before { position: absolute; top: 0; left: 0; height: 100%; object-fit: contain; pointer-events: none; } .slider-divider { position: absolute; top: 0; bottom: 0; left: 50%; width: 2px; background: var(--accent-indigo); pointer-events: none; box-shadow: 0 0 12px rgba(99, 102, 241, 0.8); } .slider-pill { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 38px; height: 38px; border-radius: 50%; background: #4f46e5; color: white; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; box-shadow: 0 4px 16px rgba(79, 70, 229, 0.5); } .badge-tag { position: absolute; bottom: 12px; font-family: 'JetBrains Mono', monospace; font-size: 10px; font-weight: 600; padding: 4px 8px; border-radius: 6px; backdrop-filter: blur(8px); pointer-events: none; z-index: 5; } .tag-left { left: 12px; background: rgba(15, 23, 42, 0.85); border: 1px solid rgba(255, 255, 255, 0.15); color: #94a3b8; } .tag-right { right: 12px; background: rgba(49, 46, 129, 0.85); border: 1px solid rgba(129, 140, 248, 0.3); color: #c7d2fe; } /* Empty Placeholder */ .empty-placeholder { height: 380px; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; border: 2px dashed rgba(255, 255, 255, 0.1); border-radius: 14px; color: #64748b; } .placeholder-icon { font-size: 40px; margin-bottom: 12px; } /* Metrics Grid */ .metrics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 10px; margin-top: 14px; } .metric-card { background: rgba(15, 23, 42, 0.6); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 10px; padding: 10px 14px; display: flex; flex-direction: column; } .metric-label { font-size: 10px; text-transform: uppercase; font-weight: 700; color: #64748b; letter-spacing: 0.05em; } .metric-value { font-family: 'JetBrains Mono', monospace; font-size: 14px; font-weight: 700; color: #f8fafc; margin: 3px 0; } .metric-sub { font-size: 10px; color: #94a3b8; } .accent-indigo { color: #818cf8 !important; } .accent-emerald { color: #34d399 !important; } .accent-pink { color: #f472b6 !important; } /* Enhanced Button */ .primary-btn { background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%) !important; border: none !important; color: white !important; font-weight: 600 !important; box-shadow: 0 4px 14px rgba(79, 70, 229, 0.4) !important; transition: all 0.2s ease !important; } .primary-btn:hover { box-shadow: 0 6px 20px rgba(79, 70, 229, 0.6) !important; transform: translateY(-1px) !important; } """ with gr.Blocks( title="VectorForge ⚡ | AI 2D Character Super-Resolution & Vectorization", css=CUSTOM_CSS, theme=gr.themes.Base( primary_hue="indigo", neutral_hue="slate", font=[gr.themes.GoogleFont("DM Sans"), "sans-serif"] ) ) as demo: with gr.Row(): gr.HTML( """
⚡ ZeroGPU Powered · Rust Vector Core

VectorForge

Transform low-resolution 2D character art, stickers, and icons into crisp 4× PNGs and infinitely-scalable mathematical SVG vectors.

""" ) with gr.Row(): # Left: Controls & Upload with gr.Column(scale=5, elem_classes=["glass-panel"]): gr.Markdown("### 📥 Source Character Artwork") input_image = gr.Image( type="pil", label="Drop PNG / JPG with transparent or solid background", elem_id="source-image-input" ) # Interactive 1-click preset examples sample_avatar = str(BASE_DIR / "examples" / "mascot_avatar.png") sample_badge = str(BASE_DIR / "examples" / "game_badge.png") gr.Markdown("#### ⚡ Quick Try (1-Click Sample)") gr.Examples( examples=[ [sample_avatar, "Hybrid (AI Clean + SVG Vector)", "2D Character / Anime", "4x", True], [sample_badge, "Hybrid (AI Clean + SVG Vector)", "Flat Color / Icon", "4x", True], ], inputs=[input_image], label="Load Sample Characters" ) gr.Markdown("### ⚙️ Enhancement Controls") mode_radio = gr.Radio( choices=[ "Hybrid (AI Clean + SVG Vector)", "AI 4x (Crisp PNG)", "Direct Vectorize (SVG)" ], value="Hybrid (AI Clean + SVG Vector)", label="Processing Mode", info="Hybrid cleans pixel noise with neural CUNet then fits mathematical SVG bezier curves" ) with gr.Row(): preset_dropdown = gr.Dropdown( choices=["2D Character / Anime", "Flat Color / Icon", "Detailed Lineart", "Monochrome / Ink"], value="2D Character / Anime", label="Art Preset" ) scale_dropdown = gr.Dropdown( choices=["4x", "2x"], value="4x", label="Scale Multiplier" ) denoise_check = gr.Checkbox( value=True, label="Denoise Compression Artifacts", info="Cleans JPEG ringing and rough line edges" ) process_btn = gr.Button( "✨ Enhance & Vectorize", variant="primary", size="lg", elem_classes=["primary-btn"] ) # Right: Interactive Results & Telemetry with gr.Column(scale=7, elem_classes=["glass-panel"]): gr.Markdown("### 🔬 Live Inspection & Exports") # Real-time Metrics Card Bar metrics_display = gr.HTML( """
EngineReady
HardwareZeroGPU
ModeHybrid
""" ) # Output Tabs with gr.Tabs(): with gr.TabItem("↔️ Split Comparison Slider"): slider_output = gr.HTML( """
🎨

Awaiting Image

Upload a 2D character or click an example on the left to see the split slider comparison.

""" ) with gr.TabItem("🖼️ High-Res Preview"): preview_output = gr.Image(type="pil", label="High-Resolution 4x Output", interactive=False) with gr.TabItem("📄 SVG Code Inspector"): svg_code_output = gr.Code(label="Scalable Vector Graphic (SVG XML Code)", language="html") # One-Click Downloads with gr.Row(): download_svg = gr.File(label="Download Scalable Vector (.SVG)") download_png = gr.File(label="Download High-Res (.PNG)") # Event binding process_btn.click( fn=process_pipeline, inputs=[input_image, mode_radio, preset_dropdown, scale_dropdown, denoise_check], outputs=[preview_output, download_png, download_svg, slider_output, svg_code_output, metrics_display] ) if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)