aiqtech commited on
Commit
9632d12
·
verified ·
1 Parent(s): 4308608

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -83
app.py CHANGED
@@ -1,5 +1,7 @@
1
  import random
2
-
 
 
3
  import gradio as gr
4
  import numpy as np
5
  import spaces
@@ -7,6 +9,11 @@ import torch
7
  from diffusers import DiffusionPipeline
8
  from PIL import Image
9
 
 
 
 
 
 
10
  device = "cuda" if torch.cuda.is_available() else "cpu"
11
  repo_id = "black-forest-labs/FLUX.1-dev"
12
  adapter_id = "alvarobartt/ghibli-characters-flux-lora"
@@ -15,10 +22,40 @@ pipeline = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16
15
  pipeline.load_lora_weights(adapter_id)
16
  pipeline = pipeline.to(device)
17
 
18
-
19
  MAX_SEED = np.iinfo(np.int32).max
20
  MAX_IMAGE_SIZE = 1024
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  @spaces.GPU(duration=120)
24
  def inference(
@@ -45,16 +82,25 @@ def inference(
45
  generator=generator,
46
  joint_attention_kwargs={"scale": lora_scale},
47
  ).images[0]
48
-
49
- return image, seed
50
-
 
 
 
51
 
52
  examples = [
53
- (
54
- "Ghibli style futuristic stormtrooper with glossy white armor and a sleek helmet,"
55
- " standing heroically on a lush alien planet, vibrant flowers blooming around, soft"
56
- " sunlight illuminating the scene, a gentle breeze rustling the leaves"
57
- ),
 
 
 
 
 
 
58
  ]
59
 
60
  css = """
@@ -63,83 +109,102 @@ footer {
63
  }
64
  """
65
 
66
- with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css
67
- ) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- with gr.Row():
70
- prompt = gr.Text(
71
- label="Prompt",
72
- show_label=False,
73
- max_lines=1,
74
- placeholder="Enter your prompt",
75
- container=False,
76
- )
77
-
78
- run_button = gr.Button("Run", scale=0)
79
-
80
- result = gr.Image(label="Result", show_label=False)
81
-
82
- with gr.Accordion("Advanced Settings", open=False):
83
- seed = gr.Slider(
84
- label="Seed",
85
- minimum=0,
86
- maximum=MAX_SEED,
87
- step=1,
88
- value=42,
89
- )
90
-
91
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
92
-
93
- with gr.Row():
94
- width = gr.Slider(
95
- label="Width",
96
- minimum=256,
97
- maximum=MAX_IMAGE_SIZE,
98
- step=32,
99
- value=1024,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  )
101
 
102
- height = gr.Slider(
103
- label="Height",
104
- minimum=256,
105
- maximum=MAX_IMAGE_SIZE,
106
- step=32,
107
- value=768,
108
- )
109
-
110
- with gr.Row():
111
- guidance_scale = gr.Slider(
112
- label="Guidance scale",
113
- minimum=0.0,
114
- maximum=10.0,
115
- step=0.1,
116
- value=3.5,
117
- )
118
-
119
- num_inference_steps = gr.Slider(
120
- label="Number of inference steps",
121
- minimum=1,
122
- maximum=50,
123
- step=1,
124
- value=30,
125
- )
126
 
127
- lora_scale = gr.Slider(
128
- label="LoRA scale",
129
- minimum=0.0,
130
- maximum=1.0,
131
- step=0.1,
132
- value=1.0,
133
- )
134
 
135
- gr.Examples(
136
- examples=examples,
137
- fn=lambda x: (Image.open("./example.jpg"), 42),
138
- inputs=[prompt],
139
- outputs=[result, seed],
140
- run_on_click=True,
141
- )
142
 
 
 
 
 
 
143
 
144
  gr.on(
145
  triggers=[run_button.click, prompt.submit],
@@ -154,7 +219,7 @@ with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css
154
  num_inference_steps,
155
  lora_scale,
156
  ],
157
- outputs=[result, seed],
158
  )
159
 
160
  demo.queue()
 
1
  import random
2
+ import os
3
+ import uuid
4
+ from datetime import datetime
5
  import gradio as gr
