ankitkupadhyay commited on
Commit
4512528
·
verified ·
1 Parent(s): afbe276

initial app file

Browse files
Files changed (1) hide show
  1. app.py +328 -0
app.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ import random
4
+ import subprocess
5
+ import os
6
+ from PIL import Image
7
+ from diffusers import StableDiffusionPipeline, UNet2DConditionModel
8
+ # ... any other imports you need ...
9
+
10
+ # ------------------------------------------------------------------------------
11
+ # 1. Load your models ONCE in global scope (so they don't reload on every run).
12
+ # ------------------------------------------------------------------------------
13
+
14
+ @st.cache_resource
15
+ def load_sd_pipeline(base_model_path: str, fine_tuned_path: str):
16
+ # Safety checker dummy function for demonstration:
17
+ def dummy_safety_checker(images, clip_input):
18
+ return images, False
19
+
20
+ pipe = StableDiffusionPipeline.from_pretrained(
21
+ base_model_path,
22
+ torch_dtype=torch.float16
23
+ )
24
+ pipe.to("cuda")
25
+
26
+ # Load the fine-tuned UNet
27
+ unet = UNet2DConditionModel.from_pretrained(
28
+ fine_tuned_path,
29
+ subfolder="unet",
30
+ torch_dtype=torch.float16
31
+ ).to('cuda')
32
+
33
+ pipe.unet = unet
34
+ pipe.safety_checker = dummy_safety_checker
35
+
36
+ return pipe
37
+
38
+ # Similarly, if you want to load Zero123++ or other pipelines:
39
+ @st.cache_resource
40
+ def load_zero123_pipeline():
41
+ from diffusers import DiffusionPipeline, EulerAncestralDiscreteScheduler
42
+
43
+ pipeline = DiffusionPipeline.from_pretrained(
44
+ "sudo-ai/zero123plus-v1.2",
45
+ custom_pipeline="sudo-ai/zero123plus-pipeline",
46
+ torch_dtype=torch.float16
47
+ )
48
+ pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(
49
+ pipeline.scheduler.config, timestep_spacing='trailing'
50
+ )
51
+ pipeline.to("cuda")
52
+ return pipeline
53
+
54
+
55
+ # Example placeholders for the SyncDreamer command or internal functions:
56
+ def run_syncdreamer(input_path: str, output_dir: str = "syncdreamer_output"):
57
+ """Runs SyncDreamer on input_path and places results into output_dir."""
58
+ st.info("Running SyncDreamer... (placeholder)")
59
+ # This is where your actual command would go:
60
+ # subprocess.run([...], check=True)
61
+ os.makedirs(output_dir, exist_ok=True)
62
+ # (In a real scenario, you'd handle .jpg to .png conversion, etc.)
63
+ st.success(f"SyncDreamer completed. Results in: {output_dir}")
64
+
65
+
66
+ # Helper function for Zero123++ pipeline
67
+ def make_square_min_dim(image: Image.Image, min_side: int = 320) -> Image.Image:
68
+ w, h = image.size
69
+ scale = max(min_side / w, min_side / h, 1.0)
70
+ new_w, new_h = int(w * scale), int(h * scale)
71
+ image = image.resize((new_w, new_h), Image.LANCZOS)
72
+
73
+ side = max(new_w, new_h)
74
+ new_img = Image.new(mode="RGB", size=(side, side), color=(255, 255, 255))
75
+ offset_x = (side - new_w) // 2
76
+ offset_y = (side - new_h) // 2
77
+ new_img.paste(image, (offset_x, offset_y))
78
+ return new_img
79
+
80
+
81
+ # ------------------------------------------------------------------------------
82
+ # 2. Streamlit application.
83
+ # ------------------------------------------------------------------------------
84
+
85
+ def main():
86
+ st.title("Funko Generator Demo")
87
+
88
+ # Let’s load pipelines in the background:
89
+ base_model_path = "runwayml/stable-diffusion-v1-5"
90
+ fine_tuned_path = "/content/drive/MyDrive/CC_Project/checkpoint-3000" # adapt if needed
91
+ sd_pipe = load_sd_pipeline(base_model_path, fine_tuned_path)
92
+
93
+ zero123_pipe = load_zero123_pipeline() # For multi-view generation
94
+
95
+ # Session state to hold:
96
+ if "latest_image" not in st.session_state:
97
+ st.session_state["latest_image"] = None
98
+ if "original_prompt" not in st.session_state:
99
+ st.session_state["original_prompt"] = ""
100
+
101
+ # --------------------------------------------------------------------------
102
+ # A) Prompt input & initial generation
103
+ # --------------------------------------------------------------------------
104
+ st.subheader("1. Enter your Funko prompt")
105
+
106
+ # Show examples in the UI
107
+ with st.expander("Examples of valid prompts"):
108
+ st.write("""
109
+ - A standing plain human Funko in a blue shirt and blue pants with round black eyes with glasses with a belt.
110
+ - A sitting angry animal Funko with squint black eyes.
111
+ - A standing happy robot Funko in a brown shirt and grey pants with squint black eyes with cane and monocle.
112
+ - ...
113
+ """)
114
+
115
+ user_prompt = st.text_area("Type your Funko prompt here:",
116
+ value="A standing plain human Funko in a blue shirt and blue pants with round black eyes with glasses.")
117
+ generate_button = st.button("Generate Initial Funko")
118
+
119
+ if generate_button:
120
+ st.session_state["original_prompt"] = user_prompt
121
+ with st.spinner("Generating image..."):
122
+ with torch.autocast("cuda"):
123
+ image = sd_pipe(user_prompt, num_inference_steps=50).images[0]
124
+ st.session_state["latest_image"] = image
125
+
126
+ st.success("Image generated!")
127
+
128
+ if st.session_state["latest_image"] is not None:
129
+ st.image(st.session_state["latest_image"], caption="Latest Generated Image", use_column_width=True)
130
+
131
+ # --------------------------------------------------------------------------
132
+ # B) Change the Funko (attributes)
133
+ # --------------------------------------------------------------------------
134
+ st.subheader("2. Modify Funko Attributes")
135
+ st.write("Select new attributes below. If you choose 'none', that attribute will be ignored/omitted in the prompt.")
136
+
137
+ # Possible attributes (from your code) — including 'none'
138
+ characters = ['none', 'animal', 'human', 'robot']
139
+ eyes_shape = ['none', 'anime', 'black', 'closed', 'round', 'square', 'squint']
140
+ eyes_color = ['none', 'black', 'blue', 'brown', 'green', 'grey', 'orange', 'pink', 'purple', 'red', 'white', 'yellow']
141
+ eyewear = ['none', 'eyepatch', 'glasses', 'goggles', 'helmet', 'mask', 'sunglasses']
142
+ hair_color = ['none', 'black', 'blonde', 'blue', 'brown', 'green', 'grey', 'orange', 'pink', 'purple', 'red', 'white', 'yellow']
143
+ emotion = ['none', 'angry', 'happy', 'plain', 'sad']
144
+ shirt_color = ['none', 'black', 'blue', 'brown', 'green', 'grey', 'orange', 'pink', 'purple', 'red', 'white', 'yellow']
145
+ pants_color = ['none', 'black', 'blue', 'brown', 'green', 'grey', 'orange', 'pink', 'purple', 'red', 'white', 'yellow']
146
+ accessories = ['none', 'bag', 'ball', 'belt', 'bird', 'book', 'cape', 'guitar', 'hat', 'helmet', 'sword', 'wand', 'wings']
147
+ pose = ['none', 'sitting', 'standing']
148
+
149
+ # Create selection widgets:
150
+ chosen_char = st.selectbox("Character:", characters)
151
+ chosen_eyes_shape = st.selectbox("Eyes Shape:", eyes_shape)
152
+ chosen_eyes_color = st.selectbox("Eyes Color:", eyes_color)
153
+ chosen_eyewear = st.selectbox("Eyewear:", eyewear)
154
+ chosen_hair_color = st.selectbox("Hair Color:", hair_color)
155
+ chosen_emotion = st.selectbox("Emotion:", emotion)
156
+ chosen_shirt_color = st.selectbox("Shirt Color:", shirt_color)
157
+ chosen_pants_color = st.selectbox("Pants Color:", pants_color)
158
+ chosen_accessories = st.selectbox("Accessories:", accessories)
159
+ chosen_pose = st.selectbox("Pose:", pose)
160
+
161
+ # Now we form a modified prompt. For demonstration,
162
+ # let's do something simple: we take the original prompt, parse it, and
163
+ # replace only the attributes that are not 'none'.
164
+ def modify_prompt(base_prompt: str):
165
+ # A simple example: we can build a new prompt from scratch, ignoring the old text.
166
+ # In reality, you might parse the old text or do something more sophisticated.
167
+ new_prompt_segments = []
168
+
169
+ # Pose
170
+ if chosen_pose != 'none':
171
+ new_prompt_segments.append(f"A {chosen_pose}")
172
+ else:
173
+ new_prompt_segments.append("A standing") # default fallback
174
+
175
+ # Emotion + Character
176
+ if chosen_emotion != 'none':
177
+ new_prompt_segments.append(chosen_emotion)
178
+ else:
179
+ new_prompt_segments.append("plain") # fallback
180
+
181
+ if chosen_char != 'none':
182
+ new_prompt_segments.append(chosen_char + " Funko")
183
+ else:
184
+ new_prompt_segments.append("human Funko")
185
+
186
+ # Shirt color
187
+ if chosen_shirt_color != 'none':
188
+ new_prompt_segments.append(f"in a {chosen_shirt_color} shirt")
189
+ else:
190
+ new_prompt_segments.append("in a blue shirt")
191
+
192
+ # Pants color
193
+ if chosen_pants_color != 'none':
194
+ new_prompt_segments.append(f"and {chosen_pants_color} pants")
195
+ else:
196
+ new_prompt_segments.append("and blue pants")
197
+
198
+ # Eyes
199
+ eye_text = []
200
+ if chosen_eyes_shape != 'none':
201
+ eye_text.append(f"{chosen_eyes_shape}")
202
+ else:
203
+ eye_text.append("round")
204
+ if chosen_eyes_color != 'none':
205
+ eye_text.append(f"{chosen_eyes_color}")
206
+ else:
207
+ eye_text.append("black")
208
+ eye_text.append("eyes")
209
+ new_prompt_segments.append("with " + " ".join(eye_text))
210
+
211
+ # Eyewear
212
+ if chosen_eyewear != 'none':
213
+ new_prompt_segments.append(f"with {chosen_eyewear}")
214
+
215
+ # Hair
216
+ if chosen_hair_color != 'none':
217
+ new_prompt_segments.append(f"with {chosen_hair_color} hair")
218
+
219
+ # Accessories
220
+ if chosen_accessories != 'none':
221
+ new_prompt_segments.append(f"with a {chosen_accessories}")
222
+
223
+ return " ".join(new_prompt_segments) + "."
224
+
225
+ if st.button("Generate Modified Funko"):
226
+ if not st.session_state["original_prompt"]:
227
+ st.warning("Please generate an initial Funko (step 1) before modifying it.")
228
+ else:
229
+ new_prompt = modify_prompt(st.session_state["original_prompt"])
230
+ st.write(f"**New Prompt**: {new_prompt}")
231
+
232
+ with st.spinner("Generating modified image..."):
233
+ with torch.autocast("cuda"):
234
+ image = sd_pipe(new_prompt, num_inference_steps=50).images[0]
235
+ st.session_state["latest_image"] = image
236
+
237
+ st.image(st.session_state["latest_image"], caption="Modified Image", use_column_width=True)
238
+
239
+ # --------------------------------------------------------------------------
240
+ # C) Animate the Funko with SyncDreamer
241
+ # --------------------------------------------------------------------------
242
+ st.subheader("3. Animate the Funko (SyncDreamer)")
243
+ st.write("Click the button to run SyncDreamer on the last generated image. (Demo)")
244
+
245
+ if st.button("Animate with SyncDreamer"):
246
+ if st.session_state["latest_image"] is None:
247
+ st.warning("No image found. Please generate a Funko first.")
248
+ else:
249
+ # Save latest image locally so SyncDreamer can process it
250
+ input_path = "latest_funko.png"
251
+ st.session_state["latest_image"].save(input_path)
252
+ run_syncdreamer(input_path, output_dir="syncdreamer_output")
253
+
254
+ # Optionally display a placeholder or actual frames/GIF
255
+ # ...
256
+ st.success("SyncDreamer animation completed (placeholder).")
257
+
258
+ # --------------------------------------------------------------------------
259
+ # D) Multi-View 3D Funko (Zero123++)
260
+ # --------------------------------------------------------------------------
261
+ st.subheader("4. Generate Multi-View 3D Funko (Zero123++)")
262
+
263
+ if st.button("Generate Multi-View 3D"):
264
+ if st.session_state["latest_image"] is None:
265
+ st.warning("No image found. Please generate a Funko first.")
266
+ else:
267
+ # Save the last image as input for Zero123
268
+ input_path = "funko_for_zero123.png"
269
+ st.session_state["latest_image"].save(input_path)
270
+
271
+ # Make sure image is at least 320x320 and square
272
+ original_img = Image.open(input_path).convert("RGB")
273
+ cond = make_square_min_dim(original_img, min_side=320)
274
+
275
+ # Inference
276
+ st.info("Running Zero123++ pipeline... Please wait.")
277
+ with torch.autocast("cuda"):
278
+ result_grid = zero123_pipe(cond, num_inference_steps=50).images[0]
279
+
280
+ result_grid.save("zero123_grid.png")
281
+ st.image(result_grid, caption="Zero123++ Multi-View Grid (640x960)")
282
+
283
+ # Optionally crop and display sub-views
284
+ # Here we crop 6 sub-images of 320x320 from the 640x960 grid:
285
+ coords = [
286
+ (0, 0, 320, 320),
287
+ (320, 0, 640, 320),
288
+ (0, 320, 320, 640),
289
+ (320, 320, 640, 640),
290
+ (0, 640, 320, 960),
291
+ (320, 640, 640, 960),
292
+ ]
293
+ st.write("### Generated Views:")
294
+ for i, (x1, y1, x2, y2) in enumerate(coords):
295
+ sub_img = result_grid.crop((x1, y1, x2, y2))
296
+ sub_path = f"zero123_view_{i}.png"
297
+ sub_img.save(sub_path)
298
+ st.image(sub_path, width=256)
299
+
300
+ # --------------------------------------------------------------------------
301
+ # E) Integrate a New Background
302
+ # --------------------------------------------------------------------------
303
+ st.subheader("5. Apply a New Background to Each View")
304
+
305
+ st.write("Upload a background image, then apply it to each previously generated view.")
306
+ bg_file = st.file_uploader("Upload Background Image", type=["png", "jpg", "jpeg"])
307
+ if bg_file is not None:
308
+ st.image(bg_file, caption="Selected Background", width=200)
309
+
310
+ if st.button("Apply Background to Multi-View"):
311
+ if bg_file is None:
312
+ st.warning("No background uploaded.")
313
+ else:
314
+ # Save background to disk:
315
+ bg_path = "background.png"
316
+ with open(bg_path, "wb") as f:
317
+ f.write(bg_file.read())
318
+
319
+ # In a real implementation, you would do the compositing described
320
+ # in your original code with threshold-based masking, etc.
321
+ # For demonstration, let's just say "Applied!"
322
+ st.success("Background compositing placeholder done. Check your images in the output folder.")
323
+
324
+ st.write("End of the Demo. Adjust code as needed for your pipeline paths and logic.")
325
+
326
+
327
+ if __name__ == "__main__":
328
+ main()