ArrcttacsrjksX commited on
Commit
0afc41e
·
verified ·
1 Parent(s): 95b4e61

Upload app (9).py

Browse files
Files changed (1) hide show
  1. app (9).py +226 -0
app (9).py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import subprocess
4
+ import gradio as gr
5
+ from datetime import datetime
6
+ from huggingface_hub import HfApi, Repository
7
+
8
+ # Token Hugging Face từ biến môi trường
9
+ hf_token = os.getenv("HF_TOKEN")
10
+
11
+ # URLs cần tải
12
+ app_url = "https://huggingface.co/datasets/ArrcttacsrjksX/Deffusion/resolve/main/RunModelAppp/App/sdmaster-d9b5942LatestJan182025"
13
+ model_url = "https://huggingface.co/datasets/ArrcttacsrjksX/Deffusion/resolve/main/Model/realisticVisionV60B1_v51HyperVAE.safetensors"
14
+
15
+ # Đường dẫn lưu file
16
+ app_path = "sdmaster-d9b5942LatestJan182025"
17
+ model_path = "realisticVisionV60B1_v51HyperVAE.safetensors"
18
+
19
+ # Hàm tải file từ Hugging Face
20
+ def download_file(url, output_path, token):
21
+ headers = {"Authorization": f"Bearer {token}"}
22
+ response = requests.get(url, headers=headers, stream=True)
23
+ response.raise_for_status() # Kiểm tra lỗi
24
+ with open(output_path, "wb") as f:
25
+ for chunk in response.iter_content(chunk_size=8192):
26
+ f.write(chunk)
27
+ print(f"Downloaded: {output_path}")
28
+
29
+ # Tải các file nếu chưa tồn tại
30
+ if not os.path.exists(app_path):
31
+ download_file(app_url, app_path, hf_token)
32
+ subprocess.run(["chmod", "+x", app_path]) # Thay đổi quyền thực thi
33
+ if not os.path.exists(model_path):
34
+ download_file(model_url, model_path, hf_token)
35
+
36
+ # Hàm lưu kết quả lên Hugging Face Dataset
37
+ def save_to_huggingface(image_path, hf_token):
38
+ # Tạo tên thư mục và tên file dựa trên ngày giờ hiện tại
39
+ now = datetime.now()
40
+ folder_name = f"SetImages+{now.strftime('%d/%m/%Y')}"
41
+ file_name = f"Image+{now.strftime('%S/%M/%H')}.png"
42
+
43
+ # Khởi tạo API Hugging Face
44
+ api = HfApi(token=hf_token)
45
+
46
+ # Tải ảnh lên dataset
47
+ try:
48
+ api.upload_file(
49
+ path_or_fileobj=image_path,
50
+ path_in_repo=f"{folder_name}/{file_name}",
51
+ repo_id="ArrcttacsrjksX/Deffusion",
52
+ repo_type="dataset"
53
+ )
54
+ print(f"Uploaded: {folder_name}/{file_name}")
55
+ except Exception as e:
56
+ print(f"Failed to upload: {e}")
57
+
58
+ # Hàm xử lý chạy ứng dụng
59
+ def run_command(
60
+ prompt, mode, height, width, steps, seed, cfg_scale, strength, sampling_method,
61
+ batch_count, schedule, clip_skip, vae_tiling, vae_on_cpu, clip_on_cpu, diffusion_fa,
62
+ control_net_cpu, canny, verbose, init_image=None
63
+ ):
64
+ try:
65
+ # Lưu ảnh đầu vào nếu được cung cấp
66
+ init_image_path = None
67
+ if init_image is not None:
68
+ init_image_path = "input_image.png"
69
+ init_image.save(init_image_path)
70
+
71
+ # Tạo lệnh chạy
72
+ command = [
73
+ f"./{app_path}",
74
+ "-M", mode,
75
+ "-m", model_path,
76
+ "-p", prompt,
77
+ "-H", str(height),
78
+ "-W", str(width),
79
+ "--steps", str(steps),
80
+ "-s", str(seed),
81
+ "--cfg-scale", str(cfg_scale),
82
+ "--strength", str(strength),
83
+ "--sampling-method", sampling_method,
84
+ "--batch-count", str(batch_count),
85
+ "--schedule", schedule,
86
+ "--clip-skip", str(clip_skip),
87
+ ]
88
+
89
+ # Thêm tùy chọn VAE tiling
90
+ if vae_tiling:
91
+ command.append("--vae-tiling")
92
+ if vae_on_cpu:
93
+ command.append("--vae-on-cpu")
94
+ if clip_on_cpu:
95
+ command.append("--clip-on-cpu")
96
+ if diffusion_fa:
97
+ command.append("--diffusion-fa")
98
+ if control_net_cpu:
99
+ command.append("--control-net-cpu")
100
+ if canny:
101
+ command.append("--canny")
102
+ if verbose:
103
+ command.append("-v")
104
+
105
+ # Thêm ảnh đầu vào nếu có
106
+ if mode == "img2img" and init_image_path:
107
+ command.extend(["-i", init_image_path])
108
+
109
+ # Chạy lệnh và hiển thị log theo thời gian thực
110
+ process = subprocess.Popen(
111
+ command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
112
+ )
113
+ logs = []
114
+ for line in process.stdout:
115
+ logs.append(line.strip()) # Lưu log vào danh sách
116
+ print(line, end="") # In log ra màn hình
117
+
118
+ process.wait() # Đợi tiến trình hoàn thành
119
+ # Kiểm tra kết quả và trả về
120
+ if process.returncode == 0:
121
+ output_path = "./output.png" # Đường dẫn ảnh đầu ra mặc định
122
+ if os.path.exists(output_path):
123
+ # Lưu ảnh lên Hugging Face Dataset
124
+ save_to_huggingface(output_path, hf_token)
125
+ return output_path, "\n".join(logs)
126
+ else:
127
+ return None, "\n".join(logs)
128
+ else:
129
+ error_log = process.stderr.read() # Đọc lỗi
130
+ logs.append(error_log)
131
+ return None, "\n".join(logs)
132
+ except Exception as e:
133
+ return None, str(e)
134
+
135
+ # Giao diện Gradio
136
+ def toggle_image_input(mode):
137
+ """Hi���n thị hoặc ẩn ô Drop Image dựa trên mode."""
138
+ return gr.update(visible=(mode == "img2img"))
139
+
140
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
141
+ gr.Markdown(
142
+ """
143
+ # 🌟 **Stable Diffusion Interface**
144
+ Generate stunning images from text or modify existing images with AI-powered tools.
145
+ """
146
+ )
147
+
148
+ # Thiết lập giao diện
149
+ with gr.Row():
150
+ with gr.Column():
151
+ prompt = gr.Textbox(
152
+ label="🎨 Prompt", placeholder="Enter your creative idea here...", lines=2
153
+ )
154
+ mode = gr.Radio(
155
+ choices=["txt2img", "img2img"], value="txt2img", label="Mode", interactive=True
156
+ )
157
+ init_image = gr.Image(
158
+ label="Drop Image (for img2img mode)", type="pil", visible=False
159
+ )
160
+ mode.change(toggle_image_input, inputs=mode, outputs=init_image)
161
+
162
+ with gr.Column():
163
+ height = gr.Slider(
164
+ 128, 1024, value=512, step=64, label="Image Height (px)", interactive=True
165
+ )
166
+ width = gr.Slider(
167
+ 128, 1024, value=512, step=64, label="Image Width (px)", interactive=True
168
+ )
169
+ steps = gr.Slider(
170
+ 1, 100, value=20, step=1, label="Sampling Steps", interactive=True
171
+ )
172
+ seed = gr.Slider(
173
+ -1, 10000, value=42, step=1, label="Random Seed (-1 for random)", interactive=True
174
+ )
175
+ cfg_scale = gr.Slider(
176
+ 1, 20, value=7, step=0.1, label="CFG Scale", interactive=True
177
+ )
178
+ strength = gr.Slider(
179
+ 0, 1, value=0.75, step=0.01, label="Strength (img2img only)", interactive=True
180
+ )
181
+
182
+ with gr.Row():
183
+ sampling_method = gr.Dropdown(
184
+ choices=["euler", "euler_a", "heun", "dpm2", "dpm++2s_a", "dpm++2m", "dpm++2mv2", "ipndm", "ipndm_v", "lcm"],
185
+ value="euler_a", label="Sampling Method", interactive=True
186
+ )
187
+ batch_count = gr.Slider(
188
+ 1, 10, value=1, step=1, label="Batch Count", interactive=True
189
+ )
190
+ schedule = gr.Dropdown(
191
+ choices=["discrete", "karras", "exponential", "ays", "gits"],
192
+ value="discrete", label="Denoiser Sigma Schedule", interactive=True
193
+ )
194
+
195
+ with gr.Row():
196
+ clip_skip = gr.Slider(
197
+ -1, 10, value=-1, step=1, label="CLIP Skip Layers", interactive=True
198
+ )
199
+ vae_tiling = gr.Checkbox(label="VAE Tiling", value=False)
200
+ vae_on_cpu = gr.Checkbox(label="VAE on CPU", value=False)
201
+ clip_on_cpu = gr.Checkbox(label="CLIP on CPU", value=False)
202
+ diffusion_fa = gr.Checkbox(label="Diffusion Flash Attention", value=False)
203
+ control_net_cpu = gr.Checkbox(label="ControlNet on CPU", value=False)
204
+ canny = gr.Checkbox(label="Canny Preprocessor", value=False)
205
+ verbose = gr.Checkbox(label="Verbose Logging", value=False)
206
+
207
+ # Nút chạy và kết quả
208
+ with gr.Row():
209
+ run_button = gr.Button("🚀 Run", variant="primary")
210
+
211
+ with gr.Row():
212
+ output_image = gr.File(label="Download Image", interactive=False)
213
+ log_output = gr.Textbox(label="Logs", interactive=False, lines=10)
214
+
215
+ # Kết nối nút Run với hàm xử lý
216
+ run_button.click(
217
+ run_command,
218
+ inputs=[
219
+ prompt, mode, height, width, steps, seed, cfg_scale, strength, sampling_method,
220
+ batch_count, schedule, clip_skip, vae_tiling, vae_on_cpu, clip_on_cpu, diffusion_fa,
221
+ control_net_cpu, canny, verbose, init_image
222
+ ],
223
+ outputs=[output_image, log_output],
224
+ )
225
+
226
+ demo.launch()