abbiepam commited on
Commit
2b1a68e
·
1 Parent(s): 4239ca7

Upload abbiexgarrLeXy.ipynb

Browse files
Files changed (1) hide show
  1. abbiexgarrLeXy.ipynb +353 -0
abbiexgarrLeXy.ipynb ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {
7
+ "cellView": "form",
8
+ "id": "3nahOq36UE6Y"
9
+ },
10
+ "outputs": [],
11
+ "source": [
12
+ "# @title SETUP\n",
13
+ "!pip install git+https://github.com/Garry435/diffusers.git transformers xformers accelerate omegaconf torchsde\n",
14
+ "!apt -y install -qq aria2"
15
+ ]
16
+ },
17
+ {
18
+ "cell_type": "markdown",
19
+ "metadata": {
20
+ "id": "GZqqwr8aK-PH"
21
+ },
22
+ "source": [
23
+ "THE **DOWNLOAD MODEL** CELL CAN BE USED TO DOWNLOAD BOTH MODELS AND LORAS , ANY LINK TO A .safetensors FILE CAN BE PASSED AS URL"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "metadata": {
30
+ "cellView": "form",
31
+ "id": "4r90dC0AUltr"
32
+ },
33
+ "outputs": [],
34
+ "source": [
35
+ "import os\n",
36
+ "os.makedirs(f'models',exist_ok=True)\n",
37
+ "\n",
38
+ "# @title DOWNLOAD MODEL\n",
39
+ "\n",
40
+ "Model_url = 'https://civitai.com/api/download/models/174609'# @param {type:\"string\"}\n",
41
+ "Model_name = 'sdxlUnstableDiffusers_v8HEAVENSWRATH'# @param {type:\"string\"}\n",
42
+ "if not Model_name.endswith('.safetensors'):\n",
43
+ " Model_name=Model_name+'.safetensors'\n",
44
+ "\n",
45
+ "!aria2c --console-log-level=error -c -x 16 -s 16 -k 1M \"{Model_url}\" -d models -o {Model_name}\n",
46
+ "print('\\nAvailable models :')\n",
47
+ "for MODEL in os.listdir('models'):\n",
48
+ " print(MODEL.replace('.safetensors',''))"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": null,
54
+ "metadata": {
55
+ "cellView": "form",
56
+ "id": "jmouxkB2U3Bf"
57
+ },
58
+ "outputs": [],
59
+ "source": [
60
+ "# @title LOAD MODEL\n",
61
+ "import hashlib\n",
62
+ "from diffusers import StableDiffusionXLPipeline, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSDEScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, KDPM2AncestralDiscreteScheduler, KDPM2DiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, UniPCMultistepScheduler\n",
63
+ "from diffusers.utils import make_image_grid\n",
64
+ "import torch,random,os\n",
65
+ "from IPython.display import display\n",
66
+ "\n",
67
+ "\n",
68
+ "os.makedirs(f'outputs',exist_ok=True)\n",
69
+ "MODEL_NAME = \"sdxlUnstableDiffusers_v8HEAVENSWRATH\"# @param {type:\"string\"}\n",
70
+ "if not MODEL_NAME.endswith('.safetensors'):\n",
71
+ " MODEL_NAME=MODEL_NAME+'.safetensors'\n",
72
+ "print(f'\\n\\nCurrently selected : {MODEL_NAME}')\n",
73
+ "model_path = f'models/{MODEL_NAME}'\n",
74
+ "\n",
75
+ "pipe = StableDiffusionXLPipeline.from_single_file(\n",
76
+ " model_path, revision=\"fp16\", torch_dtype=torch.float16,variant=\"fp16\",scheduler_type='dpm'\n",
77
+ ")\n",
78
+ "\n",
79
+ "pipe.to(\"cuda\")\n",
80
+ "pipe.enable_xformers_memory_efficient_attention()\n",
81
+ "\n",
82
+ "def compute_sha256(file_path):\n",
83
+ " \"\"\"Compute the SHA-256 hash of a file.\"\"\"\n",
84
+ " sha256 = hashlib.sha256()\n",
85
+ " with open(file_path, 'rb') as f:\n",
86
+ " # Read the file in chunks to save memory\n",
87
+ " for chunk in iter(lambda: f.read(4096), b\"\"):\n",
88
+ " sha256.update(chunk)\n",
89
+ " return sha256.hexdigest()\n",
90
+ "\n",
91
+ "def compute_autov2_from_sha256(sha256):\n",
92
+ " return sha256[:10]\n",
93
+ "\n",
94
+ "AUTOV2_HASH_MODEL = compute_autov2_from_sha256(compute_sha256(model_path))"
95
+ ]
96
+ },
97
+ {
98
+ "cell_type": "markdown",
99
+ "metadata": {
100
+ "id": "ZlefDN6r6I5A"
101
+ },
102
+ "source": [
103
+ "EMBEDDING_URL SHOULD BE A URL TO A '.safetensors' FILE"
104
+ ]
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "execution_count": null,
109
+ "metadata": {
110
+ "cellView": "form",
111
+ "id": "-AJZNgEu6VWH"
112
+ },
113
+ "outputs": [],
114
+ "source": [
115
+ "# @title LOAD EMBEDDING\n",
116
+ "import requests as req\n",
117
+ "from safetensors.torch import load_file\n",
118
+ "EMBEDDING_URL= ''# @param {type:\"string\"}\n",
119
+ "embed = req.get(EMBEDDING_URL)\n",
120
+ "filename = embed.headers['Content-Disposition'].split('filename=')[1].strip('\"')\n",
121
+ "tk = filename.strip('.safetensors')\n",
122
+ "with open(filename,\"wb\") as r:\n",
123
+ " r.write(embed.content)\n",
124
+ "state_dict = load_file(filename)\n",
125
+ "try:\n",
126
+ " pipe.load_textual_inversion(state_dict[\"clip_g\"], token=tk, text_encoder=pipe.text_encoder_2, tokenizer=pipe.tokenizer_2)\n",
127
+ " pipe.load_textual_inversion(state_dict[\"clip_l\"], token=tk, text_encoder=pipe.text_encoder, tokenizer=pipe.tokenizer)\n",
128
+ " print(f\"Successfuly Loaded\\n\\nTrigger Keyword :\\n{tk}\")\n",
129
+ "except Exception as e:\n",
130
+ " em = str(e)\n",
131
+ " if f\"Token {tk} already\" in em:\n",
132
+ " print(f\"Successfuly Loaded\\n\\nTrigger Keyword :\\n{tk}\")\n",
133
+ " else:\n",
134
+ " print(em)"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "markdown",
139
+ "metadata": {
140
+ "id": "y-7T6PSOKnRZ"
141
+ },
142
+ "source": [
143
+ "LOADING MANY LORAs IS NOT SUGGESTED AS COLAB HAS LIMITED RESOURCES AND IT MIGHT CRASH , 1-2 LORAs WORK FINE"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "execution_count": null,
149
+ "metadata": {
150
+ "cellView": "form",
151
+ "id": "mIymmFSDGZ2S"
152
+ },
153
+ "outputs": [],
154
+ "source": [
155
+ "# @title LOAD LORA\n",
156
+ "LORA_NAME= ''# @param {type:\"string\"}\n",
157
+ "LORA_SCALE = 0.5# @param {type:\"number\"}\n",
158
+ "if not LORA_NAME.endswith('.safetensors'):\n",
159
+ " LORA_NAME=LORA_NAME+'.safetensors'\n",
160
+ "print(f'\\n\\nCurrently selected : {LORA_NAME}')\n",
161
+ "lora_path = f'models/{LORA_NAME}'\n",
162
+ "pipe.load_lora_weights(lora_path)\n",
163
+ "pipe.fuse_lora(1)"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": null,
169
+ "metadata": {
170
+ "cellView": "form",
171
+ "id": "evZs88UOVdzn"
172
+ },
173
+ "outputs": [],
174
+ "source": [
175
+ "# @title GENERATE IMAGE\n",
176
+ "from PIL import PngImagePlugin\n",
177
+ "\n",
178
+ "PROMPT= ''# @param {type:\"string\"}\n",
179
+ "NEGATIVE_PROMPT = ''# @param {type:\"string\"}\n",
180
+ "WIDTH = 704# @param {type:\"integer\"}\n",
181
+ "HEIGHT = 1408 # @param {type:\"integer\"}\n",
182
+ "SAMPLING_STEPS = 50# @param {type:\"integer\"}\n",
183
+ "CFG_scale = 12# @param {type:\"number\"}\n",
184
+ "SEED = -1# @param {type:\"number\"}\n",
185
+ "CLIP_SKIP = 1# @param {type:\"number\"}\n",
186
+ "SCHEDULER = \"DPMSolverMultistepScheduler\"# @param [\"DDIMParallelScheduler\",\"DDIMScheduler\",\"DDPMParallelScheduler\",\"DDPMScheduler\",\"DEISMultistepScheduler\",\"DPMSolverMultistepScheduler\",\"DPMSolverSDEScheduler\",\"DPMSolverSinglestepScheduler\",\"EulerAncestralDiscreteScheduler\",\"EulerDiscreteScheduler\",\"HeunDiscreteScheduler\",\"KDPM2AncestralDiscreteScheduler\",\"KDPM2DiscreteScheduler\",\"LMSDiscreteScheduler\",\"PNDMScheduler\",\"UniPCMultistepScheduler\"]\n",
187
+ "USE_KARRAS = False # @param {type:\"boolean\"}\n",
188
+ "NUMBER_OF_IMAGES = 4# @param {type:\"number\"}\n",
189
+ "CLIP_SKIP = None if CLIP_SKIP == 1 else CLIP_SKIP - 1\n",
190
+ "\n",
191
+ "# Schedulers mapping: https://huggingface.co/docs/diffusers/api/schedulers/overview\n",
192
+ "def get_a1111_name(scheduler, use_karras):\n",
193
+ " diffusers_to_a1111_map = {\n",
194
+ " \"DPMSolverMultistepScheduler\": {\n",
195
+ " False: \"DPM++ 2M\",\n",
196
+ " True: \"DPM++ 2M Karras\"\n",
197
+ " },\n",
198
+ " \"DPMSolverSinglestepScheduler\": {\n",
199
+ " False: \"DPM++ SDE\",\n",
200
+ " True: \"DPM++ SDE Karras\"\n",
201
+ " },\n",
202
+ " \"KDPM2DiscreteScheduler\": {\n",
203
+ " False: \"DPM2\",\n",
204
+ " True: \"DPM2 Karras\"\n",
205
+ " },\n",
206
+ " \"KDPM2AncestralDiscreteScheduler\": {\n",
207
+ " False: \"DPM2 a\",\n",
208
+ " True: \"DPM2 a Karras\"\n",
209
+ " },\n",
210
+ " \"EulerDiscreteScheduler\": {\n",
211
+ " False: \"Euler\"\n",
212
+ " },\n",
213
+ " \"EulerAncestralDiscreteScheduler\": {\n",
214
+ " False: \"Euler a\"\n",
215
+ " },\n",
216
+ " \"HeunDiscreteScheduler\": {\n",
217
+ " False: \"Heun\"\n",
218
+ " },\n",
219
+ " \"LMSDiscreteScheduler\": {\n",
220
+ " False: \"LMS\",\n",
221
+ " True: \"LMS Karras\"\n",
222
+ " },\n",
223
+ " \"DEISMultistepScheduler\": {\n",
224
+ " False: \"N/A\"\n",
225
+ " },\n",
226
+ " \"UniPCMultistepScheduler\": {\n",
227
+ " False: \"N/A\"\n",
228
+ " }\n",
229
+ " }\n",
230
+ "\n",
231
+ " return diffusers_to_a1111_map.get(scheduler, {}).get(use_karras, scheduler)\n",
232
+ "\n",
233
+ "\n",
234
+ "def embed_png_info(image_path, info):\n",
235
+ " with PngImagePlugin.PngImageFile(image_path) as img:\n",
236
+ " # Embed the info as a PNG text chunk\n",
237
+ " meta = PngImagePlugin.PngInfo()\n",
238
+ " #encoded_info = b'UNICODE' + info.encode('utf-8')\n",
239
+ " meta.add_text(\"parameters\", info)\n",
240
+ " img.save(image_path, pnginfo=meta)\n",
241
+ "\n",
242
+ "def format_png_info(prompt, negative_prompt, steps, width, height, seed, scheduler, cfg_scale, clip_skip, model_hash, model_name, **kwargs):\n",
243
+ " # Construct the PNG info\n",
244
+ " info = prompt + \"\\n\"\n",
245
+ " info += f\"Negative prompt: {negative_prompt}\\n\"\n",
246
+ " info += f\"Steps: {steps}, Size: {width}x{height}, Seed: {seed}, Sampler: {scheduler}, CFG scale: {cfg_scale}, Clip skip: {clip_skip}, Model hash: {model_hash}, Model: {model_name}, \\n\"\n",
247
+ "\n",
248
+ " # Add any additional kwargs\n",
249
+ " for key, value in kwargs.items():\n",
250
+ " info += f\"{key}: {value}, \"\n",
251
+ "\n",
252
+ " # Remove trailing comma and space\n",
253
+ " info = info.rstrip(\", \")\n",
254
+ "\n",
255
+ " return info\n",
256
+ "\n",
257
+ "def save_image_with_png_info(image_path):\n",
258
+ " global PROMPT\n",
259
+ " global NEGATIVE_PROMPT\n",
260
+ " global SAMPLING_STEPS\n",
261
+ " global WIDTH\n",
262
+ " global HEIGHT\n",
263
+ " global SEED\n",
264
+ " global SCHEDULER\n",
265
+ " global USE_KARRAS\n",
266
+ " global CFG_scale\n",
267
+ " global CLIP_SKIP\n",
268
+ " global AUTOV2_HASH_MODEL\n",
269
+ " global MODEL_NAME\n",
270
+ "\n",
271
+ " clip_skip = CLIP_SKIP\n",
272
+ " if clip_skip is None:\n",
273
+ " clip_skip = 1\n",
274
+ "\n",
275
+ " # Save the image\n",
276
+ " image.save(image_path)\n",
277
+ "\n",
278
+ " # Generate PNG info and embed it into the image\n",
279
+ " embed_png_info(image_path,\n",
280
+ " format_png_info(PROMPT, NEGATIVE_PROMPT, SAMPLING_STEPS,\n",
281
+ " WIDTH, HEIGHT, SEED, get_a1111_name(SCHEDULER, USE_KARRAS), CFG_scale,\n",
282
+ " clip_skip, AUTOV2_HASH_MODEL, MODEL_NAME ) )\n",
283
+ "\n",
284
+ "if SEED == -1:\n",
285
+ " SEED = random.randint(1,10000000000)\n",
286
+ "generator = torch.Generator(device=\"cuda\").manual_seed(SEED)\n",
287
+ "sc = f'''pipe.scheduler = {SCHEDULER}.from_config(pipe.scheduler.config, use_karras_sigmas={USE_KARRAS})'''\n",
288
+ "exec(sc)\n",
289
+ "final_images=[]\n",
290
+ "if NUMBER_OF_IMAGES != 1:\n",
291
+ " for i in range(NUMBER_OF_IMAGES):\n",
292
+ " SEED = random.randint(1,10000000000)\n",
293
+ " print(f'SEED : {SEED}')\n",
294
+ " generator = torch.Generator(device=\"cuda\").manual_seed(SEED)\n",
295
+ " image = pipe(PROMPT,negative_prompt = NEGATIVE_PROMPT,clip_skip=CLIP_SKIP,generator=generator,width = WIDTH , height = HEIGHT,num_inference_steps=SAMPLING_STEPS,guidance_scale = CFG_scale).images[0]\n",
296
+ " final_images.append(image)\n",
297
+ " save_image_with_png_info(f'outputs/{PROMPT[:10]}_{SEED}.png')\n",
298
+ " f_images = make_image_grid(final_images, 1, len(final_images))\n",
299
+ " display(f_images)\n",
300
+ "else:\n",
301
+ " print(f'SEED : {SEED}')\n",
302
+ " image = pipe(PROMPT,negative_prompt = NEGATIVE_PROMPT,clip_skip=CLIP_SKIP,generator=generator,width = WIDTH , height = HEIGHT,num_inference_steps=SAMPLING_STEPS,guidance_scale = CFG_scale).images[0]\n",
303
+ " save_image_with_png_info(f'outputs/{PROMPT[:11]}_{SEED}_{CLIP_SKIP}_{SCHEDULER}.png')\n",
304
+ " display(image)"
305
+ ]
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "execution_count": null,
310
+ "metadata": {
311
+ "cellView": "form",
312
+ "id": "JNFyUckuixpr"
313
+ },
314
+ "outputs": [],
315
+ "source": [
316
+ "# @title DOWNLOAD THE ZIP WITH ALL THE IMAGES\n",
317
+ "import zipfile\n",
318
+ "import os\n",
319
+ "from google.colab import files\n",
320
+ "\n",
321
+ "def zip_folder(folder_path, zip_filename):\n",
322
+ " with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:\n",
323
+ " for root, _, files in os.walk(folder_path):\n",
324
+ " for file in files:\n",
325
+ " file_path = os.path.join(root, file)\n",
326
+ " arcname = os.path.relpath(file_path, folder_path)\n",
327
+ " zipf.write(file_path, arcname)\n",
328
+ "\n",
329
+ "folder_to_zip = \"outputs\"\n",
330
+ "zip_filename = \"output.zip\"\n",
331
+ "zip_folder(folder_to_zip, zip_filename)\n",
332
+ "print(f'Succesfully saved all the images in {zip_filename}\\nDownloading the zip.....')\n",
333
+ "files.download(zip_filename)"
334
+ ]
335
+ }
336
+ ],
337
+ "metadata": {
338
+ "accelerator": "GPU",
339
+ "colab": {
340
+ "gpuType": "T4",
341
+ "provenance": []
342
+ },
343
+ "kernelspec": {
344
+ "display_name": "Python 3",
345
+ "name": "python3"
346
+ },
347
+ "language_info": {
348
+ "name": "python"
349
+ }
350
+ },
351
+ "nbformat": 4,
352
+ "nbformat_minor": 0
353
+ }