huangdffs
/

huangdffs 8BitStudio commited on
Commit
74927f2
Β·
0 Parent(s):

Duplicate from 8BitStudio/Aniimage-2

Browse files

Co-authored-by: Jackson Yeskie <8BitStudio@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ collage.png filter=lfs diff=lfs merge=lfs -text
37
+ Softly[[:space:]]lit[[:space:]]forest[[:space:]]at[[:space:]]midday,[[:space:]]peaceful[[:space:]]atmosphere,[[:space:]]no[[:space:]]people.png filter=lfs diff=lfs merge=lfs -text
38
+ assets/an[[:space:]]anime[[:space:]]boy[[:space:]]with[[:space:]]black[[:space:]]hair[[:space:]]and[[:space:]]green[[:space:]]eyes filter=lfs diff=lfs merge=lfs -text
Aniimage_2_Interactive_Colab.ipynb ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Aniimage-2 Image generator\n",
8
+ "\n",
9
+ "This notebook runs [`8BitStudio/Aniimage-2`](https://huggingface.co/8BitStudio/Aniimage-2) with a Gradio interface. It manually assembles the repository's UNet with the matching VAE and CLIP text encoder because the repository is not packaged as a complete Diffusers pipeline.\n",
10
+ "\n",
11
+ "## Before running\n",
12
+ "\n",
13
+ "1. In Colab choose **Runtime β†’ Change runtime type β†’ T4 GPU** (or a better GPU).\n",
14
+ "2. Run every cell in order. The first model load downloads several gigabytes and can take a few minutes.\n",
15
+ "3. Open the Gradio link printed by the final cell. Generated images are also saved under `/content/aniimage2_outputs`.\n",
16
+ "\n",
17
+ "The defaults follow the model card: 512Γ—512, DPM++ SDE Karras, 50 steps, v-prediction, zero-terminal-SNR, CLIP penultimate layer, and CFG rescale 0.7. The default negative prompt includes `NSFW` because omitting it may produce NSFW images.\n",
18
+ "\n",
19
+ "If you want to generate NSFW images, remove the `NSFW` text in the negative prompt. \n",
20
+ "\n",
21
+ "If your results look \"glitched\", try lowering your CFG to around 7 or 6.5"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": null,
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "!pip -q install -U \"diffusers>=0.37.1\" \"transformers>=4.46,<5\" accelerate safetensors huggingface_hub \"gradio>=5,<7\" \"click>=8.2\" \"Pillow<11.0.0\""
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": null,
36
+ "metadata": {},
37
+ "outputs": [],
38
+ "source": [
39
+ "import json\n",
40
+ "import random\n",
41
+ "from pathlib import Path\n",
42
+ "\n",
43
+ "import gradio as gr\n",
44
+ "import numpy as np\n",
45
+ "import torch\n",
46
+ "from PIL import Image\n",
47
+ "from diffusers import (\n",
48
+ " AutoencoderKL,\n",
49
+ " DDIMScheduler,\n",
50
+ " DPMSolverMultistepScheduler,\n",
51
+ " EulerAncestralDiscreteScheduler,\n",
52
+ " EulerDiscreteScheduler,\n",
53
+ " UNet2DConditionModel,\n",
54
+ ")\n",
55
+ "from huggingface_hub import hf_hub_download\n",
56
+ "from transformers import CLIPTextModel, CLIPTokenizer\n",
57
+ "\n",
58
+ "REPO_ID = \"8BitStudio/Aniimage-2\"\n",
59
+ "CLIP_ID = \"openai/clip-vit-large-patch14\"\n",
60
+ "OUTPUT_DIR = Path(\"/content/aniimage2_outputs\")\n",
61
+ "OUTPUT_DIR.mkdir(parents=True, exist_ok=True)\n",
62
+ "\n",
63
+ "if not torch.cuda.is_available():\n",
64
+ " raise RuntimeError(\"No GPU detected. In Colab select Runtime > Change runtime type > T4 GPU, then run again.\")\n",
65
+ "\n",
66
+ "DEVICE = \"cuda\"\n",
67
+ "DTYPE = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16\n",
68
+ "torch.backends.cuda.matmul.allow_tf32 = True\n",
69
+ "torch.backends.cudnn.allow_tf32 = True\n",
70
+ "print(f\"GPU: {torch.cuda.get_device_name(0)}\")\n",
71
+ "print(f\"Model dtype: {DTYPE}\")\n"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "execution_count": null,
77
+ "metadata": {},
78
+ "outputs": [],
79
+ "source": [
80
+ "# Download the small model metadata first so every component matches training.\n",
81
+ "config_path = hf_hub_download(REPO_ID, \"model_config.json\")\n",
82
+ "with open(config_path, \"r\", encoding=\"utf-8\") as f:\n",
83
+ " MODEL_CONFIG = json.load(f)\n",
84
+ "\n",
85
+ "VAE_ID = MODEL_CONFIG[\"vae\"]\n",
86
+ "GUIDANCE_RESCALE = float(MODEL_CONFIG.get(\"guidance_rescale\", 0.7))\n",
87
+ "\n",
88
+ "print(\"Loading Aniimage-2 UNet...\")\n",
89
+ "unet = UNet2DConditionModel.from_pretrained(\n",
90
+ " REPO_ID,\n",
91
+ " torch_dtype=DTYPE,\n",
92
+ " low_cpu_mem_usage=True,\n",
93
+ ").to(DEVICE).eval()\n",
94
+ "unet.requires_grad_(False)\n",
95
+ "\n",
96
+ "print(f\"Loading VAE: {VAE_ID}...\")\n",
97
+ "vae = AutoencoderKL.from_pretrained(VAE_ID, torch_dtype=DTYPE).to(DEVICE).eval()\n",
98
+ "vae.requires_grad_(False)\n",
99
+ "vae.enable_slicing()\n",
100
+ "\n",
101
+ "print(f\"Loading text encoder: {CLIP_ID}...\")\n",
102
+ "tokenizer = CLIPTokenizer.from_pretrained(CLIP_ID)\n",
103
+ "text_encoder = CLIPTextModel.from_pretrained(CLIP_ID, torch_dtype=DTYPE).to(DEVICE).eval()\n",
104
+ "text_encoder.requires_grad_(False)\n",
105
+ "\n",
106
+ "# Aniimage-2 was trained using CLIP's penultimate transformer layer.\n",
107
+ "clip_inner = getattr(text_encoder, \"text_model\", text_encoder)\n",
108
+ "clip_inner.encoder.layers = torch.nn.ModuleList(list(clip_inner.encoder.layers[:-1]))\n",
109
+ "\n",
110
+ "print(\"Aniimage-2 is loaded and ready.\")\n"
111
+ ]
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "execution_count": null,
116
+ "metadata": {},
117
+ "outputs": [],
118
+ "source": [
119
+ "def make_scheduler(name):\n",
120
+ " base = dict(\n",
121
+ " num_train_timesteps=int(MODEL_CONFIG.get(\"num_train_timesteps\", 1000)),\n",
122
+ " beta_schedule=MODEL_CONFIG.get(\"beta_schedule\", \"scaled_linear\"),\n",
123
+ " prediction_type=MODEL_CONFIG.get(\"prediction_type\", \"v_prediction\"),\n",
124
+ " rescale_betas_zero_snr=bool(MODEL_CONFIG.get(\"zero_terminal_snr\", True)),\n",
125
+ " timestep_spacing=MODEL_CONFIG.get(\"timestep_spacing\", \"trailing\"),\n",
126
+ " )\n",
127
+ " if name == \"DPM++ SDE Karras\":\n",
128
+ " return DPMSolverMultistepScheduler(\n",
129
+ " **base, algorithm_type=\"sde-dpmsolver++\", solver_order=2, use_karras_sigmas=True\n",
130
+ " )\n",
131
+ " if name == \"DPM++ 2M Karras\":\n",
132
+ " return DPMSolverMultistepScheduler(\n",
133
+ " **base, algorithm_type=\"dpmsolver++\", solver_order=2, use_karras_sigmas=True\n",
134
+ " )\n",
135
+ " if name == \"Euler a\":\n",
136
+ " return EulerAncestralDiscreteScheduler(**base)\n",
137
+ " if name == \"Euler\":\n",
138
+ " return EulerDiscreteScheduler(**base)\n",
139
+ " if name == \"DDIM\":\n",
140
+ " return DDIMScheduler(**base, clip_sample=False, set_alpha_to_one=False)\n",
141
+ " raise ValueError(f\"Unknown scheduler: {name}\")\n",
142
+ "\n",
143
+ "\n",
144
+ "@torch.inference_mode()\n",
145
+ "def encode_prompts(prompt, negative_prompt):\n",
146
+ " tokens = tokenizer(\n",
147
+ " [negative_prompt or \"\", prompt],\n",
148
+ " padding=\"max_length\",\n",
149
+ " max_length=tokenizer.model_max_length,\n",
150
+ " truncation=True,\n",
151
+ " return_tensors=\"pt\",\n",
152
+ " )\n",
153
+ " return text_encoder(tokens.input_ids.to(DEVICE))[0]\n",
154
+ "\n",
155
+ "\n",
156
+ "def rescale_cfg(noise_cfg, noise_text, amount):\n",
157
+ " dims = tuple(range(1, noise_cfg.ndim))\n",
158
+ " std_text = noise_text.std(dim=dims, keepdim=True)\n",
159
+ " std_cfg = noise_cfg.std(dim=dims, keepdim=True).clamp_min(1e-6)\n",
160
+ " noise_rescaled = noise_cfg * (std_text / std_cfg)\n",
161
+ " return amount * noise_rescaled + (1.0 - amount) * noise_cfg\n",
162
+ "\n",
163
+ "\n",
164
+ "@torch.inference_mode()\n",
165
+ "def generate_one(prompt, negative_prompt, scheduler_name, steps, cfg_scale, seed):\n",
166
+ " scheduler = make_scheduler(scheduler_name)\n",
167
+ " scheduler.set_timesteps(int(steps), device=DEVICE)\n",
168
+ " embeddings = encode_prompts(prompt, negative_prompt)\n",
169
+ "\n",
170
+ " generator = torch.Generator(device=DEVICE).manual_seed(int(seed))\n",
171
+ " latent_size = int(MODEL_CONFIG.get(\"image_size\", 512)) // 8\n",
172
+ " latents = torch.randn(\n",
173
+ " (1, int(unet.config.in_channels), latent_size, latent_size),\n",
174
+ " generator=generator, device=DEVICE, dtype=torch.float32,\n",
175
+ " ) * scheduler.init_noise_sigma\n",
176
+ "\n",
177
+ " for timestep in scheduler.timesteps:\n",
178
+ " latent_input = torch.cat([latents, latents], dim=0)\n",
179
+ " latent_input = scheduler.scale_model_input(latent_input, timestep)\n",
180
+ " with torch.autocast(\"cuda\", dtype=DTYPE):\n",
181
+ " prediction = unet(latent_input, timestep, encoder_hidden_states=embeddings).sample\n",
182
+ " pred_negative, pred_text = prediction.chunk(2)\n",
183
+ " prediction = pred_negative + float(cfg_scale) * (pred_text - pred_negative)\n",
184
+ " prediction = rescale_cfg(prediction, pred_text, GUIDANCE_RESCALE)\n",
185
+ " latents = scheduler.step(prediction, timestep, latents).prev_sample\n",
186
+ "\n",
187
+ " scaled = (latents / vae.config.scaling_factor).to(dtype=DTYPE)\n",
188
+ " with torch.autocast(\"cuda\", dtype=DTYPE):\n",
189
+ " image = vae.decode(scaled).sample\n",
190
+ " image = (image.float() / 2 + 0.5).clamp(0, 1)\n",
191
+ " array = (image[0].permute(1, 2, 0).cpu().numpy() * 255).round().astype(np.uint8)\n",
192
+ " return Image.fromarray(array)\n",
193
+ "\n",
194
+ "\n",
195
+ "def generate_gallery(prompt, negative_prompt, scheduler_name, steps, cfg_scale, seed, randomize_seed, image_count, progress=gr.Progress()):\n",
196
+ " prompt = (prompt or \"\").strip()\n",
197
+ " if not prompt:\n",
198
+ " raise gr.Error(\"Enter a prompt first.\")\n",
199
+ "\n",
200
+ " count = int(image_count)\n",
201
+ " base_seed = random.randint(0, 2**31 - 1) if randomize_seed or int(seed) < 0 else int(seed)\n",
202
+ " images, records = [], []\n",
203
+ "\n",
204
+ " for index in range(count):\n",
205
+ " used_seed = (base_seed + index) % (2**31)\n",
206
+ " progress(index / count, desc=f\"Generating image {index + 1} of {count}\")\n",
207
+ " image = generate_one(prompt, negative_prompt, scheduler_name, steps, cfg_scale, used_seed)\n",
208
+ " path = OUTPUT_DIR / f\"aniimage2_{used_seed}.png\"\n",
209
+ " image.save(path)\n",
210
+ " images.append(image)\n",
211
+ " records.append(f\"- Seed `{used_seed}` β€” `{path}`\")\n",
212
+ "\n",
213
+ " progress(1.0, desc=\"Done\")\n",
214
+ " details = \"### Results\\n\" + \"\\n\".join(records)\n",
215
+ " return images, details, base_seed\n"
216
+ ]
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "execution_count": null,
221
+ "metadata": {},
222
+ "outputs": [],
223
+ "source": [
224
+ "DEFAULT_NEGATIVE = (\n",
225
+ " \"NSFW, low quality, ugly, blurry, distorted, deformed, bad anatomy, bad proportions, \"\n",
226
+ " \"extra limbs, missing limbs, watermark, text, signature, washed out, flat colors, \"\n",
227
+ " \"manga panel, disfigured, poorly drawn, jpeg artifacts, cropped, out of frame\"\n",
228
+ ")\n",
229
+ "\n",
230
+ "with gr.Blocks(title=\"Aniimage-2 Generator\", theme=gr.themes.Soft()) as demo:\n",
231
+ " gr.Markdown(\n",
232
+ " \"# Aniimage-2 Interactive Generator\\n\"\n",
233
+ " \"Use a short plain-English prompt for best results. Images are 512Γ—512.\"\n",
234
+ " )\n",
235
+ " with gr.Row():\n",
236
+ " with gr.Column(scale=2):\n",
237
+ " prompt = gr.Textbox(\n",
238
+ " label=\"Prompt\",\n",
239
+ " value=\"A smiling anime girl with red hair and a school uniform\",\n",
240
+ " lines=3,\n",
241
+ " )\n",
242
+ " negative = gr.Textbox(label=\"Negative prompt\", value=DEFAULT_NEGATIVE, lines=4)\n",
243
+ " generate_button = gr.Button(\"Generate\", variant=\"primary\")\n",
244
+ " with gr.Column(scale=1):\n",
245
+ " scheduler = gr.Dropdown(\n",
246
+ " [\"DPM++ SDE Karras\", \"DPM++ 2M Karras\", \"Euler a\", \"Euler\", \"DDIM\"],\n",
247
+ " value=\"DPM++ SDE Karras\", label=\"Scheduler\",\n",
248
+ " )\n",
249
+ " steps = gr.Slider(10, 80, value=50, step=1, label=\"Steps\")\n",
250
+ " cfg = gr.Slider(1.0, 15.0, value=7.5, step=0.1, label=\"CFG scale\")\n",
251
+ " seed = gr.Number(value=-1, precision=0, label=\"Seed (-1 = random)\")\n",
252
+ " randomize = gr.Checkbox(value=True, label=\"Randomize seed\")\n",
253
+ " count = gr.Slider(1, 4, value=1, step=1, label=\"Number of images\")\n",
254
+ "\n",
255
+ " gallery = gr.Gallery(label=\"Generated images\", columns=2, object_fit=\"contain\", height=620)\n",
256
+ " result_info = gr.Markdown()\n",
257
+ "\n",
258
+ " generate_button.click(\n",
259
+ " fn=generate_gallery,\n",
260
+ " inputs=[prompt, negative, scheduler, steps, cfg, seed, randomize, count],\n",
261
+ " outputs=[gallery, result_info, seed],\n",
262
+ " concurrency_limit=1,\n",
263
+ " )\n",
264
+ "\n",
265
+ "demo.queue(max_size=8)\n",
266
+ "print(\"Interface created. Run the final cell to launch it.\")\n"
267
+ ]
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "execution_count": null,
272
+ "metadata": {},
273
+ "outputs": [],
274
+ "source": [
275
+ "demo.launch(share=True, show_error=True)\n"
276
+ ]
277
+ }
278
+ ],
279
+ "metadata": {
280
+ "accelerator": "GPU",
281
+ "colab": {
282
+ "name": "Aniimage_2_Interactive_Colab.ipynb",
283
+ "provenance": []
284
+ },
285
+ "kernelspec": {
286
+ "display_name": "Python 3",
287
+ "name": "python3"
288
+ },
289
+ "language_info": {
290
+ "name": "python"
291
+ }
292
+ },
293
+ "nbformat": 4,
294
+ "nbformat_minor": 5
295
+ }
README.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ tags:
4
+ - anime
5
+ - diffusion
6
+ - text-to-image
7
+ - image-generation
8
+ library_name: diffusers
9
+ pipeline_tag: text-to-image
10
+ language:
11
+ - en
12
+ ---
13
+ ![Aniimage-2 Samples](https://huggingface.co/8BitStudio/Aniimage-2/resolve/main/assets/collage.png)
14
+
15
+ # Aniimage-2
16
+
17
+ Aniimage-2 is the second public model in the Aniimage series.
18
+ The model is a 512x512 anime image generation model trained from scratch using a UNet + VAE + CLIP architecture with 441.9 million parameters.
19
+ Aniimage-2 has been trained on 1.2M anime images from [Danbooru](https://danbooru.donmai.us/) and other sources.
20
+ It is not based on any existing models, the UNet is trained from scratch.
21
+
22
+ ## Model Details
23
+
24
+ | | |
25
+ |---|---|
26
+ | **Resolution** | 512x512 |
27
+ | **Architecture** | Latent Diffusion (UNet + VAE + CLIP) |
28
+ | **Parameters** | 441.9M |
29
+ | **Training Steps** | 70,000 |
30
+ | **Batch Size** | 64 |
31
+ | **Dataset** | ~1.2 million curated anime images from Danbooru |
32
+ | **GPU** | NVIDIA RTX 5060 Ti 16GB |
33
+ | **Scheduler** | DPM++ SDE |
34
+ | **Recommended steps** | 50|
35
+
36
+ ## Requirements
37
+
38
+ - **GPU**: ~6 GB VRAM minimum (recommend 8+ GB)
39
+ - **CPU**: ~7 GB RAM. Image generation is extremely slow on CPU. (recommend 10+ GB)
40
+
41
+ ## Prompting
42
+
43
+ Aniimage uses plain text captions as well as Danbooru tags.
44
+
45
+ An example of acceptable captions:
46
+
47
+ "A smiling anime girl with red hair and a school uniform"
48
+
49
+ "1girl, solo, smile, red_hair, school_uniform, anime_coloring"
50
+
51
+ Long prompts and enhanced prompts usually result in worse overall results. Try to keep your prompts short.
52
+
53
+ Although you can use Danbooru tags, you will get the best results with plain text captions
54
+
55
+ Adding a negative prompt is required for a good output. The one used during inference in the preview image is:
56
+
57
+ "low quality, ugly, blurry, distorted, deformed, bad anatomy, bad proportions, extra limbs, missing limbs, watermark, text, signature, washed out, flat colors, manga panel, disfigured, poorly drawn, jpeg artifacts, cropped, out of frame"
58
+
59
+
60
+ For the best quality, use DPM++ SDE at 50 steps.
61
+
62
+
63
+ ## Run
64
+
65
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/#fileId=https://huggingface.co/8BitStudio/Aniimage-2/blob/main/Aniimage_2_Interactive_Colab.ipynb)
66
+
67
+ [![Download Generator](https://img.shields.io/badge/Download-generate__images.py-blue?style=for-the-badge)](https://huggingface.co/8BitStudio/Aniimage-2/resolve/main/generate_images.py)
68
+
69
+ After downloading, install the dependencies.
70
+
71
+ ```bash
72
+ pip install torch torchvision diffusers transformers safetensors pillow huggingface_hub
73
+ python generate_images.py
74
+ ```
75
+
76
+ ## Capabilities
77
+
78
+ Aniimage-2 has significantly higher capabilities than [Aniimage-1](https://huggingface.co/8BitStudio/Aniimage-1). Especially when it comes to backgrounds.
79
+
80
+ <table width="700">
81
+ <tr>
82
+ <td colspan="2">
83
+ <img
84
+ src="https://huggingface.co/8BitStudio/Aniimage-2/resolve/main/assets/Softly%20lit%20forest%20at%20midday%2C%20peaceful%20atmosphere%2C%20no%20people.png"
85
+ width="700"
86
+ alt="Forest comparison between Aniimage-1 and Aniimage-2"
87
+ >
88
+ </td>
89
+ </tr>
90
+
91
+ <tr>
92
+ <td align="center" width="50%">
93
+ <b>Aniimage-1</b>
94
+ </td>
95
+ <td align="center" width="50%">
96
+ <b>Aniimage-2</b>
97
+ </td>
98
+ </tr>
99
+
100
+ <tr>
101
+ <td colspan="2">
102
+ <sub>Prompt: Softly lit forest at midday, peaceful atmosphere, no people.</sub>
103
+ </td>
104
+ </tr>
105
+ </table>
106
+
107
+ <table width="700">
108
+ <tr>
109
+ <td colspan="2">
110
+ <img
111
+ src="https://huggingface.co/8BitStudio/Aniimage-2/resolve/main/assets/anime-boy.png"
112
+ width="700"
113
+ alt="Anime boy comparison between Aniimage-1 and Aniimage-2"
114
+ >
115
+ </td>
116
+ </tr>
117
+
118
+ <tr>
119
+ <td align="center" width="50%">
120
+ <b>Aniimage-1</b>
121
+ </td>
122
+ <td align="center" width="50%">
123
+ <b>Aniimage-2</b>
124
+ </td>
125
+ </tr>
126
+
127
+ Aniimage-2 produces male characters much more reliably than Aniimage-1.
128
+
129
+ <tr>
130
+ <td colspan="2">
131
+ <sub>Prompt: An anime boy with black hair and green eyes.</sub>
132
+ </td>
133
+ </tr>
134
+ </table>
135
+
136
+ ## Limitations
137
+
138
+ Aniimage-2 is bad at generating hands. It may generate hands but they often melt into surfaces if they are similar colors and usually have more or fewer than five fingers.
139
+ The model generates male characters less reliably than female characters, it may take many images to find a good image like above.
140
+
141
+ ## License
142
+
143
+ Apache 2.0
assets/Softly lit forest at midday, peaceful atmosphere, no people.png ADDED

Git LFS Details

  • SHA256: e76663107df2dbe276b82627f05ae6cfc18afa2d55ed9229f5eaa650286295e8
  • Pointer size: 132 Bytes
  • Size of remote file: 2.08 MB
assets/anime-boy.png ADDED

Git LFS Details

  • SHA256: 3dc119438b26bc84e22f360b1f184e45d578bcf76cfa1cb1c1fefe5a0c80cbeb
  • Pointer size: 132 Bytes
  • Size of remote file: 1.51 MB
assets/collage.png ADDED

Git LFS Details

  • SHA256: 6c1de508e7a0fa96b1e8412d39f193121482428da53e40d02bd9e22d81677dec
  • Pointer size: 132 Bytes
  • Size of remote file: 5.73 MB
config.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "UNet2DConditionModel",
3
+ "_diffusers_version": "0.37.1",
4
+ "act_fn": "silu",
5
+ "addition_embed_type": null,
6
+ "addition_embed_type_num_heads": 64,
7
+ "addition_time_embed_dim": null,
8
+ "attention_head_dim": 8,
9
+ "attention_type": "default",
10
+ "block_out_channels": [
11
+ 256,
12
+ 512,
13
+ 768,
14
+ 1024
15
+ ],
16
+ "center_input_sample": false,
17
+ "class_embed_type": null,
18
+ "class_embeddings_concat": false,
19
+ "conv_in_kernel": 3,
20
+ "conv_out_kernel": 3,
21
+ "cross_attention_dim": 768,
22
+ "cross_attention_norm": null,
23
+ "down_block_types": [
24
+ "CrossAttnDownBlock2D",
25
+ "CrossAttnDownBlock2D",
26
+ "CrossAttnDownBlock2D",
27
+ "DownBlock2D"
28
+ ],
29
+ "downsample_padding": 1,
30
+ "dropout": 0.0,
31
+ "dual_cross_attention": false,
32
+ "encoder_hid_dim": null,
33
+ "encoder_hid_dim_type": null,
34
+ "flip_sin_to_cos": true,
35
+ "freq_shift": 0,
36
+ "in_channels": 4,
37
+ "layers_per_block": 2,
38
+ "mid_block_only_cross_attention": null,
39
+ "mid_block_scale_factor": 1,
40
+ "mid_block_type": "UNetMidBlock2DCrossAttn",
41
+ "norm_eps": 1e-05,
42
+ "norm_num_groups": 32,
43
+ "num_attention_heads": null,
44
+ "num_class_embeds": null,
45
+ "only_cross_attention": false,
46
+ "out_channels": 4,
47
+ "projection_class_embeddings_input_dim": null,
48
+ "resnet_out_scale_factor": 1.0,
49
+ "resnet_skip_time_act": false,
50
+ "resnet_time_scale_shift": "default",
51
+ "reverse_transformer_layers_per_block": null,
52
+ "sample_size": 64,
53
+ "time_cond_proj_dim": null,
54
+ "time_embedding_act_fn": null,
55
+ "time_embedding_dim": null,
56
+ "time_embedding_type": "positional",
57
+ "timestep_post_act": null,
58
+ "transformer_layers_per_block": 1,
59
+ "up_block_types": [
60
+ "UpBlock2D",
61
+ "CrossAttnUpBlock2D",
62
+ "CrossAttnUpBlock2D",
63
+ "CrossAttnUpBlock2D"
64
+ ],
65
+ "upcast_attention": false,
66
+ "use_linear_projection": false
67
+ }
diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c298c8d61a380e4941d02372bf2e7de27de15ecd28c2236cd005c59c598105a4
3
+ size 1767752200
generate_images.py ADDED
@@ -0,0 +1,1460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Aniimage Generator β€” Generate anime images from text prompts.
3
+ https://huggingface.co/8BitStudio/Aniimage-2
4
+
5
+ Usage:
6
+ pip install -U torch torchvision "diffusers>=0.37.1" "transformers>=4.46,<5" accelerate safetensors pillow huggingface_hub
7
+ python generate_images.py
8
+ """
9
+
10
+ import os
11
+ import sys
12
+ import gc
13
+ import json
14
+ import torch
15
+ import numpy as np
16
+ import tkinter as tk
17
+ from tkinter import ttk, simpledialog
18
+ from pathlib import Path
19
+ from PIL import Image, ImageTk
20
+ from threading import Thread
21
+
22
+ # ── Paths ─────────────────────────────────────────────────────────────────────
23
+ SCRIPT_DIR = Path(__file__).resolve().parent
24
+ MODEL_DIR = SCRIPT_DIR / "models"
25
+ OUTPUT_DIR = SCRIPT_DIR / "generated"
26
+
27
+ # ── HuggingFace repo ─────────────────────────────────────────────────────────
28
+ HF_REPO_ID = "8BitStudio/Aniimage-2"
29
+
30
+ # ── Aniimage-2 training configuration fallback ────────────────────────────────
31
+ # The downloaded model_config.json is preferred. These values mirror it so the
32
+ # launcher still behaves correctly if only the UNet files were copied locally.
33
+ UNET_CONFIG = dict(
34
+ sample_size=64,
35
+ in_channels=4,
36
+ out_channels=4,
37
+ block_out_channels=(256, 512, 768, 1024),
38
+ layers_per_block=2,
39
+ cross_attention_dim=768,
40
+ attention_head_dim=8,
41
+ down_block_types=("CrossAttnDownBlock2D", "CrossAttnDownBlock2D",
42
+ "CrossAttnDownBlock2D", "DownBlock2D"),
43
+ up_block_types=("UpBlock2D", "CrossAttnUpBlock2D",
44
+ "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
45
+ )
46
+
47
+ # Aniimage-2 was trained with this VAE, not the SD 1.x MSE VAE.
48
+ VAE_ID = "madebyollin/sdxl-vae-fp16-fix"
49
+ CLIP_ID = "openai/clip-vit-large-patch14"
50
+
51
+ SCHEDULER_LIST = [
52
+ "DPM++ 2M Karras",
53
+ "DPM++ SDE Karras",
54
+ "Euler a",
55
+ "Euler",
56
+ "DDIM",
57
+ ]
58
+
59
+ DEFAULT_NEGATIVE = (
60
+ "low quality, ugly, blurry, distorted, deformed, bad anatomy, "
61
+ "bad proportions, extra limbs, missing limbs, watermark, text, "
62
+ "signature, washed out, flat colors, manga panel, disfigured, "
63
+ "poorly drawn, jpeg artifacts, cropped, out of frame"
64
+ )
65
+
66
+
67
+ # ── Model discovery ───────────────────────────────────────────────────────────
68
+
69
+ def _read_json(path: Path):
70
+ """Read a JSON file, returning an empty dict when it is unusable."""
71
+ try:
72
+ data = json.loads(path.read_text(encoding="utf-8"))
73
+ return data if isinstance(data, dict) else {}
74
+ except (OSError, ValueError, TypeError):
75
+ return {}
76
+
77
+
78
+ def _looks_like_unet_config(config: dict) -> bool:
79
+ """Return True when a config contains the core Diffusers UNet fields."""
80
+ required = {
81
+ "in_channels", "out_channels", "block_out_channels",
82
+ "down_block_types", "up_block_types",
83
+ }
84
+ return required.issubset(config)
85
+
86
+
87
+ def _find_model_config(model_dir: Path):
88
+ """Find the Aniimage model_config.json that describes training settings."""
89
+ if not model_dir.exists():
90
+ return None
91
+ candidates = [
92
+ p for p in model_dir.rglob("model_config.json")
93
+ if p.is_file() and ".cache" not in p.parts
94
+ ]
95
+ for path in sorted(candidates, key=lambda p: (len(p.relative_to(model_dir).parts), str(p))):
96
+ config = _read_json(path)
97
+ if isinstance(config.get("unet"), dict):
98
+ return path
99
+ return None
100
+
101
+
102
+ def _find_unet_assets(model_dir: Path):
103
+ """Find Aniimage UNet weights/config, including nested repo folders.
104
+
105
+ Aniimage-2 has been published with an extra ``Aniimage-2/unet`` directory
106
+ inside the repository snapshot. Searching recursively keeps the launcher
107
+ compatible with that layout as well as normal Diffusers layouts.
108
+ """
109
+ if not model_dir.exists():
110
+ return None
111
+
112
+ # Prefer the canonical single-file names, but accept fp16/variant names.
113
+ weight_candidates = []
114
+ for pattern in (
115
+ "diffusion_pytorch_model.safetensors",
116
+ "diffusion_pytorch_model.bin",
117
+ "diffusion_pytorch_model*.safetensors",
118
+ "diffusion_pytorch_model*.bin",
119
+ ):
120
+ weight_candidates.extend(model_dir.rglob(pattern))
121
+
122
+ # Remove duplicates, metadata files, and anything under the HF cache.
123
+ unique_weights = []
124
+ seen = set()
125
+ for path in weight_candidates:
126
+ if not path.is_file() or path.name.endswith(".index.json"):
127
+ continue
128
+ if ".cache" in path.parts:
129
+ continue
130
+ key = str(path.resolve())
131
+ if key not in seen:
132
+ seen.add(key)
133
+ unique_weights.append(path)
134
+
135
+ if unique_weights:
136
+ # Exact canonical filenames first, then the shallowest path.
137
+ def weight_rank(path: Path):
138
+ exact = path.name in {
139
+ "diffusion_pytorch_model.safetensors",
140
+ "diffusion_pytorch_model.bin",
141
+ }
142
+ safe = path.suffix.lower() == ".safetensors"
143
+ return (not exact, not safe, len(path.relative_to(model_dir).parts), str(path))
144
+
145
+ weights_path = sorted(unique_weights, key=weight_rank)[0]
146
+
147
+ # Search from the weights folder upward, then across the model root.
148
+ config_candidates = []
149
+ current = weights_path.parent
150
+ while True:
151
+ config_candidates.extend((current / "config.json", current / "model_config.json"))
152
+ if current == model_dir or model_dir not in current.parents:
153
+ break
154
+ current = current.parent
155
+ config_candidates.extend(model_dir.rglob("config.json"))
156
+ config_candidates.extend(model_dir.rglob("model_config.json"))
157
+
158
+ config_path = None
159
+ seen_configs = set()
160
+ for candidate in config_candidates:
161
+ if not candidate.is_file() or ".cache" in candidate.parts:
162
+ continue
163
+ key = str(candidate.resolve())
164
+ if key in seen_configs:
165
+ continue
166
+ seen_configs.add(key)
167
+ if _looks_like_unet_config(_read_json(candidate)):
168
+ config_path = candidate
169
+ break
170
+
171
+ return {
172
+ "kind": "diffusers_weights",
173
+ "weights": weights_path,
174
+ "config": config_path,
175
+ }
176
+
177
+ # Older local checkpoints are still supported.
178
+ for filename in ("ema_unet.pt", "unet.pt"):
179
+ candidates = [p for p in model_dir.rglob(filename)
180
+ if p.is_file() and ".cache" not in p.parts]
181
+ if candidates:
182
+ checkpoint = sorted(
183
+ candidates,
184
+ key=lambda p: (len(p.relative_to(model_dir).parts), str(p)),
185
+ )[0]
186
+ return {
187
+ "kind": "checkpoint",
188
+ "weights": checkpoint,
189
+ "config": None,
190
+ }
191
+
192
+ return None
193
+
194
+
195
+ def _detect_model_resolution(model_dir: Path) -> str:
196
+ """Infer output resolution from model metadata or the UNet config."""
197
+ model_config_path = _find_model_config(model_dir)
198
+ if model_config_path:
199
+ image_size = _read_json(model_config_path).get("image_size")
200
+ if isinstance(image_size, int) and image_size > 0:
201
+ return str(image_size)
202
+
203
+ assets = _find_unet_assets(model_dir)
204
+ config_path = assets.get("config") if assets else None
205
+ if config_path:
206
+ config = _read_json(config_path)
207
+ sample_size = config.get("sample_size")
208
+ if isinstance(sample_size, (list, tuple)) and sample_size:
209
+ sample_size = sample_size[0]
210
+ if isinstance(sample_size, int) and sample_size > 0:
211
+ return str(sample_size * 8)
212
+
213
+ return "512" if "aniimage-2" in model_dir.name.lower() else "256"
214
+
215
+
216
+ def download_from_hf():
217
+ """Download Aniimage-2 from Hugging Face if it is not already present."""
218
+ try:
219
+ from huggingface_hub import snapshot_download
220
+ except ImportError:
221
+ print("Install huggingface_hub: pip install huggingface_hub")
222
+ return None
223
+
224
+ MODEL_DIR.mkdir(parents=True, exist_ok=True)
225
+ aniimage_dir = MODEL_DIR / "Aniimage-2"
226
+
227
+ existing = _find_unet_assets(aniimage_dir)
228
+ existing_config = _find_model_config(aniimage_dir)
229
+ if existing and existing_config:
230
+ print(f"Aniimage-2 weights already downloaded: {existing['weights']}")
231
+ return aniimage_dir
232
+
233
+ print(f"Downloading Aniimage-2 from {HF_REPO_ID}...")
234
+ aniimage_dir.mkdir(parents=True, exist_ok=True)
235
+
236
+ try:
237
+ snapshot_download(
238
+ repo_id=HF_REPO_ID,
239
+ local_dir=aniimage_dir,
240
+ allow_patterns=[
241
+ "model_config.json",
242
+ "config.json",
243
+ "diffusion_pytorch_model.safetensors",
244
+ ],
245
+ )
246
+ except Exception as exc:
247
+ print(f"Aniimage-2 download failed: {exc}")
248
+ return None
249
+
250
+ assets = _find_unet_assets(aniimage_dir)
251
+ if not assets:
252
+ print(
253
+ "Aniimage-2 repository downloaded, but no supported UNet weights "
254
+ "were found anywhere below:\n"
255
+ f" {aniimage_dir}\n"
256
+ "Expected diffusion_pytorch_model.safetensors or "
257
+ "diffusion_pytorch_model.bin."
258
+ )
259
+ return None
260
+
261
+ print(f"Download complete! Found weights at: {assets['weights']}")
262
+ return aniimage_dir
263
+
264
+
265
+ def find_models():
266
+ """Find models, including checkpoints nested inside repository folders."""
267
+ options = []
268
+ if MODEL_DIR.exists():
269
+ for d in sorted(MODEL_DIR.iterdir()):
270
+ if not d.is_dir():
271
+ continue
272
+ assets = _find_unet_assets(d)
273
+ if not assets:
274
+ continue
275
+ resolution = _detect_model_resolution(d)
276
+ model_kind = (
277
+ "safetensors"
278
+ if assets["weights"].suffix.lower() == ".safetensors"
279
+ else assets["kind"]
280
+ )
281
+ options.append((model_kind, d.name, d, resolution))
282
+ return options
283
+
284
+
285
+ # ── Theme ─────────────────────────────────────────────────────────────────────
286
+
287
+ C = {
288
+ "bg": "#111119",
289
+ "panel": "#1b1b2f",
290
+ "card": "#24243e",
291
+ "card_sel": "#3a3a6e",
292
+ "border": "#2e2e52",
293
+ "accent": "#6c5ce7",
294
+ "accent_h": "#8577ed",
295
+ "red": "#e74c3c",
296
+ "green": "#2ecc71",
297
+ "text": "#eaeaea",
298
+ "text2": "#a0a0b8",
299
+ "text3": "#60607a",
300
+ "input": "#16162a",
301
+ "input_fg": "#dcdcf0",
302
+ }
303
+
304
+
305
+ class Generator:
306
+ def __init__(self, device="cuda"):
307
+ self.device = device if device == "cuda" and torch.cuda.is_available() else "cpu"
308
+ self.dtype = self._select_dtype()
309
+ self.vae = None
310
+ self.text_encoder = None
311
+ self.tokenizer = None
312
+ self.unet = None
313
+ self.scheduler = None
314
+ self.loaded_checkpoint = None
315
+ self.loaded_vae_id = None
316
+ self.model_config = {}
317
+ self._clip_inner = None
318
+ self._clip_full_layers = None
319
+ self.latent_size = 64
320
+ self.output_size = 512
321
+ self.prediction_type = "v_prediction"
322
+ self.zero_terminal_snr = True
323
+ self.timestep_spacing = "trailing"
324
+ self.guidance_rescale = 0.7
325
+ self.num_train_timesteps = 1000
326
+ self.beta_schedule = "scaled_linear"
327
+ self.clip_penultimate = True
328
+ self.vae_id = VAE_ID
329
+ self.scheduler_name = "DPM++ SDE Karras"
330
+ self.cancelled = False
331
+ self._configure_backends()
332
+
333
+ def _select_dtype(self):
334
+ if self.device != "cuda":
335
+ return torch.float32
336
+ bf16_supported = getattr(torch.cuda, "is_bf16_supported", lambda: False)()
337
+ return torch.bfloat16 if bf16_supported else torch.float16
338
+
339
+ def _configure_backends(self):
340
+ if self.device == "cuda":
341
+ torch.backends.cudnn.benchmark = True
342
+ torch.backends.cuda.matmul.allow_tf32 = True
343
+ torch.backends.cudnn.allow_tf32 = True
344
+ if hasattr(torch, "set_float32_matmul_precision"):
345
+ torch.set_float32_matmul_precision("high")
346
+
347
+ def _autocast(self):
348
+ return torch.autocast(
349
+ device_type="cuda",
350
+ dtype=self.dtype,
351
+ enabled=(self.device == "cuda"),
352
+ )
353
+
354
+ def switch_device(self, new_device):
355
+ """Switch device and rebuild the models in the correct precision."""
356
+ new_device = new_device if new_device == "cuda" and torch.cuda.is_available() else "cpu"
357
+ if new_device == self.device:
358
+ return
359
+ self.device = new_device
360
+ self.dtype = self._select_dtype()
361
+ self._configure_backends()
362
+ self.vae = None
363
+ self.text_encoder = None
364
+ self.tokenizer = None
365
+ self.unet = None
366
+ self.scheduler = None
367
+ self.loaded_checkpoint = None
368
+ self.loaded_vae_id = None
369
+ self._clip_inner = None
370
+ self._clip_full_layers = None
371
+ gc.collect()
372
+ if torch.cuda.is_available():
373
+ torch.cuda.empty_cache()
374
+ print(f"Switched to {self.device.upper()} ({self.dtype})")
375
+
376
+ def _load_model_metadata(self, model_path: Path, res_label: str):
377
+ """Load the exact training objective and component IDs for Aniimage-2."""
378
+ config_path = _find_model_config(model_path)
379
+ config = _read_json(config_path) if config_path else {}
380
+ self.model_config = config
381
+
382
+ self.prediction_type = config.get("prediction_type", "v_prediction")
383
+ self.zero_terminal_snr = bool(config.get("zero_terminal_snr", True))
384
+ self.timestep_spacing = config.get(
385
+ "timestep_spacing",
386
+ "trailing" if self.zero_terminal_snr else "leading",
387
+ )
388
+ self.guidance_rescale = float(config.get("guidance_rescale", 0.7))
389
+ self.num_train_timesteps = int(config.get("num_train_timesteps", 1000))
390
+ self.beta_schedule = config.get("beta_schedule", "scaled_linear")
391
+ self.clip_penultimate = bool(config.get("clip_penultimate", True))
392
+ self.vae_id = config.get("vae", VAE_ID)
393
+
394
+ try:
395
+ fallback_size = int(res_label)
396
+ except (TypeError, ValueError):
397
+ fallback_size = 512
398
+ self.output_size = int(config.get("image_size", fallback_size))
399
+ self.latent_size = self.output_size // 8
400
+
401
+ if config_path:
402
+ print(f"Using model metadata: {config_path}")
403
+ else:
404
+ print("model_config.json was not found; using Aniimage-2 defaults.")
405
+
406
+ def _apply_clip_layer_mode(self):
407
+ if self.text_encoder is None:
408
+ return
409
+ self._clip_inner = getattr(self.text_encoder, "text_model", self.text_encoder)
410
+ if self._clip_full_layers is None:
411
+ self._clip_full_layers = self._clip_inner.encoder.layers
412
+ if self.clip_penultimate:
413
+ self._clip_inner.encoder.layers = self._clip_full_layers[:-1]
414
+ print("Text encoder: CLIP penultimate layer (matches training).")
415
+ else:
416
+ self._clip_inner.encoder.layers = self._clip_full_layers
417
+
418
+ def load_shared(self):
419
+ from diffusers import AutoencoderKL
420
+ from transformers import (CLIPConfig, CLIPTextConfig,
421
+ CLIPTextModel, CLIPTokenizer)
422
+
423
+ load_kwargs = {"low_cpu_mem_usage": True}
424
+ if self.device == "cuda":
425
+ load_kwargs["torch_dtype"] = self.dtype
426
+
427
+ if self.vae is None or self.loaded_vae_id != self.vae_id:
428
+ print(f"Loading VAE: {self.vae_id}...")
429
+ self.vae = AutoencoderKL.from_pretrained(
430
+ self.vae_id,
431
+ **load_kwargs,
432
+ ).to(self.device).eval()
433
+ self.vae.requires_grad_(False)
434
+ self.vae.enable_slicing()
435
+ if self.device == "cuda":
436
+ self.vae.to(memory_format=torch.channels_last)
437
+ self.loaded_vae_id = self.vae_id
438
+
439
+ if self.text_encoder is None:
440
+ print(f"Loading CLIP text encoder: {CLIP_ID}...")
441
+ self.tokenizer = CLIPTokenizer.from_pretrained(CLIP_ID)
442
+
443
+ # Explicitly pass the nested text config. This avoids the
444
+ # CLIPConfig.hidden_size crash seen with some Transformers builds.
445
+ clip_config = CLIPConfig.from_pretrained(CLIP_ID)
446
+ text_config = getattr(clip_config, "text_config", None)
447
+ if isinstance(text_config, dict):
448
+ text_config = CLIPTextConfig.from_dict(text_config)
449
+ if not isinstance(text_config, CLIPTextConfig):
450
+ text_config = CLIPTextConfig.from_pretrained(CLIP_ID)
451
+
452
+ self.text_encoder = CLIPTextModel.from_pretrained(
453
+ CLIP_ID,
454
+ config=text_config,
455
+ **load_kwargs,
456
+ ).to(self.device).eval()
457
+ self.text_encoder.requires_grad_(False)
458
+ self._clip_full_layers = None
459
+
460
+ self._apply_clip_layer_mode()
461
+ self.scheduler = self._make_scheduler(self.scheduler_name)
462
+ print("Shared models loaded.")
463
+
464
+ def _make_scheduler(self, name="DPM++ SDE Karras"):
465
+ from diffusers import (DDIMScheduler, DPMSolverMultistepScheduler,
466
+ EulerAncestralDiscreteScheduler,
467
+ EulerDiscreteScheduler)
468
+ base = dict(
469
+ num_train_timesteps=self.num_train_timesteps,
470
+ beta_schedule=self.beta_schedule,
471
+ prediction_type=self.prediction_type,
472
+ rescale_betas_zero_snr=self.zero_terminal_snr,
473
+ timestep_spacing=self.timestep_spacing,
474
+ )
475
+ if name == "DPM++ 2M Karras":
476
+ return DPMSolverMultistepScheduler(
477
+ **base, algorithm_type="dpmsolver++",
478
+ solver_order=2, use_karras_sigmas=True)
479
+ if name == "DPM++ SDE Karras":
480
+ return DPMSolverMultistepScheduler(
481
+ **base, algorithm_type="sde-dpmsolver++",
482
+ solver_order=2, use_karras_sigmas=True)
483
+ if name == "Euler a":
484
+ return EulerAncestralDiscreteScheduler(**base)
485
+ if name == "Euler":
486
+ return EulerDiscreteScheduler(**base)
487
+ return DDIMScheduler(
488
+ **base, clip_sample=False, set_alpha_to_one=False)
489
+
490
+ def set_scheduler(self, name):
491
+ self.scheduler_name = name
492
+ self.scheduler = self._make_scheduler(name)
493
+
494
+ def load_model(self, model_path: Path, res_label: str = "512"):
495
+ if str(model_path) == self.loaded_checkpoint:
496
+ return
497
+ from diffusers import UNet2DConditionModel
498
+
499
+ assets = _find_unet_assets(model_path)
500
+ if not assets:
501
+ raise FileNotFoundError(
502
+ f"No supported UNet weights found anywhere inside {model_path}"
503
+ )
504
+
505
+ self._load_model_metadata(model_path, res_label)
506
+ self.load_shared()
507
+
508
+ weights_path = assets["weights"]
509
+ config_path = assets.get("config")
510
+ suffix = weights_path.suffix.lower()
511
+ same_dir_config = weights_path.parent / "config.json"
512
+
513
+ print(
514
+ f"Loading UNet from {weights_path} "
515
+ f"({self.output_size}px, {self.prediction_type}, {self.dtype})..."
516
+ )
517
+
518
+ self.unet = None
519
+ if torch.cuda.is_available():
520
+ torch.cuda.empty_cache()
521
+
522
+ loaded_directly = False
523
+ if same_dir_config.exists() and _looks_like_unet_config(_read_json(same_dir_config)):
524
+ try:
525
+ kwargs = {"low_cpu_mem_usage": True}
526
+ if self.device == "cuda":
527
+ kwargs["torch_dtype"] = self.dtype
528
+ if suffix == ".safetensors":
529
+ kwargs["use_safetensors"] = True
530
+ elif suffix == ".bin":
531
+ kwargs["use_safetensors"] = False
532
+ self.unet = UNet2DConditionModel.from_pretrained(
533
+ weights_path.parent,
534
+ **kwargs,
535
+ ).to(self.device)
536
+ loaded_directly = True
537
+ print("Loaded the repository UNet config and weights directly.")
538
+ except Exception as exc:
539
+ print(f"Direct Diffusers load failed ({exc}); loading manually.")
540
+
541
+ if not loaded_directly:
542
+ if config_path:
543
+ unet_config = _read_json(config_path)
544
+ print(f"Using UNet config: {config_path}")
545
+ elif isinstance(self.model_config.get("unet"), dict):
546
+ unet_config = dict(self.model_config["unet"])
547
+ print("Using UNet config from model_config.json.")
548
+ else:
549
+ unet_config = dict(UNET_CONFIG)
550
+ print("Using built-in Aniimage-2 UNet config.")
551
+ unet_config["sample_size"] = self.latent_size
552
+ self.unet = UNet2DConditionModel.from_config(unet_config)
553
+
554
+ if suffix == ".safetensors":
555
+ from safetensors.torch import load_file
556
+ state = load_file(str(weights_path), device="cpu")
557
+ else:
558
+ try:
559
+ state = torch.load(weights_path, map_location="cpu", weights_only=True)
560
+ except TypeError:
561
+ state = torch.load(weights_path, map_location="cpu")
562
+
563
+ if weights_path.name == "ema_unet.pt" and isinstance(state, dict) and "shadow_params" in state:
564
+ params = dict(self.unet.named_parameters())
565
+ keys = list(params.keys())
566
+ if len(state["shadow_params"]) != len(keys):
567
+ raise RuntimeError("EMA parameter count does not match the UNet.")
568
+ for key, shadow_param in zip(keys, state["shadow_params"]):
569
+ params[key].data.copy_(shadow_param)
570
+ else:
571
+ if isinstance(state, dict) and "state_dict" in state:
572
+ state = state["state_dict"]
573
+ if isinstance(state, dict) and state and all(
574
+ isinstance(key, str) and key.startswith("module.") for key in state
575
+ ):
576
+ state = {key[7:]: value for key, value in state.items()}
577
+ self.unet.load_state_dict(state, strict=True)
578
+
579
+ if self.device == "cuda":
580
+ self.unet = self.unet.to(device=self.device, dtype=self.dtype)
581
+ else:
582
+ self.unet = self.unet.to(self.device)
583
+
584
+ sample_size = self.unet.config.sample_size
585
+ if isinstance(sample_size, (list, tuple)) and sample_size:
586
+ sample_size = sample_size[0]
587
+ if isinstance(sample_size, int) and sample_size > 0:
588
+ self.latent_size = sample_size
589
+ vae_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
590
+ self.output_size = sample_size * vae_factor
591
+
592
+ self.unet.eval().requires_grad_(False)
593
+ if self.device == "cuda":
594
+ self.unet.to(memory_format=torch.channels_last)
595
+ self.scheduler = self._make_scheduler(self.scheduler_name)
596
+ self.loaded_checkpoint = str(model_path)
597
+ print(
598
+ f"Ready at {self.output_size}x{self.output_size}; "
599
+ f"zero-SNR={self.zero_terminal_snr}, spacing={self.timestep_spacing}, "
600
+ f"CFG rescale={self.guidance_rescale}."
601
+ )
602
+
603
+ def _encode_prompts(self, prompt: str, negative_prompt: str):
604
+ tokens = self.tokenizer(
605
+ [negative_prompt or "", prompt],
606
+ padding="max_length",
607
+ max_length=self.tokenizer.model_max_length,
608
+ truncation=True,
609
+ return_tensors="pt",
610
+ )
611
+ with self._autocast():
612
+ return self.text_encoder(tokens.input_ids.to(self.device))[0]
613
+
614
+ @staticmethod
615
+ def _cfg_rescale(noise_cfg, noise_text, amount):
616
+ if amount <= 0:
617
+ return noise_cfg
618
+ dims = tuple(range(1, noise_cfg.ndim))
619
+ std_text = noise_text.std(dim=dims, keepdim=True)
620
+ std_cfg = noise_cfg.std(dim=dims, keepdim=True).clamp_min(1e-6)
621
+ noise_rescaled = noise_cfg * (std_text / std_cfg)
622
+ return amount * noise_rescaled + (1.0 - amount) * noise_cfg
623
+
624
+ def _decode_latents(self, latents, post_process=False):
625
+ del post_process # Kept for compatibility with the preview callbacks.
626
+ decode_dtype = self.dtype if self.device == "cuda" else torch.float32
627
+ scaled = (latents / self.vae.config.scaling_factor).to(dtype=decode_dtype)
628
+ with self._autocast():
629
+ image = self.vae.decode(scaled).sample
630
+ image = (image.float() / 2 + 0.5).clamp(0, 1)
631
+ image = image[0].cpu().permute(1, 2, 0).numpy()
632
+ image = (image * 255).round().astype("uint8")
633
+ return Image.fromarray(image)
634
+
635
+ @torch.inference_mode()
636
+ def generate(self, prompt: str, negative_prompt: str = "",
637
+ steps: int = 50, guidance_scale: float = 7.5,
638
+ seed: int = -1, preview_callback=None,
639
+ preview_every: int = 5) -> tuple:
640
+
641
+ if seed < 0:
642
+ seed = torch.randint(0, 2**32, (1,)).item()
643
+ generator = torch.Generator(device=self.device).manual_seed(seed)
644
+ embeddings = self._encode_prompts(prompt, negative_prompt)
645
+
646
+ scheduler = self._make_scheduler(self.scheduler_name)
647
+ scheduler.set_timesteps(int(steps), device=self.device)
648
+
649
+ in_channels = int(self.unet.config.in_channels)
650
+ latents = torch.randn(
651
+ (1, in_channels, self.latent_size, self.latent_size),
652
+ generator=generator,
653
+ device=self.device,
654
+ dtype=torch.float32,
655
+ ) * scheduler.init_noise_sigma
656
+
657
+ total_steps = len(scheduler.timesteps)
658
+ preview_interval = max(1, int(preview_every))
659
+
660
+ for step_i, timestep in enumerate(scheduler.timesteps):
661
+ if self.cancelled:
662
+ return None, seed
663
+
664
+ latent_input = torch.cat([latents, latents], dim=0)
665
+ latent_input = scheduler.scale_model_input(latent_input, timestep)
666
+
667
+ with self._autocast():
668
+ prediction = self.unet(
669
+ latent_input,
670
+ timestep,
671
+ encoder_hidden_states=embeddings,
672
+ ).sample
673
+
674
+ pred_negative, pred_text = prediction.chunk(2)
675
+ prediction = pred_negative + float(guidance_scale) * (pred_text - pred_negative)
676
+ prediction = self._cfg_rescale(
677
+ prediction, pred_text, self.guidance_rescale)
678
+ latents = scheduler.step(prediction, timestep, latents).prev_sample
679
+
680
+ if (preview_callback
681
+ and (step_i + 1) % preview_interval == 0
682
+ and step_i < total_steps - 1):
683
+ preview_callback(
684
+ self._decode_latents(latents),
685
+ step_i + 1,
686
+ total_steps,
687
+ )
688
+
689
+ return self._decode_latents(latents), seed
690
+
691
+ @torch.inference_mode()
692
+ def refine(self, source_image: Image.Image, prompt: str,
693
+ negative_prompt: str = "", extra_steps: int = 20,
694
+ strength: float = 0.35, guidance_scale: float = 7.5,
695
+ preview_callback=None, preview_every: int = 5) -> Image.Image:
696
+
697
+ img = source_image.convert("RGB").resize(
698
+ (self.output_size, self.output_size), Image.LANCZOS)
699
+ img_tensor = torch.from_numpy(np.array(img)).float().div(127.5).sub(1.0)
700
+ img_tensor = img_tensor.permute(2, 0, 1).unsqueeze(0).to(self.device)
701
+ img_tensor = img_tensor.to(
702
+ dtype=self.dtype if self.device == "cuda" else torch.float32)
703
+
704
+ with self._autocast():
705
+ latents = self.vae.encode(img_tensor).latent_dist.sample()
706
+ latents = (latents * self.vae.config.scaling_factor).float()
707
+ embeddings = self._encode_prompts(prompt, negative_prompt)
708
+
709
+ scheduler = self._make_scheduler(self.scheduler_name)
710
+ scheduler.set_timesteps(int(extra_steps), device=self.device)
711
+ start_step = max(0, int(len(scheduler.timesteps) * (1.0 - float(strength))))
712
+ timesteps = scheduler.timesteps[start_step:]
713
+ if len(timesteps) == 0:
714
+ return source_image.copy()
715
+
716
+ noise = torch.randn_like(latents)
717
+ latents = scheduler.add_noise(latents, noise, timesteps[:1])
718
+ total_steps = len(timesteps)
719
+ preview_interval = max(1, int(preview_every))
720
+
721
+ for step_i, timestep in enumerate(timesteps):
722
+ if self.cancelled:
723
+ return None
724
+
725
+ latent_input = torch.cat([latents, latents], dim=0)
726
+ latent_input = scheduler.scale_model_input(latent_input, timestep)
727
+ with self._autocast():
728
+ prediction = self.unet(
729
+ latent_input,
730
+ timestep,
731
+ encoder_hidden_states=embeddings,
732
+ ).sample
733
+
734
+ pred_negative, pred_text = prediction.chunk(2)
735
+ prediction = pred_negative + float(guidance_scale) * (pred_text - pred_negative)
736
+ prediction = self._cfg_rescale(
737
+ prediction, pred_text, self.guidance_rescale)
738
+ latents = scheduler.step(prediction, timestep, latents).prev_sample
739
+
740
+ if (preview_callback
741
+ and (step_i + 1) % preview_interval == 0
742
+ and step_i < total_steps - 1):
743
+ preview_callback(
744
+ self._decode_latents(latents),
745
+ step_i + 1,
746
+ total_steps,
747
+ )
748
+
749
+ return self._decode_latents(latents)
750
+
751
+
752
+ # ── GUI ───────────────────────────────────────────────────────────────────────
753
+
754
+ class App:
755
+ def __init__(self):
756
+ self.gen = Generator()
757
+ self.models = find_models()
758
+ self.generated_images = []
759
+ self.generated_seeds = []
760
+ self.photo_refs = []
761
+ self.generating = False
762
+ self.selected_index = None
763
+
764
+ self.root = tk.Tk()
765
+ self.root.title("Aniimage")
766
+ self.root.configure(bg=C["bg"])
767
+ self.root.resizable(True, True)
768
+ self.root.geometry("900x780")
769
+ self.root.minsize(640, 500)
770
+
771
+ self._setup_styles()
772
+ self._build_ui()
773
+
774
+ def _setup_styles(self):
775
+ s = ttk.Style()
776
+ s.theme_use("clam")
777
+
778
+ # Base
779
+ s.configure(".", background=C["bg"], foreground=C["text"], font=("Segoe UI", 10))
780
+ s.configure("TFrame", background=C["bg"])
781
+ s.configure("TLabel", background=C["bg"], foreground=C["text"])
782
+ s.configure("TCheckbutton", background=C["bg"], foreground=C["text"])
783
+
784
+ # Combobox β€” readable text
785
+ s.configure("TCombobox", fieldbackground=C["input"], foreground=C["input_fg"],
786
+ selectbackground=C["accent"], selectforeground="#ffffff",
787
+ arrowcolor=C["text2"], padding=4)
788
+ s.map("TCombobox",
789
+ fieldbackground=[("readonly", C["input"])],
790
+ foreground=[("readonly", C["input_fg"])],
791
+ selectbackground=[("readonly", C["accent"])],
792
+ selectforeground=[("readonly", "#ffffff")])
793
+ # Combobox dropdown list colors
794
+ self.root.option_add("*TCombobox*Listbox.background", C["input"])
795
+ self.root.option_add("*TCombobox*Listbox.foreground", C["input_fg"])
796
+ self.root.option_add("*TCombobox*Listbox.selectBackground", C["accent"])
797
+ self.root.option_add("*TCombobox*Listbox.selectForeground", "#ffffff")
798
+ self.root.option_add("*TCombobox*Listbox.font", ("Segoe UI", 10))
799
+
800
+ # Spinbox
801
+ s.configure("TSpinbox", fieldbackground=C["input"], foreground=C["input_fg"],
802
+ arrowcolor=C["text2"], padding=3)
803
+
804
+ # Buttons
805
+ s.configure("TButton", font=("Segoe UI", 10), padding=(14, 7),
806
+ background=C["card"], foreground=C["text"])
807
+ s.map("TButton", background=[("active", C["card_sel"]), ("disabled", C["bg"])],
808
+ foreground=[("disabled", C["text3"])])
809
+
810
+ s.configure("Go.TButton", font=("Segoe UI", 11, "bold"), padding=(20, 9),
811
+ background=C["accent"], foreground="#ffffff")
812
+ s.map("Go.TButton", background=[("active", C["accent_h"]),
813
+ ("disabled", C["border"])])
814
+
815
+ s.configure("Stop.TButton", font=("Segoe UI", 10, "bold"), padding=(14, 7),
816
+ background=C["red"], foreground="#ffffff")
817
+ s.map("Stop.TButton", background=[("active", "#c0392b"),
818
+ ("disabled", C["border"])])
819
+
820
+ # Labelframe
821
+ s.configure("TLabelframe", background=C["bg"], foreground=C["text2"])
822
+ s.configure("TLabelframe.Label", background=C["bg"],
823
+ foreground=C["text2"], font=("Segoe UI", 9, "bold"))
824
+
825
+ # Scrollbar
826
+ s.configure("Vertical.TScrollbar", background=C["card"],
827
+ troughcolor=C["bg"], arrowcolor=C["text3"])
828
+
829
+ def _make_entry(self, parent, font_size=11, dim=False):
830
+ """Create a styled tk.Entry with readable text."""
831
+ return tk.Entry(parent, font=("Segoe UI", font_size),
832
+ bg=C["input"], fg=C["input_fg"] if not dim else C["text2"],
833
+ insertbackground=C["input_fg"],
834
+ relief="flat", bd=6,
835
+ selectbackground=C["accent"], selectforeground="#ffffff",
836
+ highlightthickness=1, highlightcolor=C["accent"],
837
+ highlightbackground=C["border"])
838
+
839
+ def _build_ui(self):
840
+ # ── Header ────────────────────────────────────────────────────────
841
+ header = tk.Frame(self.root, bg=C["panel"], padx=20, pady=12)
842
+ header.pack(fill=tk.X)
843
+
844
+ tk.Label(header, text="Aniimage", bg=C["panel"], fg=C["accent"],
845
+ font=("Segoe UI", 20, "bold")).pack(side=tk.LEFT)
846
+ tk.Label(header, text="by 8BitStudio", bg=C["panel"], fg=C["text3"],
847
+ font=("Segoe UI", 10)).pack(side=tk.LEFT, padx=(10, 0), pady=(6, 0))
848
+
849
+ # Device switch β€” right side of header
850
+ device_frame = tk.Frame(header, bg=C["panel"])
851
+ device_frame.pack(side=tk.RIGHT)
852
+
853
+ tk.Label(device_frame, text="Device:", bg=C["panel"], fg=C["text2"],
854
+ font=("Segoe UI", 9)).pack(side=tk.LEFT, padx=(0, 5))
855
+
856
+ self.device_var = tk.StringVar(value="GPU" if self.gen.device == "cuda" else "CPU")
857
+ devices = ["GPU", "CPU"] if torch.cuda.is_available() else ["CPU"]
858
+ device_combo = ttk.Combobox(device_frame, textvariable=self.device_var,
859
+ values=devices, state="readonly", width=5)
860
+ device_combo.pack(side=tk.LEFT)
861
+ device_combo.bind("<<ComboboxSelected>>", self._on_device_change)
862
+
863
+ # ── Main content β€” two-column: controls left, images right ────────
864
+ main = tk.Frame(self.root, bg=C["bg"])
865
+ main.pack(fill=tk.BOTH, expand=True, padx=12, pady=(8, 12))
866
+
867
+ # Left panel (controls)
868
+ left = tk.Frame(main, bg=C["panel"], width=340, padx=16, pady=12)
869
+ left.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 8))
870
+ left.pack_propagate(False)
871
+
872
+ # Right panel (image grid)
873
+ right = tk.Frame(main, bg=C["bg"])
874
+ right.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
875
+
876
+ self._build_controls(left)
877
+ self._build_grid(right)
878
+
879
+ def _build_controls(self, parent):
880
+ # ── Model ─────────────────────────────────────────────────────────
881
+ tk.Label(parent, text="Model", bg=C["panel"], fg=C["text2"],
882
+ font=("Segoe UI", 9, "bold")).pack(anchor=tk.W)
883
+
884
+ self.model_var = tk.StringVar()
885
+ model_names = [m[1] for m in self.models] or ["No models found"]
886
+ self.model_combo = ttk.Combobox(parent, textvariable=self.model_var,
887
+ values=model_names, state="readonly", width=32)
888
+ self.model_combo.pack(fill=tk.X, pady=(3, 12))
889
+ self.model_combo.current(len(model_names) - 1)
890
+
891
+ # ── Prompt ────────────────────────────────────────────────────────
892
+ tk.Label(parent, text="Prompt", bg=C["panel"], fg=C["text2"],
893
+ font=("Segoe UI", 9, "bold")).pack(anchor=tk.W)
894
+ self.prompt_entry = self._make_entry(parent)
895
+ self.prompt_entry.pack(fill=tk.X, pady=(3, 8))
896
+ self.prompt_entry.insert(0, "a smiling anime girl with long blue hair")
897
+ self.prompt_entry.bind("<Return>", lambda e: self.on_generate())
898
+
899
+ # ── Negative prompt ───────────────────────────────────────────────
900
+ tk.Label(parent, text="Negative prompt", bg=C["panel"], fg=C["text3"],
901
+ font=("Segoe UI", 9)).pack(anchor=tk.W)
902
+ self.neg_entry = self._make_entry(parent, font_size=9, dim=True)
903
+ self.neg_entry.pack(fill=tk.X, pady=(3, 12))
904
+ self.neg_entry.insert(0, DEFAULT_NEGATIVE)
905
+
906
+ # ── Settings grid ─────────────────────────────────────────────────
907
+ grid = tk.Frame(parent, bg=C["panel"])
908
+ grid.pack(fill=tk.X, pady=(0, 8))
909
+
910
+ # Row 1: Scheduler
911
+ tk.Label(grid, text="Scheduler", bg=C["panel"], fg=C["text2"],
912
+ font=("Segoe UI", 9)).grid(row=0, column=0, sticky="w", pady=(0, 6))
913
+ self.scheduler_var = tk.StringVar(value="DPM++ SDE Karras")
914
+ sched_combo = ttk.Combobox(grid, textvariable=self.scheduler_var,
915
+ values=SCHEDULER_LIST, state="readonly", width=18)
916
+ sched_combo.grid(row=0, column=1, columnspan=3, sticky="ew", padx=(8, 0), pady=(0, 6))
917
+ sched_combo.bind("<<ComboboxSelected>>", self._on_scheduler_change)
918
+
919
+ # Row 2: Steps, CFG, Count
920
+ tk.Label(grid, text="Steps", bg=C["panel"], fg=C["text2"],
921
+ font=("Segoe UI", 9)).grid(row=1, column=0, sticky="w", pady=(0, 6))
922
+ self.steps_var = tk.StringVar(value="50")
923
+ tk.Entry(grid, textvariable=self.steps_var, width=5, font=("Segoe UI", 10),
924
+ bg=C["input"], fg=C["input_fg"], insertbackground=C["input_fg"],
925
+ relief="flat", bd=4).grid(row=1, column=1, sticky="w", padx=(8, 12), pady=(0, 6))
926
+
927
+ tk.Label(grid, text="CFG", bg=C["panel"], fg=C["text2"],
928
+ font=("Segoe UI", 9)).grid(row=1, column=2, sticky="w", pady=(0, 6))
929
+ self.cfg_var = tk.StringVar(value="7.5")
930
+ tk.Entry(grid, textvariable=self.cfg_var, width=5, font=("Segoe UI", 10),
931
+ bg=C["input"], fg=C["input_fg"], insertbackground=C["input_fg"],
932
+ relief="flat", bd=4).grid(row=1, column=3, sticky="w", padx=(8, 0), pady=(0, 6))
933
+
934
+ # Row 3: Count, Live preview
935
+ tk.Label(grid, text="Count", bg=C["panel"], fg=C["text2"],
936
+ font=("Segoe UI", 9)).grid(row=2, column=0, sticky="w", pady=(0, 6))
937
+ self.count_var = tk.StringVar(value="4")
938
+ ttk.Spinbox(grid, from_=1, to=12, textvariable=self.count_var, width=4,
939
+ font=("Segoe UI", 10)).grid(row=2, column=1, sticky="w", padx=(8, 12), pady=(0, 6))
940
+
941
+ self.live_preview_var = tk.BooleanVar(value=False)
942
+ ttk.Checkbutton(grid, text="Live preview",
943
+ variable=self.live_preview_var).grid(
944
+ row=2, column=2, columnspan=2, sticky="w", pady=(0, 6))
945
+
946
+ grid.columnconfigure(1, weight=1)
947
+ grid.columnconfigure(3, weight=1)
948
+
949
+ # ── Buttons ───────────────────────────────────────────────────────
950
+ btn_frame = tk.Frame(parent, bg=C["panel"])
951
+ btn_frame.pack(fill=tk.X, pady=(0, 10))
952
+
953
+ self.gen_btn = ttk.Button(btn_frame, text="Generate", command=self.on_generate,
954
+ style="Go.TButton")
955
+ self.gen_btn.pack(fill=tk.X, pady=(0, 5))
956
+
957
+ btn_row = tk.Frame(btn_frame, bg=C["panel"])
958
+ btn_row.pack(fill=tk.X)
959
+
960
+ self.stop_btn = ttk.Button(btn_row, text="Stop", command=self.on_stop,
961
+ state=tk.DISABLED, style="Stop.TButton")
962
+ self.stop_btn.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 3))
963
+
964
+ self.save_btn = ttk.Button(btn_row, text="Save Selected", command=self.on_save,
965
+ state=tk.DISABLED)
966
+ self.save_btn.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(3, 3))
967
+
968
+ self.save_all_btn = ttk.Button(btn_row, text="Save All", command=self.on_save_all,
969
+ state=tk.DISABLED)
970
+ self.save_all_btn.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(3, 0))
971
+
972
+ # ── Prompt queue ─────────────────────────────────────────────────
973
+ sep = tk.Frame(parent, height=1, bg=C["border"])
974
+ sep.pack(fill=tk.X, pady=(8, 10))
975
+
976
+ tk.Label(parent, text="Prompt Queue", bg=C["panel"], fg=C["text2"],
977
+ font=("Segoe UI", 9, "bold")).pack(anchor=tk.W)
978
+
979
+ queue_input = tk.Frame(parent, bg=C["panel"])
980
+ queue_input.pack(fill=tk.X, pady=(4, 0))
981
+
982
+ self.queue_entry = self._make_entry(queue_input, font_size=9)
983
+ self.queue_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 4))
984
+ self.queue_entry.bind("<Return>", lambda e: self._queue_add())
985
+
986
+ ttk.Button(queue_input, text="Add", width=4,
987
+ command=self._queue_add).pack(side=tk.LEFT)
988
+
989
+ self.queue_listbox = tk.Listbox(
990
+ parent, height=4, bg=C["input"], fg=C["input_fg"],
991
+ selectbackground=C["accent"], selectforeground="#fff",
992
+ font=("Segoe UI", 9), activestyle="none",
993
+ relief="flat", bd=4, highlightthickness=0)
994
+ self.queue_listbox.pack(fill=tk.X, pady=(5, 0))
995
+
996
+ queue_btns = tk.Frame(parent, bg=C["panel"])
997
+ queue_btns.pack(fill=tk.X, pady=(4, 0))
998
+
999
+ self.queue_run_btn = ttk.Button(queue_btns, text="Run Queue",
1000
+ command=self.on_run_queue, style="Go.TButton")
1001
+ self.queue_run_btn.pack(side=tk.LEFT, padx=(0, 4))
1002
+
1003
+ for txt, cmd in [("Remove", self._queue_remove), ("Clear", self._queue_clear),
1004
+ ("Up", self._queue_move_up), ("Down", self._queue_move_down),
1005
+ ("+ Current", self._queue_add_current)]:
1006
+ ttk.Button(queue_btns, text=txt, command=cmd).pack(side=tk.LEFT, padx=2)
1007
+
1008
+ # ── Status bar ────────────────────────────────────────────────────
1009
+ status_frame = tk.Frame(parent, bg=C["bg"], padx=8, pady=6)
1010
+ status_frame.pack(fill=tk.X, side=tk.BOTTOM)
1011
+
1012
+ self.status_var = tk.StringVar(value="Ready")
1013
+ tk.Label(status_frame, textvariable=self.status_var,
1014
+ bg=C["bg"], fg=C["green"], font=("Segoe UI", 9),
1015
+ anchor="w").pack(fill=tk.X)
1016
+
1017
+ def _build_grid(self, parent):
1018
+ self.canvas = tk.Canvas(parent, bg=C["bg"], highlightthickness=0)
1019
+ scrollbar = ttk.Scrollbar(parent, orient=tk.VERTICAL, command=self.canvas.yview)
1020
+ self.grid_frame = tk.Frame(self.canvas, bg=C["bg"])
1021
+
1022
+ self.grid_frame.bind("<Configure>",
1023
+ lambda e: self.canvas.configure(
1024
+ scrollregion=self.canvas.bbox("all")))
1025
+ self.canvas_window = self.canvas.create_window((0, 0), window=self.grid_frame,
1026
+ anchor="nw")
1027
+ self.canvas.configure(yscrollcommand=scrollbar.set)
1028
+
1029
+ self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
1030
+ scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
1031
+
1032
+ self.canvas.bind("<Configure>", self._on_canvas_resize)
1033
+ self.canvas.bind_all("<MouseWheel>",
1034
+ lambda e: self.canvas.yview_scroll(
1035
+ int(-1 * (e.delta / 120)), "units"))
1036
+
1037
+ self.placeholder = tk.Label(self.grid_frame,
1038
+ text="Generated images\nwill appear here",
1039
+ bg=C["bg"], fg=C["text3"],
1040
+ font=("Segoe UI", 13), justify="center")
1041
+ self.placeholder.grid(row=0, column=0, pady=80)
1042
+
1043
+ # ── Event handlers ────────────────────────────────────────────────────
1044
+
1045
+ def _on_device_change(self, event=None):
1046
+ choice = self.device_var.get()
1047
+ new_dev = "cuda" if choice == "GPU" else "cpu"
1048
+ self.status_var.set(f"Switching to {choice}...")
1049
+ self.root.update()
1050
+ self.gen.switch_device(new_dev)
1051
+ self.status_var.set(f"Now using {choice}")
1052
+
1053
+ def _on_scheduler_change(self, event=None):
1054
+ name = self.scheduler_var.get()
1055
+ self.gen.set_scheduler(name)
1056
+ self.status_var.set(f"Scheduler: {name}")
1057
+
1058
+ def _on_canvas_resize(self, event):
1059
+ self.canvas.itemconfig(self.canvas_window, width=event.width)
1060
+ if self.generated_images:
1061
+ self._layout_grid()
1062
+
1063
+ def _get_grid_cols(self):
1064
+ canvas_w = self.canvas.winfo_width()
1065
+ if canvas_w < 50:
1066
+ canvas_w = 560
1067
+ tile_size = self._get_tile_size()
1068
+ return max(1, canvas_w // (tile_size + 16))
1069
+
1070
+ def _get_tile_size(self):
1071
+ n = len(self.generated_images)
1072
+ if n <= 2: return 260
1073
+ elif n <= 4: return 220
1074
+ elif n <= 6: return 180
1075
+ else: return 160
1076
+
1077
+ def _layout_grid(self):
1078
+ for w in self.grid_frame.winfo_children():
1079
+ w.destroy()
1080
+ self.photo_refs.clear()
1081
+
1082
+ if not self.generated_images:
1083
+ return
1084
+
1085
+ tile_size = self._get_tile_size()
1086
+ cols = self._get_grid_cols()
1087
+
1088
+ for i, (img, seed) in enumerate(zip(self.generated_images, self.generated_seeds)):
1089
+ row, col = divmod(i, cols)
1090
+ is_selected = (i == self.selected_index)
1091
+
1092
+ card_bg = C["accent"] if is_selected else C["card"]
1093
+ card = tk.Frame(self.grid_frame, bg=card_bg, padx=3, pady=3)
1094
+ card.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
1095
+
1096
+ display = img.resize((tile_size, tile_size), Image.LANCZOS)
1097
+ photo = ImageTk.PhotoImage(display)
1098
+ self.photo_refs.append(photo)
1099
+
1100
+ img_label = tk.Label(card, image=photo, bg=card_bg, bd=0)
1101
+ img_label.pack()
1102
+ img_label.bind("<Button-1>", lambda e, idx=i: self._select_image(idx))
1103
+ img_label.bind("<Button-3>", lambda e, idx=i: self._show_refine_menu(e, idx))
1104
+
1105
+ tk.Label(card, text=f"seed: {seed}", bg=card_bg,
1106
+ fg=C["text3"], font=("Segoe UI", 8)).pack()
1107
+
1108
+ for c in range(cols):
1109
+ self.grid_frame.columnconfigure(c, weight=1)
1110
+
1111
+ def _select_image(self, idx):
1112
+ if idx >= len(self.generated_images):
1113
+ return
1114
+ self.selected_index = idx
1115
+ self.save_btn.configure(state=tk.NORMAL)
1116
+ self.status_var.set(f"Selected image {idx + 1} (seed: {self.generated_seeds[idx]})")
1117
+ self._layout_grid()
1118
+
1119
+ def _show_refine_menu(self, event, idx):
1120
+ if self.generating:
1121
+ return
1122
+ menu = tk.Menu(self.root, tearoff=0, bg=C["card"], fg=C["text"],
1123
+ activebackground=C["accent"], activeforeground="#fff",
1124
+ font=("Segoe UI", 10), bd=0)
1125
+ menu.add_command(label=" Refine (more steps)... ",
1126
+ command=lambda: self._ask_refine(idx))
1127
+ menu.tk_popup(event.x_root, event.y_root)
1128
+
1129
+ def _ask_refine(self, idx):
1130
+ extra = simpledialog.askinteger(
1131
+ "Refine Image", "Extra denoising steps:",
1132
+ initialvalue=20, minvalue=5, maxvalue=200, parent=self.root)
1133
+ if extra is None:
1134
+ return
1135
+ self._select_image(idx)
1136
+ self.generating = True
1137
+ self.gen.cancelled = False
1138
+ self.gen_btn.configure(state=tk.DISABLED)
1139
+ self.stop_btn.configure(state=tk.NORMAL)
1140
+ self.status_var.set(f"Refining image {idx + 1}...")
1141
+ self.root.update()
1142
+ Thread(target=self._refine_thread, args=(idx, extra), daemon=True).start()
1143
+
1144
+ def _refine_thread(self, idx, extra_steps):
1145
+ try:
1146
+ source = self.generated_images[idx]
1147
+ prompt = self.prompt_entry.get().strip()
1148
+ neg = self.neg_entry.get().strip()
1149
+ cfg = float(self.cfg_var.get())
1150
+ callback = self._show_preview if self.live_preview_var.get() else None
1151
+
1152
+ refined = self.gen.refine(
1153
+ source_image=source, prompt=prompt, negative_prompt=neg,
1154
+ extra_steps=extra_steps, guidance_scale=cfg,
1155
+ preview_callback=callback, preview_every=5)
1156
+
1157
+ if refined is not None:
1158
+ self.generated_images[idx] = refined
1159
+ self.generated_seeds[idx] = f"{self.generated_seeds[idx]}+R{extra_steps}"
1160
+ self._layout_grid()
1161
+ self.status_var.set(f"Refined image {idx + 1}")
1162
+ else:
1163
+ self.status_var.set("Refine stopped.")
1164
+ self.root.update()
1165
+ except Exception as e:
1166
+ self.status_var.set(f"Refine error: {e}")
1167
+ import traceback; traceback.print_exc()
1168
+ finally:
1169
+ self.generating = False
1170
+ self.gen.cancelled = False
1171
+ self.gen_btn.configure(state=tk.NORMAL)
1172
+ self.stop_btn.configure(state=tk.DISABLED)
1173
+
1174
+ # ── Queue ─────────────────────────────────────────────────────────────
1175
+
1176
+ def _queue_add(self):
1177
+ text = self.queue_entry.get().strip()
1178
+ if text:
1179
+ self.queue_listbox.insert(tk.END, text)
1180
+ self.queue_entry.delete(0, tk.END)
1181
+
1182
+ def _queue_add_current(self):
1183
+ text = self.prompt_entry.get().strip()
1184
+ if text:
1185
+ self.queue_listbox.insert(tk.END, text)
1186
+
1187
+ def _queue_remove(self):
1188
+ sel = self.queue_listbox.curselection()
1189
+ if sel:
1190
+ self.queue_listbox.delete(sel[0])
1191
+
1192
+ def _queue_clear(self):
1193
+ self.queue_listbox.delete(0, tk.END)
1194
+
1195
+ def _queue_move_up(self):
1196
+ sel = self.queue_listbox.curselection()
1197
+ if sel and sel[0] > 0:
1198
+ idx = sel[0]
1199
+ text = self.queue_listbox.get(idx)
1200
+ self.queue_listbox.delete(idx)
1201
+ self.queue_listbox.insert(idx - 1, text)
1202
+ self.queue_listbox.selection_set(idx - 1)
1203
+
1204
+ def _queue_move_down(self):
1205
+ sel = self.queue_listbox.curselection()
1206
+ if sel and sel[0] < self.queue_listbox.size() - 1:
1207
+ idx = sel[0]
1208
+ text = self.queue_listbox.get(idx)
1209
+ self.queue_listbox.delete(idx)
1210
+ self.queue_listbox.insert(idx + 1, text)
1211
+ self.queue_listbox.selection_set(idx + 1)
1212
+
1213
+ def on_run_queue(self):
1214
+ if self.generating or not self.models:
1215
+ return
1216
+ prompts = list(self.queue_listbox.get(0, tk.END))
1217
+ if not prompts:
1218
+ self.status_var.set("Queue is empty")
1219
+ return
1220
+ self.generating = True
1221
+ self.gen.cancelled = False
1222
+ self.gen_btn.configure(state=tk.DISABLED)
1223
+ self.queue_run_btn.configure(state=tk.DISABLED)
1224
+ self.stop_btn.configure(state=tk.NORMAL)
1225
+ Thread(target=self._queue_thread, args=(prompts,), daemon=True).start()
1226
+
1227
+ def _queue_thread(self, prompts):
1228
+ try:
1229
+ idx = self.model_combo.current()
1230
+ mdl = self.models[idx]
1231
+ self.status_var.set(f"Loading {mdl[1]}...")
1232
+ self.root.update()
1233
+ self.gen.load_model(mdl[2], mdl[3])
1234
+
1235
+ neg = self.neg_entry.get().strip()
1236
+ steps = int(self.steps_var.get())
1237
+ cfg = float(self.cfg_var.get())
1238
+ num_images = max(1, min(12, int(self.count_var.get())))
1239
+ live_preview = self.live_preview_var.get()
1240
+
1241
+ self.generated_images.clear()
1242
+ self.generated_seeds.clear()
1243
+ self.selected_index = None
1244
+ if self.placeholder:
1245
+ self.placeholder.destroy()
1246
+ self.placeholder = None
1247
+
1248
+ for p_idx, prompt in enumerate(prompts):
1249
+ if self.gen.cancelled:
1250
+ break
1251
+ self.queue_listbox.selection_clear(0, tk.END)
1252
+ self.queue_listbox.selection_set(p_idx)
1253
+ self.queue_listbox.see(p_idx)
1254
+
1255
+ for img_i in range(num_images):
1256
+ if self.gen.cancelled:
1257
+ break
1258
+ self.status_var.set(
1259
+ f"[{p_idx + 1}/{len(prompts)}] image {img_i + 1}/{num_images}")
1260
+ self.root.update()
1261
+
1262
+ callback = None
1263
+ if live_preview:
1264
+ self._setup_preview_card()
1265
+ callback = self._show_preview
1266
+
1267
+ image, used_seed = self.gen.generate(
1268
+ prompt=prompt, negative_prompt=neg,
1269
+ steps=steps, guidance_scale=cfg,
1270
+ preview_callback=callback, preview_every=5)
1271
+
1272
+ if image is None:
1273
+ break
1274
+ self.generated_images.append(image)
1275
+ self.generated_seeds.append(used_seed)
1276
+ save_path = self._next_save_path(prompt)
1277
+ image.save(save_path)
1278
+ self._layout_grid()
1279
+ self.root.update()
1280
+
1281
+ if self.gen.cancelled:
1282
+ break
1283
+
1284
+ done = len(self.generated_images)
1285
+ self.status_var.set(
1286
+ f"Queue {'stopped' if self.gen.cancelled else 'done'}! {done} images saved.")
1287
+ if done > 0:
1288
+ self.save_all_btn.configure(state=tk.NORMAL)
1289
+
1290
+ except Exception as e:
1291
+ self.status_var.set(f"Queue error: {e}")
1292
+ import traceback; traceback.print_exc()
1293
+ finally:
1294
+ self.generating = False
1295
+ self.gen.cancelled = False
1296
+ self.gen_btn.configure(state=tk.NORMAL)
1297
+ self.queue_run_btn.configure(state=tk.NORMAL)
1298
+ self.stop_btn.configure(state=tk.DISABLED)
1299
+
1300
+ # ── Generation ────────────────────────────────────────────────────────
1301
+
1302
+ def on_stop(self):
1303
+ if self.generating:
1304
+ self.gen.cancelled = True
1305
+ self.status_var.set("Stopping...")
1306
+ self.root.update()
1307
+
1308
+ def on_generate(self):
1309
+ if self.generating or not self.models:
1310
+ return
1311
+ self.generating = True
1312
+ self.gen.cancelled = False
1313
+ self.gen_btn.configure(state=tk.DISABLED)
1314
+ self.stop_btn.configure(state=tk.NORMAL)
1315
+ self.status_var.set("Loading model...")
1316
+ self.root.update()
1317
+ Thread(target=self._generate_thread, daemon=True).start()
1318
+
1319
+ def _setup_preview_card(self):
1320
+ tile_size = self._get_tile_size()
1321
+ cols = self._get_grid_cols()
1322
+ row, col = divmod(len(self.generated_images), cols)
1323
+ card = tk.Frame(self.grid_frame, bg=C["card"], padx=3, pady=3)
1324
+ card.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
1325
+ self._preview_label = tk.Label(card, bg=C["card"],
1326
+ width=tile_size, height=tile_size)
1327
+ self._preview_label.pack()
1328
+ self.root.update()
1329
+
1330
+ def _show_preview(self, preview_img, step, total):
1331
+ tile_size = self._get_tile_size()
1332
+ display = preview_img.resize((tile_size, tile_size), Image.LANCZOS)
1333
+ photo = ImageTk.PhotoImage(display)
1334
+ self._preview_photo = photo
1335
+ if hasattr(self, '_preview_label') and self._preview_label.winfo_exists():
1336
+ self._preview_label.configure(image=photo)
1337
+ self.status_var.set(f"Step {step}/{total}")
1338
+ self.root.update()
1339
+
1340
+ def _generate_thread(self):
1341
+ try:
1342
+ idx = self.model_combo.current()
1343
+ mdl = self.models[idx]
1344
+ self.status_var.set(f"Loading {mdl[1]}...")
1345
+ self.root.update()
1346
+ self.gen.load_model(mdl[2], mdl[3])
1347
+
1348
+ prompt = self.prompt_entry.get().strip()
1349
+ neg = self.neg_entry.get().strip()
1350
+ steps = int(self.steps_var.get())
1351
+ cfg = float(self.cfg_var.get())
1352
+ num_images = max(1, min(12, int(self.count_var.get())))
1353
+ live_preview = self.live_preview_var.get()
1354
+
1355
+ self.generated_images.clear()
1356
+ self.generated_seeds.clear()
1357
+ self.selected_index = None
1358
+ if self.placeholder:
1359
+ self.placeholder.destroy()
1360
+ self.placeholder = None
1361
+
1362
+ for i in range(num_images):
1363
+ if self.gen.cancelled:
1364
+ break
1365
+ self.status_var.set(f"Generating {i + 1}/{num_images}...")
1366
+ self.root.update()
1367
+
1368
+ callback = None
1369
+ if live_preview:
1370
+ self._setup_preview_card()
1371
+ callback = self._show_preview
1372
+
1373
+ image, used_seed = self.gen.generate(
1374
+ prompt=prompt, negative_prompt=neg,
1375
+ steps=steps, guidance_scale=cfg,
1376
+ preview_callback=callback, preview_every=5)
1377
+
1378
+ if image is None:
1379
+ break
1380
+ self.generated_images.append(image)
1381
+ self.generated_seeds.append(used_seed)
1382
+ self._layout_grid()
1383
+ self.root.update()
1384
+
1385
+ done = len(self.generated_images)
1386
+ if self.gen.cancelled:
1387
+ self.status_var.set(f"Stopped. {done} image(s) kept.")
1388
+ else:
1389
+ self.status_var.set(f"Done! {done} images. Click to select.")
1390
+ if done > 0:
1391
+ self.save_all_btn.configure(state=tk.NORMAL)
1392
+ self.save_btn.configure(state=tk.DISABLED)
1393
+
1394
+ except Exception as e:
1395
+ self.status_var.set(f"Error: {e}")
1396
+ import traceback; traceback.print_exc()
1397
+ finally:
1398
+ self.generating = False
1399
+ self.gen.cancelled = False
1400
+ self.gen_btn.configure(state=tk.NORMAL)
1401
+ self.stop_btn.configure(state=tk.DISABLED)
1402
+
1403
+ # ── Save ──────────────────────────────────────────────────────────────
1404
+
1405
+ def _next_save_path(self, prompt_text):
1406
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
1407
+ slug = prompt_text.strip()[:50] if prompt_text.strip() else "untitled"
1408
+ base = OUTPUT_DIR / f"{slug}.png"
1409
+ if not base.exists():
1410
+ return base
1411
+ n = 1
1412
+ while True:
1413
+ path = OUTPUT_DIR / f"{slug} {n}.png"
1414
+ if not path.exists():
1415
+ return path
1416
+ n += 1
1417
+
1418
+ def on_save(self):
1419
+ if self.selected_index is None or not self.generated_images:
1420
+ return
1421
+ img = self.generated_images[self.selected_index]
1422
+ path = self._next_save_path(self.prompt_entry.get().strip())
1423
+ img.save(path)
1424
+ self.status_var.set(f"Saved: {path.name}")
1425
+
1426
+ def on_save_all(self):
1427
+ if not self.generated_images:
1428
+ return
1429
+ prompt_text = self.prompt_entry.get().strip()
1430
+ for img in self.generated_images:
1431
+ path = self._next_save_path(prompt_text)
1432
+ img.save(path)
1433
+ self.status_var.set(f"Saved {len(self.generated_images)} images")
1434
+
1435
+ def run(self):
1436
+ self.root.mainloop()
1437
+
1438
+
1439
+ # ── Entry point ───────────────────────────────────────────────────────────────
1440
+
1441
+ if __name__ == "__main__":
1442
+ models = find_models()
1443
+ if not models:
1444
+ print("No models found locally. Downloading from HuggingFace...")
1445
+ result = download_from_hf()
1446
+ if result:
1447
+ models = find_models()
1448
+
1449
+ if not models:
1450
+ print("No models found!")
1451
+ print(f"Place model weights in: {MODEL_DIR}/YourModelName/")
1452
+ print("Expected files: diffusion_pytorch_model.safetensors or ema_unet.pt")
1453
+ sys.exit(1)
1454
+
1455
+ print(f"Found {len(models)} model(s): {', '.join(m[1] for m in models)}")
1456
+ print(f"Device: {'CUDA (GPU)' if torch.cuda.is_available() else 'CPU'}")
1457
+ print("Starting Aniimage...")
1458
+
1459
+ app = App()
1460
+ app.run()
model_config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "unet": {
3
+ "sample_size": 64,
4
+ "in_channels": 4,
5
+ "out_channels": 4,
6
+ "layers_per_block": 2,
7
+ "block_out_channels": [
8
+ 256,
9
+ 512,
10
+ 768,
11
+ 1024
12
+ ],
13
+ "down_block_types": [
14
+ "CrossAttnDownBlock2D",
15
+ "CrossAttnDownBlock2D",
16
+ "CrossAttnDownBlock2D",
17
+ "DownBlock2D"
18
+ ],
19
+ "up_block_types": [
20
+ "UpBlock2D",
21
+ "CrossAttnUpBlock2D",
22
+ "CrossAttnUpBlock2D",
23
+ "CrossAttnUpBlock2D"
24
+ ],
25
+ "cross_attention_dim": 768,
26
+ "attention_head_dim": 8
27
+ },
28
+ "prediction_type": "v_prediction",
29
+ "zero_terminal_snr": true,
30
+ "beta_schedule": "scaled_linear",
31
+ "num_train_timesteps": 1000,
32
+ "clip_penultimate": true,
33
+ "guidance_rescale": 0.7,
34
+ "image_size": 512,
35
+ "vae": "madebyollin/sdxl-vae-fp16-fix"
36
+ }