6
  import numpy as np
7
  import spaces
 
9
  from diffusers import DiffusionPipeline
10
  from PIL import Image
11
 
12
+ # Create permanent storage directory
13
+ SAVE_DIR = "saved_images" # Gradio will handle the persistence
14
+ if not os.path.exists(SAVE_DIR):
15
+ os.makedirs(SAVE_DIR, exist_ok=True)
16
+
17
  device = "cuda" if torch.cuda.is_available() else "cpu"
18
  repo_id = "black-forest-labs/FLUX.1-dev"
19
  adapter_id = "alvarobartt/ghibli-characters-flux-lora"
 
22
  pipeline.load_lora_weights(adapter_id)
23
  pipeline = pipeline.to(device)
24
 
 
25
  MAX_SEED = np.iinfo(np.int32).max
26
  MAX_IMAGE_SIZE = 1024
27
 
28
+ def save_generated_image(image, prompt):
29
+ # Generate unique filename with timestamp
30
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
31
+ unique_id = str(uuid.uuid4())[:8]
32
+ filename = f"{timestamp}_{unique_id}.png"
33
+ filepath = os.path.join(SAVE_DIR, filename)
34
+
35
+ # Save the image
36
+ image.save(filepath)
37
+
38
+ # Save metadata
39
+ metadata_file = os.path.join(SAVE_DIR, "metadata.txt")
40
+ with open(metadata_file, "a", encoding="utf-8") as f:
41
+ f.write(f"{filename}|{prompt}|{timestamp}\n")
42
+
43
+ return filepath
44
+
45
+ def load_generated_images():
46
+ if not os.path.exists(SAVE_DIR):
47
+ return []
48
+
49
+ # Load all images from the directory
50
+ image_files = [os.path.join(SAVE_DIR, f) for f in os.listdir(SAVE_DIR)
51
+ if f.endswith(('.png', '.jpg', '.jpeg', '.webp'))]
52
+ # Sort by creation time (newest first)
53
+ image_files.sort(key=lambda x: os.path.getctime(x), reverse=True)
54
+ return image_files
55
+
56
+ def load_predefined_images():
57
+ # Return empty list since we're not using predefined images
58
+ return []
59
 
60
  @spaces.GPU(duration=120)
61
  def inference(
 
82
  generator=generator,
83
  joint_attention_kwargs={"scale": lora_scale},
84
  ).images[0]
85
+
86
+ # Save the generated image
87
+ filepath = save_generated_image(image, prompt)
88
+
89
+ # Return the image, seed, and updated gallery
90
+ return image, seed, load_generated_images()
91
 
92
  examples = [
93
+ "Ghibli style futuristic stormtrooper with glossy white armor and a sleek helmet, standing heroically on a lush alien planet, vibrant flowers blooming around, soft sunlight illuminating the scene, a gentle breeze rustling the leaves. The armor reflects the pink and purple hues of the alien sunset, creating an ethereal glow around the figure. [trigger]",
94
+
95
+ "Ghibli style young mechanic girl in a floating workshop, surrounded by hovering tools and glowing mechanical parts, her blue overalls covered in oil stains, tinkering with a semi-transparent robot companion. Magical sparks fly as she works, while floating islands with waterfalls drift past her open workshop window. [trigger]",
96
+
97
+ "Ghibli style ancient forest guardian robot, covered in moss and flowering vines, sitting peacefully in a crystal-clear lake. Its gentle eyes glow with soft blue light, while bioluminescent dragonflies dance around its weathered metal frame. Ancient tech symbols on its surface pulse with a gentle rhythm. [trigger]",
98
+
99
+ "Ghibli style sky whale transport ship, its metallic skin adorned with traditional Japanese patterns, gliding through cotton candy clouds at sunrise. Small floating gardens hang from its sides, where workers in futuristic kimonos tend to glowing plants. Rainbow auroras shimmer in the background. [trigger]",
100
+
101
+ "Ghibli style cyber-shrine maiden with flowing holographic robes, performing a ritual dance among floating lanterns and digital cherry blossoms. Her traditional headdress emits soft light patterns, while spirit-like AI constructs swirl around her in elegant patterns. The scene is set in a modern shrine with both ancient wood and sleek chrome elements. [trigger]",
102
+
103
+ "Ghibli style robot farmer tending to floating rice paddies in the sky, wearing a traditional straw hat with advanced sensors. Its gentle movements create ripples in the water as it plants glowing rice seedlings. Flying fish leap between the terraced fields, leaving trails of sparkles in their wake, while future Tokyo's spires gleam in the distance. [trigger]"
104
  ]
