cocoat commited on
Commit
6292a70
·
verified ·
1 Parent(s): 6811fc9

Create tospacecommit_beta

Browse files
Files changed (1) hide show
  1. tospacecommit_beta +574 -0
tospacecommit_beta ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import random
4
+ import numpy as np
5
+ import datetime
6
+
7
+ # 履歴保存
8
+ from huggingface_hub import HfApi
9
+ from huggingface_hub import login
10
+ from huggingface_hub import Repository
11
+
12
+ import os
13
+ # HF_TOKEN 環境変数からトークンを明示的に読み込む
14
+ hf_token_value = os.getenv("HF_TOKEN")
15
+
16
+ if hf_token_value:
17
+ api = HfApi(token=hf_token_value)
18
+ print("token ok.")
19
+ else:
20
+ # トークンが設定されていない場合の警告と代替処理
21
+ print("HF_TOKEN error")
22
+ api = HfApi() # トークンなしで初期化
23
+
24
+ # 画像をアップロードするリポジトリID
25
+ HF_REPO_ID = "cocoat/images"
26
+
27
+ # Space内で画像を保存するディレクトリ
28
+ SPACE_IMAGE_DIR = "generated_images"
29
+ os.makedirs(SPACE_IMAGE_DIR, exist_ok=True)
30
+
31
+ # Spaceのリポジトリを初期化
32
+ # Gradio Spaceでは、カレントディレクトリがSpaceのリポジトリのルートになります。
33
+ # HF_SPACE_ID 環境変数には "ユーザー名/スペース名" が入っています。
34
+ space_repo_id = "cocoat/Re.cocoamixXL3"
35
+ repo = None # repoオブジェクトを初期化
36
+ if space_repo_id:
37
+ try:
38
+ repo = Repository(local_dir=".")
39
+ print(f"Successfully initialized Repository object for Space: {space_repo_id}")
40
+ except Exception as e:
41
+ print(f"Failed to initialize Repository object for Space ({space_repo_id}): {e}")
42
+ else:
43
+ print("HF_SPACE_ID environment variable not found. Cannot operate on Space repository.")
44
+
45
+ # 履歴ファイルを定義
46
+ HISTORY_FILE = "history/generation_history_coamixXL3.txt"
47
+
48
+ # 履歴をロードする関数
49
+ import os
50
+ import requests
51
+ def load_history():
52
+ history_data = []
53
+ hf_raw_file_url = f"https://huggingface.co/datasets/{HF_REPO_ID}/raw/main/{HISTORY_FILE}"
54
+ headers = {}
55
+ if hf_token_value:
56
+ headers["Authorization"] = f"Bearer {hf_token_value}"
57
+
58
+ try:
59
+ response = requests.get(hf_raw_file_url, headers=headers)
60
+ response.raise_for_status()
61
+
62
+ loaded_hub_paths = set() # 重複ロードを防ぐため
63
+
64
+ for line in response.text.splitlines():
65
+ parts = line.strip().split("|||")
66
+ if len(parts) == 2:
67
+ image_path_in_repo, caption = parts
68
+
69
+ filename_from_hub_path = os.path.basename(image_path_in_repo)
70
+ space_local_image_path = os.path.join(SPACE_IMAGE_DIR, filename_from_hub_path)
71
+
72
+ # Space内にファイルが存在するか確認
73
+ if os.path.exists(space_local_image_path):
74
+ # 存在するなら Space のパスを使用
75
+ history_data.append((image_path_in_repo, caption, space_local_image_path))
76
+ loaded_hub_paths.add(image_path_in_repo)
77
+ else:
78
+ print(f"Warning: Space image not found for Hub path: {image_path_in_repo}. Skipping for display.")
79
+ print(f"History loaded from Hub and matched with Space images: {len(history_data)} entries.")
80
+ except requests.exceptions.RequestException as e:
81
+ print(f"Error loading history from Hub via raw URL: {e}. Starting with empty history.")
82
+ except Exception as e:
83
+ print(f"An unexpected error occurred while parsing history: {e}. Starting with empty history.")
84
+
85
+ return history_data[:10]
86
+
87
+
88
+ # 履歴を初期化時にロード (修正された load_history を使用)
89
+ history = load_history()
90
+
91
+
92
+ # 履歴を初期化時にロード
93
+ history = load_history()
94
+
95
+ from PIL import Image
96
+ from diffusers import (
97
+ StableDiffusionXLPipeline,
98
+ EulerAncestralDiscreteScheduler,
99
+ DPMSolverMultistepScheduler
100
+ )
101
+ from huggingface_hub import hf_hub_download, HfApi
102
+
103
+ # デバイスと型の設定
104
+ device = "cuda" if torch.cuda.is_available() else "cpu"
105
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
106
+ MAX_SEED = np.iinfo(np.int32).max
107
+ MAX_SIZE = 2048
108
+
109
+ # モデルファイルのダウンロード
110
+ model_path = hf_hub_download(
111
+ repo_id="cocoat/cocoamix",
112
+ filename="recocoamixXL3_coamixXL3.safetensors"
113
+ )
114
+
115
+ # パイプライン構築
116
+ pipe = StableDiffusionXLPipeline.from_single_file(
117
+ model_path,
118
+ torch_dtype=torch_dtype,
119
+ use_safetensors=True
120
+ ).to(device)
121
+
122
+ # スケジューラ設定
123
+ euler_scheduler = EulerAncestralDiscreteScheduler.from_config(
124
+ pipe.scheduler.config,
125
+ use_karras_sigmas=True
126
+ )
127
+ dpm_scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
128
+ pipe.scheduler = euler_scheduler
129
+
130
+ def upload_image_to_hub(image_pil, prompt_text):
131
+ # ファイル名を生成(タイムスタンプとプロンプトの一部)
132
+ timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
133
+ # プロンプトから安全なファイル名の一部を生成
134
+ # safe_prompt = "".join(c for c in prompt_text if c.isalnum() or c in (' ', '.', '_')).replace(' ', '_')[:30]
135
+ filename = f"image_{timestamp}.png"
136
+ filepath = f"temp_{filename}"
137
+ image_pil.save(filepath)
138
+
139
+ # Hubにアップロード
140
+ try:
141
+ # リポジトリ内にディレクトリを作成する場合は path_in_repo を使う
142
+ path_in_repo = f"generated_images/{filename}"
143
+ upload_info = api.upload_file(
144
+ path_or_fileobj=filepath,
145
+ path_in_repo=path_in_repo,
146
+ repo_id=HF_REPO_ID,
147
+ repo_type="dataset", # または "space", "model" など、目的のリポジトリタイプ
148
+ # 通常、画像保存には "dataset" タイプのリポジトリが適しています
149
+ )
150
+ # アップロードされたファイルのURLを構築する
151
+ uploaded_file_url = f"https://huggingface.co/datasets/{HF_REPO_ID}/resolve/main/{path_in_repo}"
152
+ print(f"Uploaded {filepath} to {uploaded_file_url}")
153
+ return uploaded_file_url
154
+ except Exception as e:
155
+ print(f"Error uploading image to Hub: {e}")
156
+ return None
157
+ finally:
158
+ # 一時ファイルを削除
159
+ if os.path.exists(filepath):
160
+ os.remove(filepath)
161
+ print(f"一時画像ファイル {filepath} を削除しました。")
162
+
163
+ def make_html_table(caption):
164
+ formatted_caption = caption.replace("|-|", "\n")
165
+ rows = formatted_caption.split("\n")
166
+ html = '<table style="width:100%;border-collapse:collapse;background:#fffaf1;color:#000">'
167
+ for row in rows:
168
+ if ": " in row:
169
+ key, val = row.split(": ", 1)
170
+ html += (
171
+ # f'{key}: {val}\n'
172
+ f'<tr><th style="text-align:left;border:1px solid #ddd;padding:4px;">{key}</th>'
173
+ f'<td style="border:1px solid #ddd;padding:4px;">{val}</td></tr>'
174
+ )
175
+ html += '</table>'
176
+ return html
177
+
178
+ def create_dummy_image(width=512, height=512, alpha=0):
179
+ return Image.new("RGBA", (width, height), (0, 0, 0, alpha))
180
+
181
+ def update_history_tables_on_select(evt: gr.SelectData):
182
+ if evt.index is not None and 0 <= evt.index < len(history):
183
+ selected_caption = history[evt.index][1]
184
+ return make_html_table(selected_caption)
185
+ return ""
186
+
187
+ def update_history():
188
+ tables_html = "".join(
189
+ f'<div style="margin-bottom:12px">{make_html_table(item[1])}</div>'
190
+ for item in history
191
+ )
192
+ return tables_html
193
+
194
+ def infer(prompt, neg, seed, rand, w, h, cfg, steps, scheduler_type,
195
+ progress=gr.Progress(track_tqdm=True)):
196
+ if rand:
197
+ seed = random.randint(0, MAX_SEED)
198
+ generator = torch.Generator(device=device).manual_seed(seed)
199
+
200
+ pipe.scheduler = euler_scheduler if scheduler_type == "Euler Ancestral" else dpm_scheduler
201
+ pipe.scheduler.set_timesteps(steps)
202
+
203
+ def _callback(pipeline, step_idx, timestep, callback_kwargs):
204
+ progress(step_idx / steps, desc=f"Step {step_idx}/{steps}")
205
+ return callback_kwargs
206
+
207
+ output = pipe(
208
+ prompt=prompt,
209
+ negative_prompt=neg or None,
210
+ guidance_scale=cfg,
211
+ num_inference_steps=steps,
212
+ width=w,
213
+ height=h,
214
+ generator=generator,
215
+ callback_on_step_end=_callback
216
+ )
217
+ img = output.images[0]
218
+
219
+ caption_text = (
220
+ f"Prompt: {prompt}\n"
221
+ f"Negative: {neg or 'None'}\n"
222
+ f"Seed: {seed}\n"
223
+ f"Size: {w}×{h}\n"
224
+ f"CFG: {cfg}\n"
225
+ f"Steps: {steps}\n"
226
+ f"Scheduler: {scheduler_type}"
227
+ )
228
+
229
+ caption_text_for_history = caption_text.replace("\n", "|-|").strip()
230
+
231
+ # 画像をHubにアップロードし、そのURLを取得
232
+ uploaded_image_url = upload_image_to_hub(img, prompt)
233
+
234
+ # Space内に画像を保存し、Gitリポジリにコミット・プッシュ
235
+ timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
236
+ space_image_filename = f"space_image_{timestamp}.png"
237
+ space_image_filepath = os.path.join(SPACE_IMAGE_DIR, space_image_filename)
238
+
239
+ saved_to_space_git = False
240
+ try:
241
+ img.save(space_image_filepath)
242
+ print(f"Image saved to Space local filesystem: {space_image_filepath}")
243
+
244
+ # SpaceのGitリポジトリにコミット・プッシュ
245
+ if repo:
246
+ try:
247
+ # Git LFS で追跡するように .gitattributes を確認/追加
248
+ gitattributes_path = os.path.join(SPACE_IMAGE_DIR, ".gitattributes")
249
+ if not os.path.exists(gitattributes_path):
250
+ with open(gitattributes_path, "w") as f:
251
+ f.write("*.png filter=lfs diff=lfs merge=lfs -text\n")
252
+ repo.git_add(gitattributes_path)
253
+ print(f"Added .gitattributes for LFS tracking in {SPACE_IMAGE_DIR}.")
254
+
255
+ repo.git_add(space_image_filepath)
256
+ repo.git_commit(f"Add generated image {space_image_filename}")
257
+ repo.git_push() # これでHubにプッシュされる
258
+ print(f"Image {space_image_filename} committed and pushed to Space repository.")
259
+ saved_to_space_git = True
260
+ except Exception as e:
261
+ print(f"Error committing/pushing image to Space repository: {e}")
262
+ else:
263
+ print("Space repository object not initialized, skipping Git operations for Space.")
264
+
265
+ except Exception as e:
266
+ print(f"Error saving image to Space local filesystem: {e}")
267
+ saved_to_space_git = False # エラー時にはFalseに設定を保証
268
+
269
+ # 履歴を更新
270
+ global history
271
+ # Hubへのアップロードが成功し、かつSpaceへのGit保存も成功した場合のみ履歴に追加
272
+ if uploaded_image_url and saved_to_space_git:
273
+ path_in_repo_for_history = uploaded_image_url.split(f"huggingface.co/datasets/{HF_REPO_ID}/resolve/main/")[1]
274
+ history.insert(0, (path_in_repo_for_history, caption_text_for_history, space_image_filepath))
275
+ else:
276
+ print(f"Skipping history update due to failed Hub upload ({uploaded_image_url is None}) or Space Git save ({not saved_to_space_git}).")
277
+
278
+ history_max_items = 10
279
+ if len(history) > history_max_items:
280
+ # Space内の最も古い画像を削除
281
+ if history[-1][2] and os.path.exists(history[-1][2]):
282
+ oldest_space_image_path = history[-1][2]
283
+ try:
284
+ if repo: # repoオブジェクトが初期化されていればGit操作
285
+ repo.git_rm(oldest_space_image_path) # Gitからファイルを削除
286
+ repo.git_commit(f"Remove oldest image {os.path.basename(oldest_space_image_path)}")
287
+ repo.git_push()
288
+ print(f"Deleted oldest image from Space repository: {oldest_space_image_path}")
289
+ else: # repoオブジェクトがない場合はローカルファイルのみ削除
290
+ os.remove(oldest_space_image_path)
291
+ print(f"Deleted oldest image from Space local filesystem (no Git): {oldest_space_image_path}")
292
+ except Exception as e:
293
+ print(f"Error deleting oldest image from Space (local/Git): {e}")
294
+ history.pop()
295
+
296
+ # 履歴ファイルを更新し、Hubにアップロードする
297
+ temp_history_filepath = "temp_history.txt"
298
+ with open(temp_history_filepath, "w", encoding="utf-8") as f:
299
+ for img_path_in_repo, cap_text, _ in history:
300
+ f.write(f"{img_path_in_repo}|||{cap_text}\n")
301
+
302
+ try:
303
+ api.upload_file(
304
+ path_or_fileobj=temp_history_filepath,
305
+ path_in_repo=HISTORY_FILE,
306
+ repo_id=HF_REPO_ID,
307
+ repo_type="dataset",
308
+ )
309
+ print(f"History file '{HISTORY_FILE}' updated on Hugging Face Hub.")
310
+ except Exception as e:
311
+ print(f"Error updating history file on Hub: {e}")
312
+ finally:
313
+ if os.path.exists(temp_history_filepath):
314
+ os.remove(temp_history_filepath)
315
+
316
+ progress(1.0, desc="Done!")
317
+
318
+ # ギャラリー表示用のアイテムリストを生成(Hub上のURLを使用)
319
+ gallery_items = [(item[2], item[1].replace("|-|", "\n")) for item in history]
320
+
321
+ processed_img, processed_gallery_items = process_image(img, gallery_items)
322
+
323
+ latest_caption_table = make_html_table(caption_text)
324
+ return processed_img, processed_gallery_items, latest_caption_table
325
+
326
+ import gc
327
+ import torch
328
+ def process_image(img, gallery_items): # Assuming this is part of a function
329
+ try:
330
+ gc.collect()
331
+ # Clear PyTorch's cache if GPU memory is being used
332
+ if torch.cuda.is_available():
333
+ torch.cuda.empty_cache()
334
+ return img, gallery_items
335
+
336
+ except RuntimeError as e:
337
+ # Catch errors like CUDA Out of Memory
338
+ error_message = f"error in generate: {e}\n\n"
339
+ if "CUDA out of memory" in str(e):
340
+ error_message += "memory error"
341
+ else:
342
+ error_message += "other error"
343
+ print(error_message) # Output to server logs
344
+ return None, None
345
+
346
+ # CSS 設定(ダークモード強制防止+カフェ風テーマ)
347
+ css = """
348
+ @import url('https://fonts.googleapis.com/css2?family=Playpen+Sans+Hebrew:wght@100;200;300;400;500;600;700;800&display=swap');
349
+ body {
350
+ background-color: #f4e1c1 !important;
351
+ font-family:'Playpen Sans Hebrew', ‘Georgia’, serif !important;
352
+ color: #000 !important;
353
+ }
354
+ html, .gradio-container, .dark, .dark * {
355
+ background: #fffaf1 !important;
356
+ color: #000 !important;
357
+ }
358
+ #col-container {
359
+ background: #fffaf1;
360
+ padding: 20px;
361
+ border-radius: 16px;
362
+ box-shadow: 0 4px 12px rgba(0,0,0,0.1);
363
+ margin: auto;
364
+ max-width: 780px;
365
+ }
366
+ .gr-button {
367
+ background-color: #d4a373 !important;
368
+ color: white !important;
369
+ border-radius: 8px !important;
370
+ padding: 10px 24px !important;
371
+ font-weight: bold;
372
+ transition: background-color 0.3s;
373
+ }
374
+ .gr-button:hover {
375
+ background-color: #c48f61 !important;
376
+ }
377
+ .gr-textbox, .gr-slider, .gr-radio, .gr-checkbox, .gr-image {
378
+ background: #fff;
379
+ border-radius: 8px;
380
+ }
381
+ .gr-gallery {
382
+ background: #fffaf1;
383
+ padding: 10px;
384
+ border-radius: 12px;
385
+ }
386
+ .gr-gallery .gallery-item Figcaption,
387
+ .gr-gallery .gallery-item figcaption {
388
+ width:420px !important;
389
+ word-wrap:break-word !important;
390
+ }
391
+ .gradio-spinner { display: none !important; }
392
+ #custom-loader {
393
+ align-items: center;
394
+ justify-content: center;
395
+ font-weight: bold;
396
+ margin: 12px 0;
397
+ position: fixed;
398
+ z-index: 9999;
399
+ }
400
+ .block.svelte-11xb1hd {
401
+ background: #efd1bf !important;
402
+ }
403
+ span.svelte-g2oxp3, label.svelte-5ncdh7.svelte-5ncdh7.svelte-5ncdh7 {
404
+ color: #915325 !important;
405
+ }
406
+ .svelte-zyxd38 g {
407
+ display: none !important;
408
+ }
409
+ .secondary.svelte-1ixn6qd {
410
+ background: #dca08a !important;
411
+ color: #631c00 !important;
412
+ }
413
+ :root {
414
+ --color-accent: #a57659;
415
+ }
416
+ .max_value.svelte-10lj3xl.svelte-10lj3xl, span.min_value {
417
+ color: #a54618 !important;
418
+ }
419
+ body.gradio-running #custom-loader { display: flex; }
420
+ #custom-loader, .loading-text {
421
+ width: auto !important;
422
+ height: auto !important;
423
+ }
424
+ @keyframes fadeLetter {
425
+ 0%,100% { opacity: 1; }
426
+ 50% { opacity: 0.2; }
427
+ }
428
+ #custom-loader .loading-text span {
429
+ display: inline-block;
430
+ animation: fadeLetter 1.8s ease-in-out infinite;
431
+ font-size:3em;
432
+ }
433
+ #custom-loader img {
434
+ width: 64px;
435
+ height: 64px;
436
+ border-radius: 50%;
437
+ margin-left: 8px;
438
+ display: inline-block;
439
+ animation: jump 2s infinite ease-in-out;
440
+ vertical-align: middle;
441
+ }
442
+ .svelte-zyxd38{
443
+ width: 100% !important;
444
+ height: 100% !important;
445
+ }
446
+ @keyframes jump {
447
+ 0%, 100% { transform: translateY(10px); opacity: 1;}
448
+ 50% { transform: translateY(-10px); opacity: 1;}
449
+ }
450
+ .nobackground, .nobackground div, .nobackground.parent.parent.parent {
451
+ background-color: transparent !important;
452
+ }
453
+ progress::-webkit-progress-value {
454
+ background-color: #a57659 !important;
455
+ }
456
+ progress::-moz-progress-bar {
457
+ background-color: #a57659 !important;
458
+ }
459
+ .gradio-progress .progress-bar,
460
+ .gradio-progress-bar {
461
+ background-color: #a57659 !important;
462
+ }
463
+
464
+ """
465
+
466
+ with gr.Blocks(css=css, theme=gr.themes.Default(font=[gr.themes.GoogleFont("Playpen Sans Hebrew"), "Arial", "sans-serif"])) as demo:
467
+ with gr.Column(elem_id="col-container"):
468
+ gr.HTML('<section class="nobackground"><h2>SDXL – Re:cocoamixXL3 (coamixXL3) Demo</h2><br>The log is shared with other. (No more than 10 images will be displayed in history.)<br>Please use this model at your own risk. I am not responsible in any way for any problems with the generated images.</section>')
469
+ gr.HTML('<section class="nobackground"><a href="https://civitai.com/models/1553716?modelVersionId=1855218" target="_blank">Link: Civitai</a></section>')
470
+
471
+ with gr.Row():
472
+ prompt = gr.Textbox(lines=1, placeholder="Prompt…", value="1girl, cocoart, masterpiece, anime, high quality,", label="Prompt")
473
+ neg = gr.Textbox(lines=1, placeholder="Negative prompt", value="low quality, worst quality, bad, bad lighting, lowres, error, miss stroke, smoke, ugly, extra digits, creepy, imprecise, blurry,", label="Negative prompt")
474
+ with gr.Row():
475
+ seed_sl = gr.Slider(0, MAX_SEED, step=1, value=0, label="Seed")
476
+ rand = gr.Checkbox(True, label="Randomize seed")
477
+ with gr.Row():
478
+ width = gr.Slider(256, 512, step=32, value=512, label="Width")
479
+ height = gr.Slider(256, 768, step=32, value=512, label="Height")
480
+ with gr.Row():
481
+ cfg = gr.Slider(1.0, 30.0, step=0.5, value=6, label="CFG Scale")
482
+ steps = gr.Slider(1, 15, step=1, value=12, label="Steps")
483
+ with gr.Row():
484
+ scheduler_type = gr.Radio(choices=["Euler Ancestral", "DPM++ 2M SDE"], value="Euler Ancestral", label="Scheduler")
485
+ run = gr.Button("Generate")
486
+
487
+ # カスタムローダー
488
+ gr.HTML(
489
+ """
490
+ <script>
491
+ window.addEventListener('load', () => {
492
+ const observer = new MutationObserver(() => {
493
+ const svg = document.querySelector('svg.svelte-zyxd38');
494
+ if (!svg) return;
495
+ // 一度挿入したら再挿入しない
496
+ if (svg.querySelector('foreignObject#custom-loader-fo')) return;
497
+
498
+ const SVG_NS = 'http://www.w3.org/2000/svg';
499
+ // foreignObject を作成
500
+ const fo = document.createElementNS(SVG_NS, 'foreignObject');
501
+ fo.setAttribute('id', 'custom-loader-fo');
502
+ fo.setAttribute('width', '100%'); // SVG 内の表示エリア幅に合わせて調整
503
+ fo.setAttribute('height', '100%'); // SVG 内の表示エリア高さに合わせて調整
504
+ fo.setAttribute('x', '-200');
505
+ fo.setAttribute('y', '0');
506
+
507
+ // HTML 部分を innerHTML で一発挿入
508
+ fo.innerHTML = `
509
+ <div id="custom-loader" xmlns="http://www.w3.org/1999/xhtml">
510
+ <div class="loading-text">
511
+ <span style="animation-delay:0s">i</span>
512
+ <span style="animation-delay:0.1s">n</span>
513
+ <span style="animation-delay:0.2s"> </span>
514
+ <span style="animation-delay:0.3s">p</span>
515
+ <span style="animation-delay:0.4s">r</span>
516
+ <span style="animation-delay:0.5s">o</span>
517
+ <span style="animation-delay:0.6s">g</span>
518
+ <span style="animation-delay:0.7s">r</span>
519
+ <span style="animation-delay:0.8s">e</span>
520
+ <span style="animation-delay:0.9s">s</span>
521
+ <span style="animation-delay:1.0s">s</span>
522
+ <img src="https://huggingface.co/spaces/cocoat/Re.cocoamixXL3/resolve/main/icon.png" width="32" height="32" />
523
+ </div>
524
+ </div>
525
+ `;
526
+
527
+ svg.appendChild(fo);
528
+ });
529
+ observer.observe(document.body, { childList: true, subtree: true });
530
+ });
531
+ </script>
532
+ """
533
+ )
534
+ img_out = gr.Image(
535
+ interactive=None,
536
+ value=create_dummy_image(width=512, height=512, alpha=0),
537
+ label="生成画像"
538
+ )
539
+ state = gr.State([])
540
+ history_gallery = gr.Gallery(
541
+ label="生成履歴",
542
+ columns=4,
543
+ height=280,
544
+ show_label=False,
545
+ interactive=None,
546
+ type="auto",
547
+ value=[]
548
+ )
549
+ # テーブル部分だけを下にまとめて生HTMLレンダー
550
+ history_tables = gr.HTML(value="")
551
+
552
+ run.click(
553
+ fn=infer,
554
+ inputs=[prompt, neg, seed_sl, rand, width, height, cfg, steps, scheduler_type],
555
+ outputs=[img_out, history_gallery, history_tables]
556
+ )
557
+ history_gallery.select(
558
+ fn=update_history_tables_on_select,
559
+ inputs=None, # select イベントは自動的にイベントデータ (gr.SelectData) を渡す
560
+ outputs=[history_tables]
561
+ )
562
+
563
+ # ページロード時に history から初期表示
564
+ demo.load(
565
+ fn=lambda: ( # history リストの各要素が (Hub上のファイルパス, キャプション, Space内のファイルパス)
566
+ [ (item[2], item[1].replace("|-|", "\n")) for item in history if item[2] is not None ],
567
+ make_html_table(history[0][1]) if history else "" # 最初のアイテムのキャプションを表示
568
+ ),
569
+ inputs=[],
570
+ outputs=[history_gallery, history_tables]
571
+ )
572
+
573
+ demo.queue()
574
+ demo.launch()