CoolFace
Apppublic

GitDiff/SceneYou-Free-AI-Generator

sourceHugging Faceapache-2.0updated 9mo agoView on Hugging Face
0likes
app.py246 linesDownload Raw Back to root
1import gradio as gr2import spaces3import torch4from diffusers import AutoPipelineForImage2Image5from PIL import Image, ImageDraw, ImageFont6import gc7 8# --- 1. 基础配置 ---9MODEL_ID = "Tongyi-MAI/Z-Image-Turbo"10PRODUCT_URL = "https://sceneyou.art"11WATERMARK_TEXT = "Created with SceneYou.art"12TARGET_SIZE = (512, 512)13 14# --- 2. 扩充至 50+ 专业模板库 ---15TEMPLATES = {16    "Professional Photography": [17        "Cinematic portrait of a woman, soft window lighting, 85mm lens, f1.8, high fidelity",18        "National Geographic style wildlife shot, tiger in the snow, sharp focus, dramatic lighting",19        "Street photography in Tokyo, rainy night, neon reflections, bokeh background, moody",20        "Minimalist architectural shot, concrete textures, brutalist style, blue sky contrast",21        "Fashion editorial shot, full body model, avant-garde outfit, studio lighting, white background",22        "Macro photography of a dew drop on a leaf, intricate details, fresh green tones",23        "Aerial view of a coastline, waves crashing against rocks, drone photography, 4k",24        "Black and white portrait of an old man, deep wrinkles, high contrast, emotional",25        "Product photography of a perfume bottle, splashing water, high speed sync, commercial look",26        "Interior design shot, modern living room, beige tones, natural sunlight, cozy atmosphere"27    ],28    "Anime & Illustration": [29        "Anime style, Makoto Shinkai inspired, blue sky with cumulus clouds, school girl, emotional",30        "Cyberpunk anime character, glowing mechanical parts, futuristic city background, detailed line art",31        "Studio Ghibli style, lush green meadow, small cottage, watercolor textures, peaceful",32        "Retro 90s anime style, cel shading, grainy texture, VHS aesthetic, nostalgic",33        "Fantasy illustration, warrior princess in silver armor, magical forest, glowing fireflies",34        "Chibi style character, cute big eyes, simple background, sticker art style",35        "Mecha robot design, heavy metal textures, battle damage, dramatic angle, anime poster",36        "Lofi hip hop girl, studying at desk, rainy window, cozy room, muted colors",37        "Vector art illustration, flat design, bold colors, clean lines, corporate memphis style",38        "Dark fantasy anime, demon hunter, red moon background, gothic architecture"39    ],40    "3D & CGI Design": [41        "Cute isometric 3D render of a gaming room, purple neon lighting, blender, clay material",42        "3D icon of a rocket ship, glossy plastic material, soft studio lighting, pastel colors",43        "Abstract 3D fluid art, swirling colorful liquid, glass texture, ray tracing, 4k wallpaper",44        "Pixar style 3D character, fluffy fur monster, bright colors, friendly expression",45        "Low poly landscape, mountains and trees, geometric shapes, game asset style",46        "Futuristic sci-fi corridor, unreal engine 5 render, metallic textures, cold blue lighting",47        "3D typography design, floating letters, gold material, dark background, luxury look",48        "Product mockup, blank t-shirt on hanger, realistic fabric texture, neutral background",49        "Automotive rendering, sports car on a wet road, motion blur, realistic reflections",50        "Architectural visualization, modern villa, pool side, evening lighting, realistic water"51    ],52    "Artistic Styles": [53        "Oil painting, thick impasto brushstrokes, van gogh style, starry night sky",54        "Watercolor painting, wet on wet technique, blooming colors, white paper texture",55        "Sketch style, pencil drawing, rough charcoal lines, black and white, artistic",56        "Pop art style, warhol inspired, repetitive patterns, bright primary colors",57        "Ukiyo-e style japanese woodblock print, great wave, mount fuji, traditional ink",58        "Cyberpunk digital art, glitch effect, neon pink and cyan, chaotic composition",59        "Concept art, dystopian city ruins, matte painting, epic scale, atmospheric perspective",60        "Stained glass window art, colorful mosaic, light shining through, religious theme",61        "Pixel art, 16-bit game style, city skyline at sunset, dithering shading",62        "Abstract expressionism, splatter paint, jackson pollock style, chaotic energy"63    ],64    "Fantasy & Sci-Fi": [65        "Epic fantasy landscape, floating islands, waterfalls, dragon flying, magical atmosphere",66        "Cyberpunk city street, flying cars, holograms, rain, blade runner vibe",67        "Steampunk airship, brass gears, steam clouds, victorian era pilot, adventure",68        "Space opera scene, alien planet landscape, two moons, strange plants, cinematic",69        "Post-apocalyptic survivor, wearing gas mask, ruined city background, dusty atmosphere",70        "Magical wizard tower, glowing crystals, purple mist, night sky, mystery",71        "Futuristic cyborg portrait, half human half machine, exposed wiring, sad expression",72        "Lovecraftian horror, giant tentacle monster in the ocean, foggy weather, dark mood",73        "Solarpunk city, buildings covered in plants, solar panels, bright optimistic future",74        "Dwarf blacksmith shop, glowing forge, anvil, intricate tools, fantasy interior"75    ]76}77 78# --- 3. 懒加载全局变量 ---79pipe = None80 81# --- 4. 核心生成逻辑 ---82@spaces.GPU(duration=120)83def generate_image(init_image, prompt, strength):84    global pipe85    86    # 懒加载:仅在 GPU 环境下初始化87    if pipe is None:88        print("Initializing model on GPU...")89        pipe = AutoPipelineForImage2Image.from_pretrained(90            MODEL_ID,91            torch_dtype=torch.float16,92            use_safetensors=True,93            safety_checker=None, 94            requires_safety_checker=False95        )96        pipe.to("cuda")97 98    if init_image is None:99        raise gr.Error("Error: Please upload a reference image first.")100 101    # 预处理102    input_img_resized = init_image.convert("RGB").resize(TARGET_SIZE, Image.LANCZOS)103    104    # 自动优化 Prompt105    magic_suffix = ", high quality, masterpiece, sharp focus, 8k"106    full_prompt = prompt + magic_suffix107    108    # 生成109    image = pipe(110        prompt=full_prompt,111        image=input_img_resized,112        strength=strength,113        num_inference_steps=3,114        guidance_scale=0.0,115    ).images[0]116    117    # 添加水印 (保持专业,稍微缩小字号)118    w, h = image.size119    draw = ImageDraw.Draw(image, "RGBA")120    text = WATERMARK_TEXT121    122    # 黑色遮罩条123    draw.rectangle([(0, h-40), (w, h)], fill=(0, 0, 0, 180))124    # 居中文字125    draw.text((w/2 - 60, h-28), text, fill=(255, 255, 255))126    127    return image128 129# --- 5. 界面 UI 设计 ---130 131# CSS 样式表:去渐变,去圆角,走 B 端专业风132css = """133body { font-family: 'Inter', sans-serif; }134footer { visibility: hidden; }135 136/* 顶部横幅:纯色,无渐变 */137.pro-banner {138    background-color: #1e293b; /* 深蓝灰色 */139    color: #f8fafc;140    padding: 24px;141    border-radius: 4px; /* 微圆角 */142    margin-bottom: 24px;143    border-left: 5px solid #3b82f6; /* 左侧蓝色装饰条 */144    text-align: left;145}146.pro-banner h1 {147    font-size: 1.5rem;148    font-weight: 600;149    margin: 0 0 8px 0;150    color: #ffffff;151}152.pro-banner p {153    font-size: 0.95rem;154    margin: 0;155    color: #cbd5e1;156    line-height: 1.5;157}158.pro-banner a {159    color: #60a5fa;160    text-decoration: none;161    font-weight: 500;162}163.pro-banner a:hover {164    text-decoration: underline;165}166 167/* 调整 Tab 样式 */168.svelte-1g805jl { 169    border-radius: 4px !important; 170}171"""172 173# 使用默认主题,而不是 Soft,显得更干练174theme = gr.themes.Default(175    primary_hue="blue",176    secondary_hue="slate",177    neutral_hue="slate",178    radius_size=gr.themes.sizes.radius_sm, # 小圆角179).set(180    button_primary_background_fill="#2563eb",181    button_primary_background_fill_hover="#1d4ed8",182    button_primary_text_color="white",183)184 185with gr.Blocks(css=css, theme=theme) as demo:186    187    # 顶部专业横幅188    gr.HTML(f"""189    <div class='pro-banner'>190        <h1>SceneYou AI Generator</h1>191        <p>Free research preview powered by Z-Image Turbo. 192        For unrestricted access, 4K resolution, and video generation, 193        please visit <a href='{PRODUCT_URL}' target='_blank'>SceneYou.art</a>.</p>194    </div>195    """)196    197    with gr.Row():198        # 左侧控制区199        with gr.Column(scale=4):200            image_input = gr.Image(201                label="Reference Image", 202                type="pil", 203                sources=["upload", "clipboard"], 204                height=280205            )206            207            with gr.Group():208                prompt_input = gr.Textbox(209                    label="Prompt", 210                    placeholder="Select a template below or type your own...", 211                    lines=2,212                    show_label=True213                )214                strength_slider = gr.Slider(215                    label="Denoising Strength",216                    minimum=0.1, maximum=1.0, value=0.60, step=0.05,217                    info="Lower keeps original structure, Higher adds more AI creativity."218                )219            220            generate_btn = gr.Button("Generate Image", variant="primary", size="lg")221 222        # 右侧结果区223        with gr.Column(scale=5):224            result_output = gr.Image(label="Generated Result", interactive=False)225            gr.Markdown(f"Get full access at [{PRODUCT_URL}]({PRODUCT_URL})")226 227    # 模板区 - 分类 Tab228    gr.Markdown("### Style Templates")229    with gr.Tabs():230        for category, prompts in TEMPLATES.items():231            with gr.TabItem(category):232                gr.Examples(233                    examples=[[p] for p in prompts],234                    inputs=[prompt_input], 235                    label="Click to apply"236                )237 238    # 事件绑定239    generate_btn.click(240        fn=generate_image, 241        inputs=[image_input, prompt_input, strength_slider], 242        outputs=result_output243    )244 245demo.queue()246demo.launch()