Advertisement
Dvadch

Untitled

Aug 22nd, 2022 (edited)
389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.58 KB | None | 0 0
  1. import PIL
  2. import gradio as gr
  3. import argparse, os, sys, glob
  4. import torch
  5. import torch.nn as nn
  6. import numpy as np
  7. from omegaconf import OmegaConf
  8. from PIL import Image
  9. from tqdm.notebook import tqdm, trange
  10. from itertools import islice
  11. from einops import rearrange, repeat
  12. from torchvision.utils import make_grid
  13. import time
  14. from pytorch_lightning import seed_everything
  15. from torch import autocast
  16. from contextlib import contextmanager, nullcontext
  17. import accelerate
  18. import mimetypes
  19. import gc
  20. from basicsr.utils import imwrite
  21. import cv2
  22. from gfpgan import GFPGANer
  23. from io import BytesIO
  24. import random
  25.  
  26. mimetypes.init()
  27. mimetypes.add_type('application/javascript', '.js')
  28.  
  29.  
  30. import k_diffusion as K
  31. from ldm.util import instantiate_from_config
  32. from ldm.models.diffusion.ddim import DDIMSampler
  33. from ldm.models.diffusion.plms import PLMSSampler
  34.  
  35. def FACE_RESTORATION(image, bg_upsampling, upscale):
  36. from basicsr.archs.rrdbnet_arch import RRDBNet
  37. from realesrgan import RealESRGANer
  38. model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)
  39. bg_upsampler = RealESRGANer(
  40. scale=2,
  41. model_path='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth',
  42. model=model,
  43. tile=400,
  44. tile_pad=10,
  45. pre_pad=0,
  46. half=True)
  47. arch = 'clean'
  48. channel_multiplier = 2
  49. model_name = 'GFPGANv1.3'
  50. model_path = os.path.join('/content/GFPGAN/experiments/pretrained_models/GFPGANv1.3.pth')
  51. restorer = GFPGANer(
  52. model_path=model_path,
  53. upscale=1,
  54. arch=arch,
  55. channel_multiplier=channel_multiplier,
  56. bg_upsampler=None
  57. )
  58.  
  59. image=np.array(image)
  60. input_img = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
  61.  
  62. cropped_faces, restored_faces, restored_img = restorer.enhance(
  63. input_img, has_aligned=False, only_center_face=False, paste_back=True)
  64.  
  65. for idx, (cropped_face, restored_face) in enumerate(zip(cropped_faces, restored_faces)):
  66. image = cv2.cvtColor(restored_img, cv2.COLOR_BGR2RGB)
  67. image = bg_upsampler.enhance(image, outscale=upscale)[0]
  68. return image
  69.  
  70. def chunk(it, size):
  71. it = iter(it)
  72. return iter(lambda: tuple(islice(it, size)), ())
  73.  
  74.  
  75. def load_model_from_config(config, ckpt, verbose=False):
  76. print(f"Loading model from {ckpt}")
  77. pl_sd = torch.load(ckpt, map_location="cpu")
  78. if "global_step" in pl_sd:
  79. print(f"Global Step: {pl_sd['global_step']}")
  80. sd = pl_sd["state_dict"]
  81. model = instantiate_from_config(config.model)
  82. m, u = model.load_state_dict(sd, strict=False)
  83. if len(m) > 0 and verbose:
  84. print("missing keys:")
  85. print(m)
  86. if len(u) > 0 and verbose:
  87. print("unexpected keys:")
  88. print(u)
  89.  
  90. model.cuda()
  91. model.eval()
  92. return model
  93.  
  94. def load_img_pil(img_pil):
  95. image = img_pil.convert("RGB")
  96. w, h = image.size
  97. print(f"loaded input image of size ({w}, {h})")
  98. w, h = map(lambda x: x - x % 64, (w, h)) # resize to integer multiple of 64
  99. image = image.resize((w, h), resample=PIL.Image.LANCZOS)
  100. print(f"cropped image to size ({w}, {h})")
  101. image = np.array(image).astype(np.float32) / 255.0
  102. image = image[None].transpose(0, 3, 1, 2)
  103. image = torch.from_numpy(image)
  104. return 2.*image - 1.
  105.  
  106. def load_img(path):
  107. return load_img_pil(Image.open(path))
  108.  
  109.  
  110. class CFGDenoiser(nn.Module):
  111. def __init__(self, model):
  112. super().__init__()
  113. self.inner_model = model
  114.  
  115. def forward(self, x, sigma, uncond, cond, cond_scale):
  116. x_in = torch.cat([x] * 2)
  117. sigma_in = torch.cat([sigma] * 2)
  118. cond_in = torch.cat([uncond, cond])
  119. uncond, cond = self.inner_model(x_in, sigma_in, cond=cond_in).chunk(2)
  120. return uncond + (cond - uncond) * cond_scale
  121.  
  122. #from https://github.com/lstein/stable-diffusion/blob/main/ldm/simplet2i.py
  123. def split_weighted_subprompts(text):
  124. """
  125. grabs all text up to the first occurrence of ':'
  126. uses the grabbed text as a sub-prompt, and takes the value following ':' as weight
  127. if ':' has no value defined, defaults to 1.0
  128. repeats until no text remaining
  129. """
  130. remaining = len(text)
  131. prompts = []
  132. weights = []
  133. while remaining > 0:
  134. if ":" in text:
  135. idx = text.index(":") # first occurrence from start
  136. # grab up to index as sub-prompt
  137. prompt = text[:idx]
  138. remaining -= idx
  139. # remove from main text
  140. text = text[idx+1:]
  141. # find value for weight
  142. if " " in text:
  143. idx = text.index(" ") # first occurence
  144. else: # no space, read to end
  145. idx = len(text)
  146. if idx != 0:
  147. try:
  148. weight = float(text[:idx])
  149. except: # couldn't treat as float
  150. print(f"Warning: '{text[:idx]}' is not a value, are you missing a space?")
  151. weight = 1.0
  152. else: # no value found
  153. weight = 1.0
  154. # remove from main text
  155. remaining -= idx
  156. text = text[idx+1:]
  157. # append the sub-prompt and its weight
  158. prompts.append(prompt)
  159. weights.append(weight)
  160. else: # no : found
  161. if len(text) > 0: # there is still text though
  162. # take remainder as weight 1
  163. prompts.append(text)
  164. weights.append(1.0)
  165. remaining = 0
  166. return prompts, weights
  167.  
  168.  
  169. config = OmegaConf.load("configs/stable-diffusion/v1-inference.yaml")
  170. model = load_model_from_config(config, "/gdrive/My Drive/model.ckpt")
  171.  
  172. device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
  173. model = model.half().to(device)
  174.  
  175.  
  176. def dream(prompt: str, init_img, ddim_steps: int, plms: bool, fixed_code: bool, ddim_eta: float, n_iter: int, n_samples: int, cfg_scales: str, denoising_strength: float, seed: int, height: int, width: int, same_seed: bool, GFPGAN: bool, bg_upsampling: bool, upscale: int):
  177. torch.cuda.empty_cache()
  178. parser = argparse.ArgumentParser()
  179.  
  180. parser.add_argument(
  181. "--outdir",
  182. type=str,
  183. nargs="?",
  184. help="dir to write results to",
  185. default="/content/"
  186. )
  187.  
  188. parser.add_argument(
  189. "--skip_grid",
  190. action='store_true',
  191. help="do not save a grid, only individual samples. Helpful when evaluating lots of samples",
  192. )
  193.  
  194. parser.add_argument(
  195. "--skip_save",
  196. action='store_true',
  197. help="do not save indiviual samples. For speed measurements.",
  198. )
  199. parser.add_argument(
  200. "--C",
  201. type=int,
  202. default=4,
  203. help="latent channels",
  204. )
  205. parser.add_argument(
  206. "--f",
  207. type=int,
  208. default=8,
  209. help="downsampling factor, most often 8 or 16",
  210. )
  211. parser.add_argument(
  212. "--n_rows",
  213. type=int,
  214. default=0,
  215. help="rows in the grid (default: n_samples)",
  216. )
  217. parser.add_argument(
  218. "--from-file",
  219. type=str,
  220. help="if specified, load prompts from this file",
  221. )
  222. parser.add_argument(
  223. "--H",
  224. type=int,
  225. default=height,
  226. help="image height, in pixel space",
  227. )
  228. parser.add_argument(
  229. "--W",
  230. type=int,
  231. default=width,
  232. help="image width, in pixel space",
  233. )
  234. parser.add_argument(
  235. "--config",
  236. type=str,
  237. default="configs/stable-diffusion/v1-inference.yaml",
  238. help="path to config which constructs model",
  239. )
  240. parser.add_argument(
  241. "--ckpt",
  242. type=str,
  243. default="/gdrive/My Drive/model.ckpt\model.ckpt",
  244. help="path to checkpoint of model",
  245. )
  246. parser.add_argument(
  247. "--precision",
  248. type=str,
  249. help="evaluate at this precision",
  250. choices=["full", "autocast"],
  251. default="autocast"
  252. )
  253.  
  254. opt = parser.parse_args()
  255.  
  256. accelerator = accelerate.Accelerator()
  257. device = accelerator.device
  258. rng_seed = seed_everything(seed)
  259. seeds = torch.randint(-2 ** 63, 2 ** 63 - 1, [accelerator.num_processes])
  260. torch.manual_seed(seeds[accelerator.process_index].item())
  261.  
  262. if plms and init_img == None:
  263. sampler = PLMSSampler(model)
  264. else:
  265. sampler = DDIMSampler(model)
  266.  
  267. model_wrap = K.external.CompVisDenoiser(model)
  268. sigma_min, sigma_max = model_wrap.sigmas[0].item(), model_wrap.sigmas[-1].item()
  269.  
  270. os.makedirs(opt.outdir, exist_ok=True)
  271. outpath = opt.outdir
  272.  
  273. batch_size = n_samples
  274. n_rows = opt.n_rows if opt.n_rows > 0 else batch_size
  275. if not opt.from_file:
  276. prompt = prompt
  277. assert prompt is not None
  278. data = [batch_size * [prompt]]
  279. else:
  280. print(f"reading prompts from {opt.from_file}")
  281. with open(opt.from_file, "r") as f:
  282. data = f.read().splitlines()
  283. data = list(chunk(data, batch_size))
  284.  
  285. sample_path = os.path.join(outpath)
  286. os.makedirs(sample_path, exist_ok=True)
  287. base_count = len(os.listdir(sample_path))
  288. seedit = 0
  289.  
  290. if fixed_code and init_img == None:
  291. start_code = torch.randn([n_samples, opt.C, opt.H // opt.f, opt.W // opt.f], device=device)
  292.  
  293. if init_img != None:
  294. image = init_img.convert("RGB")
  295. w, h = image.size
  296. print(f"loaded input image of size ({w}, {h})")
  297. w, h = map(lambda x: x - x % 32, (opt.W, opt.H)) # resize to integer multiple of 32
  298. image = image.resize((w, h), resample=PIL.Image.LANCZOS)
  299. print(f"cropped image to size ({w}, {h})")
  300. image = np.array(image).astype(np.float32) / 255.0
  301. image = image[None].transpose(0, 3, 1, 2)
  302. image = torch.from_numpy(image)
  303. if len(cfg_scales) > 1: cfg_scales = list(map(float, cfg_scales.split(' ')))
  304. output_images = []
  305. precision_scope = autocast if opt.precision == "autocast" else nullcontext
  306. with torch.no_grad():
  307. gc.collect()
  308. torch.cuda.empty_cache()
  309. with precision_scope("cuda"):
  310. if init_img != None:
  311. init_image = 2.*image - 1.
  312. init_image = init_image.to(device)
  313. init_image = repeat(init_image, '1 ... -> b ...', b=batch_size)
  314. init_latent = model.get_first_stage_encoding(model.encode_first_stage(init_image)) # move to latent space
  315. x0 = init_latent
  316.  
  317. sampler.make_schedule(ddim_num_steps=ddim_steps, ddim_eta=ddim_eta, verbose=False)
  318.  
  319. assert 0. <= denoising_strength <= 1., 'can only work with strength in [0.0, 1.0]'
  320. t_enc = int(denoising_strength * ddim_steps)
  321. print(f"target t_enc is {t_enc} steps")
  322. with model.ema_scope():
  323. tic = time.time()
  324. all_samples = list()
  325. for prompts in tqdm(data, desc="data", disable=not accelerator.is_main_process):
  326. output_images.append([])
  327.  
  328. aaa = f'{rng_seed + seedit}{random.randint(8, 10000)}'
  329. output_images[-1].append(aaa)
  330. output_images[-1].append(prompts[0])
  331.  
  332. os.makedirs(f'/content/{aaa}', exist_ok=True)
  333. for n in trange(n_iter, desc="Sampling", disable=not accelerator.is_main_process):
  334.  
  335.  
  336. with open(f'/content/{aaa}/prompt.txt', 'w') as f:
  337. f.write(prompts[0])
  338.  
  339. if n_iter > 1: seedit += 1
  340. for cfg in tqdm(cfg_scales, desc="cfg_scales", disable=not accelerator.is_main_process):
  341. cfg_scale = cfg
  342. uc = None
  343. if cfg_scale != 1.0:
  344. uc = model.get_learned_conditioning(batch_size * [""])
  345. if isinstance(prompts, tuple):
  346. prompts = list(prompts)
  347.  
  348.  
  349. #from https://github.com/lstein/stable-diffusion/blob/main/ldm/simplet2i.py
  350. subprompts,weights = split_weighted_subprompts(prompts[0])
  351.  
  352. if len(subprompts) > 1:
  353. # i dont know if this is correct.. but it works
  354. c = torch.zeros_like(uc)
  355. # get total weight for normalizing
  356. totalWeight = sum(weights)
  357. # normalize each "sub prompt" and add it
  358. for i in range(0,len(subprompts)):
  359. weight = weights[i]
  360. weight = weight / totalWeight
  361. c = torch.add(c,model.get_learned_conditioning(subprompts[i]), alpha=weight)
  362.  
  363.  
  364. else: # just standard 1 prompt
  365. c = model.get_learned_conditioning(prompts)
  366.  
  367. torch.manual_seed(rng_seed + seedit) # changes manual seeding procedure
  368. sigmas = model_wrap.get_sigmas(ddim_steps)
  369. if init_img == None:
  370. shape = [opt.C, opt.H // opt.f, opt.W // opt.f]
  371. x = torch.randn([n_samples, *shape], device=device) * sigmas[0] # for GPU draw
  372. else:
  373. noise = torch.randn_like(x0) * sigmas[ddim_steps - t_enc - 1] # for GPU draw
  374. x = x0 + noise
  375. sigmas = sigmas[ddim_steps - t_enc - 1:]
  376.  
  377. model_wrap_cfg = CFGDenoiser(model_wrap)
  378. extra_args = {'cond': c, 'uncond': uc, 'cond_scale': cfg_scale}
  379. samples_ddim = K.sampling.sample_lms(model_wrap_cfg, x, sigmas, extra_args=extra_args, disable=not accelerator.is_main_process)
  380. x_samples_ddim = model.decode_first_stage(samples_ddim)
  381. x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
  382. x_samples_ddim = accelerator.gather(x_samples_ddim)
  383.  
  384. if accelerator.is_main_process and not opt.skip_save:
  385. for x_sample in x_samples_ddim:
  386. x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c')
  387. #Image.fromarray(x_sample.astype(np.uint8)).save(os.path.join(sample_path, f"{base_count:05}-{rng_seed + seedit}-{cfg_scale}_{prompt.replace(' ', '_')[:128]}.png"))
  388. output_images[-1].append(Image.fromarray(x_sample.astype(np.uint8)))
  389. print(prompt, cfg_scale, rng_seed + seedit)
  390. #output_images[-1].show() #not working
  391. #display(output_images[-1])#not working
  392. ########
  393. base_count += 1
  394. if not same_seed: seedit += 1
  395.  
  396.  
  397.  
  398. toc = time.time()
  399. gc.collect()
  400. torch.cuda.empty_cache()
  401. del sampler
  402.  
  403.  
  404.  
  405. f = []
  406. message = ''
  407. for i in range(len(output_images)):
  408. aaa = output_images[i][0]
  409. message+= f'Запрос "{output_images[i][1]}" находится в папке /content/{aaa}/ \n'
  410. for k in range(2, len(output_images[i])):
  411. cfg=cfg_scales
  412. pt = f'/content/{aaa}/{k-2}.jpg'
  413. if GFPGAN:
  414. (Image.fromarray(FACE_RESTORATION(output_images[i][k], bg_upsampling, upscale).astype(np.uint8))).save(pt, format = 'JPEG', optimize = True)
  415. else:
  416. output_images[i][k].save(pt, format = 'JPEG', optimize = True)
  417. f.append(pt)
  418. with Image.open(f[i]) as img:
  419. print(img.size)
  420.  
  421. #files.download(f'/content/waifu-diffusion/outputs/img2img-samples/samples/0.jpg') #not working
  422. return f, rng_seed, message
  423.  
  424. dream_interface = gr.Interface(
  425. dream,
  426. inputs=[
  427. gr.Textbox(label='Текстовый запрос. Поддерживает придание частям запроса веса с помощью ":число " (пробел после числа обязателен). Обычный запрос так же поддерживается.', placeholder="A corgi wearing a top hat as an oil painting.", lines=1), gr.Variable(value=None, visible=False),
  428. gr.Slider(minimum=1, maximum=200, step=1, label="Шаги диффузии, идеал - 100.", value=50),
  429. gr.Checkbox(label='Включить PLMS ', value=True),
  430. gr.Checkbox(label='Сэмплинг с одной точки', value=False),
  431. gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="DDIM ETA", value=0.0, visible=False),
  432. gr.Slider(minimum=1, maximum=50, step=1, label='Сколько раз сгенерировать по запросу (последовательно)', value=1),
  433. gr.Slider(minimum=1, maximum=8, step=1, label='Сколько картинок за раз (одновременно). ЖРЕТ МНОГО ПАМЯТИ', value=1),
  434. gr.Textbox(placeholder="7.0", label='Classifier Free Guidance Scales, через пробел либо только одна. Если больше одной, сэмплит один и тот же запрос с разными cfg. Обязательно число с точкой, типа 7.0 или 15.0', lines=1, value=9.0),
  435. gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Процент шагов, указанных выше чтобы пройтись по картинке. Моюно считать "силой"', value=0.75, visible=False),
  436. gr.Number(label='Сид', value=-1),
  437. gr.Slider(minimum=64, maximum=2048, step=64, label="Высота", value=512),
  438. gr.Slider(minimum=64, maximum=2048, step=64, label="Ширина", value=512),
  439. gr.Checkbox(label='Один и тот же сид каждый раз. Для того чтобы генерировать одно и тоже с одинаковым запросом.', value=False),
  440. gr.Checkbox(label='GFPGAN, восстанавливает лица, может апскейлить. Все настройки ниже к нему.', value=True),
  441. gr.Checkbox(label='Улучшение фона', value=True),
  442. gr.Slider(minimum=1, maximum=8, step=1, label="Апскейлинг. 1 значит не используется.", value=2)
  443. ],
  444. outputs=[
  445. gr.Gallery(),
  446. gr.Number(label='Seed'),
  447. gr.Textbox(label='Чтобы скачать папку с результатами, открой в левой части колаба файлы и скачай указанные папки')
  448. ],
  449. title="Stable Diffusion 1.4 текст в картинку",
  450. description=" создай картинку из текста, анон, K-LMS используется по умолчанию",
  451. )
  452.  
  453. # prompt, init_img, ddim_steps, plms, ddim_eta, n_iter, n_samples, cfg_scale, denoising_strength, seed
  454.  
  455. img2img_interface = gr.Interface(
  456. dream,
  457. inputs=[
  458. gr.Textbox(label='Текстовый запрос. Поддерживает придание частям запроса веса с помощью ":число " (пробел после числа обязателен). Обычный запрос так же поддерживается.', placeholder="A corgi wearing a top hat as an oil painting.", lines=1), gr.Image(value="https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg", source="upload", interactive=True, type="pil"),
  459. gr.Slider(minimum=1, maximum=200, step=1, label="Шаги диффузии, идеал - 100.", value=100),
  460. gr.Checkbox(label='Включить PLMS ', value=True, vivible=False),
  461. gr.Checkbox(label='Сэмплинг с одной точки', value=False, vivible=False),
  462. gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="DDIM ETA", value=0.0, visible=False),
  463. gr.Slider(minimum=1, maximum=50, step=1, label='Сколько раз сгенерировать по запросу (последовательно)', value=1),
  464. gr.Slider(minimum=1, maximum=8, step=1, label='Сколько картинок за раз (одновременно). ЖРЕТ МНОГО ПАМЯТИ', value=1),
  465. gr.Textbox(placeholder="7.0", label='Classifier Free Guidance Scales, через пробел либо только одна. Если больше одной, сэмплит один и тот же запрос с разными cfg. Обязательно число с точкой, типа 7.0 или 15.0', lines=1, value=9.0),
  466. gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Процент шагов, указанных выше чтобы пройтись по картинке. Моюно считать "силой"', value=0.75),
  467. gr.Number(label='Сид', value=-1),
  468. gr.Slider(minimum=64, maximum=2048, step=64, label="Resize Height", value=512),
  469. gr.Slider(minimum=64, maximum=2048, step=64, label="Resize Width", value=512),
  470. gr.Checkbox(label='Один и тот же сид каждый раз. Для того чтобы генерировать одно и тоже с одинаковым запросом.', value=False),
  471. gr.Checkbox(label='GFPGAN, восстанавливает лица, может апскейлить. Все настройки ниже к нему.', value=True),
  472. gr.Checkbox(label='Улучшение фона', value=True),
  473. gr.Slider(minimum=1, maximum=8, step=1, label="Апскейлинг. 1 значит не используется.", value=2)
  474.  
  475. ],
  476. outputs=[
  477. gr.Gallery(),
  478. gr.Number(label='Seed'),
  479. gr.Textbox(label='Чтобы скачать папку с результатами, открой в левой части колаба файлы и скачай указанные папки')
  480. ],
  481. title="Stable Diffusion Image-to-Image",
  482. description="генерация изображения из изображения",
  483. )
  484.  
  485. ctrbbl_interface = gr.Interface(
  486. dream,
  487. inputs=[
  488. gr.Textbox(label='Текстовый запрос. Поддерживает придание частям запроса веса с помощью ":число " (пробел после числа обязателен). Обычный запрос так же поддерживается.', placeholder="A corgi wearing a top hat as an oil painting.", lines=1), gr.Image(value="https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg", source="upload", interactive=True, type="pil"),
  489. gr.Slider(minimum=1, maximum=200, step=1, label="Шаги диффузии, идеал - 100.", value=100),
  490. gr.Checkbox(label='Включить PLMS ', value=True, vivible=False),
  491. gr.Checkbox(label='Сэмплинг с одной точки', value=False, vivible=False),
  492. gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="DDIM ETA", value=0.0, visible=False),
  493. gr.Slider(minimum=1, maximum=50, step=1, label='Сколько раз сгенерировать по запросу (последовательно)', value=1),
  494. gr.Slider(minimum=1, maximum=8, step=1, label='Сколько картинок за раз (одновременно). ЖРЕТ МНОГО ПАМЯТИ', value=1),
  495. gr.Textbox(placeholder="7.0", label='Classifier Free Guidance Scales, через пробел либо только одна. Если больше одной, сэмплит один и тот же запрос с разными cfg. Обязательно число с точкой, типа 7.0 или 15.0', lines=1, value=9.0),
  496. gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Процент шагов, указанных выше чтобы пройтись по картинке. Моюно считать "силой"', value=0.75),
  497. gr.Number(label='Сид', value=-1),
  498. gr.Slider(minimum=64, maximum=2048, step=64, label="Resize Height", value=512),
  499. gr.Slider(minimum=64, maximum=2048, step=64, label="Resize Width", value=512),
  500. gr.Checkbox(label='Один и тот же сид каждый раз. Для того чтобы генерировать одно и тоже с одинаковым запросом.', value=False),
  501. gr.Checkbox(label='GFPGAN, восстанавливает лица, может апскейлить. Все настройки ниже к нему.', value=True),
  502. gr.Checkbox(label='Улучшение фона', value=True),
  503. gr.Slider(minimum=1, maximum=8, step=1, label="Апскейлинг. 1 значит не используется.", value=2)
  504.  
  505. ],
  506. outputs=[
  507. gr.Gallery(),
  508. gr.Number(label='Seed'),
  509. gr.Textbox(label='Чтобы скачать папку с результатами, открой в левой части колаба файлы и скачай указанные папки')
  510. ],
  511. title="Stable Diffusion Imagewegwsg-to-Image",
  512. description="генерация изображения из изображения",
  513. )
  514.  
  515.  
  516.  
  517. demo = gr.TabbedInterface(interface_list=[dream_interface, img2img_interface, ctrbbl_interface], tab_names=["Dream", "Image Translation", "Dev inference"])
  518.  
  519. demo.launch(share=True)
  520.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement