├── current_requests.txt
├── GeneratedImages
└── placeholder
├── examples
├── example1.png
├── example2.png
└── example3.png
├── README.md
├── prompts.py
├── LICENSE
└── bot.py
/current_requests.txt:
--------------------------------------------------------------------------------
1 | 0
--------------------------------------------------------------------------------
/GeneratedImages/placeholder:
--------------------------------------------------------------------------------
1 | guys it's just a placeholder
--------------------------------------------------------------------------------
/examples/example1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheBloke/Stable-Diffusion-Discord-Bot/HEAD/examples/example1.png
--------------------------------------------------------------------------------
/examples/example2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheBloke/Stable-Diffusion-Discord-Bot/HEAD/examples/example2.png
--------------------------------------------------------------------------------
/examples/example3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheBloke/Stable-Diffusion-Discord-Bot/HEAD/examples/example3.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Stable Diffusion Discord Bot
2 | A python discord bot with many features which uses A1111 as backend and uses my prompt templates for beautiful generations - even with short prompts.
3 |
4 | ## Features
5 | It has many features:
6 | - It generates 2 images
7 | - Abitlity to upscale the images
8 | - Abitlity to create small variations of the images
9 | - Retrying with the same settings
10 | - Beautiful images with simple prompts thanks to the prompt templates
11 | - Works with the A1111 - no need for 2 stable diffusion installations
12 | - Blocks direct messages
13 | - Generate random images using a finetuned GPT 2 which runs on cpu (Thanks to: FredZhang7/distilgpt2-stable-diffusion-v2)
14 |
15 | ## How to use this
16 | First you need to install all the python dependencies:
17 | `pip install transformers Pillow requests py-cord`
18 |
19 | Then you can install set the settings variables in bot.py and paste there your discord bot api key. (You first have to create a discord bot at discord.com/developers/ but I won't explain this here. Just make sure that the bot has access to commands and can type messages / embed things. Don't forget to add the bot to your discord using the generated link in the devoloper portal with the correct rights, but I think that should be clear)
20 |
21 | Finally, start the bot using `python3 bot.py` - after this you can use the bot using /generate or /generate_random.
22 |
23 | To change / add styles, add the style to the command array in bot.py and add the preprompt, afterprompt and negative_prompt to prompts.py. There you can also find the prompts for the other styles.
24 |
25 | Since this is my first Discord bot, things could probably be solved in a simpler/better way. So feel free to submit a pull request to fix some issues.
26 |
27 | ## Tips
28 | Load hassanblend (https://huggingface.co/hassanblend/HassanBlend1.5.1.2) in stable diffusion as this is the model all the prompts are tuned on.
29 |
30 | ## Demo
31 | Feel free to test it out in the #sd-art channel in TheBloke's Discord (https://discord.gg/F7jfGhaGRX)
32 |
33 | ## Screenshots
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/prompts.py:
--------------------------------------------------------------------------------
1 | def make_prompt(prompt, style, original_negativeprompt):
2 | if style == 'No Style Preset':
3 | preprompt = ""
4 | afterprompt = ""
5 | negativeprompt_template = "monochrome, nsfw, nude, borders, low quality, low resolution, greyscale"
6 | elif style == 'Low Poly':
7 | preprompt = "A low poly image of a "
8 | afterprompt = ", low poly, soft lighting, cute, masterpiece, (best quality), polygon, trending on artstation, sharp focus, low poly model, render, 4k, flat colors"
9 | negativeprompt_template = "Bad, low quality, worst quality, ugly, old, realistic, watermarks, text, signature"
10 | elif style == 'Anime':
11 | preprompt = "An picture of a "
12 | afterprompt = ", anime style, masterpiece, (best quality), fantasy, trending on artstation, anime-style, bokeh, dreamlike, concept art, hyperrealism, color digital painting, anime aesthetic, cinematic lighting, trending pixiv, by Brad Rigney and greg rutkowski makoto shinkai takashi takeuchi studio ghibli"
13 | negativeprompt_template = "Bad, low quality, worst quality, ugly, border, old, deformed iris, deformed pupils, out of frame, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, nsfw, extra legs, frame, borders, fused fingers, too many fingers, long neck, raw, drops, particles, watermarks, text, signature"
14 | elif style == 'Oilpainting':
15 | preprompt = "Oil painting of a "
16 | afterprompt = ", oil painting, colors, art, ink, drawing, oil brushstrokes, abstract, paint textures, by Leonid Afremov and Brad Rigney"
17 | negativeprompt_template = "Bad, low quality, worst quality, ugly, old, nsfw, watermarks, text, signature"
18 | elif style == 'Cute':
19 | preprompt = "Cute image of a "
20 | afterprompt = ", fantasy, miniature, soft lighting, flat colors, dreamlike, small, surrealism, bokeh, unreal engine, trending on artstation"
21 | negativeprompt_template = "Bad, low quality, worst quality, ugly, old, realistic, nsfw, dark, reallife, texture, realistic, raw"
22 | elif style == 'Comic':
23 | preprompt = "Retro comic style artwork, a "
24 | afterprompt = ", comic, anime style, 1970's, vibrant"
25 | negativeprompt_template = "Bad, low quality, worst quality, ugly, old, nsfw, realistic, raw, watermarks, text, signature"
26 | elif style == 'Cyberpunk':
27 | preprompt = "A picture of a "
28 | afterprompt = ", futuristic, lights, high quality, cyberpunk, octane render, greg rutkowski, highly detailed, trending on artstation, volumetric lighting, dynamic lighting"
29 | negativeprompt_template = "Bad, low quality, worst quality, ugly, old, human, nsfw, watermarks, text, signature"
30 | elif style == 'Steampunk':
31 | preprompt = "A digital illustration of a steampunk "
32 | afterprompt = ", clockwork machines, 4k, detailed, trending in artstation, mechanism, metal, pipes, fantasy vivid colors, sharp focus"
33 | negativeprompt_template = "Bad, low quality, worst quality, ugly, realistic, raw, human, watermarks, text, signature"
34 | elif style == 'Vintage':
35 | preprompt = "Vintage 1950s illustration poster of a "
36 | afterprompt = ", low contrast, vintage, 1950, old fashion, illustration, vector, flat colors, flat design"
37 | negativeprompt_template = "ugly, realistic, raw, text, title, borders, colorful, description, nsfw, watermarks, text, signature"
38 | elif style == 'Apocalyptic':
39 | preprompt = "A apocalyptic picture of a "
40 | afterprompt = ", distopic, cinestill, photography, scary, foggy, ruin, realistic, hyper detailed, unreal engine, cinematic, octane render, lights, greg rutkowski"
41 | negativeprompt_template = "ugly, realistic, raw, text, title, colorful, description, watermarks, text, signature"
42 | elif style == 'Natural':
43 | preprompt = "RAW photo of a "
44 | afterprompt = ", dslr, soft lighting, intricate details, sharp focus, 8k, 4k, UHD, raw, Fujifilm XT3"
45 | negativeprompt_template = "(deformed iris, deformed pupils, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime:1.4), text, close up, cropped, out of frame, worst quality, low quality, jpeg artifacts, bokeh, ugly, duplicate, fat, old, aged, fat, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, 480p, 360p, poorly drawn face, camera, nude, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, watermarks, text, signature"
46 | elif style == 'Watercolor':
47 | preprompt = "A watercolor painting of a "
48 | afterprompt = ", detailed line art, color explosion, ink drips, art, watercolors, wet, single color, abstract, by ilya kuvshinov"
49 | negativeprompt_template = "Bad, low quality, worst quality, ugly, old, human, woman, realistic, anime, japan, nsfw, watermarks, text, signature"
50 | elif style == 'Fantasy':
51 | preprompt = "Digital concept art of a "
52 | afterprompt = ", masterpiece, (best quality), fantasy, volumetric lighting, trending on artstation, dreamlike, concept art, hyperrealism, color digital painting, aesthetic, cinematic lighting, 4k, 8k, trending pixiv, by greg rutkowski"
53 | negativeprompt_template = "Bad, low quality, worst quality, ugly, old, human, nsfw, watermarks, text, signature"
54 | elif style == 'Cinematic':
55 | preprompt = "RAW cinematic picture of a "
56 | afterprompt = ", cinematic look, cinematic, best quality, perfect focus, color grading, 70mm lens, lightroom, 8k, 4k, UHD, Nikon Z FX, sharp focus, Fujifilm XT3, (rutkowski:1.1), artstation, HDR, greg rutkowski"
57 | negativeprompt_template = "(deformed iris, nsfw, barely clothed, naked, deformed pupils, borders, frame, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime:1.4), text, nude, nsfw, borders, cropped, out of frame, worst quality, low quality, low resolution, 480p, jpeg artifacts, ugly, duplicate, fat, old, aged, fat, morbid, mutilated, extra fingers, camera, border, mutated hands, poorly drawn hands, poorly drawn face, nude, mutation, nsfw, deformed, blurry, skin, dehydrated, bad anatomy, 480p, 360p, bad proportions, extra limbs, bad focus, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, watermarks, text, signature"
58 | else:
59 | preprompt = ""
60 | afterprompt = ""
61 | negativeprompt_template = "monochrome, nsfw, nude, borders, low quality, low resolution, greyscale"
62 |
63 | prompt = preprompt + prompt + afterprompt
64 | negativeprompt = original_negativeprompt + ", " + negativeprompt_template
65 | return prompt, negativeprompt
66 |
67 | def make_orientation(orientation):
68 | if 'Landscape' in orientation:
69 | width = 683
70 | height = 512
71 | elif 'Portrait' in orientation:
72 | width = 512
73 | height = 683
74 | elif 'Square' in orientation:
75 | width = 512
76 | height = 512
77 | else:
78 | width = 512
79 | height = 512
80 | return width, height
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/bot.py:
--------------------------------------------------------------------------------
1 | from transformers import AutoTokenizer, GPT2Tokenizer, GPT2LMHeadModel
2 | from PIL import Image, PngImagePlugin
3 | from prompts import make_prompt, make_orientation
4 | from datetime import datetime
5 | import requests
6 | import discord
7 | import string
8 | import random
9 | import base64
10 | import io
11 | import os
12 |
13 | # Settings:
14 | webui_url = "http://localhost:7680" # URL/Port of the A1111 webui
15 | upscaler_model = "R-ESRGAN 4x+" # Name of the upscaler. I recommend "4x_NMKD-Siax_200k" but you have to download it manually.
16 | variation_strenght = 0.065 # How much should the varied image varie from the original?
17 | discord_bot_key = "Your discord bot key here" # Set this to the discord bot key from the bot you created on the discord devoloper page.
18 |
19 | # Initialize
20 | bot = discord.Bot()
21 | os.system('clear')
22 | print ("Bot is running")
23 | characters = string.ascii_letters + string.digits
24 | tokenizer = GPT2Tokenizer.from_pretrained('distilgpt2')
25 | tokenizer.add_special_tokens({'pad_token': '[PAD]'})
26 | model = GPT2LMHeadModel.from_pretrained('FredZhang7/distilgpt2-stable-diffusion-v2')
27 | with open('current_requests.txt', 'r') as file:
28 | total_requests = int(file.read())
29 |
30 | # The single upscale button after generating a variation
31 | class UpscaleOnlyView(discord.ui.View):
32 | def __init__(self, filename, **kwargs):
33 | super().__init__(**kwargs)
34 | self.filename = filename
35 |
36 | @discord.ui.button(label="Upscale", style=discord.ButtonStyle.primary, emoji="🖼️")
37 | async def button_upscale(self, button, interaction):
38 | await interaction.response.send_message(f"Upscaling the image...", ephemeral=True, delete_after=3)
39 | upscaled_image = await upscale(self.filename)
40 | with open(upscaled_image, 'rb') as f:
41 | image_bytes = f.read()
42 | message = await interaction.followup.send(f"Upscaled This Generation:", file=discord.File(io.BytesIO(image_bytes), f'upscaled.png'))
43 |
44 | # The upscale L and upscale R button after retrying
45 | class UpscaleOnlyView2(discord.ui.View):
46 | def __init__(self, filename, filename2, **kwargs):
47 | super().__init__(**kwargs)
48 | self.filename = filename
49 | self.filename2 = filename2
50 |
51 | @discord.ui.button(label="Upscale L", style=discord.ButtonStyle.primary, emoji="🖼️")
52 | async def button_upscale2(self, button, interaction):
53 | await interaction.response.send_message(f"Upscaling the image...", ephemeral=True, delete_after=3)
54 | upscaled_image = await upscale(self.filename)
55 | with open(upscaled_image, 'rb') as f:
56 | image_bytes = f.read()
57 | message = await interaction.followup.send(f"Upscaled This Generation:", file=discord.File(io.BytesIO(image_bytes), f'upscaled.png'))
58 |
59 | @discord.ui.button(label="Upscale R", style=discord.ButtonStyle.primary, emoji="🖼️")
60 | async def button_upscale3(self, button, interaction):
61 | await interaction.response.send_message(f"Upscaling the image...", ephemeral=True, delete_after=3)
62 | upscaled_image = await upscale(self.filename2)
63 | with open(upscaled_image, 'rb') as f:
64 | image_bytes = f.read()
65 | message = await interaction.followup.send(f"Upscaled This Generation:", file=discord.File(io.BytesIO(image_bytes), f'upscaled.png'))
66 |
67 | # The main button rows, contains Upscale L/R, Variation L/R and Retry
68 | # Variation generates almost the same image again using same settings / seed. In addition, this uses an variation strengt.
69 | # We have to refernce all the settings like you see below to generate the correct image again - or we need a reference to the filename to upscale it.
70 | class MyView(discord.ui.View):
71 | def __init__(self, prompt, style, orientation, negative_prompt, seed, filename, image_id, seed1, filename1, image_id1, **kwargs):
72 | super().__init__(**kwargs)
73 | self.prompt = prompt
74 | self.style = style
75 | self.orientation = orientation
76 | self.negative_prompt = negative_prompt
77 | self.seed = seed
78 | self.filename = filename
79 | self.image_id = image_id
80 | self.seed1 = seed1
81 | self.filename1 = filename1
82 | self.image_id1 = image_id1
83 |
84 | @discord.ui.button(label="Upscale L", row=0, style=discord.ButtonStyle.primary, emoji="🖼️")
85 | async def button_upscale(self, button, interaction):
86 | await interaction.response.send_message(f"Upscaling the image...", ephemeral=True, delete_after=4)
87 | upscaled_image = await upscale("GeneratedImages/" + self.image_id + ".png")
88 | with open(upscaled_image, 'rb') as f:
89 | image_bytes = f.read()
90 | message = await interaction.followup.send(f"Upscaled This Generation:", file=discord.File(io.BytesIO(image_bytes), f'{self.prompt}-{self.style}-upscaled.png'))
91 |
92 | @discord.ui.button(label="Upscale R", row=0, style=discord.ButtonStyle.primary, emoji="🖼️")
93 | async def button_upscale2(self, button, interaction):
94 | await interaction.response.send_message(f"Upscaling the image...", ephemeral=True, delete_after=4)
95 | upscaled_image = await upscale("GeneratedImages/" + self.image_id1 + ".png")
96 | with open(upscaled_image, 'rb') as f:
97 | image_bytes = f.read()
98 | message = await interaction.followup.send(f"Upscaled This Generation:", file=discord.File(io.BytesIO(image_bytes), f'{self.prompt}-{self.style}-upscaled.png'))
99 |
100 | @discord.ui.button(label="Variation L", row=1, style=discord.ButtonStyle.primary, emoji="🌱")
101 | async def button_variation(self, button, interaction):
102 | await interaction.response.send_message(f"Creating a variation of the image...", ephemeral=True, delete_after=4)
103 | variation_image, image_id = await imagegen(self.prompt, self.style, self.orientation, self.negative_prompt, self.seed, variation=True)
104 | with open(variation_image, 'rb') as f:
105 | image_bytes = f.read()
106 | message = await interaction.followup.send(f"Varied This Generation:", file=discord.File(io.BytesIO(image_bytes), f'{self.prompt}-{self.style}-{image_id}-varied.png'), view=UpscaleOnlyView(f"GeneratedImages/{image_id}.png"))
107 |
108 | @discord.ui.button(label="Variation R", row=1, style=discord.ButtonStyle.primary, emoji="🌱")
109 | async def button_variation2(self, button, interaction):
110 | await interaction.response.send_message(f"Creating a variation of the image...", ephemeral=True, delete_after=4)
111 | variation_image, image_id = await imagegen(self.prompt, self.style, self.orientation, self.negative_prompt, self.seed1, variation=True)
112 | with open(variation_image, 'rb') as f:
113 | image_bytes = f.read()
114 | message = await interaction.followup.send(f"Varied This Generation:", file=discord.File(io.BytesIO(image_bytes), f'{self.prompt}-{self.style}-{image_id}-varied.png'), view=UpscaleOnlyView(f"GeneratedImages/{image_id}.png"))
115 |
116 | @discord.ui.button(label="Retry", row=2, style=discord.ButtonStyle.primary, emoji="🔄")
117 | async def button_retry(self, button, interaction):
118 | await interaction.response.send_message(f"Regenerating the image using the same settings...", ephemeral=True, delete_after=4)
119 | retried_image, image_id = await imagegen(self.prompt, self.style, self.orientation, self.negative_prompt, random.randint(0, 1000000000000))
120 | retried_image2, image_id2 = await imagegen(self.prompt, self.style, self.orientation, self.negative_prompt, random.randint(0, 1000000000000))
121 | retried_images = [
122 | discord.File(retried_image),
123 | discord.File(retried_image2),
124 | ]
125 | message = await interaction.followup.send(f"Retried These Generations:", files=retried_images, view=UpscaleOnlyView2(f"GeneratedImages/{image_id}.png", f"GeneratedImages/{image_id2}.png"))
126 |
127 | # This is the function the generate the image and send the request to A1111.
128 | async def imagegen(prompt, style, orientation, original_negativeprompt, seed, variation=False):
129 | global total_requests
130 | total_requests = total_requests + 1
131 | global webui_url
132 | global variation_strenght
133 | currentTime = datetime.now()
134 | width, height = make_orientation(orientation)
135 | prompt, negativeprompt = make_prompt(prompt, style, original_negativeprompt)
136 | if variation:
137 | variation_strenght = variation_strenght
138 | else:
139 | variation_strenght = 0
140 | payload = {
141 | "prompt": prompt,
142 | 'negative_prompt': negativeprompt,
143 | "steps": 20,
144 | 'width': width,
145 | 'height': height,
146 | 'cfg_scale': 7,
147 | 'sampler_name': 'Euler',
148 | 'seed': seed,
149 | 'tiling': False,
150 | 'restore_faces': True,
151 | 'subseed_strength': variation_strenght
152 | }
153 | response = requests.post(url=f'{webui_url}/sdapi/v1/txt2img', json=payload)
154 | r = response.json()
155 | for i in r['images']:
156 | image = Image.open(io.BytesIO(base64.b64decode(i.split(",",1)[0])))
157 | png_payload = {
158 | "image": "data:image/png;base64," + i
159 | }
160 | response2 = requests.post(url=f'{webui_url}/sdapi/v1/png-info', json=png_payload)
161 |
162 | pnginfo = PngImagePlugin.PngInfo()
163 | pnginfo.add_text("parameters", response2.json().get("info"))
164 | global characters
165 | image_id = ''.join(random.choice(characters) for i in range(24))
166 | file_path = f"GeneratedImages/{image_id}.png"
167 | image.save(file_path, pnginfo=pnginfo)
168 | print ("Generated Image:", file_path)
169 | print (total_requests)
170 | with open('current_requests.txt', 'w') as file:
171 | file.write(str(total_requests))
172 | return file_path, image_id
173 |
174 | # Sends the upscale request to A1111
175 | async def upscale(image):
176 | global total_requests
177 | total_requests = total_requests + 1
178 | with open(image, 'rb') as image_file:
179 | image_b64 = base64.b64encode(image_file.read()).decode()
180 | upscale_payload = {
181 | "upscaling_resize": 4,
182 | "upscaling_crop": True,
183 | "gfpgan_visibility": 0.6,
184 | "codeformer_visibility": 0,
185 | "codeformer_weight": 0,
186 | "upscaler_1": "4x_NMKD-Siax_200k",
187 | "image": image_b64
188 | }
189 | response_upscaled = requests.post(url=f'{webui_url}/sdapi/v1/extra-single-image', json=upscale_payload)
190 | r_u = response_upscaled.json()
191 | image_bytes = base64.b64decode(r_u['image'])
192 | image_upscaled = Image.open(io.BytesIO(image_bytes))
193 | file_path = image
194 | file_path = file_path.replace('.png', '')
195 | file_path = f"{file_path}-upscaled.png"
196 | image_upscaled.save(file_path)
197 | print ("Upscaled Image:", file_path)
198 | print (total_requests)
199 | with open('current_requests.txt', 'w') as file:
200 | file.write(str(total_requests))
201 | return file_path
202 |
203 | async def generate_prompt():
204 | # This generates a random prompt using a finetuned gpt 2. Uses the transformers library.
205 | prompt_beginnings = ["landscape of", "a beautiful", "digital concept art", "a", "abstract", "highly detailed", "landscape", "fantasy", "isometric", "Greg Rutkowski", "makoto shinkai", "undergrowth, lush", "volumetric lighting", "4k", "by", "dreamlike", "surreal", "lust city", "By Brad Rigney", "vivid colors"]
206 | prompt = random.choice(prompt_beginnings)
207 | temperature = 0.9
208 | top_k = 50
209 | max_length = 50
210 | repitition_penalty = 1.15
211 | num_return_sequences=1
212 | input_ids = tokenizer(prompt, return_tensors='pt').input_ids
213 | output = model.generate(input_ids, do_sample=True, temperature=temperature, top_k=top_k, max_length=max_length, num_return_sequences=num_return_sequences, repetition_penalty=repitition_penalty, early_stopping=True)
214 | return str(tokenizer.decode(output[0], skip_special_tokens=True) + ", colorful, sharp focus")
215 |
216 | # Command for the 2 random images
217 | @bot.command(description="Generates 2 random images")
218 | async def generate_random(
219 | ctx: discord.ApplicationContext,
220 | orientation: discord.Option(str, choices=['Square', 'Portrait', 'Landscape'], default='Square', description='In which orientation should the image be?'),
221 | ):
222 | global total_requests
223 | if ctx.guild is None:
224 | await ctx.respond("This command cannot be used in direct messages.")
225 | return
226 | await ctx.respond("Generating 2 random images...", ephemeral=True, delete_after=4)
227 | prompt = await generate_prompt()
228 | prompt2 = await generate_prompt()
229 | style = "No Style Preset"
230 | seed = random.randint(0, 1000000000000)
231 | seed2 = random.randint(0, 1000000000000)
232 | negative_prompt = "Default"
233 | title_prompt = prompt
234 | if len(title_prompt) > 150:
235 | title_prompt = title_prompt[:150] + "..."
236 | title_prompt2 = prompt2
237 | if len(title_prompt2) > 150:
238 | title_prompt2 = title_prompt2[:150] + "..."
239 | embed = discord.Embed(
240 | title="Generated 2 random images using these settings:",
241 | description=f"Prompt (Left): `{title_prompt}`\nPrompt (Right): `{title_prompt2}`\nOrientation: `{orientation}`\nSeed (Left): `{seed}`\nSeed (Right): `{seed2}`\nNegative Prompt: `{negative_prompt}`\nTotal generated images: `{total_requests}`",
242 | color=discord.Colour.blurple(),
243 | )
244 | generated_image, image_id = await imagegen(prompt, style, orientation, negative_prompt, seed)
245 | generated_image2, image_id2 = await imagegen(prompt2, style, orientation, negative_prompt, seed2)
246 | generated_images = [
247 | discord.File(generated_image),
248 | discord.File(generated_image2),
249 | ]
250 | with open(generated_image, 'rb') as f:
251 | image_bytes = f.read()
252 | if len(prompt) > 100:
253 | prompt = prompt[:100]
254 | message = await ctx.respond(f"<@{ctx.author.id}>'s Random Generations:", files=generated_images, view=MyView(prompt, style, orientation, negative_prompt, seed, generated_image, image_id, seed2, generated_image2, image_id2), embed=embed)
255 | await message.add_reaction('👍')
256 | await message.add_reaction('👎')
257 |
258 | # Command for the normal 2 image generation
259 | @bot.command(description="Generates 2 image")
260 | async def generate(
261 | ctx: discord.ApplicationContext,
262 | prompt: discord.Option(str, description='What do you want to generate?'),
263 | style: discord.Option(str, choices=['Cinematic', 'Low Poly', 'Anime', 'Oilpainting', 'Cute', 'Comic', 'Steampunk', 'Vintage', 'Natural', 'Cyberpunk', 'Watercolor', 'Apocalyptic', 'Fantasy', 'No Style Preset'], description='In which style should the image be?'),
264 | orientation: discord.Option(str, choices=['Square', 'Portrait', 'Landscape'], default='Square', description='In which orientation should the image be?'),
265 | negative_prompt: discord.Option(str, description='What do you want to avoid?', default='')
266 | ):
267 | global total_requests
268 | if ctx.guild is None:
269 | await ctx.respond("This command cannot be used in direct messages.")
270 | return
271 | seed = random.randint(0, 1000000000000)
272 | seed2 = random.randint(0, 1000000000000)
273 | banned_words = ["nude", "naked", "nsfw", "porn"] # The most professional nsfw filter lol
274 | if not negative_prompt:
275 | negative_prompt = "Default"
276 | for word in banned_words:
277 | prompt = prompt.replace(word, "clothes :)")
278 | title_prompt = prompt
279 | if len(title_prompt) > 150:
280 | title_prompt = title_prompt[:150] + "..."
281 | embed = discord.Embed(
282 | title="Prompt: " + title_prompt,
283 | description=f"Style: `{style}`\nOrientation: `{orientation}`\nSeed (Left): `{seed}`\nSeed (Right): `{seed2}`\nNegative Prompt: `{negative_prompt}`\nTotal generated images: `{total_requests}`",
284 | color=discord.Colour.blurple(),
285 | )
286 | await ctx.respond("Generating 2 images...", ephemeral=True, delete_after=3)
287 | generated_image, image_id = await imagegen(prompt, style, orientation, negative_prompt, seed)
288 | generated_image2, image_id2 = await imagegen(prompt, style, orientation, negative_prompt, seed2)
289 | generated_images = [
290 | discord.File(generated_image),
291 | discord.File(generated_image2),
292 | ]
293 | if len(prompt) > 100:
294 | prompt = prompt[:100]
295 | message = await ctx.respond(f"<@{ctx.author.id}>'s Generations:", files=generated_images, view=MyView(prompt, style, orientation, negative_prompt, seed, generated_image, image_id, seed2, generated_image2, image_id2), embed=embed)
296 | await message.add_reaction('👍')
297 | await message.add_reaction('👎')
298 |
299 | bot.run(discord_bot_key)
300 |
--------------------------------------------------------------------------------