Saravutw commited on
Commit
804ef40
·
verified ·
1 Parent(s): eb4db26

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -66
app.py CHANGED
@@ -1,78 +1,122 @@
1
- import torch
2
  import gradio as gr
3
- import os
4
- from diffusers import AutoPipelineForText2Image, DPMSolverMultistepScheduler
5
 
6
- # ตั้งค่า Model ID เป็นตัวที่คุณต้องการ
7
- MODEL_ID = "Tongyi-MAI/Z-Image-Turbo"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- print(f"🚀 Initializing Recovery Mode for: {MODEL_ID}")
 
 
 
 
 
 
10
 
11
- # 1. โหลดโมเดลด้วยระบบ Low RAM Usage
12
- pipe = AutoPipelineForText2Image.from_pretrained(
13
- MODEL_ID,
14
- torch_dtype=torch.float32,
15
- low_cpu_mem_usage=True
16
- )
 
 
 
 
 
 
 
 
17
 
18
- # 2. บังคับรันบน CPU เพื่อหลีกเลี่ยง Error เกี่ยวกับ CUDA Driver
19
- pipe.to("cpu")
 
 
 
20
 
21
- # 3. มาตรการ Never OOM: หั่นการประมวลผลเป็นส่วนย่อย
22
- pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
23
- pipe.enable_attention_slicing("max")
24
- pipe.enable_vae_tiling()
25
- torch.set_num_threads(os.cpu_count())
 
 
 
 
 
 
26
 
27
- # ระบบ Style สำเร็จรูปเพื่อความสะดวก
28
- STYLE_MAP = {
29
- "สมจริง (Realistic)": "hyperrealistic, 8k, highly detailed, cinematic lighting",
30
- "อนิเมะ (Anime)": "anime style, vibrant colors, masterpiece, clean lines",
31
- "ศิลปะดิจิทัล (Digital Art)": "detailed digital painting, concept art, artistic",
32
- "ดั้งเดิม (None)": ""
33
- }
34
 
35
- def gen(prompt, style, steps, cfg, width, height):
36
- if not prompt: return None
37
-
38
- # รวม Prompt กับ Style เข้าด้วยกัน
39
- full_prompt = f"{prompt}, {STYLE_MAP[style]}" if style != "ดั้งเดิม (None)" else prompt
40
-
41
- with torch.no_grad():
42
- image = pipe(
43
- prompt=full_prompt,
44
- num_inference_steps=int(steps),
45
- guidance_scale=float(cfg),
46
- width=int(width),
47
- height=int(height)
48
- ).images[0]
49
- return image
50
 
51
- # จัดหน้าจอ UI ให้ใช้ง่ายและดูดี
52
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
53
- gr.Markdown(f"## 🛠️ Space Recovery: {MODEL_ID}")
54
- gr.Markdown("สถานะ: **CPU Mode (Never OOM Enabled)**")
55
-
56
- with gr.Row():
57
- with gr.Column(scale=1):
58
- prompt = gr.Textbox(label="คำสั่ง (Prompt)", placeholder="เช่น futuristic city, cyberpunk style", lines=3)
59
- style = gr.Radio(choices=list(STYLE_MAP.keys()), value="ดั้งเดิม (None)", label="เลือกสไตล์")
60
-
61
- with gr.Accordion("การตั้งค่าขั้นสูง (Advanced)", open=False):
62
- steps = gr.Slider(1, 10, 4, step=1, label="Steps (แนะนำ 4-6)")
63
- cfg = gr.Slider(0.0, 3.0, 1.2, step=0.1, label="CFG (แนะนำ 1.0-1.5)")
64
- width = gr.Slider(256, 512, 384, step=64, label="Width")
65
- height = gr.Slider(256, 512, 512, step=64, label="Height")
66
 
67
- btn = gr.Button("Generate", variant="primary")
68
-
69
- with gr.Column(scale=1):
70
- output_img = gr.Image(label="ผลลัพธ์", interactive=False)
 
 
 
 
 
 
71
 
72
- btn.click(
73
- fn=gen,
74
- inputs=[prompt, style, steps, cfg, width, height],
75
- outputs=[output_img]
76
- )
77
 
78
- demo.launch()
 
 
 
