stable-diffusion-webui

Форк
0
121 строка · 4.7 Кб
1
import json
2
from contextlib import closing
3

4
import modules.scripts
5
from modules import processing, infotext_utils
6
from modules.infotext_utils import create_override_settings_dict, parse_generation_parameters
7
from modules.shared import opts
8
import modules.shared as shared
9
from modules.ui import plaintext_to_html
10
from PIL import Image
11
import gradio as gr
12

13

14
def txt2img_create_processing(id_task: str, request: gr.Request, prompt: str, negative_prompt: str, prompt_styles, steps: int, sampler_name: str, n_iter: int, batch_size: int, cfg_scale: float, height: int, width: int, enable_hr: bool, denoising_strength: float, hr_scale: float, hr_upscaler: str, hr_second_pass_steps: int, hr_resize_x: int, hr_resize_y: int, hr_checkpoint_name: str, hr_sampler_name: str, hr_prompt: str, hr_negative_prompt, override_settings_texts, *args, force_enable_hr=False):
15
    override_settings = create_override_settings_dict(override_settings_texts)
16

17
    if force_enable_hr:
18
        enable_hr = True
19

20
    p = processing.StableDiffusionProcessingTxt2Img(
21
        sd_model=shared.sd_model,
22
        outpath_samples=opts.outdir_samples or opts.outdir_txt2img_samples,
23
        outpath_grids=opts.outdir_grids or opts.outdir_txt2img_grids,
24
        prompt=prompt,
25
        styles=prompt_styles,
26
        negative_prompt=negative_prompt,
27
        sampler_name=sampler_name,
28
        batch_size=batch_size,
29
        n_iter=n_iter,
30
        steps=steps,
31
        cfg_scale=cfg_scale,
32
        width=width,
33
        height=height,
34
        enable_hr=enable_hr,
35
        denoising_strength=denoising_strength,
36
        hr_scale=hr_scale,
37
        hr_upscaler=hr_upscaler,
38
        hr_second_pass_steps=hr_second_pass_steps,
39
        hr_resize_x=hr_resize_x,
40
        hr_resize_y=hr_resize_y,
41
        hr_checkpoint_name=None if hr_checkpoint_name == 'Use same checkpoint' else hr_checkpoint_name,
42
        hr_sampler_name=None if hr_sampler_name == 'Use same sampler' else hr_sampler_name,
43
        hr_prompt=hr_prompt,
44
        hr_negative_prompt=hr_negative_prompt,
45
        override_settings=override_settings,
46
    )
47

48
    p.scripts = modules.scripts.scripts_txt2img
49
    p.script_args = args
50

51
    p.user = request.username
52

53
    if shared.opts.enable_console_prompts:
54
        print(f"\ntxt2img: {prompt}", file=shared.progress_print_out)
55

56
    return p
57

58

59
def txt2img_upscale(id_task: str, request: gr.Request, gallery, gallery_index, generation_info, *args):
60
    assert len(gallery) > 0, 'No image to upscale'
61
    assert 0 <= gallery_index < len(gallery), f'Bad image index: {gallery_index}'
62

63
    p = txt2img_create_processing(id_task, request, *args, force_enable_hr=True)
64
    p.batch_size = 1
65
    p.n_iter = 1
66
    # txt2img_upscale attribute that signifies this is called by txt2img_upscale
67
    p.txt2img_upscale = True
68

69
    geninfo = json.loads(generation_info)
70

71
    image_info = gallery[gallery_index] if 0 <= gallery_index < len(gallery) else gallery[0]
72
    p.firstpass_image = infotext_utils.image_from_url_text(image_info)
73

74
    parameters = parse_generation_parameters(geninfo.get('infotexts')[gallery_index], [])
75
    p.seed = parameters.get('Seed', -1)
76
    p.subseed = parameters.get('Variation seed', -1)
77

78
    p.override_settings['save_images_before_highres_fix'] = False
79

80
    with closing(p):
81
        processed = modules.scripts.scripts_txt2img.run(p, *p.script_args)
82

83
        if processed is None:
84
            processed = processing.process_images(p)
85

86
    shared.total_tqdm.clear()
87

88
    new_gallery = []
89
    for i, image in enumerate(gallery):
90
        if i == gallery_index:
91
            geninfo["infotexts"][gallery_index: gallery_index+1] = processed.infotexts
92
            new_gallery.extend(processed.images)
93
        else:
94
            fake_image = Image.new(mode="RGB", size=(1, 1))
95
            fake_image.already_saved_as = image["name"].rsplit('?', 1)[0]
96
            new_gallery.append(fake_image)
97

98
    geninfo["infotexts"][gallery_index] = processed.info
99

100
    return new_gallery, json.dumps(geninfo), plaintext_to_html(processed.info), plaintext_to_html(processed.comments, classname="comments")
101

102

103
def txt2img(id_task: str, request: gr.Request, *args):
104
    p = txt2img_create_processing(id_task, request, *args)
105

106
    with closing(p):
107
        processed = modules.scripts.scripts_txt2img.run(p, *p.script_args)
108

109
        if processed is None:
110
            processed = processing.process_images(p)
111

112
    shared.total_tqdm.clear()
113

114
    generation_info_js = processed.js()
115
    if opts.samples_log_stdout:
116
        print(generation_info_js)
117

118
    if opts.do_not_show_images:
119
        processed.images = []
120

121
    return processed.images, generation_info_js, plaintext_to_html(processed.info), plaintext_to_html(processed.comments, classname="comments")
122

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.