greendra commited on
Commit
87ae37d
·
1 Parent(s): 61feb51

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +269 -4
app.py CHANGED
@@ -1,8 +1,273 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!"
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import time
3
+ import base64
4
+ from io import BytesIO
5
+ import requests
6
+ import json
7
+ import io
8
+ import time
9
+ from io import BytesIO
10
+ from PIL import Image
11
+ from stability_sdk import client
12
+ import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation
13
+ import re
14
+ import random
15
+ import datetime
16
+ import pytz
17
+ from proxy_randomizer import RegisteredProviders
18
+ from cryptography.fernet import Fernet
19
+ import os
20
 
21
+ sd_decode = os.environ.get('sd_decode')
22
+ bbtries = 0
23
 
24
+ def freeimagehost(prompt, img, seed):
25
+ try:
26
+ rp = RegisteredProviders()
27
+ rp.parse_providers()
28
+ # get one proxy
29
+ proxy = rp.get_random_proxy()
30
+ proxy = proxy.get_proxy()
31
+ # convert proxy to dictionary
32
+ proxy = proxy.split(':')
33
+ # convert list to dictionary
34
+ proxy = {'http': 'http://' + proxy[0] + ':' + proxy[1]}
35
+ except:
36
+ print("Error getting proxy")
37
+ proxy = {}
38
 
