-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathstreamlit_app.py
688 lines (516 loc) · 24.5 KB
/
streamlit_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
from docarray import Document
import streamlit as st
import time
# from PIL import Image
# import requests
import plotly.graph_objects as go
import grpc
import os
import pymongo
import streamlit.components.v1 as components
DEFAULT_SERVER_URL = 'grpcs://dalle-flow.dev.jina.ai'
if 'SERVER_URL' in st.secrets:
SERVER_URL = st.secrets['SERVER_URL']
else:
SERVER_URL = DEFAULT_SERVER_URL
LOGO_PATH = 'res/logo.png'
LOG_FILE_LOAD_STATS = 'stats.csv'
PROMPTS_LOG_CSV = 'propmts.csv'
if 'PRIMARY_CONNECTION_STRING' in st.secrets:
PRIMARY_CONNECTION_STRING = st.secrets['PRIMARY_CONNECTION_STRING']
db = pymongo.MongoClient(PRIMARY_CONNECTION_STRING).get_database('dalle-flow-streamlit')
else:
db = None
def display_donation_badge():
html_badge = '''
<p align="center">
<a href="https://www.buymeacoffee.com/TomDoerr" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 41px !important;width: 174px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>
</p>
'''
st.markdown(html_badge, unsafe_allow_html=True)
def write_document(collection_link, document):
if db:
try:
collection = db[collection_link]
collection.insert_one(document)
print('Document inserted')
except Exception as e:
print('Failed to insert document: {}'.format(e))
else:
print(f'No database connection, not inserting into {collection_link}')
def get_all_documents(collection_link):
collection = db[collection_link]
return_list = []
for document in collection.find():
return_list.append(document)
return return_list
if 'prompt' in st.experimental_get_query_params():
prompt_in_url = st.experimental_get_query_params()['prompt'][0]
else:
prompt_in_url = None
if not prompt_in_url:
st.set_page_config(page_title="DALL·E Flow Streamlit", initial_sidebar_state="auto", page_icon="res/logo.png")
else:
st.set_page_config(page_title=prompt_in_url, initial_sidebar_state="collapsed", page_icon="res/logo.png")
if not prompt_in_url:
col1, col2, col3 = st.columns([10,1,10])
else:
col1, col2, col3 = st.columns([10,1,1])
with col1:
if not prompt_in_url:
st.title('DALL·E Flow')
else:
st.title(f'Images of {prompt_in_url}')
with col2:
st.write("")
with col3:
if not prompt_in_url:
st.image(LOGO_PATH, width=200)
if False:
st.markdown('[GitHub Repo](https://github.com/tom-doerr/dalle_flow_streamlit)')
num_images = st.sidebar.slider('Number of initial images', 1, 9, 4)
num_images_variation = st.sidebar.slider('Number of images variation', 1, 9, 9)
skip_rate = 1 - st.sidebar.slider('Variations change amount', 0.0, 1.0, 0.5)
import psutil
import datetime
import sys
def get_cpu_usage():
return psutil.cpu_percent(interval=1)
def get_ram_usage():
return psutil.virtual_memory().percent
def get_disk_usage():
return psutil.disk_usage('/').percent
def get_ram_usage_absolute():
return psutil.virtual_memory().used
def get_disk_usage_absolute():
return psutil.disk_usage('/').used
def get_ram_usage_absolute_gb():
return psutil.virtual_memory().used / 1024**3
def get_disk_usage_absolute_gb():
return psutil.disk_usage('/').used / 1024**3
print(str(datetime.datetime.now()) + ": CPU: " + str(get_cpu_usage()) + "% RAM: " + str(get_ram_usage()) + "% DISK: " + str(get_disk_usage()) + "%")
# print(f'RAM usage: {get_ram_usage_absolute()} DISK usage: {get_disk_usage_absolute()}')
print(f'RAM usage: {get_ram_usage_absolute_gb():.3f} GB DISK usage: {get_disk_usage_absolute_gb():.3f} GB')
sys.stdout.flush()
# with open(LOGO_PATH, 'rb') as f:
# with open('test_image.png', 'rb') as f:
# logo = f.read()
# example str: data:image/png;charset=utf-8,%89PNG%0D%0A%1A
# logo_str = f'data:image/png;charset=utf-8,{logo.decode("utf-8")}'
# fix UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
# logo_str = f'data:image/png;charset=utf-8,{logo.decode("latin-1")}'
def write_page_load_stats():
write_document('page_loads', {'time': time.time()})
with open(LOG_FILE_LOAD_STATS, 'a') as f:
f.write(f'{time.time()}\n')
def log_prompt(prompt):
write_document('prompts', {'time': time.time(), 'prompt': prompt})
with open(PROMPTS_LOG_CSV, 'a') as f:
f.write(f'{time.time()},{prompt}\n')
def plot_page_load_stats():
with st.spinner('Loading page load stats...'):
with open(LOG_FILE_LOAD_STATS, 'r') as f:
lines = f.readlines()
times = [float(line.strip()) for line in lines]
times = sorted(times)
num_times = len(times)
first_time = times[0]
first_time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(first_time))
# st.write(f'{num_times} page loads since {first_time_formatted}')
st.write(f'{num_times} page loads')
fig = go.Figure()
fig.add_trace(go.Scatter(x=[time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t)) for t in times], y=[i for i in range(num_times)], mode='lines+markers'))
st.plotly_chart(fig, use_container_width=True)
st.write("Page loads DB:")
page_loads = get_all_documents('page_loads')
print(f'page_loads: {list(page_loads)}')
# plot them
times = [float(page_load['time']) for page_load in page_loads]
times = sorted(times)
num_times = len(times)
first_time = times[0]
first_time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(first_time))
# st.write(f'{num_times} page loads since {first_time_formatted}')
st.write(f'{num_times} page loads')
fig = go.Figure()
# fig.add_trace(go.Scatter(x=[time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t)) for t in times], y=[i for i in range(num_times)], mode='lines+markers'))
x = [time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t)) for t in times]
y = [i for i in range(num_times)]
# subsample to 1000 points with equal spacing
if len(x) > 1000:
x = x[::len(x)//1000]
y = y[::len(y)//1000]
fig.add_trace(go.Scatter(x=x, y=y, mode='lines+markers'))
st.plotly_chart(fig, use_container_width=True)
overloaded_times_document = get_all_documents('overloaded')
overloaded_times = [float(overloaded_time['time']) for overloaded_time in overloaded_times_document]
overloaded_times = sorted(overloaded_times)
num_overloaded_times = len(overloaded_times)
first_overloaded_time = overloaded_times[0]
first_overloaded_time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(first_overloaded_time))
st.write("Overloaded times:")
st.write(f'{num_overloaded_times} times')
fig = go.Figure()
# fig.add_trace(go.Scatter(x=[time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t)) for t in overloaded_times], y=[i for i in range(num_overloaded_times)], mode='lines+markers'))
x = [time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t)) for t in overloaded_times]
y = [i for i in range(num_overloaded_times)]
# subsample to 1000 points with equal spacing
if len(x) > 1000:
x = x[::len(x)//1000]
y = y[::len(y)//1000]
fig.add_trace(go.Scatter(x=x, y=y, mode='lines+markers'))
st.plotly_chart(fig, use_container_width=True)
# from the collection initial_images get the duration for each entry using the db object
durations_raw = db.initial_images.find({}, {'time': 1, 'duration': 1})
# print("durations_raw:", list(durations_raw))
durations = [{'time': float(duration['time']), 'duration': float(duration['duration'])} for duration in durations_raw]
durations = sorted(durations, key=lambda x: x['time'])
num_durations = len(durations)
first_duration = durations[0]['time']
first_duration_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(first_duration))
st.write("Durations initial:")
fig = go.Figure()
# use points instead of lines
# fig.add_trace(go.Scatter(x=[time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(d['time'])) for d in durations], y=[d['duration'] for d in durations], mode='markers'))
x = [time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(d['time'])) for d in durations]
y = [d['duration'] for d in durations]
# subsample to 1000 points with equal spacing
if len(x) > 1000:
x = x[::len(x)//1000]
y = y[::len(y)//1000]
fig.add_trace(go.Scatter(x=x, y=y, mode='lines+markers'))
st.plotly_chart(fig, use_container_width=True)
# from the collection diffusion_images get the duration for each entry using the db object
diffusion_image_durations_raw = db.diffusion_images.find({}, {'time': 1, 'duration': 1})
diffusion_image_durations = [{'time': float(diffusion_image_duration['time']), 'duration': float(diffusion_image_duration['duration'])} for diffusion_image_duration in diffusion_image_durations_raw if 'duration' in diffusion_image_duration]
diffusion_image_durations = sorted(diffusion_image_durations, key=lambda x: x['time'])
num_diffusion_image_durations = len(diffusion_image_durations)
first_diffusion_image_duration = diffusion_image_durations[0]['time']
first_diffusion_image_duration_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(first_diffusion_image_duration))
st.write("Durations diffusion:")
fig = go.Figure()
# fig.add_trace(go.Scatter(x=[time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(d['time'])) for d in diffusion_image_durations], y=[d['duration'] for d in diffusion_image_durations], mode='markers'))
x = [time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(d['time'])) for d in diffusion_image_durations]
y = [d['duration'] for d in diffusion_image_durations]
# subsample to 1000 points with equal spacing
if len(x) > 1000:
x = x[::len(x)//1000]
y = y[::len(y)//1000]
fig.add_trace(go.Scatter(x=x, y=y, mode='lines+markers'))
st.plotly_chart(fig, use_container_width=True)
# plot number of diffusions
diffusion_times_raw = db.diffusion_images.find({}, {'time': 1})
diffusion_times = [float(diffusion_time['time']) for diffusion_time in diffusion_times_raw]
diffusion_times = sorted(diffusion_times)
num_diffusion_times = len(diffusion_times)
first_diffusion_time = diffusion_times[0]
first_diffusion_time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(first_diffusion_time))
st.write("Diffusions:")
st.write(f'{num_diffusion_times} diffusions')
fig = go.Figure()
# fig.add_trace(go.Scatter(x=[time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(d)) for d in diffusion_times], y=[i for i in range(num_diffusion_times)], mode='lines+markers'))
x = [time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(d)) for d in diffusion_times]
y = [i for i in range(num_diffusion_times)]
# subsample to 1000 points with equal spacing
if len(x) > 1000:
x = x[::len(x)//1000]
y = y[::len(y)//1000]
fig.add_trace(go.Scatter(x=x, y=y, mode='lines+markers'))
st.plotly_chart(fig, use_container_width=True)
# def load_prompts():
# # check if file exists
# if not os.path.isfile(PROMPTS_LOG_CSV):
# return []
# with open(PROMPTS_LOG_CSV, 'r') as f:
# lines = f.readlines()
# lines = [line.strip().split(',') for line in lines]
# lines = [line for line in lines if len(line) == 2]
# lines = [line for line in lines if line[1] != '']
# lines = [line[1] for line in lines]
# return lines
def load_prompts_with_times():
if not os.path.isfile(PROMPTS_LOG_CSV):
return []
with open(PROMPTS_LOG_CSV, 'r') as f:
lines = f.readlines()
lines = [line.strip().split(',') for line in lines]
lines = [line for line in lines if len(line) == 2]
lines = [line for line in lines if line[1] != '']
lines = [line for line in lines if line[0] != '']
return lines
def load_prompts_with_times_unique():
prompts_with_times = load_prompts_with_times()
output = []
prompts_set = set()
for prompt_with_time in prompts_with_times:
if prompt_with_time[1] not in prompts_set:
output.append(prompt_with_time)
prompts_set.add(prompt_with_time[1])
return output
def load_prompts():
lines = load_prompts_with_times()
lines = [line[1] for line in lines]
return lines
def load_prompts_unique():
prompts_all = load_prompts()
prompts_unique = set(prompts_all)
return prompts_unique
def plot_prompts_stats(prompts):
with st.spinner('Loading prompts stats...'):
times = [float(line[0].strip()) for line in prompts]
times = sorted(times)
num_times = len(times)
first_time = times[0]
first_time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(first_time))
# st.write(f'{num_times} prompts since {first_time_formatted}')
st.write(f'{num_times} prompts')
fig = go.Figure()
fig.add_trace(go.Scatter(x=[time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t)) for t in times], y=[i for i in range(num_times)], mode='lines+markers'))
st.plotly_chart(fig, use_container_width=True)
def show_stats():
# add stats to url
st.experimental_set_query_params(stats='true')
plot_page_load_stats()
num_prompts = len(load_prompts())
prompts_with_times = load_prompts_with_times()
st.write('Prompts:')
plot_prompts_stats(prompts_with_times)
num_unique_prompts = len(load_prompts_unique())
prompts_with_times_unique = load_prompts_with_times_unique()
st.write('Unique prompts:')
plot_prompts_stats(prompts_with_times_unique)
def get_images(prompt, num_images):
# time.sleep(10)
# return 'test'
try:
# if use_dalle and use_glid3:
# target_executor = None
# elif use_dalle:
# target_executor = 'dalle'
# elif use_glid3:
# target_executor = 'glid3'
# else:
# st.info('No AI selected. Please select an AI to use in the sidebar.')
# st.stop()
target_executor = AI_EXECUTOR_DICT[selected_ai]
return Document(text=prompt).post(SERVER_URL, parameters={'num_images': num_images}, target_executor=target_executor).matches
# except BlockingIOError as e:
except grpc.aio._call.AioRpcError as e:
st.write(e)
st.stop()
def display_image_with_buttons(image):
col_left, col_right = st.columns([1,1])
with col_left:
st.image(image.uri)
with col_right:
st.button('Create variations', key=image.uri, on_click=diffuse_image, args=(image,))
st.button('Create high resolution version', key=image.uri, on_click=upscale_image, args=(image,))
def display_images(images, original=None):
if original:
images.append(original)
for i, image in enumerate(images):
if original and i == len(images) - 1:
st.write('---')
st.write('Original image:')
# d:
# <Document ('id', 'adjacency', 'mime_type', 'text', 'uri', 'tags') at f98709a922457dea22a7f19d398e3977>
display_image_with_buttons(image)
st.write('---')
display_donation_badge()
# images = get_images(prompt, num_images)
async def get_images_async(prompt, num_images):
# time.sleep(3)
yield
# return
# return get_images(prompt, num_images)
import asyncio
def create_initial_image(prompt):
start_time = time.time()
with st.spinner('Creating the images. This may take over 10 minutes...'):
# images = get_images(prompt, num_images)
# same but async:
# loop = asyncio.get_event_loop()
# loop = asyncio.new_event_loop()
# get_images_task = loop.create_task(get_images_async(prompt, num_images))
# future = asyncio.run_coroutine_threadsafe(get_images_async(prompt, num_images), loop)
import concurrent.futures
_pool = concurrent.futures.ThreadPoolExecutor()
images_future = _pool.submit(get_images, prompt, num_images)
col1, col2, col3 = st.columns(3)
with col1:
st.text('')
with col2:
# components.iframe(links[1], width=120, height=240)
iframe_component = st.empty()
with col3:
st.text('')
previous_component = None
iframe_container = st.empty()
display_affiliate_links()
while True:
print("images_future.done():", images_future.done())
if images_future.done():
break
time.sleep(1)
if False:
links = get_affiliate_links(number_links=1)
# iframe_component.iframe(links[0], width=120, height=240)
iframe_container = st.container()
with iframe_container:
components.iframe(links[0], width=120, height=240)
images = images_future.result()
print("images:", images)
print(f'id: {images[0].id}')
print(f'adjacency: {images[0].adjacency}')
print(f'mime_type: {images[0].mime_type}')
print(f'text: {images[0].text}')
# print(f'uri: {images[0].uri}')
print(f'tags: {images[0].tags}')
end_time = time.time()
print(f'Took {end_time - start_time:.1f} seconds')
with initial_image_container:
st.write(f'Took {end_time - start_time:.1f} seconds')
display_images(images)
if False:
import urllib.request
images_data = []
# download images
for image in images:
urllib.request.urlretrieve(image.uri, f'{image.id}.png')
images_data.append(urllib.request.urlopen(image.uri).read())
else:
# images_data = images
# images_data = [image.uri for image in images]
images_data = [convert_image_to_dict(image) for image in images]
write_document('initial_images', {'time': time.time(), 'num_images': num_images, 'prompt': prompt, 'duration': end_time - start_time, 'images': images_data})
# display_images(images)
st.balloons()
def convert_image_to_dict(image):
return {'id': image.id, 'adjacency': image.adjacency, 'mime_type': image.mime_type, 'text': image.text, 'uri': image.uri, 'tags': image.tags}
def diffuse_image(chosen_image):
st.title('Image variations')
# if True:
if False:
st.warning('Overwritting chosen image!')
chosen_image.uri = logo_str
with st.spinner('Creating variations, this may take a few minutes...'):
start_time = time.time()
diffused_images = chosen_image.post(f'{SERVER_URL}', parameters={'skip_rate': skip_rate, 'num_images': num_images_variation}, target_executor='diffusion').matches
end_time = time.time()
display_images(diffused_images, chosen_image)
# <Document ('id', 'adjacency', 'mime_type', 'text', 'uri', 'tags', 'scores')
image_dict = convert_image_to_dict(chosen_image)
image_dicts = [convert_image_to_dict(image) for image in diffused_images]
duration = end_time - start_time
write_document('diffusion_images', {'time': time.time(), 'skip_rate': skip_rate, 'num_images': num_images_variation, 'prompt': prompt, 'duration': duration, 'chosen_image': image_dict, 'diffused_images': image_dicts})
st.balloons()
st.stop()
def upscale_image(chosen_image):
st.title('High resolution image')
with st.spinner('Creating a high resolution image from the selected image, this may take a few minutes...'):
upscaled_image = chosen_image.post(f'{SERVER_URL}/upscale', target_executor='upscaler')
st.image(upscaled_image.uri)
# display_images([upscaled_image], original=chosen_image)
st.write('---')
st.write('Original image:')
display_image_with_buttons(chosen_image)
image_chosen_dict = convert_image_to_dict(chosen_image)
image_upscaled_dict = convert_image_to_dict(upscaled_image)
write_document('upscaled_images', {'time': time.time(), 'chosen_image': image_chosen_dict, 'upscaled_image': image_upscaled_dict})
st.stop()
def download_image(chosen_image):
st.title('Downloading image')
st.download_button(chosen_image.uri, chosen_image.uri, mime=chosen_image.mime_type)
st.stop()
def get_num_prompts_last_x_min(mins):
prompts_with_times = load_prompts_with_times()
prompts_with_times = [prompt_with_time for prompt_with_time in prompts_with_times if time.time() - float(prompt_with_time[0]) < mins * 60]
num_prompts = len(prompts_with_times)
print(f'{num_prompts} prompts in the last {mins} minutes')
return num_prompts
st.sidebar.write('AI to use')
# use_stable_diffusion = st.sidebar.checkbox('Stable Diffusion', value=True)
# use_stable_diffusion_lite = st.sidebar.checkbox('Stable Diffusion Lite', value=False)
# use_dalle = st.sidebar.checkbox('DALL·E Mega', value=False)
# use_glid3 = st.sidebar.checkbox('GLID3 XL', value=False)
# selected_ai = st.sidebar.selectbox('Select AI', ['Stable Diffusion', 'Stable Diffusion Lite', 'DALL·E Mega', 'GLID3 XL'], index=0)
# AI_EXECUTOR_DICT = {
# 'Stable Diffusion': 'stable',
# 'Stable Diffusion Lite': 'stablelite',
# 'DALL·E Mega': 'dalle',
# 'GLID3 XL': 'glid3',
# }
AI_EXECUTOR_DICT = {
# 'Stable Diffusion': 'stable',
# 'Stable Diffusion Lite': 'stablelite',
'DALL·E Mega': 'dalle',
# 'GLID3 XL': 'glid3',
}
selected_ai = st.sidebar.selectbox('Select AI', list(AI_EXECUTOR_DICT.keys()), index=0)
st.sidebar.write('---')
show_stats_bool = (st.sidebar.button('Show statistics') or (('stats' in st.experimental_get_query_params()) and st.experimental_get_query_params()['stats'][0] == 'true'))
if st.sidebar.button('Add prompt to URL'):
st.experimental_set_query_params(prompt=prompt)
# st.experimental_set_query_params(prompt='hamster in speedo')
HTML_COUNT_WIDGET = '<img src="https://badges.pufler.dev/visits/tom-doerr/dummy1?style=for-the-badge&color=ff4b4b&logoColor=white&labelColor=302D41"/>'
# st.sidebar.markdown(HTML_COUNT_WIDGET, unsafe_allow_html=True)
write_page_load_stats()
if show_stats_bool:
show_stats()
MINUTES_TO_CONSIDER = 5
MAX_REQUESTS_PER_INTERVALL = 4
num_prompts_last_x_min = get_num_prompts_last_x_min(MINUTES_TO_CONSIDER)
from affiliate_iframes import affiliate_iframes
import random
def get_random_iframe_html():
affiliate_iframe_html_dict = affiliate_iframes
return random.choice(list(affiliate_iframe_html_dict.values()))
# import BeautifulSoup
from bs4 import BeautifulSoup
def get_link_from_iframe(iframe_html):
# soup = BeautifulSoup(iframe_html, 'html.parser')
# link = soup.find('iframe')['src']
# return link
link = iframe_html.split('src="')[1].split('"></iframe>')[0]
return link
def get_affiliate_links(number_links=5):
links = []
while True:
random_html_iframe = get_random_iframe_html()
link = get_link_from_iframe(random_html_iframe)
if link not in links:
links.append(link)
if len(links) == number_links:
break
return links
def display_affiliate_links():
links = get_affiliate_links(number_links=5)
col1, col2, col3, col4, col5 = st.columns(5)
with col1:
# components.iframe(link, width=120, height=240)
components.iframe(links[0], width=120, height=240)
with col2:
components.iframe(links[1], width=120, height=240)
with col3:
components.iframe(links[2], width=120, height=240)
with col4:
components.iframe(links[3], width=120, height=240)
with col5:
components.iframe(links[4], width=120, height=240)
if num_prompts_last_x_min >= MAX_REQUESTS_PER_INTERVALL:
st.info('The server currently gets a high number of requests, please try again later.')
write_document('overloaded', {'time': time.time(), 'num_prompts': num_prompts_last_x_min, 'max_requests_per_intervall': MAX_REQUESTS_PER_INTERVALL, 'mins_considered': MINUTES_TO_CONSIDER})
display_affiliate_links()
st.stop()
if not prompt_in_url:
st.markdown('Example description: `A raccoon astronaut with the cosmos reflecting on the glass of his helmet dreaming of the stars, digital art`')
logo_description = st.text_input('Image description:')
initial_image_container = st.container()
if not prompt_in_url:
prompt = logo_description
else:
prompt = prompt_in_url
if not prompt:
st.stop()
log_prompt(prompt)
create_initial_image(prompt)