Thafx/sdrdpv1
1
1from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler2import gradio as gr3import torch4from PIL import Image5 6model_id = 'digiplay/RunDiffusionFXPhotorealistic_v1'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;">📷 RunDiffusionFXPhotorealistic V1.0 📸</h1>111 </div>112 <p>113 Demo for <a href="https://huggingface.co/digiplay/RunDiffusionFXPhotorealistic_v1">RunDiffusionFXPhotorealistic V1.0</a>114 Stable Diffusion model by <a href="https://huggingface.co/digiplay/"><abbr title="digiplay">digiplay</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: (hyperrealism:1.2), BREAK fish swimming under the water BREAK (8K UHD:1.2), (photorealistic:1.2)127</i></q>128</code></details>129 130<br>131<b>Negative Prompt</b>:132<details><code>133e.g. : plain background, boring, plain, standard, homogenous, uncreative, unattractive, opaque, grayscale, monochrome, distorted details, low details, grains,134grainy, foggy, dark, blurry, portrait, oversaturated, low contrast, underexposed, overexposed, low-res, low quality, close-up, macro, surreal, multiple views,135multiple angles136</code></details>137<br>138Wide/Tall aspect ratios like '480x832'/'832x480' work great then you can upscale.139 140You can use a CFG scale of 3.5 to 5 to get some softer photorealistic images.141<br>142Have Fun & Enjoy ⚡ <a href="https://www.thafx.com"><abbr title="Website">//THAFX</abbr></a>143<br>144 145 </div>146 """147 )148 with gr.Row():149 150 with gr.Column(scale=55):151 with gr.Group():152 with gr.Row():153 prompt = gr.Textbox(label="Prompt", show_label=False,max_lines=2,placeholder=f"{prefix} [your prompt]").style(container=False)154 generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))155 156 image_out = gr.Image(height=512)157 error_output = gr.Markdown()158 159 with gr.Column(scale=45):160 with gr.Tab("Options"):161 with gr.Group():162 neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")163 auto_prefix = gr.Checkbox(label="Prefix styling tokens automatically (RAW photo,)", value=prefix, visible=prefix)164 165 with gr.Row():166 guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)167 steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1)168 169 with gr.Row():170 width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)171 height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)172 173 seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)174 175 with gr.Tab("Image to image"):176 with gr.Group():177 image = gr.Image(label="Image", height=256, tool="editor", type="pil")178 strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)179 180 auto_prefix.change(lambda x: gr.update(placeholder=f"{prefix} [your prompt]" if x else "[Your prompt]"), inputs=auto_prefix, outputs=prompt, queue=False)181 182 inputs = [prompt, guidance, steps, width, height, seed, image, strength, neg_prompt, auto_prefix]183 outputs = [image_out, error_output]184 prompt.submit(inference, inputs=inputs, outputs=outputs)185 generate.click(inference, inputs=inputs, outputs=outputs)186 187 188 189demo.queue(concurrency_count=1)190demo.launch()191 