Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import torchimport gradio as grimport osfrom diffusers import AutoPipelineForText2Image, DPMSolverMultistepScheduler# ตั้งค่า Model ID เป็นตัวที่คุณต้องการMODEL_ID = "Tongyi-MAI/Z-Image-Turbo"print(f"🚀 Initializing Recovery Mode for: {MODEL_ID}")# 1. โหลดโมเดลด้วยระบบ Low RAM Usagepipe = AutoPipelineForText2Image.from_pretrained(MODEL_ID,torch_dtype=torch.float32,low_cpu_mem_usage=True)# 2. บังคับรันบน CPU เพื่อหลีกเลี่ยง Error เกี่ยวกับ CUDA Driverpipe.to("cpu")# 3. มาตรการ Never OOM: หั่นการประมวลผลเป็นส่วนย่อยpipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)pipe.enable_attention_slicing("max")pipe.enable_vae_tiling()torch.set_num_threads(os.cpu_count())# ระบบ Style สำเร็จรูปเพื่อความสะดวกSTYLE_MAP = {"สมจริง (Realistic)": "hyperrealistic, 8k, highly detailed, cinematic lighting","อนิเมะ (Anime)": "anime style, vibrant colors, masterpiece, clean lines","ศิลปะดิจิทัล (Digital Art)": "detailed digital painting, concept art, artistic","ดั้งเดิม (None)": ""}def gen(prompt, style, steps, cfg, width, height):if not prompt: return None# รวม Prompt กับ Style เข้าด้วยกันfull_prompt = f"{prompt}, {STYLE_MAP[style]}" if style != "ดั้งเดิม (None)" else promptwith torch.no_grad():image = pipe(prompt=full_prompt,num_inference_steps=int(steps),guidance_scale=float(cfg),width=int(width),height=int(height)).images[0]return image# จัดหน้าจอ UI ให้ใช้ง่ายและดูดีwith gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown(f"## 🛠️ Space Recovery: {MODEL_ID}")gr.Markdown("สถานะ: **CPU Mode (Never OOM Enabled)**")with gr.Row():with gr.Column(scale=1):prompt = gr.Textbox(label="คำสั่ง (Prompt)", placeholder="เช่น futuristic city, cyberpunk style", lines=3)style = gr.Radio(choices=list(STYLE_MAP.keys()), value="ดั้งเดิม (None)", label="เลือกสไตล์")with gr.Accordion("การตั้งค่าขั้นสูง (Advanced)", open=False):steps = gr.Slider(1, 10, 4, step=1, label="Steps (แนะนำ 4-6)")cfg = gr.Slider(0.0, 3.0, 1.2, step=0.1, label="CFG (แนะนำ 1.0-1.5)")width = gr.Slider(256, 512, 384, step=64, label="Width")height = gr.Slider(256, 512, 512, step=64, label="Height")btn = gr.Button("Generate", variant="primary")with gr.Column(scale=1):output_img = gr.Image(label="ผลลัพธ์", interactive=False)btn.click(fn=gen,inputs=[prompt, style, steps, cfg, width, height],outputs=[output_img])demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122import gradio as grhtml_content = """<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Google Veo 3 Generator</title><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"><meta http-equiv="Pragma" content="no-cache"><meta http-equiv="Expires" content="0"><style>html, body {margin: 0;padding: 0;width: 100%;height: 100vh;overflow: hidden;background-color: #ffffff;}#loading {position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: rgba(255, 255, 255, 0.9);display: flex;justify-content: center;align-items: center;font-size: 24px;font-family: sans-serif;z-index: 1000;}iframe {width: 100%;height: 100%;border: none;display: block;}</style></head><body><div id="loading">Selecting optimal server...</div><iframe id="streamlit-frame" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" allowfullscreen></iframe><script>const VERSION = "v1";const SERVERS = ["https://zenefil-veobatch.hf.space/","https://zenefil-veobatch.hf.space/"];async function checkServerSpeed(url) {const start = performance.now();try {const response = await Promise.race([fetch(url, { method: 'HEAD', mode: 'no-cors' }),new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 5000))]);const end = performance.now();return end - start;} catch (error) {console.error(`Error checking ${url}:`, error);return Infinity;}}async function chooseServer() {const speeds = await Promise.all(SERVERS.map(checkServerSpeed));const fastestIndex = speeds.indexOf(Math.min(...speeds));return SERVERS[fastestIndex];}async function loadStreamlit() {const loadingElement = document.getElementById('loading');const iframe = document.getElementById('streamlit-frame');const storageKey = `streamlitUrl_${VERSION}`;let chosenUrl = sessionStorage.getItem(storageKey);if (!chosenUrl) {chosenUrl = await chooseServer();sessionStorage.setItem(storageKey, chosenUrl);}const cacheBuster = new Date().getTime();const separator = chosenUrl.includes('?') ? '&' : '?';const iframeSrc = `${chosenUrl}${separator}cb=${cacheBuster}`;iframe.src = iframeSrc;iframe.onload = () => {loadingElement.style.display = 'none';};iframe.onerror = async () => {console.warn('Iframe load failed, rechoosing server...');sessionStorage.removeItem(storageKey);chosenUrl = await chooseServer();sessionStorage.setItem(storageKey, chosenUrl);const newSeparator = chosenUrl.includes('?') ? '&' : '?';iframe.src = `${chosenUrl}${newSeparator}cb=${new Date().getTime()}`;};}window.onload = loadStreamlit;</script></body></html>"""with gr.Blocks(title="Veo 3 App", fill_height=True, css="footer {display: none !important;} .gradio-container {padding: 0 !important; margin: 0 !important; max-width: 100% !important;}") as demo:gr.HTML(html_content)if __name__ == "__main__":demo.launch(show_api=False)
app.py+110-66