cocoat commited on
Commit
fb4a25b
·
verified ·
1 Parent(s): 8d8e5f3

大型改変。

Browse files

import gradio as gr
import torch
import random
import numpy as np
from PIL import Image
from diffusers import (
StableDiffusionXLPipeline,
EulerAncestralDiscreteScheduler,
DPMSolverMultistepScheduler
)
from huggingface_hub import hf_hub_download

# デバイスと型の設定
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
MAX_SEED = np.iinfo(np.int32).max
MAX_SIZE = 2048

# モデルファイルのダウンロード
model_path = hf_hub_download(
repo_id="cocoat/cocoamix",
filename="recocoamixXL3_coamixXL3.safetensors"
)

# パイプライン構築
pipe = StableDiffusionXLPipeline.from_single_file(
model_path,
torch_dtype=torch_dtype,
use_safetensors=True
).to(device)

# スケジューラ設定
euler_scheduler = EulerAncestralDiscreteScheduler.from_config(
pipe.scheduler.config,
use_karras_sigmas=True
)
dpm_scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe.scheduler = euler_scheduler

# 履歴保存
history = []

def make_html_table(caption):
rows = caption.split("\n")
html = '<table style="width:100%;border-collapse:collapse;background:#fffaf1;color:#000">'
for row in rows:
if ": " in row:
key, val = row.split(": ", 1)
html += (
# f'{key}: {val}\n'
f'<tr><th style="text-align:left;border:1px solid #ddd;padding:4px;">{key}</th>'
f'<td style="border:1px solid #ddd;padding:4px;">{val}</td></tr>'
)
html += '</table>'
return html

def create_dummy_image(width=512, height=512, alpha=0):
return Image.new("RGBA", (width, height), (0, 0, 0, alpha))

def update_history(img, gallery_items):
tables_html = "".join(
f'<div style="margin-bottom:12px">{make_html_table(item[1])}</div>'
for item in history
)
return tables_html

def infer(prompt, neg, seed, rand, w, h, cfg, steps, scheduler_type,
progress=gr.Progress(track_tqdm=True)):
if rand:
seed = random.randint(0, MAX_SEED)
generator = torch.Generator(device=device).manual_seed(seed)

pipe.scheduler = euler_scheduler if scheduler_type == "Euler Ancestral" else dpm_scheduler
pipe.scheduler.set_timesteps(steps)

def _callback(pipeline, step_idx, timestep, callback_kwargs):
progress(step_idx / steps, desc=f"Step {step_idx}/{steps}")
return callback_kwargs

output = pipe(
prompt=prompt,
negative_prompt=neg or None,
guidance_scale=cfg,
num_inference_steps=steps,
width=w,
height=h,
generator=generator,
callback_on_step_end=_callback
)
img = output.images[0]

caption_text = (
f"Prompt: {prompt}\n"
f"Negative: {neg or 'None'}\n"
f"Seed: {seed}\n"
f"Size: {w}×{h}\n"
f"CFG: {cfg}\n"
f"Steps: {steps}\n"
f"Scheduler: {scheduler_type}"
)
history.insert(0, (img, caption_text))
progress(1.0, desc="Done!")

gallery_items = [(img_obj, raw_caption_text) for img_obj, raw_caption_text in history]
tables_html = "".join(f'<div style="margin-bottom:12px">{make_html_table(item[1])}</div>' for item in history)
return img, gallery_items

