-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.py
1510 lines (1411 loc) · 65.2 KB
/
bot.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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# https://docs.aiogram.dev/en/latest/
from aiogram import Bot, Dispatcher, types
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.utils import executor
from aiogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
Message,
CallbackQuery,
InputMediaDocument,
InputFile,
InputMediaPhoto,
)
import webuiapi, io
import subprocess
import time
import json
import requests
import asyncio
import os
import random
from datetime import datetime
import aiohttp
from typing import Union
from PIL import Image
from transformers import GPT2Tokenizer, GPT2LMHeadModel
import inspect
from translate import Translator
import base64
from pathlib import Path
import logging
import vk_api
from vk_api import VkUpload #https://github.com/python273/vk_api
from ok_api import OkApi, Upload # https://github.com/needkirem/ok_api
# Настройка логгера
logging.basicConfig(format="[%(asctime)s] %(levelname)s : %(name)s : %(message)s",
level=logging.DEBUG, datefmt="%d-%m-%y %H:%M:%S")
logging.getLogger('aiogram').setLevel(logging.DEBUG)
logger = logging.getLogger(__name__)
# from https://t.me/BotFather
API_BOT_TOKEN = "TOKEN_HERE"
#заходим в https://oauth.vk.com/authorize?client_id=51626357&scope=photos&redirect_uri=http%3A%2F%2Foauth.vk.com%2Fblank.html&display=page&response_type=token
# где 51626357 - номер вашего включенного приложения, созданного в https://vk.com/apps?act=manage,
# photos - зона доступа.
# После перехода и подтверждения выцепляем access_token из адресной строки
# TODO auto requests
# OK https://ok.ru/vitrine/myuploaded
# Добавить приложение - https://ok.ru/app/setup
# дбавить платформу - OAUTH
# VALUABLE_ACCESS = Обязательно
# PHOTO_CONTENT = Обязательно
# Ссылка на страницу = https://apiok.ru/oauth_callback
# Список разрешённых redirect_uri = https://apiok.ru/oauth_callback
# сохранить, перезайти
# Ищем ID приложения справа от "Основные настройки приложения" - ID 512002358821
# Открываем в браузере https://connect.ok.ru/oauth/authorize?client_id=512002358821&scope=PHOTO_CONTENT;VALUABLE_ACCESS&response_type=token&redirect_uri=https://apiok.ru/oauth_callback
# С адресной строки копируем token в access_token ниже
# application_key = Публичный ключ справа от "Основные настройки приложения"
# Вечный access_token - Получить новый
# application_secret_key = Session_secret_key
VK_TOKEN = 'VK_TOKEN_HERE'
API_BOT_TOKEN = 'API_BOT_TOKEN_HERE'
VK_ALBUM_ID = 'VK_ALBUM_ID' # брать с адресной строки, когда открываешь ВК. Пример https://vk.com/album123_789
OK_ACCESS_TOKEN = 'OK_ACCESS_TOKEN_HERE'
OK_APPLICATION_KEY = 'OK_APPLICATION_KEY_HERE'
OK_APPLICATION_SECRET_KEY = 'OK_APPLICATION_SECRET_KEY_HERE'
OK_GROUP_ID = 'OK_GROUP_ID_HERE'
ARRAY_INLINE = []
bot = Bot(token=API_BOT_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
# /create_post_vk
@dp.message_handler(commands=['create_post_vk'])
async def create_post_vk(message: types.Message) -> None:
result = subprocess.run(
['C:\OSPanel\modules\php\PHP_7.3\php.exe', "C:/OSPanel/domains/localhost/vk/create_post.php"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
output = result.stdout.decode('utf-8')
await message.reply(output, reply_markup=types.ReplyKeyboardRemove())
# Получаем список аргументов функции api.txt2img и возвращаем JSON {"/prompt": "","/seed": "-1",...}
def getAttrtxt2img():
spec = inspect.getfullargspec(api.txt2img)
arguments = spec.args
values = [spec.defaults[i] if i >= (len(spec.defaults) or 0)*-1 else None for i in range(-1, (-1)*(len(arguments)+1), -1)][::-1]
params = {arg: value for arg, value in zip(arguments, values) if value is not None}
params = {arg: json.loads(value) if isinstance(value, str) and value.startswith(('{', '[')) else json.loads(json.dumps(value)) if value is not None else None for arg, value in params.items()}
return params
# -------- GLOBAL ----------
formatted_date = datetime.today().strftime("%Y-%m-%d")
host = "127.0.0.1"
port = "7861"
# https://github.com/mix1009/sdwebuiapi
api = webuiapi.WebUIApi(host=host, port=port)
# TODO --share used shared link. https://123456.gradio.live/docs does not work
local = "http://" + host + ":" + port
process = None
sd = "❌"
doc = ''
chatHistory = ''
chatHistoryPrompt = ''
data = getAttrtxt2img()
data['prompt'] = 'cat in space' # Ý
data['steps'] = 15
data['sampler_name'] = 'Euler a'
data['scheduler'] = 'karras'
dataParams = {"img_thumb": "true",
"img_tg": "false",
"img_real": "true",
"stop_sd": "true",
"sd_model_checkpoint": "",
"use_prompt": "true",
"json_prompt": "false",
"just_gen": "false",
"send_vk": "false"}
dataOld = data.copy()
dataOldParams = dataParams.copy()
dataOrig = data.copy()
# -------- CLASSES ----------
# https://aiogram-birdi7.readthedocs.io/en/latest/examples/finite_state_machine_example.html
# Dynamically create a new class with the desired attributes
state_classes = {}
for key in data:
state_classes[key] = State()
for key in dataParams:
state_classes[key] = State()
# Inherit from the dynamically created class
Form = type("Form", (StatesGroup,), state_classes)
# -------- FUNCTIONS ----------
# Запуск SD через subprocess и запись в глобальную переменную process
def start_sd():
global process, sd
if not process:
logging.info('start_process start_sd')
process = subprocess.Popen(["python", "../../launch.py", "--nowebui", "--xformers"]) #, "--disable-nan-check"
sd = "✅"
async def stop_sd():
global process, sd
if process:
logging.info('stop_process stop_sd')
process.terminate()
process = None
sd = "❌"
def submit_get(url: str, data: dict):
return requests.get(url, data=json.dumps(data))
def pilToImages(res, typeImages="tg"):
media_group = []
imagesAll = res.images
if len(res.images) == 1:
i = 0
if len(res.images) > 1:
i = -1
for image in imagesAll:
# костыль для отсечения первой картинки с гридами
#if i == -1:
# i = i + 1
# continue
seed = str(res.info["all_seeds"][i])
image_buffer = io.BytesIO()
image.save(image_buffer, format="PNG")
image_buffer.seek(0)
# картинка в телеге
if typeImages == "tg":
media_group.append(types.InputMediaPhoto(media=image_buffer, caption=seed))
# оригинал
if typeImages == "real":
media_group.append(
types.InputMediaDocument(
media=InputFile(image_buffer, filename=seed + ".png"), caption=seed
)
)
# превью
if typeImages == "thumbs":
img = Image.open(image_buffer)
width, height = img.size
# пропорции
ratio = min(256 / width, 256 / height)
new_size = (round(width * ratio), round(height * ratio))
img = img.resize(new_size)
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format="PNG")
img_byte_arr.seek(0)
media_group.append(types.InputMediaPhoto(media=img_byte_arr, caption=seed))
i = i + 1
return media_group
def getJson(params=0):
if params == 0:
d = data
else:
d = dataParams
json_list = [f"/{key} = {value}" for key, value in d.items()]
json_str = "\n".join(json_list)
return json_str
# генератор промптов https://huggingface.co/FredZhang7/distilgpt2-stable-diffusion-v2
def get_random_prompt(text = data['prompt'], max_length = 120):
if str(dataParams['use_prompt']).lower() == 'true':
text = data['prompt']
tokenizer = GPT2Tokenizer.from_pretrained("distilgpt2")
tokenizer.add_special_tokens({"pad_token": "[PAD]"})
model = GPT2LMHeadModel.from_pretrained("FredZhang7/distilgpt2-stable-diffusion-v2")
input_ids = tokenizer(text, return_tensors="pt").input_ids
txt = model.generate(
input_ids,
do_sample=True,
temperature=0.8,
top_k=8,
max_length=max_length,
num_return_sequences=1,
repetition_penalty=1.2,
penalty_alpha=0.6,
no_repeat_ngram_size=0,
early_stopping=True,
)
prompt = tokenizer.decode(txt[0], skip_special_tokens=True)
return prompt
def rnd_prmt_lxc():
txt = data['prompt']
if str(dataParams['use_prompt']).lower() == 'false':
txt = dataOrig['prompt']
txt = random.choice(submit_get('https://lexica.art/api/v1/search?q='+txt, '').json()['images'])['prompt']
return txt
# рандомный промпт из JSON
async def rnd_prmt_json():
logging.info("rnd_prmt_json")
global chatHistory, chatHistoryPrompt
file = await chatHistory.download()
with open(file.name, 'r', encoding='utf-8') as f:
data = json.load(f)
t = random.choice(data['messages'])['text']
if t == '':
while True:
t2 = random.choice(data['messages'])['text']
if t2 != '':
t = t2
break
chatHistoryPrompt = t
return t.replace('<', '<').replace('>', '>')
# get settings. TODO - cut 4000 symbols
def get_prompt_settings(typeCode = 'HTML'):
global sd
prompt = data['prompt'].replace('<', '<').replace('>', '>')
cfg_scale = data['cfg_scale']
width = data['width']
height = data['height']
steps = data['steps']
negative_prompt = data['negative_prompt'].replace('<', '<').replace('>', '>')
sampler_name = data['sampler_name']
scheduler = data['scheduler']
if sd == '❌':
sd_model_checkpoint = dataParams['sd_model_checkpoint']
else:
sd_model_checkpoint = api.get_options()['sd_model_checkpoint']
if typeCode == 'HTML':
txt = f"prompt = <code>{prompt}</code>\nsteps = {steps} \ncfg_scale = {cfg_scale} \nwidth = {width} \nheight = {height} \nsampler_name = {sampler_name} \nscheduler = {scheduler} \nsd_model_checkpoint = {sd_model_checkpoint} \nnegative_prompt = <code>{negative_prompt}</code> "
else:
txt = f"prompt = {prompt}\n\nsteps = {steps} cfg_scale = {cfg_scale} width = {width} height = {height} sampler_name = {sampler_name} scheduler = {scheduler} sd_model_checkpoint = {sd_model_checkpoint} \n\nnegative_prompt = {negative_prompt} "
return txt
# Translate
def translateRuToEng(text):
translator = Translator(from_lang="ru", to_lang="en")
return translator.translate(text)
# Вывод прогресса в заменяемое сообщение
async def getProgress(msgTime):
while True:
# TODO aiogram.utils.exceptions.MessageToEditNotFound: Message to edit not found
proc = round(api.get_progress()['progress']*100)
points = '.' * (proc % 9)
await bot.edit_message_text(
chat_id=msgTime.chat.id,
message_id=msgTime.message_id,
text=str(proc)+'% ' + points
)
await asyncio.sleep(1)
#TODO
async def getProgress2(msgTime):
points = '.'
while True:
# TODO aiogram.utils.exceptions.MessageToEditNotFound: Message to edit not found
await asyncio.sleep(2)
print(187)
print(api.get_progress())
proc = round(api.get_progress()['progress']*100)
points = '.' * (proc % 9)
#await bot.edit_message_text(
# chat_id=msgTime.chat.id,
# message_id=msgTime.message_id,
# #text=str(proc)+'% ' + points# + str(int(time.time() * 1000))
# text=str(proc)+'% ' + points + '\n'+str(api.get_progress()['eta_relative']) + '\n'+str(api.get_progress()['state'])
#)
#await bot.send_message(
# chat_id=msgTime.chat.id,
# text='проверка'
#)
#image = base64.b64decode(api.get_progress()['current_image'])
#image_buffer = io.BytesIO()
#image.save(image_buffer, format="PNG")
#image_buffer.seek(0)
#img = Image.open(image_buffer)
#width, height = img.size
#ratio = min(256 / width, 256 / height)
#new_size = (round(width * ratio), round(height * ratio))
#img = img.resize(new_size)
#img_byte_arr = io.BytesIO()
#img.save(img_byte_arr, format="PNG")
#img_byte_arr.seek(0)
#image_data = base64.b64decode(api.get_progress()['current_image'])
#input_file = InputFile(image_data, filename="image.png")
#input_media = InputMediaPhoto(input_file)
#await bot.edit_message_media(chat_id=msgTime.chat.id, message_id=msgTime.message_id, media=input_media,
# text=str(proc)+'% ' + points + '\n'+str(api.get_progress()['eta_relative']) + '\n'+str(api.get_progress()['state'])
# )
#await bot.send_media_group(
# chat_id=msgTime.chat.id, media=pilToImages(api.get_progress()['current_image'], "thumbs")
#)
#img_base64 = "iVBORw0KGgoAAAANSUhEUgAAAlgAAAAmAhAAAADZI+25AAAClklEQVR4nO3UwQ2AMAADwMu33Hr/gWCFnltl9Ydu0v+PiH47qajzqajvOmrx7qssxDT48mi1lKCTpSEwRWhIKgbDBA9ABViSKgMBUxSIoAAD+CvP/Z6f14klgADwRv/vKd+zXZBIg2Azgv+5fjvTtT/ran2MJS5dSVTzxg/gkAF/nXUOLj2T539nCZcLDWsAYAAAAASUVORK5CYII="
media_group = []
image_base64 = api.get_progress()['current_image']
image = base64.b64decode(image_base64)
image_buffer = io.BytesIO(image)
img = Image.open(image_buffer)
img.save(image_buffer, format="PNG")
image_buffer.seek(0)
#media_group.append(types.InputMediaPhoto(media=image_buffer.getvalue(), caption='1121'))
#await bot.send_media_group(chat_id=msgTime.chat.id, media=media_group)
# Сохраняем изображение на диск
img_path = 'image.png'
with open(img_path, 'wb') as f:
f.write(image)
# Открываем изображение в виде InputFile
media_group.append(types.InputMediaPhoto(img_path, caption='1121'))
os.remove(img_path)
# Отправляем медиа-группу
await bot.send_media_group(chat_id=msgTime.chat.id, media=media_group)
# -------- MENU ----------
# Стартовое меню
def getKeyboard(keysArr, returnAll):
keys = keysArr
keyAll = InlineKeyboardMarkup(inline_keyboard=[keys])
if returnAll == 1:
return keyAll
else:
return keys
# Стандартное меню
async def getKeyboardUnion(txt, message, keyboard, parse_mode = 'Markdown'):
# Если команда с слешем
if hasattr(message, "content_type"):
await bot.send_message(
chat_id=message.from_user.id,
text=txt,
reply_markup=keyboard,
parse_mode=parse_mode
)
else:
await bot.edit_message_text(
chat_id=message.message.chat.id,
message_id=message.message.message_id,
text=txt,
reply_markup=keyboard,
parse_mode=parse_mode
)
def getStart(returnAll = 1) -> InlineKeyboardMarkup:
keysArr = [
InlineKeyboardButton(sd + "sd", callback_data="sd"),
InlineKeyboardButton("opt", callback_data="opt"),
InlineKeyboardButton("gen", callback_data="gen"),
InlineKeyboardButton("skip", callback_data="skip"),
InlineKeyboardButton("help", callback_data="help"),
]
return (getKeyboard(keysArr, returnAll))
# Меню опций
def getOpt(returnAll = 1) -> InlineKeyboardMarkup:
keysArr = [
InlineKeyboardButton("sttngs", callback_data="sttngs"),
InlineKeyboardButton("scrpts", callback_data="scrpts"),
InlineKeyboardButton("mdl", callback_data="mdl"),
InlineKeyboardButton("smplr", callback_data="smplr"),
InlineKeyboardButton("hr", callback_data="hr"),
InlineKeyboardButton("prompt", callback_data="prompt"),
]
return (getKeyboard(keysArr, returnAll))
# Меню скриптов
def getScripts(returnAll = 1) -> InlineKeyboardMarkup:
keysArr = [
InlineKeyboardButton("get_lora", callback_data="get_lora"),
InlineKeyboardButton("rnd_mdl", callback_data="rnd_mdl"),
InlineKeyboardButton("rnd_smp", callback_data="rnd_smp"),
InlineKeyboardButton("inf", callback_data="inf"),
]
return (getKeyboard(keysArr, returnAll))
# Меню настроек
def getSet(returnAll = 1) -> InlineKeyboardMarkup:
keysArr = [
InlineKeyboardButton("change_param", callback_data="change_param"),
InlineKeyboardButton("reset_param", callback_data="reset_param"),
InlineKeyboardButton("fast_param", callback_data="fast_param"),
]
return (getKeyboard(keysArr, returnAll))
# Меню быстрых параметров
def getFastParams(returnAll = 1) -> InlineKeyboardMarkup:
keysArr = [
InlineKeyboardButton("comp", callback_data="fp_comp"),
InlineKeyboardButton("mobile", callback_data="fp_mobile"),
InlineKeyboardButton("no hr", callback_data="fp_no_hr"),
InlineKeyboardButton("big", callback_data="fp_big"),
InlineKeyboardButton("inc", callback_data="fp_inc"),
InlineKeyboardButton("sdxl", callback_data="fp_sdxl"),
InlineKeyboardButton("w↔h", callback_data="fp_wh"),
]
return (getKeyboard(keysArr, returnAll))
# Меню галочек Да/Нет
def getYesNo(returnAll = 1, nam = '') -> InlineKeyboardMarkup:
keysArr = [
InlineKeyboardButton("✅", callback_data="✅"+nam),
InlineKeyboardButton("❌", callback_data="❌"+nam)
]
return (getKeyboard(keysArr, returnAll))
# Меню промпта
def getPrompt(returnAll = 1) -> InlineKeyboardMarkup:
global chatHistory
if chatHistory != '':
keysArr = [InlineKeyboardButton("get", callback_data="get"),
InlineKeyboardButton("random", callback_data="random_prompt"),
InlineKeyboardButton("lxc", callback_data="lxc_prompt"),
InlineKeyboardButton("json", callback_data="next")]
else:
keysArr = [InlineKeyboardButton("get", callback_data="get"),
InlineKeyboardButton("random", callback_data="random_prompt"),
InlineKeyboardButton("lxc", callback_data="lxc_prompt")]
return (getKeyboard(keysArr, returnAll))
# Меню промпта из JSON
def getPromptFromJson(returnAll = 1) -> InlineKeyboardMarkup:
keysArr = [InlineKeyboardButton("Next prompt", callback_data="next"),
InlineKeyboardButton("Save", callback_data="save_prompt")]
return (getKeyboard(keysArr, returnAll))
# Меню текста
def getTxt():
return "/start /opt /gen /skip /stop /help"
def set_array(arrAll, itemArr, callback_data, useIn = 1):
logging.info('set_array')
arr = []
arr2 = []
i = 1
for item in arrAll:
if useIn == 1:
arrayIn = item[itemArr]
else:
arrayIn = item
arr.append(InlineKeyboardButton(arrayIn, callback_data=callback_data+'|'+arrayIn))
if i % 3 == 0:
arr2.append(arr)
arr = []
i += 1
if arr != []:
arr2.append(arr)
return arr2
# get all models from stable-diffusion-webui\models\Stable-diffusion
def get_models():
models = api.get_sd_models()
return set_array(models, 'model_name', 'models')
# get samplers
def get_samplers_list():
samplers = api.get_samplers()
return set_array(samplers, 'name', 'samplers')
def get_schedulers_list():
schedulers = api.get_schedulers()
return set_array(schedulers, 'name', 'schedulers')
# get hr
def get_hr_list():
hrs = [str(choice.value) for choice in webuiapi.HiResUpscaler]
return set_array(hrs, 'hr', 'hrs', 0)
# random
async def rnd_script(message, typeScript):
keyboard = InlineKeyboardMarkup(inline_keyboard=[getOpt(0), getSet(0), getStart(0)])
if hasattr(message, "content_type"):
chatId = message.chat.id
else:
chatId = message.message.chat.id
if typeScript == 'models':
elements = api.util_get_model_names()
else:
elements = api.get_samplers()
numbers = list(range(len(elements)))
random.shuffle(numbers)
dataPromptOld = data['prompt']
msgFor = await bot.send_message(
chat_id=chatId,
text=dataPromptOld
)
for i, number in enumerate(numbers):
time.sleep(1)
for itemTxt in data['prompt'].split(';'):
if typeScript == 'models':
api.util_wait_for_ready()
dataParams['sd_model_checkpoint'] = elements[number]
api.util_set_model(elements[number])
else:
options = {}
options['sampler_name'] = elements[number]['name']
api.set_options(options)
data['sampler_name'] = elements[number]['name'] # Ý
data["use_async"] = "False"
data['prompt'] = itemTxt
try:
res = await api.txt2img(**data)
await show_thumbs(chatId, res)
await msgFor.reply(
text=elements[number] if typeScript == 'models' else elements[number]['name']
)
except Exception as e:
await bot.send_message(
chat_id=chatId,
text=e
)
data['prompt'] = dataPromptOld
await bot.send_message(
chat_id=chatId,
text="```Промпт " + dataPromptOld + "```cfg = " + str(data['cfg_scale'])+ " width = " + str(data['width']) +" height = " + str(data['height']) + " steps = " + str(data['steps']) + " sampler = " + str(data['sampler_name']) + "```Негатив " + str(data['negative_prompt']) + "```#SD",
parse_mode="Markdown",
reply_markup=keyboard
)
if str(dataParams['stop_sd']).lower() == 'true':
await stop_sd()
# show thumb/tg/real
async def show_thumbs(chat_id, res):
if dataParams["img_thumb"] == "true" or dataParams["img_thumb"] == "True":
await bot.send_media_group(
chat_id=chat_id, media=pilToImages(res, "thumbs")
)
if dataParams["img_tg"] == "true" or dataParams["img_tg"] == "True":
await bot.send_media_group(
chat_id=chat_id, media=pilToImages(res, "tg")
)
if dataParams["img_real"] == "true" or dataParams["img_real"] == "True":
messages = await bot.send_media_group(
chat_id=chat_id,
media=pilToImages(res, "real")
)
if (str(dataParams['json_prompt']).lower() == 'true'):
# send button load in VK
arr = []
i = 0
for mes_file in messages:
i = i + 1
print(mes_file)
ARRAY_INLINE.append({'message_id': str(mes_file.message_id),
'num_but': str(i),
'file_id': str(mes_file.document.file_id),
'prompt': get_prompt_settings(0)})
arr.append(InlineKeyboardButton(i, callback_data='send_vk|' + str(mes_file.message_id)))
await bot.send_message(
chat_id=chat_id,
text="⬇ send to VK and OK ⬇",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[arr])
)
# -------- COMMANDS ----------
# start или help
@dp.callback_query_handler(text="help")
@dp.message_handler(commands=["help"])
@dp.message_handler(commands=["start"])
async def cmd_start(message: Union[types.Message, types.CallbackQuery]) -> None:
logging.info("cmd_start")
txt = "Это бот для локального запуска SD\n" + getTxt()
await getKeyboardUnion(txt, message, getStart())
# TODO optimize
# Запуск/Остановка SD. Завязываемся на глобальную иконку sd
@dp.message_handler(commands=["stop"])
@dp.callback_query_handler(text="sd")
async def inl_sd(message: Union[types.Message, types.CallbackQuery]) -> None:
logging.info("inl_sd")
global sd
if hasattr(message, "content_type"):
if message.text == '/stop':
await inl_skip(message)
await stop_sd()
await bot.send_message(
chat_id=message.chat.id,
text = "Останавливаем SD\n" + getTxt(),
reply_markup=getStart()
)
else:
if sd == '✅':
await stop_sd()
sd = "⌛"
await message.message.edit_text(
"Останавливаем SD\n" + getTxt(), reply_markup=getStart()
)
sd = '❌'
await message.message.edit_text(
"SD остановлена\n" + getTxt(), reply_markup=getStart()
)
else:
start_sd()
sd = "⌛"
await message.message.edit_text(
"Запускаем SD\n" + getTxt(), reply_markup=getStart()
)
url = 'http://127.0.0.1:7861/docs'
n = 0
while n != 200:
time.sleep(2)
try:
r = requests.get(url, timeout=3)
r.raise_for_status()
n = r.status_code
logging.info(r.status_code)
except requests.exceptions.HTTPError as errh:
logging.info("Http Error:", errh)
except requests.exceptions.ConnectionError as errc:
logging.info("Error Connecting:", errc)
except requests.exceptions.Timeout as errt:
logging.info("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
logging.info("OOps: Something Else", err)
sd = "✅"
await message.message.edit_text(
"SD запущена\n" + getTxt(), reply_markup=getStart()
)
# save prompt
@dp.callback_query_handler(text="save_prompt")
async def inl_save_prompt(callback: types.CallbackQuery) -> None:
logging.info("inl_save_prompt")
global data, chatHistoryPrompt
data['prompt'] = chatHistoryPrompt
keyboard = InlineKeyboardMarkup(inline_keyboard=[getPromptFromJson(0), getStart(0)])
await bot.edit_message_text(
chat_id=callback.message.chat.id,
message_id=callback.message.message_id,
text='Промпт сохранён: ' + chatHistoryPrompt,
reply_markup=keyboard
)
# upload result.json from chat history
@dp.callback_query_handler(text="uplchat")
@dp.callback_query_handler(text="next")
async def inl_uplchat(callback: types.CallbackQuery) -> None:
logging.info("inl_uplchat")
# TODO cache chatHistory
global chatHistory, chatHistoryPrompt
file = await chatHistory.download()
with open(file.name, 'r', encoding='utf-8') as f:
data = json.load(f)
t = random.choice(data['messages'])['text']
if t == '':
while True:
t2 = random.choice(data['messages'])['text']
if t2 != '':
t = t2
break
chatHistoryPrompt = t#translateRuToEng(t)
keyboard = InlineKeyboardMarkup(inline_keyboard=[getPromptFromJson(0), getStart(0)])
await bot.edit_message_text(
chat_id=callback.message.chat.id,
message_id=callback.message.message_id,
text=t.replace('<', '<').replace('>', '>'),#translateRuToEng(t).replace('<', '<').replace('>', '>'),
reply_markup=keyboard,
parse_mode = types.ParseMode.HTML
)
# upload Lora/Model
@dp.callback_query_handler(text="uplora")
@dp.callback_query_handler(text="uplmodel")
async def inl_uplora(callback: types.CallbackQuery) -> None:
logging.info("inl_uplora")
global doc
if callback.data == 'uplora':
folder_path = Path('../../models/Lora')
else:
folder_path = Path('../../models/Stable-diffusion')
file_id = doc.file_id
file_name = doc.file_name
destination_path = os.path.join(folder_path, file_name)
file_path = folder_path / file_name
if file_path.exists():
await callback.message.reply(f"Файл '{file_name}' уже существует в {folder_path}")
else:
file_path = await bot.get_file(file_id)
await file_path.download(destination_path)
await callback.message.reply(f"Файл '{file_name}' загружен в {folder_path}")
# Вызов reset_param, сброс JSON
@dp.message_handler(commands=["reset_param"])
@dp.callback_query_handler(text="reset_param")
async def inl_reset_param(message: Union[types.Message, types.CallbackQuery]) -> None:
logging.info("inl_reset_param")
global data
global dataParams
global dataOld
global dataOldParams
data = dataOld
dataParams = dataOldParams
keyboard = InlineKeyboardMarkup(inline_keyboard=[getSet(0), getOpt(0), getStart(0)])
txt = f"JSON сброшен\n{getJson()}\n{getJson(1)}"
await getKeyboardUnion(txt, message, keyboard, '')
# Вызов fast_param, быстрые настройки
@dp.message_handler(commands=["fast_param"])
@dp.callback_query_handler(text="fast_param")
async def inl_fast_param(message: Union[types.Message, types.CallbackQuery]) -> None:
logging.info("inl_fast_param")
keyboard = InlineKeyboardMarkup(inline_keyboard=[getFastParams(0), getSet(0), getOpt(0), getStart(0)])
await getKeyboardUnion('Выбери быстрые настройки', message, keyboard, '')
# Список быстрых настроек
@dp.message_handler(commands=["fp_comp"])
@dp.message_handler(commands=["fp_mobile"])
@dp.message_handler(commands=["fp_no_hr"])
@dp.message_handler(commands=["fp_sdxl"])
@dp.message_handler(commands=["fp_big"])
@dp.message_handler(commands=["fp_inc"])
@dp.message_handler(commands=["fp_wh"])
@dp.callback_query_handler(text="fp_comp")
@dp.callback_query_handler(text="fp_mobile")
@dp.callback_query_handler(text="fp_no_hr")
@dp.callback_query_handler(text="fp_sdxl")
@dp.callback_query_handler(text="fp_big")
@dp.callback_query_handler(text="fp_inc")
@dp.callback_query_handler(text="fp_wh")
async def inl_fp(message: Union[types.Message, types.CallbackQuery]) -> None:
logging.info("inl_fp")
m = message.data
keyboard = InlineKeyboardMarkup(inline_keyboard=[getFastParams(0), getSet(0), getOpt(0), getStart(0)])
global data
global dataParams
if m == 'fp_wh':
w = data['width']
data['width'] = data['height']
data['height'] = w
if m == 'fp_comp':
data['steps'] = 35
data['sampler_name'] = 'Euler a'
data['enable_hr'] = 'True'
data['denoising_strength'] = '0.5'
data['hr_upscaler'] = '4x_NMKD-Siax_200k' #https://huggingface.co/uwg/upscaler/blob/main/ESRGAN/4x_NMKD-Siax_200k.pth
data['hr_second_pass_steps'] = '10'
data['cfg_scale'] = '6'
data['width'] = '512'
data['height'] = '768'
data['restore_faces'] = 'false'
data['do_not_save_grid'] = 'true'
data['negative_prompt'] = 'easynegative, bad-hands-5, bad-picture-chill-75v, bad-artist, bad_prompt_version2, rmadanegative4_sd15-neg, bad-image-v2-39000, illustration, painting, cartoons, sketch, (worst quality:2), (low quality:2), (normal quality:2), lowres, bad anatomy, bad hands, ((monochrome)), ((grayscale)), collapsed eyeshadow, multiple eyeblows, vaginas in breasts, (cropped), oversaturated, extra limb, missing limbs, deformed hands, long neck, long body, imperfect, (bad hands), signature, watermark, username, artist name, conjoined fingers, deformed fingers, ugly eyes, imperfect eyes, skewed eyes, unnatural face, unnatural body, error, asian, obese, tatoo, stacked torsos, totem pole, watermark, black and white, close up, cartoon, 3d, denim, (disfigured), (deformed), (poorly drawn), (extra limbs), blurry, boring, sketch, lackluster, signature, letters'
data['save_images'] = 'true'
dataParams = {"img_thumb": "false",
"img_tg": "true",
"img_real": "true",
"stop_sd": "true",
"use_prompt": "true",
"json_prompt": "false"}
if m == 'fp_mobile':
data['steps'] = 15
data['enable_hr'] = 'false'
data['cfg_scale'] = '6'
data['width'] = '512'
data['height'] = '768'
data['do_not_save_grid'] = 'true'
data['negative_prompt'] = 'easynegative, bad-hands-5, bad-picture-chill-75v, bad-artist, bad_prompt_version2, rmadanegative4_sd15-neg, bad-image-v2-39000, illustration, painting, cartoons, sketch, (worst quality:2), (low quality:2), (normal quality:2), lowres, bad anatomy, bad hands, ((monochrome)), ((grayscale)), collapsed eyeshadow, multiple eyeblows, vaginas in breasts, (cropped), oversaturated, extra limb, missing limbs, deformed hands, long neck, long body, imperfect, (bad hands), signature, watermark, username, artist name, conjoined fingers, deformed fingers, ugly eyes, imperfect eyes, skewed eyes, unnatural face, unnatural body, error, asian, obese, tatoo, stacked torsos, totem pole, watermark, black and white, close up, cartoon, 3d, denim, (disfigured), (deformed), (poorly drawn), (extra limbs), blurry, boring, sketch, lackluster, signature, letters'
data['save_images'] = 'true'
dataParams = {"img_thumb": "true",
"img_tg": "false",
"img_real": "true",
"stop_sd": "true",
"use_prompt": "true",
"json_prompt": "false"}
if m == 'fp_no_hr':
data['steps'] = 20
data['enable_hr'] = 'false'
data['cfg_scale'] = '7'
data['width'] = '512'
data['height'] = '768'
data['do_not_save_grid'] = 'true'
data['negative_prompt'] = 'easynegative, bad-hands-5, bad-picture-chill-75v, bad-artist, bad_prompt_version2, rmadanegative4_sd15-neg, bad-image-v2-39000, illustration, painting, cartoons, sketch, (worst quality:2), (low quality:2), (normal quality:2), lowres, bad anatomy, bad hands, ((monochrome)), ((grayscale)), collapsed eyeshadow, multiple eyeblows, vaginas in breasts, (cropped), oversaturated, extra limb, missing limbs, deformed hands, long neck, long body, imperfect, (bad hands), signature, watermark, username, artist name, conjoined fingers, deformed fingers, ugly eyes, imperfect eyes, skewed eyes, unnatural face, unnatural body, error, asian, obese, tatoo, stacked torsos, totem pole, watermark, black and white, close up, cartoon, 3d, denim, (disfigured), (deformed), (poorly drawn), (extra limbs), blurry, boring, sketch, lackluster, signature, letters'
data['save_images'] = 'true'
dataParams = {"img_thumb": "true",
"img_tg": "false",
"img_real": "true",
"stop_sd": "true",
"use_prompt": "true",
"json_prompt": "false"}
if m == 'fp_big':
data['steps'] = 50
data['sampler_name'] = 'Euler a'
data['enable_hr'] = 'True'
data['denoising_strength'] = '0.7'
data['hr_upscaler'] = '4x_NMKD-Siax_200k'
data['hr_second_pass_steps'] = '20'
data['cfg_scale'] = '7'
data['width'] = '768'
data['height'] = '1024'
data['restore_faces'] = 'false'
data['do_not_save_grid'] = 'true'
data['negative_prompt'] = 'easynegative, bad-hands-5, bad-picture-chill-75v, bad-artist, bad_prompt_version2, rmadanegative4_sd15-neg, bad-image-v2-39000, illustration, painting, cartoons, sketch, (worst quality:2), (low quality:2), (normal quality:2), lowres, bad anatomy, bad hands, ((monochrome)), ((grayscale)), collapsed eyeshadow, multiple eyeblows, vaginas in breasts, (cropped), oversaturated, extra limb, missing limbs, deformed hands, long neck, long body, imperfect, (bad hands), signature, watermark, username, artist name, conjoined fingers, deformed fingers, ugly eyes, imperfect eyes, skewed eyes, unnatural face, unnatural body, error, asian, obese, tatoo, stacked torsos, totem pole, watermark, black and white, close up, cartoon, 3d, denim, (disfigured), (deformed), (poorly drawn), (extra limbs), blurry, boring, sketch, lackluster, signature, letters'
data['save_images'] = 'true'
dataParams = {"img_thumb": "false",
"img_tg": "true",
"img_real": "true",
"stop_sd": "true",
"use_prompt": "true",
"json_prompt": "false"}
if m == 'fp_inc':
data['steps'] = 20
data['sampler_name'] = 'Euler a'
data['enable_hr'] = 'false'
data['cfg_scale'] = '7'
data['width'] = '512'
data['height'] = '768'
data['do_not_save_grid'] = 'true'
data['negative_prompt'] = 'easynegative, bad-hands-5, bad-picture-chill-75v, bad-artist, bad_prompt_version2, rmadanegative4_sd15-neg, bad-image-v2-39000, illustration, painting, cartoons, sketch, (worst quality:2), (low quality:2), (normal quality:2), lowres, bad anatomy, bad hands, ((monochrome)), ((grayscale)), collapsed eyeshadow, multiple eyeblows, vaginas in breasts, (cropped), oversaturated, extra limb, missing limbs, deformed hands, long neck, long body, imperfect, (bad hands), signature, watermark, username, artist name, conjoined fingers, deformed fingers, ugly eyes, imperfect eyes, skewed eyes, unnatural face, unnatural body, error, asian, obese, tatoo, stacked torsos, totem pole, watermark, black and white, close up, cartoon, 3d, denim, (disfigured), (deformed), (poorly drawn), (extra limbs), blurry, boring, sketch, lackluster, signature, letters'
data['save_images'] = 'false'
dataParams = {"img_thumb": "true",
"img_tg": "false",
"img_real": "false",
"stop_sd": "true",
"use_prompt": "true",
"json_prompt": "false"}
if m == 'fp_sdxl':
data['enable_hr'] = 'True'
data['denoising_strength'] = '0.3'
data['steps'] = 15
data['sampler_name'] = 'DPM++ SDE Karras'
data['scheduler'] = 'karras'
data['cfg_scale'] = '4'
data['width'] = '1024'
data['height'] = '1024'
data['restore_faces'] = 'false'
data['hr_upscaler'] = '4x_NMKD-Siax_200k'
data['do_not_save_grid'] = 'true'
data['negative_prompt'] = 'FastNegativeV2'
data['save_images'] = 'true'
dataParams = {"img_thumb": "false",
"img_tg": "true",
"img_real": "true",
"stop_sd": "true",
"use_prompt": "true",
"json_prompt": "false",
"just_gen": "false"}
txt = f"JSON отредактирован\n{getJson()}\n{getJson(1)}"
await getKeyboardUnion(txt, message, keyboard, '')
# Обработчик команды /skip
@dp.message_handler(commands=["skip"])
@dp.callback_query_handler(text="skip")
async def inl_skip(message: Union[types.Message, types.CallbackQuery]) -> None:
logging.info('inl_skip')
# Создаем сессию
async with aiohttp.ClientSession() as session:
# Отправляем POST-запрос ко второму сервису
async with session.post(local + "/sdapi/v1/skip"):
# Получаем ответ и выводим его
#await response.json()
if hasattr(message, "content_type"):
await message.answer("skip")
else:
await bot.edit_message_text(
chat_id=message.message.chat.id,
message_id=message.message.message_id,
text="Пропущено",
reply_markup=getStart(),
)
@dp.message_handler(commands=["gen"])
@dp.callback_query_handler(text="gen")
async def inl_gen(message: Union[types.Message, types.CallbackQuery]) -> None:
if hasattr(message, "content_type"):
chatId = message.chat.id
else:
chatId = message.message.chat.id
keyboard = InlineKeyboardMarkup(inline_keyboard=[getSet(0), getOpt(0), getStart(0)])
global sd, ARRAY_INLINE
dataPromptOld = data['prompt']
if sd == '✅':
for itemTxt in data['prompt'].split(';'):
try:
msgTime = await bot.send_message(
chat_id=chatId,
text='Начали'
)
# Включаем асинхрон, чтоб заработал await api.txt2img
data["use_async"] = "True"
data["prompt"] = itemTxt # только для **data
asyncio.create_task(getProgress(msgTime))
# TODO try catch if wrong data
res = await api.txt2img(**data)
# show_thumbs dont work because use_async
if dataParams["img_thumb"] == "true" or dataParams["img_thumb"] == "True":
await bot.send_media_group(
chat_id=chatId, media=pilToImages(res, "thumbs")
)
if dataParams["img_tg"] == "true" or dataParams["img_tg"] == "True":
await bot.send_media_group(
chat_id=chatId, media=pilToImages(res, "tg")
)
if dataParams["img_real"] == "true" or dataParams["img_real"] == "True":
messages = await bot.send_media_group(
chat_id=chatId,
media=pilToImages(res, "real")
)
if (str(dataParams['json_prompt']).lower() == 'true'):
# send button load in VK
arr = []
i = 0
for mes_file in messages:
i = i + 1
print(mes_file)
ARRAY_INLINE.append({'message_id':str(mes_file.message_id),
'num_but':str(i),
'file_id':str(mes_file.document.file_id),
'prompt':get_prompt_settings(0)})
arr.append(InlineKeyboardButton(i, callback_data='send_vk|'+str(mes_file.message_id)))
await bot.send_message(
chat_id=chatId,
text="⬇ send to VK and OK ⬇",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[arr])
)
await bot.send_message(
chat_id=chatId,
text=data["prompt"] + "\n" + str(res.info["all_seeds"])
)
# Удаляем сообщение с прогрессом
await bot.delete_message(chat_id=msgTime.chat.id, message_id=msgTime.message_id)
except Exception as e:
logging.error(f"gen error: {e}")
await bot.send_message(
chat_id=chatId,
text=e,
reply_markup=keyboard,
parse_mode="Markdown",
)
await bot.send_message(
chat_id=chatId,
text=f"`{dataPromptOld}`",
reply_markup=keyboard,
parse_mode="Markdown",
)
else:
keyboard = InlineKeyboardMarkup(inline_keyboard=[getSet(0), getOpt(0), getStart(0)])
await getKeyboardUnion("Turn on SD"+sd, message, keyboard)
# upload in VK
# TODO actual prompt
@dp.callback_query_handler(text_startswith="send_vk")
async def send_vk(callback: types.CallbackQuery) -> None:
try:
global VK_TOKEN, VK_ALBUM_ID, OK_ACCESS_TOKEN, OK_APPLICATION_KEY, OK_APPLICATION_SECRET_KEY, OK_GROUP_ID, ARRAY_INLINE
message_id = callback.data.split("|")[1]