aanchal77 commited on
Commit
39ecd57
·
verified ·
1 Parent(s): a9998fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -149
app.py CHANGED
@@ -1,154 +1,96 @@
1
  import gradio as gr
2
- import numpy as np
3
- import random
4
-
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
  import torch
8
 
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
-
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
-
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
-
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
  }
65
- """
66
 
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
-
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
-
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
-
82
- result = gr.Image(label="Result", show_label=False)
83
-
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
- )
99
-
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
-
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
-
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
127
-
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
-
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
151
- )
152
-
153
- if __name__ == "__main__":
154
- demo.launch()
 
1
  import gradio as gr
2
+ from diffusers import StableDiffusionPipeline
 
 
 
 
3
  import torch
4
 
5
+ # --- Configuration ---
6
+ # Your Hugging Face repository ID where the LoRAs are stored
7
+ HF_REPO_ID = "TonyRaju/GenImg"
8
+ BASE_MODEL_ID = "runwayml/stable-diffusion-v1-5"
9
+
10
+ # --- Define Available LoRAs from your HF Repo ---
11
+ # The key is the display name in the dropdown.
12
+ # The value is the subfolder path inside your Hugging Face repository.
13
+ AVAILABLE_LORAS = {
14
+ "None (Base Model)": None,
15
+ # --- Artists ---
16
+ "Artist: Vincent van Gogh": "artists/Vincent_van_Gogh",
17
+ "Artist: Claude Monet": "artists/Claude_Monet",
18
+ "Artist: Rembrandt": "artists/Rembrandt",
19
+ "Artist: Pablo Picasso": "artists/Pablo_Picasso",
20
+ # --- Styles ---
21
+ "Style: Impressionism": "styles/Impressionism",
22
+ "Style: Baroque": "styles/Baroque",
23
+ "Style: Cubism": "styles/Cubism",
24
+ "Style: Abstract Expressionism": "styles/Abstract_Expressionism",
25
+ "Style: Romanticism": "styles/Romanticism",
26
+ "Style: Realism": "styles/Realism",
27
+ "Style: Post Impressionism": "styles/Post_Impressionism",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  }
29
+ print("✅ LoRA models from your Hugging Face repo are configured.")
30
 
31
+ # --- Setup ---
32
+ device = "cuda" if torch.cuda.is_available() else "cpu"
33
+ dtype = torch.float16 if device == "cuda" else torch.float32
34
+ print(f"Using device: {device}")
35
+
36
+ # --- Load the Base Model ---
37
+ # This will be cached in the Space for faster startups.
38
+ print(f"🎨 Loading base model: {BASE_MODEL_ID}")
39
+ pipe = StableDiffusionPipeline.from_pretrained(BASE_MODEL_ID, torch_dtype=dtype).to(device)
40
+ if device == "cpu":
41
+ pipe.enable_attention_slicing()
42
+
43
+ # --- The Core Generation Function ---
44
+ def generate(prompt, quality, lora_choice):
45
+ """
46
+ Generates an image, dynamically loading the selected LoRA from the Hub.
47
+ """
48
+ # Unload any existing LoRA to reset to the base model
49
+ pipe.unload_lora_weights()
50
+
51
+ lora_subfolder = AVAILABLE_LORAS.get(lora_choice)
52
+
53
+ if lora_subfolder:
54
+ print(f"✨ Downloading and applying LoRA: {lora_choice}")
55
+ try:
56
+ # Load LoRA directly from the Hugging Face Hub
57
+ pipe.load_lora_weights(HF_REPO_ID, subfolder=lora_subfolder)
58
+ except Exception as e:
59
+ print(f"❌ Failed to load LoRA from Hub '{HF_REPO_ID}/{lora_subfolder}': {e}")
60
+ else:
61
+ print("🎨 Using base model (no LoRA selected)")
62
+
63
+ steps = 25 if quality == "Fast" else 40
64
+ guidance_scale = 7.5
65
+
66
+ print(f"🚀 Generating with prompt: '{prompt}'")
67
+ with torch.no_grad():
68
+ image = pipe(prompt, num_inference_steps=steps, guidance_scale=guidance_scale).images[0]
69
+
70
+ return image
71
+
72
+ # --- Build the Gradio UI ---
73
+ title = f"🎨 Stable Diffusion Gallery from {HF_REPO_ID}"
74
+ description = "Select a trained LoRA model from your Hugging Face repository to apply its style. The first time you select a LoRA, it may take a moment to download."
75
+
76
+ demo = gr.Interface(
77
+ fn=generate,
78
+ inputs=[
79
+ gr.Textbox(label="Enter your prompt", placeholder="A beautiful painting of a fantasy landscape..."),
80
+ gr.Dropdown(["Fast", "High Quality"], value="Fast", label="Generation Quality"),
81
+ gr.Dropdown(
82
+ choices=list(AVAILABLE_LORAS.keys()),
83
+ value="None (Base Model)",
84
+ label="Select a Trained LoRA Model"
85
+ )
86
+ ],
87
+ outputs=gr.Image(label="Generated Image"),
88
+ title=title,
89
+ description=description,
90
+ examples=[
91
+ ["A portrait of an astronaut, cinematic lighting, by vincent van gogh", "Fast", "Artist: Vincent van Gogh"],
92
+ ["A peaceful village in the mountains, impressionism style", "High Quality", "Style: Impressionism"],
93
+ ]
94
+ )
95
+
96
+ demo.launch()