Spaces:
Running
Running
Update app.py
Browse files12345678910111213141516171819202122234 unmodified lines2829303132333435363738394041424344454647483 unmodified lines525354555657585960616263646566676869707172737475767778798081828384858687888990import torch, random, gc, numpy as npimport gradio as grfrom diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteSchedulerfrom huggingface_hub import loginfrom PIL import Imageimport os# --- 2. Load Model ---device = "cuda"model_id = "stablediffusionapi/pony-diffusion-v6-xl"if 'pipe' not in locals():pipe = StableDiffusionXLPipeline.from_pretrained(model_id, torch_dtype=torch.float16, variant="fp16", use_safetensors=True).to(device)pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)pipe.enable_vae_tiling()pipe.enable_vae_slicing()# --- 3. Function เจนภาพ (เพิ่มการจัดการนามสกุลไฟล์) ---def generate_single(prompt, neg_prompt, steps, cfg, seed, size_preset, style_preset, file_format):torch.cuda.empty_cache()style_map = {"None (ค่าดั้งเดิม)": "raw photo.cute.high resolution","Realistic Photo (ดิบๆ)": "raw photo, (photorealistic:1.3), high fidelity, skin pores, film grain, Fujifilm, ",4 unmodified lines"สไตล์บ้านๆ (Homemade)": "amateur phone photography, (casual lighting:1.2), flash photography, messy room background, (real life:1.3), grainy, ","แนวบิวตี้ (ฟรุ้งฟริ้ง)": "soft focus, (ethereal lighting:1.3), dreamy atmosphere, glowing skin, (pastel tones:1.1), high key lighting, beauty filter, "}selected_style = style_map[style_preset]if "score_9" in prompt:full_prompt = f"{selected_style}{prompt}"else:full_prompt = f"score_9, score_8_up, score_7_up, rating_explicit, masterpiece, best quality, {selected_style}{prompt}"size_map = {"Square (512x512)": (512, 512),"Square (1024x1024)": (1024, 1024),"Portrait (832x1216)": (720, 1260),"Landscape (1216x832)": (1280, 720)}width, height = size_map[size_preset]base_seed = int(seed) if int(seed) != -1 else random.randint(0, 10_000_000)with torch.inference_mode():generator = torch.manual_seed(base_seed)image = pipe(prompt=full_prompt,negative_prompt=neg_prompt,3 unmodified lineswidth=width,height=height).images[0]# บันทึกไฟล์ลงเครื่องตามนามสกุลที่เลือกfilename = f"output_{base_seed}.{file_format.lower()}"if file_format == "JPG":image.save(filename, quality=95, optimize=True)elif file_format == "PNG":image.save(filename, quality=98)else: # PNGimage.save(random)return image, base_seed, filename# --- 4. UI Layout ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 🚀 Pony V6 XL: Ultimate Realistic Engine")with gr.Row():with gr.Column(scale=1):btn = gr.Button("🚀 GENERATE NOW", variant="primary")p_in = gr.Textbox(label="Prompt", value="a young slutty asian cute girl, 2men,double-penetration. gangbang, group sex.sex on top potition.cum in pussy.creampie.deepthroat.eating sperm,public sex,bikini.nipple piercinglook pain mix happy,", lines=4)n_in = gr.Textbox(label="Negative", value="anime,,low quality, worst quality, motion artifacts, unstable motion, jitter, frame jitter, wobbling limbs, motion distortion, inconsistent movement, robotic movement, animation-like motion, awkward transitions, incorrect body mechanics, unnatural posing, off-balance poses, broken motion paths, frozen frames, duplicated frames, frame skipping, warped motion, stretching artifacts bad anatomy, incorrect proportions, deformed body, twisted torso, broken joints, dislocated limbs, distorted neck, unnatural spine curvature, malformed hands, extra fingers, missing fingers, fused fingers, distorted legs, extra limbs, collapsed feet, floating feet, foot sliding, foot jitter, backward walking, unnatural gait blurry details, long exposure blur, ghosting, shadow trails, smearing, washed-out colors, overexposure, underexposure, excessive contrast, blown highlights, poorly rendered clothing, fabric glitches, texture warping, clothing merging with body, incorrect cloth physics ugly background, cluttered scene, crowded background, random objects, unwanted text, subtitles, logos, graffiti, grain, noise, static artifacts, compression noise, jpeg artifacts, image-like stillness, painting-like look, cartoon texture, low-resolution textures manga, Disney, cartoon, low resolution, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, artist name, drawing, illustration, boring, 3d render, long neck, out of frame, extra fingers mutation, deformed, canvas frame, high contrast:1.2, over saturated:1.2, glossy:1.1, bad lighting, poorly drawn, bad art, bad angle, low-resolution, bad composition, terrible lighting, score_4, score_5, score_6, (anime, cartoon, manga, illustration, 3d, render:1.3), (extra limbs:1.2), (extra legs:1.2), (extra arms:1.2), low quality, blurry, censorship, mosaic", lines=2)with gr.Row():style_drop = gr.Dropdown(list(["None (ค่าดั้งเดิม)", "Realistic Photo (ดิบๆ)", "Cinematic Real (แสงสวย)", "3D Realistic (เนียนกริบ)", "Semi-Real (นวลตา)", "Portrait Real (เน้นหน้า)", "สไตล์บ้านๆ (Homemade)", "แนวบิวตี้ (ฟรุ้งฟริ้ง)"]), value="Realistic Photo (ดิบๆ)", label="เลือกสไตล์ภาพ")# ตั้งขนาดเริ่มต้นเป็น 1024x1024 ตามสั่งsize_drop = gr.Dropdown(["Square (512x512)", "Square (1024x1024)", "Portrait (832x1216)", "Landscape (1216x832)"], value="Square (1024x1024)", label="ขนาดภาพ")with gr.Row():# เพิ่มช่องเลือกนามสกุลไฟล์format_drop = gr.Dropdown(["PNG", "JPG", "WebP"], value="PNG", label="นามสกุลไฟล์")c_sld = gr.Slider(1, 15, value=3.0, step=0.5, label="ความคมชัดคำสั่ง (CFG)")with gr.Row():s_sld = gr.Slider(2, 100, value=70, step=1, label="รอบการวาด (Steps)")sd_in = gr.Number(value=-1, label="Seed")with gr.Column(scale=1):img_out = gr.Image(label="Result")file_out = gr.File(label="Download File") # ช่องสำหรับโหลดไฟล์ออกมาseed_out = gr.Number(label="Seed ที่ใช้")btn.click(fn=generate_single,inputs=[p_in, n_in, s_sld, c_sld, sd_in, size_drop, style_drop, format_drop],outputs=[img_out, seed_out, file_out])demo.launch(share=True)12345678910111213141516171819202122232425262728294 unmodified lines343536373839404142434445464748495051525354553 unmodified lines596061626364656667686970717273747576777879808182838485868788899091929394import torch, random, gc, numpy as npimport gradio as grfrom diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteSchedulerfrom PIL import Imageimport os# --- 1. Load Model (Free Tier HF) ---device = "cuda" if torch.cuda.is_available() else "cpu"model_id = "stablediffusionapi/pony-diffusion-v6-xl"pipe = StableDiffusionXLPipeline.from_pretrained(model_id,torch_dtype=torch.float16 if device == "cuda" else torch.float32,variant="fp16",use_safetensors=True).to(device)pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)pipe.enable_vae_tiling()pipe.enable_vae_slicing()# --- 2. Generate Function ---def generate_single(prompt, neg_prompt, steps, cfg, seed, size_preset, style_preset, file_format):torch.cuda.empty_cache()gc.collect()style_map = {"None (ค่าดั้งเดิม)": "raw photo.cute.high resolution","Realistic Photo (ดิบๆ)": "raw photo, (photorealistic:1.3), high fidelity, skin pores, film grain, Fujifilm, ",4 unmodified lines"สไตล์บ้านๆ (Homemade)": "amateur phone photography, (casual lighting:1.2), flash photography, messy room background, (real life:1.3), grainy, ","แนวบิวตี้ (ฟรุ้งฟริ้ง)": "soft focus, (ethereal lighting:1.3), dreamy atmosphere, glowing skin, (pastel tones:1.1), high key lighting, beauty filter, "}selected_style = style_map.get(style_preset, "")full_prompt = f"score_9, score_8_up, masterpiece, best quality, {selected_style}{prompt}"size_map = {"Square (512x512)": (512, 512),"Square (1024x1024)": (1024, 1024),"Portrait (832x1216)": (720, 1260),"Landscape (1216x832)": (1280, 720)}width, height = size_map.get(size_preset, (512, 512))base_seed = int(seed) if int(seed) != -1 else random.randint(0, 10_000_000)generator = torch.manual_seed(base_seed)with torch.inference_mode():image = pipe(prompt=full_prompt,negative_prompt=neg_prompt,3 unmodified lineswidth=width,height=height).images[0]filename = f"output_{base_seed}.{file_format.lower()}"image.save(filename, quality=95 if file_format == "JPG" else 98)return image, base_seed, filename# --- 3. Gradio UI ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("## 🐴 Pony V6 XL (Free Tier HF)")with gr.Row():with gr.Column(scale=1):btn = gr.Button("🚀 GENERATE NOW", variant="primary")p_in = gr.Textbox(label="Prompt", value="a beautiful cinematic portrait of a woman", lines=4)n_in = gr.Textbox(label="Negative", value="low quality, blurry, bad anatomy, watermark", lines=2)style_drop = gr.Dropdown(list(style_map.keys()), value="Realistic Photo (ดิบๆ)", label="เลือกสไตล์ภาพ")size_drop = gr.Dropdown(list(size_map.keys()), value="Square (1024x1024)", label="ขนาดภาพ")format_drop = gr.Dropdown(["PNG", "JPG", "WebP"], value="PNG", label="นามสกุลไฟล์")c_sld = gr.Slider(1, 15, value=3.0, step=0.5, label="ความคมชัดคำสั่ง (CFG)")s_sld = gr.Slider(2, 100, value=30, step=1, label="รอบการวาด (Steps)")sd_in = gr.Number(value=-1, label="Seed")with gr.Column(scale=1):img_out = gr.Image(label="Result")file_out = gr.File(label="Download File")seed_out = gr.Number(label="Seed ที่ใช้")btn.click(fn=generate_single,inputs=[p_in, n_in, s_sld, c_sld, sd_in, size_drop, style_drop, format_drop],outputs=[img_out, seed_out, file_out])demo.launch(share=True)
app.py+45-41