39
+ try:
40
+ buffered = BytesIO()
41
+ img.save(buffered, format="JPEG")
42
+ img_str = base64.b64encode(buffered.getvalue())
43
+ key = "6d207e02198a847aa98d0a2a901485a5"
44
+ payload = {'key': key, 'image': img_str, 'format': 'json', 'expiration': '3600'}
45
+ r = requests.post("https://freeimage.host/api/1/upload", data=payload, proxies=proxy)
46
+ r = json.loads(r.text)
47
+ try:
48
+ link = loglink = r['image']['url']
49
+ link = '<a style="color:blue;" href="https://arinteli.com/app/?' + link + '+' + prompt + '+' + seed + '" target=”_blank”>'+ link +'</a>'
50
+ except:
51
+ return imagebb(prompt, img, seed)
52
+ except:
53
+ return imagebb(prompt, img, seed)
54
+ return link, loglink
55
+
56
+ def imagebb(prompt, img, seed):
57
+ try:
58
+ rp = RegisteredProviders()
59
+ rp.parse_providers()
60
+ # get one proxy
61
+ proxy = rp.get_random_proxy()
62
+ proxy = proxy.get_proxy()
63
+ # convert proxy to dictionary
64
+ proxy = proxy.split(':')
65
+ # convert list to dictionary
66
+ proxy = {'http': 'http://' + proxy[0] + ':' + proxy[1]}
67
+ except:
68
+ print("Error getting proxy")
69
+ proxy = {}
70
+
71
+ try:
72
+ buffered = BytesIO()
73
+ img.save(buffered, format="JPEG")
74
+ img_str = base64.b64encode(buffered.getvalue())
75
+ with open('bb_encode.txt') as f:
76
+ bbkeys = f.readlines()
77
+ bbkey = random.choice(bbkeys)
78
+ bbkeyid = bbkeys.index(bbkey) + 1
79
+ print(bbkeyid)
80
+ bbkey = Fernet(sd_decode).decrypt(bbkey.encode())
81
+ # convert the sdkey from bytes to a string
82
+ bbkey = bbkey.decode()
83
+ bbkey = bbkey.strip()
84
+ payload = {'key': bbkey, 'image': img_str, 'name': prompt, 'format': 'json', 'expiration': '3600'}
85
+ r = requests.post("https://api.imgbb.com/1/upload", data=payload, proxies=proxy)
86
+ r = json.loads(r.text)
87
+ try:
88
+ link = loglink = r['data']['url']
89
+ link = '<a style="color:blue;" href="https://arinteli.com/app/?' + link + '+' + prompt + '+' + seed + '" target=”_blank”>'+ link +'</a>'
90
+ except:
91
+ print(r)
92
+ global bbtries
93
+ bbtries += 1
94
+ if bbtries < 3:
95
+ return imagebb(prompt, img, seed)
96
+ else:
97
+ bbtries = 0
98
+ return imgur(prompt, img, seed)
99
+ except Exception as e:
100
+ print(e)
101
+ bbtries += 1
102
+ if bbtries < 3:
103
+ return imagebb(prompt, img, seed)
104
+ else:
105
+ bbtries = 0
106
+ return imgur(prompt, img, seed)
107
+ return link, loglink
108
+
109
+ def imgur(prompt, img, seed):
110
+ try:
111
+ buffered = BytesIO()
112
+ img.save(buffered, format="JPEG")
113
+ img_str = base64.b64encode(buffered.getvalue())
114
+ url = "https://api.imgur.com/3/image"
115
+ payload={'image': img_str}
116
+ files=[
117
+ ]
118
+ headers = {
119
+ 'Authorization': 'Client-ID ab515931f7df961'
120
+ }
121
+ response = requests.request("POST", url, headers=headers, data=payload, files=files)
122
+ response = json.loads(response.text)
123
+ try:
124
+ link = loglink = response['data']['link']
125
+ link = '<a style="color:blue;" href="https://arinteli.com/app/?' + link + '+' + prompt + '+' + seed + '" target=”_blank”>'+ link +'</a>'
126
+ except:
127
+ link = loglink = "Error generating link (service rebooting)"
128
+
129
+ except:
130
+ link = loglink = "Error (2) generating link"
131
+ return link, loglink
132
+
133
+ def sd(prompt):
134
+ sdtries = 0
135
+ if prompt == "":
136
+ return Image.open('error.png'), "Error! Please enter a prompt"
137
+
138
+ london = pytz.timezone('Europe/London')
139
+ now = datetime.datetime.now(london)
140
+ timestamp = (now.strftime("%H:%M:%S"))
141
+ timestamp = str(timestamp)
142
+ with open("keys_encode2.txt", "r") as f:
143
+ sdkeys = f.readlines()
144
+ sdkey = random.choice(sdkeys)
145
+ keyid = sdkeys.index(sdkey) + 1
146
+ keyid = str(keyid)
147
+ sdkey = sdkey.strip()
148
+ # decode the sdkey with the Fernet key
149
+ sdkey = Fernet(sd_decode).decrypt(sdkey.encode())
150
+ # convert the sdkey from bytes to a string
151
+ sdkey = sdkey.decode()
152
+
153
+ # connect to dream API
154
+ stability_api = client.StabilityInference(
155
+ key = sdkey,
156
+ verbose=True,
157
+ engine="stable-diffusion-v1-5",
158
+ )
159
+ # convert string prompt to lowercase
160
+ prompt = prompt.lower()
161
+
162
+ # set random seed
163
+ seed = random.randint(0, 9999999)
164
+
165
+ # create list bad_words_list from bad_words.txt and strip whitespace
166
+ with open('bad_words.txt') as f:
167
+ bad_words_list = f.readlines()
168
+ bad_words_list = [x.strip() for x in bad_words_list]
169
+
170
+ # check if bad_words_list is in prompt
171
+ if any(re.findall(r'\b{}\b'.format(bad_word), prompt) for bad_word in bad_words_list):
172
+ # check if any bad words are in prompt
173
+ blocked_words = []
174
+ for bad_word in bad_words_list:
175
+ if re.findall(r'\b{}\b'.format(bad_word), prompt):
176
+ blocked_words.append(bad_word)
177
+
178
+
179
+ blocked_words = ', '.join(blocked_words)
180
+ print(keyid + ": " + timestamp + ": BLOCKED PROMPT \"" + prompt + "\" BANNED WORDS: " + blocked_words)
181
+ time.sleep(3)
182
+ print("User has had their time wasted.\n")
183
+ # javascript to log error to console
184
+ return Image.open('unsafe.png'), "Your prompt contains blocked words! Please try a different prompt!"
185
+
186
+ else:
187
+ try:
188
+ # send prompt to dream API
189
+ # set random seed
190
+ answers = stability_api.generate(
191
+ prompt=prompt,
192
+ steps=25,
193
+ seed=seed,
194
+ )
195
+
196
+ # convert seed to string
197
+ seed = str(seed)
198
+
199
+ # iterating over the generator produces the api response
200
+ for resp in answers:
201
+ for artifact in resp.artifacts:
202
+ if artifact.finish_reason == generation.FILTER:
203
+ print("FILTERED PROMPT \"" + prompt + "\"")
204
+ try:
205
+ img = Image.open(io.BytesIO(artifact.binary))
206
+ print("API image filter\n")
207
+ return img, "<b>Sorry, Stability.AI detected your image as unsafe (likely a false positive). Please try regenerating your image again, or adjusting your prompt.</b>", seed
208
+ except:
209
+ img = Image.open('unsafe.png')
210
+ print("API word filter\n")
211
+ return img, "<b>Sorry, Stability.AI detected unsafe words in your prompt. Please remove them and try again.</b>", seed
212
+
213
+ if artifact.type == generation.ARTIFACT_IMAGE:
214
+ img = Image.open(io.BytesIO(artifact.binary))
215
+ link = freeimagehost(prompt, img, seed)
216
+ # time.sleep(2)
217
+ print(keyid + ": " + timestamp + ": PROMPT \"" + prompt + "\" WAS GENERATED SUCCESSFULLY AND IMAGE LINK: \n" + link[1] + "\n")
218
+ return img, 'Your download URL: ' + link[0] + '<br> Seed: ' + seed
219
+ except Exception as e:
220
+ print(keyid, '\n' ,e)
221
+ sdtries += 1
222
+ if sdtries < 5:
223
+ print("Retrying...")
224
+ return sd(prompt)
225
+ else:
226
+ sdtries = 0
227
+ return Image.open('error.png'), "Error! Please try again"
228
+
229
+
230
+
231
+ examples = ["Futuristic utopian city in Coruscant. god beams. white buildings. street view. golden sunset. colorful, cityscape, green trees, future, urban, megapolis, breathtaking, Imaginative, utopia, Wallpaper, beautiful design, scifi, high detail, global illumination, ArtStation, art by Sebastian Wagner, Stephan Martiniere, Leon Tukker, Vitaly-Sokol",
232
+ "A dream of a distant galaxy, by Caspar David Friedrich, matte painting trending on artstation HQ",
233
+ "1990s movie, orbit space new york city street with many pedestrians as a loading screen, cinestill 800t 18mm, heavy grainy picture, very detailed, high quality, 4k panoramic, dramatic lightning, streetlight at night, rain, mud, foggy, anchray flags",
234
+ "Portrait of a woman by Greg Rutkowski, she is about 30 years old, pretty, blond hair with two strans around her face, slavic features, melancholic gaze, pretty aquiline nose, she is wearing a blue utilitarian jumpsuit, highly detailed portrait, digital painting, artstation, concept art, smooth, sharp foccus ilustration, Artstation HQ.",
235
+ "A small cabin on top of a snowy mountain in the style of Disney, artstation",
236
+ "futuristic space landscape by Jessica Rossier and HR Giger",
237
+ "Tiny cute isometric living room in a cutaway box, soft smooth lighting, soft colors, purple and blue color scheme, soft colors, 100mm lens, 3d blender render",
238
+ "techno mining tailing in chuquicamata bioremediation white futuristic horizontal architecture, epic, cinematic, hyperealistic, high detailed, corona render, hdr, ray tracing",
239
+ "A highly detailed matte painting of Orgrimmar the warrior city by Studio Ghibli, Makoto Shinkai, by Artgerm, by beeple, volumetric lighting, octane render, 4K resolution, trending on artstation, masterpiece",
240
+ "Cute close portrait dainty beautiful futurstic white robotic girl, portraits, white cyberpunk inflatable formfitting tops, highly detailed sharp big eyes, white fringeshort hair, transparent intricate details, professional 3d visualisation in pastel colours, by wlop, intricate linework, trending on artstation, unreal engine 5 highly rendered, epic composition, by guweiz, shal. e, laica chrose, final fantasy",]
241
+
242
+ with gr.Blocks(css = """
243
+ *, body, #name, #ex, #article, .border-gray-200, .gr-input, .border-gray-100 { background: #0b0f19; color: white; border-color: #4c4c4c; }
244
+ .gr-samples-gallery .gr-sample-textbox, #greet_btn, #save_btn, .py-1, .gr-samples-gallery:hover .gr-sample-textbox:hover, .gr-text-input, #output, .wrap.svelte-1c38quw, .h-wrap { background: #1f2937; color: white; border-color: #4c4c4c;}
245
+ .py-6 {padding-top: 0;}
246
+ """
247
+ ) as demo:
248
+ download = gr.HTML(elem_id="download")
249
+ output = gr.Image(label="Image Generation", elem_id="output")
250
+ name = gr.Textbox(label="Prompt", placeholder="Describe the image you want to generate. Longer and more detailed prompts work better.", elem_id="name")
251
+ greet_btn = gr.Button("Generate Image", elem_id="greet_btn")
252
+ bin = gr.HTML("", visible=False)
253
+ ex = gr.Examples(examples=examples, fn=sd, inputs=name, outputs=[output, download], cache_examples=True)
254
+ ex.dataset.headers = [""]
255
+ greet_btn.click(
256
+ None,
257
+ [],
258
+ bin,
259
+ _js="""
260
+ () => {
261
+ /*! js-cookie v3.0.1 | MIT */
262
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self,function(){var n=e.Cookies,o=e.Cookies=t();o.noConflict=function(){return e.Cookies=n,o}}())}(this,(function(){"use strict";function e(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}return function t(n,o){function r(t,r,i){if("undefined"!=typeof document){"number"==typeof(i=e({},o,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var c="";for(var u in i)i[u]&&(c+="; "+u,!0!==i[u]&&(c+="="+i[u].split(";")[0]));return document.cookie=t+"="+n.write(r,t)+c}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],o={},r=0;r<t.length;r++){var i=t[r].split("="),c=i.slice(1).join("=");try{var u=decodeURIComponent(i[0]);if(o[u]=n.read(c,u),e===u)break}catch(e){}}return e?o[e]:o}},remove:function(t,n){r(t,"",e({},n,{expires:-1}))},withAttributes:function(n){return t(this.converter,e({},this.attributes,n))},withConverter:function(n){return t(e({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(o)},converter:{value:Object.freeze(n)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"})}));
263
+ // create cookie
264
+ if (Cookies.get('creations') == undefined) {
265
+ Cookies.set('creations', '1', { expires: 250 / 24 / 60 / 60 });
266
+ } else {
267
+ Cookies.set('creations', parseInt(Cookies.get('creations')) + 1, { expires: 250 / 24 / 60 / 60 }); }
268
+ console.log(Cookies.get('creations'));
269
+ }""")
270
+ greet_btn.click(fn=sd, inputs=name, outputs=[output, download])
271
+
272
+
273
+ demo.queue(concurrency_count=3, max_size=20).launch(max_threads=150)