# CSS 設定(ダークモード強制防止+カフェ風テーマ)
css = """


@import
url('https://fonts.googleapis.com/css2?family=Playpen+Sans+Hebrew:wght@100;200;300;400;500;600;700;800&display=swap');
body {
background-color: #f4e1c1 !important;
font-family:'Playpen Sans Hebrew', ‘Georgia’, serif !important;
color: #000 !important;
}
html, .gradio-container, .dark, .dark * {
background: #fffaf1 !important;
color: #000 !important;
}
#col-container {
background: #fffaf1;
padding: 20px;
border-radius: 16px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
margin: auto;
max-width: 780px;
}
.gr-button {
background-color: #d4a373 !important;
color: white !important;
border-radius: 8px !important;
padding: 10px 24px !important;
font-weight: bold;
transition: background-color 0.3s;
}
.gr-button:hover {
background-color: #c48f61 !important;
}
.gr-textbox, .gr-slider, .gr-radio, .gr-checkbox, .gr-image {
background: #fff;
border-radius: 8px;
}
.gr-gallery {
background: #fffaf1;
padding: 10px;
border-radius: 12px;
}
.gr-gallery .gallery-item Figcaption,
.gr-gallery .gallery-item figcaption {
width:420px !important;
word-wrap:break-word !important;
}
.gradio-spinner { display: none !important; }
#custom-loader {
align-items: center;
justify-content: center;
font-weight: bold;
margin: 12px 0;
position: fixed;
z-index: 9999;
}
.block.svelte-11xb1hd {
background: #efd1bf !important;
}
span.svelte-g2oxp3, label.svelte-5ncdh7.svelte-5ncdh7.svelte-5ncdh7 {
color: #915325 !important;
}
.svelte-zyxd38 g {
display: none !important;
}
.secondary.svelte-1ixn6qd {
background: #dca08a !important;
color: #631c00 !important;
}
:root {
--color-accent: #a57659;
}
.max_value.svelte-10lj3xl.svelte-10lj3xl, span.min_value {
color: #a54618 !important;
}
body.gradio-running #custom-loader { display: flex; }
#custom-loader, .loading-text {
width: auto !important;
height: auto !important;
}


@keyframes
fadeLetter {
0%,100% { opacity: 1; }
50% { opacity: 0.2; }
}
#custom-loader .loading-text span {
display: inline-block;
animation: fadeLetter 1.8s ease-in-out infinite;
font-size:3em;
}
#custom-loader img {
width: 64px;
height: 64px;
border-radius: 50%;
margin-left: 8px;
display: inline-block;
animation: jump 2s infinite ease-in-out;
vertical-align: middle;
}
.svelte-zyxd38{
width: 100% !important;
height: 100% !important;
}


@keyframes
jump {
0%, 100% { transform: translateY(10px); opacity: 1;}
50% { transform: translateY(-10px); opacity: 1;}
}
.nobackground, .nobackground div, .nobackground.parent.parent.parent {
background-color: transparent !important;
}
progress::-webkit-progress-value {
background-color: #a57659 !important;
}
progress::-moz-progress-bar {
background-color: #a57659 !important;
}
.gradio-progress .progress-bar,
.gradio-progress-bar {
background-color: #a57659 !important;
}

"""

with gr.Blocks(css=css, theme=gr.themes.Default(font=[gr.themes.GoogleFont("Playpen Sans Hebrew"), "Arial", "sans-serif"])) as demo:
with gr.Column(elem_id="col-container"):
gr.HTML('<section class="nobackground"><h2>SDXL – Re:cocoamixXL3 (coamixXL3) Demo</h2><br>The log is shared with other.<br>Please use this model at your own risk. I am not responsible in any way for any problems with the generated images.</section>')
gr.HTML('<section class="nobackground"><a href="https://civitai.com/models/1553716?modelVersionId=1855218" target="_blank">Link: Civitai</a></section>')

with gr.Row():
prompt = gr.Textbox(lines=1, placeholder="Prompt…", value="1girl, cocoart, masterpiece, anime,", label="Prompt")
neg = gr.Textbox(lines=1, placeholder="Negative prompt", value="low quality, worst quality, bad shadow, lowres, error, miss stroke, sketch art, smoke, ugly, extra digits, creepy, imprecise, glowing blur,", label="Negative prompt")
with gr.Row():
seed_sl = gr.Slider(0, MAX_SEED, step=1, value=0, label="Seed")
rand = gr.Checkbox(True, label="Randomize seed")
with gr.Row():
width = gr.Slider(256, 512, step=32, value=512, label="Width")
height = gr.Slider(256, 768, step=32, value=512, label="Height")
with gr.Row():
cfg = gr.Slider(1.0, 30.0, step=0.1, value=7.5, label="CFG Scale")
steps = gr.Slider(1, 50, step=1, value=12, label="Steps")
with gr.Row():
scheduler_type = gr.Radio(choices=["Euler Ancestral", "DPM++ 2M SDE"], value="Euler Ancestral", label="Scheduler")
run = gr.Button("Generate")

