aiqcamp commited on
Commit
832aac3
·
verified ·
1 Parent(s): 279379f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -225
app.py CHANGED
@@ -1,226 +1,35 @@
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
8
- import torch
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 = "ginipick/flux-lora-eric-cat"
20
-
21
- pipeline = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16)
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(
62
- prompt: str,
63
- seed: int,
64
- randomize_seed: bool,
65
- width: int,
66
- height: int,
67
- guidance_scale: float,
68
- num_inference_steps: int,
69
- lora_scale: float,
70
- progress: gr.Progress = gr.Progress(track_tqdm=True),
71
- ):
72
- if randomize_seed:
73
- seed = random.randint(0, MAX_SEED)
74
- generator = torch.Generator(device=device).manual_seed(seed)
75
-
76
- image = pipeline(
77
- prompt=prompt,
78
- guidance_scale=guidance_scale,
79
- num_inference_steps=num_inference_steps,
80
- width=width,
81
- height=height,
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
- "A fluffy white Persian cat in a tiny royal hanbok, sitting regally on a velvet cushion. The cat wears a miniature golden crown and a silk hanbok in pastel pink and mint green. Its long fur is perfectly groomed, and it has bright blue eyes that sparkle with nobility. The background features traditional Korean palace decorations and cherry blossoms floating in the air. [trigger]",
94
-
95
- "An adorable orange tabby cat as a master chef, wearing a white chef's hat and apron, standing on its hind legs at a tiny kitchen counter. The cat is delicately holding a miniature rolling pin, preparing cat-shaped cookies. The cozy kitchen background features tiny cooking utensils and a warm, golden afternoon light streaming through the window. [trigger]",
96
-
97
- "A playful black and white tuxedo cat as a professional photographer, wearing tiny round glasses and a vintage camera around its neck. The cat is perfectly balanced on a tree branch, attempting to photograph a butterfly. It wears a cute brown leather camera bag and a mini beret, looking artistic and focused. [trigger]",
98
-
99
- "A sleepy Scottish Fold cat in astronaut gear, floating inside a spaceship cabin. The cat wears a custom-fit space suit with cute patches, gently batting at floating star-shaped toys. Through the spaceship window, Earth and twinkling stars create a magical cosmic background. [trigger]",
100
-
101
- "A graceful Siamese ballet dancer cat in a sparkly pink tutu, performing a perfect pirouette on a miniature stage. The cat wears tiny satin ballet slippers on its paws and a crystal tiara. The stage is lit with soft spotlights, and rose petals are scattered around its dancing feet. [trigger]",
102
-
103
- "A adventurous calico cat explorer in safari gear, riding on top of a friendly elephant. The cat wears a tiny khaki vest with many pockets, a safari hat, and carries a miniature map. The background shows a beautiful sunset over the African savanna with acacia trees and colorful birds flying overhead. [trigger]"
104
- ]
105
-
106
- css = """
107
- footer {
108
- visibility: hidden;
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],
211
- fn=inference,
212
- inputs=[
213
- prompt,
214
- seed,
215
- randomize_seed,
216
- width,
217
- height,
218
- guidance_scale,
219
- num_inference_steps,
220
- lora_scale,
221
- ],
222
- outputs=[result, seed, generated_gallery],
223
- )
224
-
225
- demo.queue()
226
- demo.launch()
 
 
1
  import os
2
+ import sys
3
+ import streamlit as st
4
+ from tempfile import NamedTemporaryFile
5
+
6
+ def main():
7
+ try:
8
+ # Get the code from secrets
9
+ code = os.environ.get("MAIN_CODE")
10
+
11
+ if not code:
12
+ st.error("⚠️ The application code wasn't found in secrets. Please add the MAIN_CODE secret.")
13
+ return
14
+
15
+ # Create a temporary Python file
16
+ with NamedTemporaryFile(suffix='.py', delete=False, mode='w') as tmp:
17
+ tmp.write(code)
18
+ tmp_path = tmp.name
19
+
20
+ # Execute the code
21
+ exec(compile(code, tmp_path, 'exec'), globals())
22
+
23
+ # Clean up the temporary file
24
+ try:
25
+ os.unlink(tmp_path)
26
+ except:
27
+ pass
28
+
29
+ except Exception as e:
30
+ st.error(f"⚠️ Error loading or executing the application: {str(e)}")
31
+ import traceback
32
+ st.code(traceback.format_exc())
33
+
34
+ if __name__ == "__main__":
35
+ main()