1
  import gradio as gr
 
 
2
 
3
+ html_content = """
4
+ <!DOCTYPE html>
5
+ <html lang="en">
6
+ <head>
7
+ <meta charset="UTF-8">
8
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
9
+ <title>Google Veo 3 Generator</title>
10
+
11
+ <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
12
+ <meta http-equiv="Pragma" content="no-cache">
13
+ <meta http-equiv="Expires" content="0">
14
+
15
+ <style>
16
+ html, body {
17
+ margin: 0;
18
+ padding: 0;
19
+ width: 100%;
20
+ height: 100vh;
21
+ overflow: hidden;
22
+ background-color: #ffffff;
23
+ }
24
+ #loading {
25
+ position: fixed;
26
+ top: 0;
27
+ left: 0;
28
+ width: 100%;
29
+ height: 100%;
30
+ background: rgba(255, 255, 255, 0.9);
31
+ display: flex;
32
+ justify-content: center;
33
+ align-items: center;
34
+ font-size: 24px;
35
+ font-family: sans-serif;
36
+ z-index: 1000;
37
+ }
38
+ iframe {
39
+ width: 100%;
40
+ height: 100%;
41
+ border: none;
42
+ display: block;
43
+ }
44
+ </style>
45
+ </head>
46
+ <body>
47
+ <div id="loading">Selecting optimal server...</div>
48
+ <iframe id="streamlit-frame" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" allowfullscreen></iframe>
49
 
50
+ <script>
51
+ const VERSION = "v1";
52
+
53
+ const SERVERS = [
54
+ "https://zenefil-veobatch.hf.space/",
55
+ "https://zenefil-veobatch.hf.space/"
56
+ ];
57
 
58
+ async function checkServerSpeed(url) {
59
+ const start = performance.now();
60
+ try {
61
+ const response = await Promise.race([
62
+ fetch(url, { method: 'HEAD', mode: 'no-cors' }),
63
+ new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 5000))
64
+ ]);
65
+ const end = performance.now();
66
+ return end - start;
67
+ } catch (error) {
68
+ console.error(`Error checking ${url}:`, error);
69
+ return Infinity;
70
+ }
71
+ }
72
 
73
+ async function chooseServer() {
74
+ const speeds = await Promise.all(SERVERS.map(checkServerSpeed));
75
+ const fastestIndex = speeds.indexOf(Math.min(...speeds));
76
+ return SERVERS[fastestIndex];
77
+ }
78
 
79
+ async function loadStreamlit() {
80
+ const loadingElement = document.getElementById('loading');
81
+ const iframe = document.getElementById('streamlit-frame');
82
+
83
+ const storageKey = `streamlitUrl_${VERSION}`;
84
+ let chosenUrl = sessionStorage.getItem(storageKey);
85
+
86
+ if (!chosenUrl) {
87
+ chosenUrl = await chooseServer();
88
+ sessionStorage.setItem(storageKey, chosenUrl);
89
+ }
90
 
91
+ const cacheBuster = new Date().getTime();
92
+ const separator = chosenUrl.includes('?') ? '&' : '?';
93
+ const iframeSrc = `${chosenUrl}${separator}cb=${cacheBuster}`;
94
+
95
+ iframe.src = iframeSrc;
 
 
96
 
97
+ iframe.onload = () => {
98
+ loadingElement.style.display = 'none';
99
+ };
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ iframe.onerror = async () => {
102
+ console.warn('Iframe load failed, rechoosing server...');
103
+ sessionStorage.removeItem(storageKey);
104
+ chosenUrl = await chooseServer();
105
+ sessionStorage.setItem(storageKey, chosenUrl);
 
 
 
 
 
 
 
 
 
 
106
 
107
+ const newSeparator = chosenUrl.includes('?') ? '&' : '?';
108
+ iframe.src = `${chosenUrl}${newSeparator}cb=${new Date().getTime()}`;
109
+ };
110
+ }
111
+
112
+ window.onload = loadStreamlit;
113
+ </script>
114
+ </body>
115
+ </html>
116
+ """
117
 
118
+ 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:
119
+ gr.HTML(html_content)
 
 
 
120
 
121
+ if __name__ == "__main__":
122
+ demo.launch(show_api=False)