CHEONMA010 commited on
Commit
ed7c59f
·
verified ·
1 Parent(s): 5072f0b

Upload 2 files

Browse files

Initial Files for gradio

Files changed (2) hide show
  1. app.py +63 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ import torch
4
+ from torch import autocast
5
+ from diffusers import StableDiffusionPipeline
6
+ import gradio as gr # Import Gradio
7
+ from PIL import Image
8
+
9
+ # Load the environment variables from .env
10
+ load_dotenv()
11
+
12
+ class StableBuddyApp:
13
+ def __init__(self):
14
+ # Set up the Stable Diffusion pipeline
15
+ model_id = "CompVis/stable-diffusion-v1-4"
16
+ device = "cuda" if torch.cuda.is_available() else "cpu"
17
+
18
+ # Get the auth_token from the environment variable
19
+ auth_token = os.getenv("AUTH_TOKEN")
20
+ if not auth_token:
21
+ raise ValueError("AUTH_TOKEN environment variable is not set.")
22
+
23
+ # Use float16 and fp16 so that stable diffusion can work on 4GB VRAM
24
+ self.pipe = StableDiffusionPipeline.from_pretrained(
25
+ model_id, revision='fp16', torch_dtype=torch.float16, use_auth_token=auth_token
26
+ )
27
+ self.pipe.to(device)
28
+
29
+ def generate_image(self, prompt):
30
+ """Generate an image based on the prompt."""
31
+ try:
32
+ with autocast("cuda"):
33
+ image = self.pipe(prompt, guidance_scale=8.5).images[0]
34
+
35
+ # Save the generated image temporarily
36
+ image_path = 'data/generated_image.png'
37
+ image.save(image_path)
38
+
39
+ return image_path # Return the image path for Gradio to display
40
+
41
+ except Exception as e:
42
+ print(f"An error occurred: {e}")
43
+ return None # In case of an error, return None
44
+
45
+ # Create an instance of the StableBuddyApp
46
+ stable_buddy_app = StableBuddyApp()
47
+
48
+ # Create Gradio Interface with separate buttons
49
+ def generate_and_download(prompt):
50
+ image_path = stable_buddy_app.generate_image(prompt)
51
+ return image_path, image_path # Return image for display and for download link
52
+
53
+ # Create Gradio Interface
54
+ iface = gr.Interface(
55
+ fn=generate_and_download, # Function to call
56
+ inputs=gr.Textbox(label="Enter Prompt"), # Text input for the prompt
57
+ outputs=[gr.Image(type="filepath", label="Generated Image"), gr.File(label="Download Image")], # Two outputs for display and download
58
+ title="Stable Buddy",
59
+ description="Generate images using Stable Diffusion."
60
+ )
61
+
62
+ # Launch the Gradio app
63
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ diffusers
3
+ gradio
4
+ python-dotenv
5
+ Pillow