105
 
106
  css = """
 
109
  }
110
  """
111
 
112
+ with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css, analytics_enabled=False) as demo:
113
+ gr.HTML('<div class="title"> First CAT of Huggingface </div>')
114
+ gr.HTML('<div class="title">😄Image to Video Explore: <a href="https://huggingface.co/spaces/ginigen/theater" target="_blank">https://huggingface.co/spaces/ginigen/theater</a></div>')
115
+
116
+ with gr.Tabs() as tabs:
117
+ with gr.Tab("Generation"):
118
+ with gr.Column(elem_id="col-container"):
119
+ with gr.Row():
120
+ prompt = gr.Text(
121
+ label="Prompt",
122
+ show_label=False,
123
+ max_lines=1,
124
+ placeholder="Enter your prompt",
125
+ container=False,
126
+ )
127
+ run_button = gr.Button("Run", scale=0)
128
+
129
+ result = gr.Image(label="Result", show_label=False)
130
+
131
+ with gr.Accordion("Advanced Settings", open=False):
132
+ seed = gr.Slider(
133
+ label="Seed",
134
+ minimum=0,
135
+ maximum=MAX_SEED,
136
+ step=1,
137
+ value=42,
138
+ )
139
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
140
+
141
+ with gr.Row():
142
+ width = gr.Slider(
143
+ label="Width",
144
+ minimum=256,
145
+ maximum=MAX_IMAGE_SIZE,
146
+ step=32,
147
+ value=1024,
148
+ )
149
+ height = gr.Slider(
150
+ label="Height",
151
+ minimum=256,
152
+ maximum=MAX_IMAGE_SIZE,
153
+ step=32,
154
+ value=768,
155
+ )
156
+
157
+ with gr.Row():
158
+ guidance_scale = gr.Slider(
159
+ label="Guidance scale",
160
+ minimum=0.0,
161
+ maximum=10.0,
162
+ step=0.1,
163
+ value=3.5,
164
+ )
165
+ num_inference_steps = gr.Slider(
166
+ label="Number of inference steps",
167
+ minimum=1,
168
+ maximum=50,
169
+ step=1,
170
+ value=30,
171
+ )
172
+ lora_scale = gr.Slider(
173
+ label="LoRA scale",
174
+ minimum=0.0,
175
+ maximum=1.0,
176
+ step=0.1,
177
+ value=1.0,
178
+ )
179
+
180
+ gr.Examples(
181
+ examples=examples,
182
+ inputs=[prompt],
183
+ outputs=[result, seed],
184
  )
185
 
186
+ with gr.Tab("Gallery"):
187
+ gallery_header = gr.Markdown("### Generated Images Gallery")
188
+ generated_gallery = gr.Gallery(
189
+ label="Generated Images",
190
+ columns=6,
191
+ show_label=False,
192
+ value=load_generated_images(),
193
+ elem_id="generated_gallery",
194
+ height="auto"
195
+ )
196
+ refresh_btn = gr.Button("🔄 Refresh Gallery")
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
 
 
 
 
 
 
 
198
 
199
+ # Event handlers
200
+ def refresh_gallery():
201
+ return load_generated_images()
 
 
 
 
202
 
203
+ refresh_btn.click(
204
+ fn=refresh_gallery,
205
+ inputs=None,
206
+ outputs=generated_gallery,
207
+ )
208
 
209
  gr.on(
210
  triggers=[run_button.click, prompt.submit],
 
219
  num_inference_steps,
220
  lora_scale,
221
  ],
222
+ outputs=[result, seed, generated_gallery],
223
  )
224
 
225
  demo.queue()