Thafx/sdrv30
5
1from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler2import gradio as gr3import torch4from PIL import Image5 6model_id = 'SG161222/Realistic_Vision_V3.0'7prefix = 'RAW photo,'8 9scheduler = DPMSolverMultistepScheduler.from_pretrained(model_id, subfolder="scheduler")10 11pipe = StableDiffusionPipeline.from_pretrained(12 model_id,13 torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,14 scheduler=scheduler)15 16pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(17 model_id,18 torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,19 scheduler=scheduler)20 21if torch.cuda.is_available():22 pipe = pipe.to("cuda")23 pipe_i2i = pipe_i2i.to("cuda")24 25def error_str(error, title="Error"):26 return f"""#### {title}27 {error}""" if error else ""28 29 30def _parse_args(prompt, generator):31 parser = argparse.ArgumentParser(32 description="making it work."33 )34 parser.add_argument(35 "--no-half-vae", help="no half vae"36 )37 38 cmdline_args = parser.parse_args()39 command = cmdline_args.command40 conf_file = cmdline_args.conf_file41 conf_args = Arguments(conf_file)42 opt = conf_args.readArguments()43 44 if cmdline_args.config_overrides:45 for config_override in cmdline_args.config_overrides.split(";"):46 config_override = config_override.strip()47 if config_override:48 var_val = config_override.split("=")49 assert (50 len(var_val) == 251 ), f"Config override '{var_val}' does not have the form 'VAR=val'"52 conf_args.add_opt(opt, var_val[0], var_val[1], force_override=True)53 54def inference(prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt="", auto_prefix=False):55 generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None56 prompt = f"{prefix} {prompt}" if auto_prefix else prompt57 58 try:59 if img is not None:60 return img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None61 else:62 return txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator), None63 except Exception as e:64 return None, error_str(e)65 66 67 68def txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator):69 70 result = pipe(71 prompt,72 negative_prompt = neg_prompt,73 num_inference_steps = int(steps),74 guidance_scale = guidance,75 width = width,76 height = height,77 generator = generator)78 79 return result.images[0]80 81def img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator):82 83 ratio = min(height / img.height, width / img.width)84 img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)85 result = pipe_i2i(86 prompt,87 negative_prompt = neg_prompt,88 init_image = img,89 num_inference_steps = int(steps),90 strength = strength,91 guidance_scale = guidance,92 width = width,93 height = height,94 generator = generator)95 96 return result.images[0]97 98 def fake_safety_checker(images, **kwargs):99 return result.images[0], [False] * len(images)100 101 pipe.safety_checker = fake_safety_checker102 103css = """.main-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.main-div div h1{font-weight:900;margin-bottom:7px}.main-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem}104"""105with gr.Blocks(css=css) as demo:106 gr.HTML(107 f"""108 <div class="main-div">109 <div>110 <h1 style="color:orange;">📷 Realistic Vision V3.0 📸</h1>111 </div>112 <p>113 Demo for <a href="https://huggingface.co/SG161222/Realistic_Vision_V3.0">Realistic Vision V3.0</a>114 Stable Diffusion model by <a href="https://huggingface.co/SG161222/"><abbr title="SG1611222">Eugene</abbr></a>. {"" if prefix else ""} 115 Running on {"<b>GPU 🔥</b>" if torch.cuda.is_available() else f"<b>CPU ⚡</b>"}. 116 </p>117 <p>Please use the prompt template below to get an example of the desired generation results:118 </p>119 120<b>Prompt</b>:121<details><code>122RAW photo, * subject *, (high detailed skin:1.2), 8k uhd, dslr, soft lighting, high quality, film grain, Fujifilm XT3123<br>124<br>125<q><i>126Example: RAW photo, a close up portrait photo of 26 y.o woman in wastelander clothes, long haircut, pale skin, slim body, background is city ruins, <br>127(high detailed skin:1.2), 8k uhd, dslr, soft lighting, high quality, film grain, Fujifilm XT3 128</i></q>129</code></details>130 131<br>132<b>Negative Prompt</b>:133<details><code>134(deformed iris, deformed pupils, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime:1.4), text, close up, cropped, out of frame, worst quality, <br>135low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, <br>136dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, <br>137extra legs, fused fingers, too many fingers, long neck138</code></details>139 140<br>141Have Fun & Enjoy ⚡ <a href="https://www.thafx.com"><abbr title="Website">//THAFX</abbr></a>142<br>143 144 </div>145 """146 )147 with gr.Row():148 149 with gr.Column(scale=55):150 with gr.Group():151 with gr.Row():152 prompt = gr.Textbox(label="Prompt", show_label=False,max_lines=2,placeholder=f"{prefix} [your prompt]").style(container=False)153 generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))154 155 image_out = gr.Image(height=512)156 error_output = gr.Markdown()157 158 with gr.Column(scale=45):159 with gr.Tab("Options"):160 with gr.Group():161 neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")162 auto_prefix = gr.Checkbox(label="Prefix styling tokens automatically (RAW photo,)", value=prefix, visible=prefix)163 164 with gr.Row():165 guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)166 steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1)167 168 with gr.Row():169 width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)170 height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)171 172 seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)173 174 with gr.Tab("Image to image"):175 with gr.Group():176 image = gr.Image(label="Image", height=256, tool="editor", type="pil")177 strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)178 179 auto_prefix.change(lambda x: gr.update(placeholder=f"{prefix} [your prompt]" if x else "[Your prompt]"), inputs=auto_prefix, outputs=prompt, queue=False)180 181 inputs = [prompt, guidance, steps, width, height, seed, image, strength, neg_prompt, auto_prefix]182 outputs = [image_out, error_output]183 prompt.submit(inference, inputs=inputs, outputs=outputs)184 generate.click(inference, inputs=inputs, outputs=outputs)185 186 187 188demo.queue(concurrency_count=1)189demo.launch()190 