MFawad/Image_Generator
0
1import os2import io3import IPython.display4from PIL import Image5import base646from diffusers import DiffusionPipeline7 8hf_api_key = "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"9 10from diffusers import DiffusionPipeline11 12pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")13 14def get_completion(prompt):15 return pipeline(prompt).images[0]16 17import gradio as gr18 19#A helper function to convert the PIL image to base6420#so you can send it to the API21 22#A helper function to convert the PIL image to base64 23# so you can send it to the API24def base64_to_pil(img_base64):25 base64_decoded = base64.b64decode(img_base64)26 byte_stream = io.BytesIO(base64_decoded)27 pil_image = Image.open(byte_stream)28 return pil_image29 30def generate(prompt, negative_prompt, steps, guidance, width, height):31 params = {32 "negative_prompt": negative_prompt,33 "num_inference_steps": steps,34 "guidance_scale": guidance,35 "width": width,36 "height": height37 }38 39 output = get_completion(prompt, params)40 pil_image = base64_to_pil(output)41 return pil_image42 43gr.close_all()44with gr.Blocks() as demo:45 gr.Markdown("# Image Generation with Stable Diffusion")46 with gr.Row():47 with gr.Column(scale=4):48 prompt = gr.Textbox(label="Your prompt") #Give prompt some real estate49 with gr.Column(scale=1, min_width=50):50 btn = gr.Button("Submit") #Submit button side by side!51 with gr.Accordion("Advanced options", open=False): #Let's hide the advanced options!52 negative_prompt = gr.Textbox(label="Negative prompt")53 with gr.Row():54 with gr.Column():55 steps = gr.Slider(label="Inference Steps", minimum=1, maximum=100, value=25,56 info="In many steps will the denoiser denoise the image?")57 guidance = gr.Slider(label="Guidance Scale", minimum=1, maximum=20, value=7,58 info="Controls how much the text prompt influences the result")59 with gr.Column():60 width = gr.Slider(label="Width", minimum=64, maximum=512, step=64, value=512)61 height = gr.Slider(label="Height", minimum=64, maximum=512, step=64, value=512)62 output = gr.Image(label="Result") #Move the output up too63 64 btn.click(fn=generate, inputs=[prompt,negative_prompt,steps,guidance,width,height], outputs=[output])65 66gr.close_all()67demo.launch()