theunseenones94 commited on
Commit
8d3e06d
·
verified ·
1 Parent(s): 865a651

Rename app.py.txt to app.py

Browse files
Files changed (2) hide show
  1. app.py +167 -0
  2. app.py.txt +0 -192
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import time
4
+ import random
5
+ import uuid
6
+ import requests
7
+ import gradio as gr
8
+ from io import BytesIO
9
+ from PIL import Image
10
+ from huggingface_hub import snapshot_download
11
+ import shutil
12
+
13
+ # === AUTO DOWNLOAD EVERYTHING FROM OFFICIAL REPO ===
14
+ REPO_ID = "Tongyi-MAI/Z-Image-Turbo"
15
+ LOCAL_DIR = "z-image-models"
16
+
17
+ print("Downloading ALL files from Tongyi-MAI/Z-Image-Turbo... (this takes ~3-5 mins first time)")
18
+
19
+ snapshot_download(
20
+ repo_id=REPO_ID,
21
+ local_dir=LOCAL_DIR,
22
+ local_dir_use_symlinks=False,
23
+ allow_patterns=["*.safetensors", "*.json", "*.yaml", "*.yml", "*.bin"],
24
+ ignore_patterns=["*.git*", "*.md"]
25
+ )
26
+
27
+ # === Organize into ComfyUI folders ===
28
+ os.makedirs("models/checkpoints", exist_ok=True)
29
+ os.makedirs("models/vae", exist_ok=True)
30
+ os.makedirs("models/config", exist_ok=True)
31
+
32
+ for file in os.listdir(LOCAL_DIR):
33
+ src = os.path.join(LOCAL_DIR, file)
34
+ if file.endswith(".safetensors") or file.endswith(".ckpt"):
35
+ if "vae" in file.lower():
36
+ shutil.copy(src, f"models/vae/{file}")
37
+ else:
38
+ shutil.copy(src, f"models/checkpoints/{file}")
39
+ elif file.endswith((".json", ".yaml", ".yml")):
40
+ shutil.copy(src, f"models/config/{file}")
41
+
42
+ print("All Z-Image-Turbo models downloaded and placed correctly!")
43
+
44
+ # === Start ComfyUI ===
45
+ import subprocess
46
+ import threading
47
+
48
+ def start_comfyui():
49
+ if not os.path.exists("ComfyUI"):
50
+ print("Cloning ComfyUI...")
51
+ subprocess.run(["git", "clone", "https://github.com/comfyanonymous/ComfyUI.git"])
52
+
53
+ os.chdir("ComfyUI")
54
+ subprocess.Popen([
55
+ "python", "main.py",
56
+ "--listen", "0.0.0.0",
57
+ "--port", "8188",
58
+ "--force-fp16",
59
+ "--disable-auto-launch"
60
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
61
+ print("ComfyUI starting...")
62
+ time.sleep(25)
63
+
64
+ threading.Thread(target=start_comfyui, daemon=True).start()
65
+
66
+ COMFYUI_URL = "http://127.0.0.1:8188"
67
+ WORKFLOW_PATH = "workflow.json"
68
+
69
+ # === API Helpers ===
70
+ def queue_prompt(workflow):
71
+ client_id = str(uuid.uuid4())
72
+ r = requests.post(f"{COMFYUI_URL}/prompt", json={"prompt": workflow, "client_id": client_id})
73
+ return r.json().get("prompt_id")
74
+
75
+ def get_image_from_history(prompt_id):
76
+ while True:
77
+ try:
78
+ history = requests.get(f"{COMFYUI_URL}/history/{prompt_id}").json()
79
+ if prompt_id in history:
80
+ outputs = history[prompt_id]["outputs"]
81
+ for node_id in ["7", "14", "15"]: # SaveImage / PreviewImage
82
+ if node_id in outputs and "images" in outputs[node_id]:
83
+ img_data = outputs[node_id]["images"][0]
84
+ url = f"{COMFYUI_URL}/view?filename={img_data['filename']}&type={img_data['type']}&subfolder={img_data.get('subfolder','')}"
85
+ return Image.open(BytesIO(requests.get(url).content))
86
+ except:
87
+ pass
88
+ time.sleep(0.6)
89
+
90
+ # === Generation (100% random every time) ===
91
+ def generate(
92
+ prompt, negative_prompt="",
93
+ seed=-1, steps=20, cfg=7.0,
94
+ width=1024, height=1024,
95
+ upscale=1.0, batch_size=1
96
+ ):
97
+ with open(WORKFLOW_PATH, "r", encoding="utf-8") as f:
98
+ workflow = json.load(f)
99
+
100
+ base_seed = random.randint(1, 999999999) if seed < 0 else int(seed)
101
+ cache_buster = random.random()
102
+
103
+ images = []
104
+ status_msg = ""
105
+
106
+ for i in range(batch_size):
107
+ current_seed = base_seed + i * 1000000
108
+
109
+ for node in workflow["nodes"]:
110
+ # Update prompts
111
+ if node["type"] == "CLIPTextEncode":
112
+ if "beautiful landscape" in node["widgets_values"][0]:
113
+ node["widgets_values"][0] = prompt
114
+ if node["widgets_values"][0] == "":
115
+ node["widgets_values"][0] = negative_prompt
116
+
117
+ # Update sampler
118
+ if node["type"] == "KSampler":
119
+ node["widgets_values"][0] = current_seed
120
+ node["widgets_values"][1] = steps
121
+ node["widgets_values"][2] = cfg
122
+
123
+ # Size
124
+ if node["type"] == "EmptyLatentImage":
125
+ node["widgets_values"][0] = width
126
+ node["widgets_values"][1] = height
127
+ node["widgets_values"][2] = 1
128
+
129
+ # Upscale
130
+ if node["type"] == "LatentUpscaleBy":
131
+ node["widgets_values"][0] = upscale
132
+
133
+ # Cache buster
134
+ node["_b"] = cache_buster + i
135
+
136
+ pid = queue_prompt(workflow)
137
+ if not pid:
138
+ yield "ComfyUI not ready yet...", images
139
+ return
140
+
141
+ img = get_image_from_history(pid)
142
+ if img:
143
+ images.append(img)
144
+
145
+ status_msg = f"Generated {i+1}/{batch_size} • Seed: {current_seed}"
146
+ yield status_msg, images
147
+
148
+ yield f"Complete! • Seeds: {base_seed} → {current_seed}", images
149
+
150
+ # === Gradio UI ===
151
+ with gr.Blocks(title="Z-Image Turbo • Official Models • Always Random") as demo:
152
+ gr.Markdown("# Z-Image Turbo — Official Full Download\n"
153
+ "Every file from https://huggingface.co/Tongyi-MAI/Z-Image-Turbo\n"
154
+ "100% random • Hi-Res • Batch • No duplicates ever")
155
+
156
+ with gr.Row():
157
+ with gr.Column(scale=2):
158
+ prompt = gr.Textbox(
159
+ label="Prompt", lines=4,
160
+ value="masterpiece, best quality, ultra-detailed, beautiful mountain lake at golden hour, cinematic lighting"
161
+ )
162
+ negative = gr.Textbox(label="Negative Prompt", value="blurry, ugly, deformed, low quality")
163
+
164
+ with gr.Column():
165
+ seed = gr.Number(label="Seed (-1 = random)", value=-1)
166
+ steps = gr.Slider(10, 40, value=20, step=1, label="Steps")
167
+ cfg = gr.Slider(3, 15, value=7.0, step=0.1, label
app.py.txt DELETED
@@ -1,192 +0,0 @@
1
- import os
2
- import json
3
- import time
4
- import random
5
- import uuid
6
- import requests
7
- import gradio as gr
8
- from io import BytesIO
9
- from PIL import Image
10
- from huggingface_hub import snapshot_download
11
- import shutil
12
-
13
- # === Auto-download ALL models from repo ===
14
- REPO_ID = "Tongyi-MAI/Z-Image-Turbo"
15
- MODELS_DIR = "models"
16
- os.makedirs(MODELS_DIR, exist_ok=True)
17
-
18
- # Download entire repo snapshot
19
- print("Downloading all files from Z-Image-Turbo repo...")
20
- snapshot_download(
21
- repo_id=REPO_ID,
22
- local_dir=MODELS_DIR,
23
- local_dir_use_symlinks=False,
24
- ignore_patterns=["*.git*", "*.md", "*.txt"] # Skip non-model files
25
- )
26
-
27
- # Organize into ComfyUI folders
28
- checkpoints_dir = os.path.join(MODELS_DIR, "checkpoints")
29
- vae_dir = os.path.join(MODELS_DIR, "vae")
30
- os.makedirs(checkpoints_dir, exist_ok=True)
31
- os.makedirs(vae_dir, exist_ok=True)
32
-
33
- # Move .safetensors to checkpoints (main models)
34
- for file in os.listdir(MODELS_DIR):
35
- if file.endswith((".safetensors", ".ckpt")):
36
- shutil.move(os.path.join(MODELS_DIR, file), os.path.join(checkpoints_dir, file))
37
-
38
- # Move VAE files if present (e.g., vae.safetensors)
39
- for file in os.listdir(MODELS_DIR):
40
- if "vae" in file.lower() and file.endswith((".safetensors", ".ckpt")):
41
- shutil.move(os.path.join(MODELS_DIR, file), os.path.join(vae_dir, file))
42
-
43
- # Configs/JSON to custom folder for workflow use
44
- config_dir = os.path.join(MODELS_DIR, "config")
45
- os.makedirs(config_dir, exist_ok=True)
46
- for file in os.listdir(MODELS_DIR):
47
- if file.endswith((".json", ".yaml", ".yml")):
48
- shutil.move(os.path.join(MODELS_DIR, file), os.path.join(config_dir, file))
49
-
50
- print(f"All models downloaded to {MODELS_DIR}")
51
-
52
- # === ComfyUI Setup ===
53
- COMFYUI_URL = "http://127.0.0.1:8188"
54
- WORKFLOW_PATH = "workflow.json"
55
-
56
- # Start ComfyUI in background
57
- import threading
58
- import subprocess
59
-
60
- def start_comfyui():
61
- if not os.path.exists("ComfyUI"):
62
- subprocess.run(["git", "clone", "https://github.com/comfyanonymous/ComfyUI.git"])
63
- os.chdir("ComfyUI")
64
- subprocess.Popen([
65
- "python", "main.py",
66
- "--listen", "0.0.0.0", "--port", "8188",
67
- "--disable-auto-launch", "--force-fp16"
68
- ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
69
- print("Starting ComfyUI...")
70
- time.sleep(20)
71
-
72
- threading.Thread(target=start_comfyui, daemon=True).start()
73
- time.sleep(5)
74
-
75
- # === ComfyUI API Helpers ===
76
- def queue_prompt(workflow):
77
- client_id = str(uuid.uuid4())
78
- response = requests.post(f"{COMFYUI_URL}/prompt", json={"prompt": workflow, "client_id": client_id})
79
- return response.json().get("prompt_id")
80
-
81
- def get_images(prompt_id):
82
- while True:
83
- history = requests.get(f"{COMFYUI_URL}/history/{prompt_id}").json()
84
- if prompt_id in history:
85
- node = history[prompt_id]["outputs"]
86
- # Find SaveImage or PreviewImage node (usually ID 7 or 14)
87
- for node_id in ["7", "14", "15"]: # SaveImage nodes
88
- if node_id in node and "images" in node[node_id]:
89
- img_data = node[node_id]["images"][0]
90
- img_url = f"{COMFYUI_URL}/view?filename={img_data['filename']}&type={img_data['type']}"
91
- img = Image.open(BytesIO(requests.get(img_url).content))
92
- return [img]
93
- time.sleep(0.5)
94
-
95
- # === Main Generation Function ===
96
- def generate_image(
97
- prompt: str,
98
- negative_prompt: str = "",
99
- seed: int = -1,
100
- steps: int = 20,
101
- cfg: float = 7.0,
102
- width: int = 1024,
103
- height: int = 1024,
104
- upscale_factor: float = 1.0,
105
- batch_size: int = 1
106
- ):
107
- # Load workflow
108
- with open(WORKFLOW_PATH, "r", encoding="utf-8") as f:
109
- workflow = json.load(f)
110
-
111
- # === CRITICAL: Force new seed + cache busting ===
112
- actual_seed = random.randint(1, 999999999) if seed <= 0 else int(seed)
113
- cache_buster = random.random() # Forces ComfyUI to re-run everything
114
-
115
- # Update nodes
116
- for node in workflow["nodes"]:
117
- if node["type"] == "CLIPTextEncode" and "beautiful landscape" in node["widgets_values"][0]:
118
- node["widgets_values"][0] = prompt
119
- if node["type"] == "CLIPTextEncode" and node["widgets_values"][0] == "":
120
- node["widgets_values"][0] = negative_prompt
121
-
122
- if node["type"] == "KSampler":
123
- node["widgets_values"][0] = actual_seed
124
- node["widgets_values"][1] = steps
125
- node["widgets_values"][2] = cfg
126
-
127
- if node["type"] == "EmptyLatentImage":
128
- node["widgets_values"][0] = width
129
- node["widgets_values"][1] = height
130
- node["widgets_values"][2] = batch_size
131
-
132
- # Hi-res upscale factor
133
- if node["type"] == "LatentUpscaleBy":
134
- node["widgets_values"][0] = upscale_factor
135
-
136
- # Add dummy cache buster (harmless but forces re-execution)
137
- if "widgets_values" in node and isinstance(node["widgets_values"], list):
138
- node["_cache_buster"] = cache_buster
139
-
140
- images = []
141
- for i in range(batch_size):
142
- # Unique seed per batch item
143
- batch_seed = actual_seed + i * 1000000
144
- for node in workflow["nodes"]:
145
- if node["type"] == "KSampler":
146
- node["widgets_values"][0] = batch_seed
147
-
148
- prompt_id = queue_prompt(workflow)
149
- if not prompt_id:
150
- yield "Error: ComfyUI not responding", images
151
- return
152
-
153
- imgs = get_images(prompt_id)
154
- images.extend(imgs)
155
-
156
- yield f"Generated {i+1}/{batch_size} (Seed: {batch_seed})", images
157
-
158
- yield f"Done! Final seed: {actual_seed}", images
159
-
160
- # === Gradio Interface ===
161
- with gr.Blocks(title="Z-Image Turbo — Full Repo Models") as demo:
162
- gr.Markdown("# Z-Image Turbo — All Models Loaded\nFast SDXL with complete repo support • Always Random • Hi-Res")
163
-
164
- with gr.Row():
165
- with gr.Column(scale=2):
166
- prompt = gr.Textbox(
167
- label="Prompt",
168
- lines=3,
169
- value="a beautiful mountain landscape with a crystal lake at sunset, photorealistic, ultra detailed"
170
- )
171
- negative = gr.Textbox(label="Negative Prompt", lines=2, value="blurry, ugly, low quality")
172
-
173
- with gr.Column():
174
- seed = gr.Number(label="Seed (-1 = random)", value=-1)
175
- steps = gr.Slider(10, 40, value=20, step=1, label="Steps")
176
- cfg = gr.Slider(3, 15, value=7.0, step=0.1, label="CFG Scale")
177
- width = gr.Slider(512, 1536, value=1024, step=64, label="Width")
178
- height = gr.Slider(512, 1536, value=1024, step=64, label="Height")
179
- upscale = gr.Slider(1.0, 3.0, value=1.5, step=0.5, label="Hi-Res Upscale (1.0 = off)")
180
- batch = gr.Slider(1, 8, value=1, step=1, label="Batch Size")
181
-
182
- generate_btn = gr.Button("Generate Images", variant="primary", size="lg")
183
- status = gr.Textbox(label="Status", value="Ready")
184
- gallery = gr.Gallery(label="Results", columns=3, height="auto")
185
-
186
- generate_btn.click(
187
- fn=generate_image,
188
- inputs=[prompt, negative, seed, steps, cfg, width, height, upscale, batch],
189
- outputs=[status, gallery]
190
- )
191
-
192
- demo.launch(server_name="0.0.0.0", server_port=7860)