# カスタムローダー
gr.HTML(
"""
<script>
window.addEventListener('load', () => {
const observer = new MutationObserver(() => {
const svg = document.querySelector('svg.svelte-zyxd38');
if (!svg) return;
// 一度挿入したら再挿入しない
if (svg.querySelector('foreignObject#custom-loader-fo')) return;

const SVG_NS = 'http://www.w3.org/2000/svg';
// foreignObject を作成
const fo = document.createElementNS(SVG_NS, 'foreignObject');
fo.setAttribute('id', 'custom-loader-fo');
fo.setAttribute('width', '100%'); // SVG 内の表示エリア幅に合わせて調整
fo.setAttribute('height', '100%'); // SVG 内の表示エリア高さに合わせて調整
fo.setAttribute('x', '-200');
fo.setAttribute('y', '0');

// HTML 部分を innerHTML で一発挿入
fo.innerHTML = `
<div id="custom-loader" xmlns="http://www.w3.org/1999/xhtml">
<div class="loading-text">
<span style="animation-delay:0s">i</span>
<span style="animation-delay:0.1s">n</span>
<span style="animation-delay:0.2s"> </span>
<span style="animation-delay:0.3s">p</span>
<span style="animation-delay:0.4s">r</span>
<span style="animation-delay:0.5s">o</span>
<span style="animation-delay:0.6s">g</span>
<span style="animation-delay:0.7s">r</span>
<span style="animation-delay:0.8s">e</span>
<span style="animation-delay:0.9s">s</span>
<span style="animation-delay:1.0s">s</span>
<img src="https://huggingface.co/spaces/cocoat/Re.cocoamixXL3/resolve/main/icon.png" width="32" height="32" />
</div>
</div>
`;

svg.appendChild(fo);
});
observer.observe(document.body, { childList: true, subtree: true });
});
</script>
"""
)
img_out = gr.Image(
interactive=None,
value=create_dummy_image(width=512, height=512, alpha=0),
label="生成画像"
)
state = gr.State([])
history_gallery = gr.Gallery(
label="生成履歴",
columns=4,
height=280,
show_label=False,
intera

Files changed (1) hide show
  1. app.py +64 -17
app.py CHANGED
@@ -2,13 +2,15 @@ import gradio as gr
2
  import torch
3
  import random
4
  import numpy as np
 
 
5
  from PIL import Image
6
  from diffusers import (
7
  StableDiffusionXLPipeline,
8
  EulerAncestralDiscreteScheduler,
9
  DPMSolverMultistepScheduler
10
  )
11
- from huggingface_hub import hf_hub_download
12
 
13
  # デバイスと型の設定
14
  device = "cuda" if torch.cuda.is_available() else "cpu"
@@ -39,6 +41,42 @@ pipe.scheduler = euler_scheduler
39
 
40
  # 履歴保存
41
  history = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  def make_html_table(caption):
44
  rows = caption.split("\n")
@@ -57,13 +95,13 @@ def make_html_table(caption):
57
  def create_dummy_image(width=512, height=512, alpha=0):
58
  return Image.new("RGBA", (width, height), (0, 0, 0, alpha))
59
 
60
- def update_history(img, gallery_items):
61
  tables_html = "".join(
62
  f'<div style="margin-bottom:12px">{make_html_table(item[1])}</div>'
63
  for item in history
64
  )
65
  return tables_html
66
-
67
  def infer(prompt, neg, seed, rand, w, h, cfg, steps, scheduler_type,
68
  progress=gr.Progress(track_tqdm=True)):
69
  if rand:
@@ -98,13 +136,22 @@ def infer(prompt, neg, seed, rand, w, h, cfg, steps, scheduler_type,
98
  f"Steps: {steps}\n"
99
  f"Scheduler: {scheduler_type}"
100
  )
101
- history.insert(0, (img, caption_text))
 
 
 
 
 
 
 
 
102
  progress(1.0, desc="Done!")
103
 
104
- gallery_items = [(img_obj, raw_caption_text) for img_obj, raw_caption_text in history]
105
- tables_html = "".join(f'<div style="margin-bottom:12px">{make_html_table(item[1])}</div>' for item in history)
106
  return img, gallery_items
107
 
 
108
  # CSS 設定(ダークモード強制防止+カフェ風テーマ)
109
  css = """
110
  @import url('https://fonts.googleapis.com/css2?family=Playpen+Sans+Hebrew:wght@100;200;300;400;500;600;700;800&display=swap');
@@ -317,19 +364,19 @@ window.addEventListener('load', () => {
317
  outputs=[img_out, history_gallery]
318
  ).then(
319
  fn=update_history,
320
- inputs=[img_out, history_gallery],
321
  outputs=[history_tables]
322
  )
323
-
324
- # ページロード時に history から初期表示
325
- demo.load(
326
- fn=lambda: (
327
- [(img, caption) for img, caption in history],
328
- "".join(f'<div style="margin-bottom:12px">{make_html_table(caption)}</div>' for _, caption in history)
329
- ),
330
- inputs=[],
331
- outputs=[history_gallery, history_tables]
332
- )
333
 
334
  demo.queue()
335
  demo.launch()
 
2
  import torch
3
  import random
4
  import numpy as np
5
+ import datetime
6
+ import os
7
  from PIL import Image
8
  from diffusers import (
9
  StableDiffusionXLPipeline,
10
  EulerAncestralDiscreteScheduler,
11
  DPMSolverMultistepScheduler
12
  )
13
+ from huggingface_hub import hf_hub_download, HfApi
14
 
15
  # デバイスと型の設定
16
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
41
 
42
  # 履歴保存
43
  history = []
44
+ api = HfApi()
45
+
46
+ # 画像をアップロードするリポジトリID
47
+ HF_REPO_ID = "cocoat/Re.cocoamixXL3"
48
+
49
+ def upload_image_to_hub(image_pil, prompt_text):
50
+ # ファイル名を生成(タイムスタンプとプロンプトの一部)
51
+ timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
52
+ # プロンプトから安全なファイル名の一部を生成
53
+ safe_prompt = "".join(c for c in prompt_text if c.isalnum() or c in (' ', '.', '_')).replace(' ', '_')[:30]
54
+ filename = f"image_{timestamp}_{safe_prompt}.png"
55
+ filepath = f"temp_{filename}" # 一時的にローカルに保存するパス
56
+ # PIL画像を一時ファイルとして保存
57
+ image_pil.save(filepath)
58
+
59
+ # Hubにアップロード
60
+ try:
61
+ # リポジトリ内にディレクトリを作成する場合は path_in_repo を使う
62
+ path_in_repo = f"generated_images/{filename}"
63
+ upload_info = api.upload_file(
64
+ path_or_fileobj=filepath,
65
+ path_in_repo=path_in_repo,
66
+ repo_id=HF_REPO_ID,
67
+ repo_type="dataset", # または "space", "model" など、目的のリポジトリタイプ
68
+ # 通常、画像保存には "dataset" タイプのリポジトリが適しています
69
+ )
70
+ print(f"Uploaded {filepath} to {upload_info.url}")
71
+ return upload_info.url # アップロードされたファイルのURLを返す
72
+ except Exception as e:
73
+ print(f"Error uploading image to Hub: {e}")
74
+ return None
75
+ finally:
76
+ # 一時ファイルを削除
77
+ if os.path.exists(filepath):
78
+ os.remove(filepath)
79
+
80
 
81
  def make_html_table(caption):
82
  rows = caption.split("\n")
 
95
  def create_dummy_image(width=512, height=512, alpha=0):
96
  return Image.new("RGBA", (width, height), (0, 0, 0, alpha))
97
 
98
+ def update_history():
99
  tables_html = "".join(
100
  f'<div style="margin-bottom:12px">{make_html_table(item[1])}</div>'
101
  for item in history
102
  )
103
  return tables_html
104
+
105
  def infer(prompt, neg, seed, rand, w, h, cfg, steps, scheduler_type,
106
  progress=gr.Progress(track_tqdm=True)):
107
  if rand:
 
136
  f"Steps: {steps}\n"
137
  f"Scheduler: {scheduler_type}"
138
  )
139
+ uploaded_image_url = upload_image_to_hub(img, prompt)
140
+ if uploaded_image_url:
141
+ history.insert(0, (uploaded_image_url, caption_text))
142
+ else:
143
+ history.insert(0, (create_dummy_image(alpha=0), "画像アップロードに失敗しました!"))
144
+
145
+ history_max_items = 10
146
+ if len(history) > history_max_items:
147
+ history.pop()
148
  progress(1.0, desc="Done!")
149
 
150
+ gallery_items = [(item[0], item[1]) for item in history]
151
+ # tables_html = "".join(f'<div style="margin-bottom:12px">{make_html_table(item[1])}</div>' for item in history)
152
  return img, gallery_items
153
 
154
+
155
  # CSS 設定(ダークモード強制防止+カフェ風テーマ)
156
  css = """
157
  @import url('https://fonts.googleapis.com/css2?family=Playpen+Sans+Hebrew:wght@100;200;300;400;500;600;700;800&display=swap');
 
364
  outputs=[img_out, history_gallery]
365
  ).then(
366
  fn=update_history,
367
+ inputs=[],
368
  outputs=[history_tables]
369
  )
370
+
371
+ # ページロード時に history から初期表示
372
+ demo.load(
373
+ fn=lambda: (
374
+ [(img_or_url, caption) for img_or_url, caption in history],
375
+ "".join(f'<div style="margin-bottom:12px">{make_html_table(caption)}</div>' for _, caption in history)
376
+ ),
377
+ inputs=[],
378
+ outputs=[history_gallery, history_tables]
379
+ )
380
 
381
  demo.queue()
382
  demo.launch()