ankitkupadhyay commited on
Commit
20c861f
·
verified ·
1 Parent(s): 69319f4
Files changed (1) hide show
  1. app.py +272 -200
app.py CHANGED
@@ -1,70 +1,112 @@
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)
@@ -77,34 +119,77 @@ def make_square_min_dim(image: Image.Image, min_side: int = 320) -> Image.Image:
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.
@@ -112,217 +197,204 @@ def main():
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()
 
1
  import streamlit as st
2
+ import os
3
  import random
4
  import subprocess
5
+ import io
6
+ import numpy as np
7
+
8
  from PIL import Image
9
+ import torch
10
  from diffusers import StableDiffusionPipeline, UNet2DConditionModel
11
+ from torchvision import transforms
12
+
13
+ # If you're using Zero123++:
14
+ from diffusers import DiffusionPipeline, EulerAncestralDiscreteScheduler
15
 
16
  # ------------------------------------------------------------------------------
17
+ # 0. GLOBAL CONFIG & UTILS
18
  # ------------------------------------------------------------------------------
19
 
20
+ # Provide your base SD model path & fine-tuned UNet path here.
21
+ # (In a HF Space, you might store them in a local folder or load from HF repos.)
22
+ BASE_MODEL_PATH = "runwayml/stable-diffusion-v1-5"
23
+ FINE_TUNED_PATH = "my_finetuned_unet" # e.g., local folder or HF Hub ID
24
+
25
+ # If you want to use Zero123++ from a local clone:
26
+ ZERO123_MODEL_ID = "sudo-ai/zero123plus-v1.2"
27
+
28
+ # Example safety checker dummy, as used in your snippet:
29
+ def dummy_safety_checker(images, clip_input):
30
+ return images, False
31
+
32
+ # Make sure to remove or comment out any "!pip install ..." lines and rely
33
+ # on your requirements.txt in the environment.
34
 
35
+ # ------------------------------------------------------------------------------
36
+ # 1. LOAD MODELS & PIPELINES
37
+ # ------------------------------------------------------------------------------
38
+
39
+ @st.cache_resource
40
+ def load_sd_pipeline():
41
+ """Load the base stable diffusion pipeline with fine-tuned UNet attached."""
42
  pipe = StableDiffusionPipeline.from_pretrained(
43
+ BASE_MODEL_PATH,
44
  torch_dtype=torch.float16
45
  )
46
  pipe.to("cuda")
47
+
48
+ # Load and replace UNet
49
  unet = UNet2DConditionModel.from_pretrained(
50
+ FINE_TUNED_PATH,
51
  subfolder="unet",
52
  torch_dtype=torch.float16
53
+ ).to("cuda")
54
+
55
  pipe.unet = unet
56
  pipe.safety_checker = dummy_safety_checker
 
57
  return pipe
58
 
 
59
  @st.cache_resource
60
  def load_zero123_pipeline():
61
+ """Load Zero123++ pipeline (v1.2) with EulerAncestralDiscreteScheduler."""
 
62
  pipeline = DiffusionPipeline.from_pretrained(
63
+ ZERO123_MODEL_ID,
64
  custom_pipeline="sudo-ai/zero123plus-pipeline",
65
  torch_dtype=torch.float16
66
  )
67
  pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(
68
+ pipeline.scheduler.config,
69
+ timestep_spacing='trailing'
70
  )
71
  pipeline.to("cuda")
72
  return pipeline
73
 
74
+ # ------------------------------------------------------------------------------
75
+ # 2. HELPER FUNCTIONS
76
+ # ------------------------------------------------------------------------------
77
 
78
+ def generate_funko_image(pipe, prompt: str, steps: int = 50):
79
+ """Generate a Funko image using the loaded Stable Diffusion pipeline."""
80
+ with torch.autocast("cuda"):
81
+ image = pipe(prompt, num_inference_steps=steps).images[0]
82
+ return image
83
+
84
+ def run_syncdreamer(input_path: str, output_dir: str):
85
+ """
86
+ Placeholder for the SyncDreamer command-line call.
87
+ You would adapt this to run your real command. For example:
88
+
89
+ syncdreamer_cmd = [
90
+ "python", "generate.py",
91
+ "--ckpt", "ckpt/syncdreamer-pretrain.ckpt",
92
+ "--input", input_path,
93
+ "--output", output_dir,
94
+ "--sample_num", "4",
95
+ "--cfg_scale", "2.0",
96
+ ...
97
+ ]
98
+ subprocess.run(syncdreamer_cmd, check=True)
99
+ """
100
+ st.info("Running SyncDreamer... (this is a placeholder call)")
101
  os.makedirs(output_dir, exist_ok=True)
102
+ # In real usage, call the above commented command via subprocess
103
+ st.success(f"SyncDreamer completed. Output in: {output_dir}")
 
104
 
 
105
  def make_square_min_dim(image: Image.Image, min_side: int = 320) -> Image.Image:
106
+ """
107
+ Resize 'image' so that neither dimension is < min_side,
108
+ then pad to a square with white background.
109
+ """
110
  w, h = image.size
111
  scale = max(min_side / w, min_side / h, 1.0)
112
  new_w, new_h = int(w * scale), int(h * scale)
 
119
  new_img.paste(image, (offset_x, offset_y))
120
  return new_img
121
 
122
+ def run_zero123(pipeline, input_image: Image.Image, steps: int = 50):
123
+ """Generate a 640x960 grid from Zero123++ pipeline."""
124
+ cond = make_square_min_dim(input_image, min_side=320)
125
+ with torch.autocast("cuda"):
126
+ result_grid = pipeline(cond, num_inference_steps=steps).images[0]
127
+ return result_grid
128
+
129
+ def crop_zero123_grid(grid_img: Image.Image):
130
+ """
131
+ Zero123++ default output for 6-views is 640x960 (2 columns, 3 rows).
132
+ Crop into six 320x320 sub-images.
133
+ """
134
+ coords = [
135
+ (0, 0, 320, 320),
136
+ (320, 0, 640, 320),
137
+ (0, 320, 320, 640),
138
+ (320, 320, 640, 640),
139
+ (0, 640, 320, 960),
140
+ (320, 640, 640, 960),
141
+ ]
142
+ sub_images = []
143
+ for x1, y1, x2, y2 in coords:
144
+ sub_img = grid_img.crop((x1, y1, x2, y2))
145
+ sub_images.append(sub_img)
146
+ return sub_images
147
+
148
+ # Example background compositing if desired:
149
+ def create_mask(image, bg_color=(255,255,255), threshold=30):
150
+ arr = np.array(image)
151
+ diff = np.abs(arr - np.array(bg_color))
152
+ diff = diff.max(axis=2)
153
+ mask = (diff > threshold) * 255
154
+ return Image.fromarray(mask.astype(np.uint8), mode="L")
155
+
156
+ def composite_foreground_background(fg, bg, bg_color=(255,255,255), threshold=30):
157
+ fg = fg.convert("RGBA")
158
+ bg = bg.convert("RGBA").resize(fg.size)
159
+ mask = create_mask(fg.convert("RGB"), bg_color=bg_color, threshold=threshold)
160
+ result = Image.composite(fg, bg, mask)
161
+ return result
162
+
163
+ def get_bg_color(image):
164
+ corner_pixel = image.getpixel((0, 0))
165
+ # Heuristic: if corner pixel is near-white, treat as white background
166
+ if sum(corner_pixel) / 3 > 240:
167
+ return (255, 255, 255)
168
+ else:
169
+ return (200, 200, 200)
170
 
171
  # ------------------------------------------------------------------------------
172
+ # 3. STREAMLIT UI
173
  # ------------------------------------------------------------------------------
 
174
  def main():
175
+ st.title("Funko Generator (SD + SyncDreamer + Zero123)")
176
 
177
+ # Load pipelines once
178
+ sd_pipe = load_sd_pipeline()
179
+ zero123_pipe = load_zero123_pipeline()
 
180
 
181
+ # Session state to store images
 
 
182
  if "latest_image" not in st.session_state:
183
  st.session_state["latest_image"] = None
184
  if "original_prompt" not in st.session_state:
185
  st.session_state["original_prompt"] = ""
186
 
187
+ # ---------------------------
188
+ # A) Prompt Input
189
+ # ---------------------------
190
+ st.subheader("1. Enter your initial Funko prompt")
191
 
192
+ with st.expander("Prompt Examples"):
 
193
  st.write("""
194
  - A standing plain human Funko in a blue shirt and blue pants with round black eyes with glasses with a belt.
195
  - A sitting angry animal Funko with squint black eyes.
 
197
  - ...
198
  """)
199
 
200
+ user_prompt = st.text_area(
201
+ "Type your Funko prompt here:",
202
+ value="A standing plain human Funko in a blue shirt and blue pants with round black eyes with glasses."
203
+ )
204
+ generate_initial = st.button("Generate Initial Funko")
205
 
206
+ if generate_initial:
207
  st.session_state["original_prompt"] = user_prompt
208
+ with st.spinner("Generating initial Funko..."):
209
+ out_img = generate_funko_image(sd_pipe, user_prompt, steps=50)
210
+ st.session_state["latest_image"] = out_img
 
 
211
  st.success("Image generated!")
212
 
213
  if st.session_state["latest_image"] is not None:
214
+ st.image(st.session_state["latest_image"], caption="Latest Funko Image", use_column_width=True)
215
 
216
+ # ---------------------------
217
+ # B) Modify Funko Attributes
218
+ # ---------------------------
219
+ st.subheader("2. Modify the Funko (attributes)")
220
+
221
+ st.write("Pick new attributes. If you choose 'none', we won't override that attribute.")
222
 
 
223
  characters = ['none', 'animal', 'human', 'robot']
224
+ eyes_shapes = ['none', 'anime', 'black', 'closed', 'round', 'square', 'squint']
225
+ eyes_colors = ['none', 'black', 'blue', 'brown', 'green', 'grey', 'orange', 'pink', 'purple', 'red', 'white', 'yellow']
226
+ eyewears = ['none', 'eyepatch', 'glasses', 'goggles', 'helmet', 'mask', 'sunglasses']
227
+ hair_colors = ['none', 'black', 'blonde', 'blue', 'brown', 'green', 'grey', 'orange', 'pink', 'purple', 'red', 'white', 'yellow']
228
+ emotions = ['none', 'angry', 'happy', 'plain', 'sad']
229
+ shirt_colors = ['none', 'black', 'blue', 'brown', 'green', 'grey', 'orange', 'pink', 'purple', 'red', 'white', 'yellow']
230
+ pants_colors = ['none', 'black', 'blue', 'brown', 'green', 'grey', 'orange', 'pink', 'purple', 'red', 'white', 'yellow']
231
  accessories = ['none', 'bag', 'ball', 'belt', 'bird', 'book', 'cape', 'guitar', 'hat', 'helmet', 'sword', 'wand', 'wings']
232
+ poses = ['none', 'sitting', 'standing']
233
+
234
+ chosen_char = st.selectbox("Character", characters)
235
+ chosen_eyes_shape = st.selectbox("Eyes Shape", eyes_shapes)
236
+ chosen_eyes_color = st.selectbox("Eyes Color", eyes_colors)
237
+ chosen_eyewear = st.selectbox("Eyewear", eyewears)
238
+ chosen_hair_color = st.selectbox("Hair Color", hair_colors)
239
+ chosen_emotion = st.selectbox("Emotion", emotions)
240
+ chosen_shirt_color = st.selectbox("Shirt Color", shirt_colors)
241
+ chosen_pants_color = st.selectbox("Pants Color", pants_colors)
242
+ chosen_accessory = st.selectbox("Accessories", accessories)
243
+ chosen_pose = st.selectbox("Pose", poses)
244
+
245
+ def build_modified_prompt():
246
+ # Simple new prompt builder
247
+ # If 'none', we do not override the attribute (use fallback or skip).
248
+ tokens = []
 
 
 
 
249
 
250
  # Pose
251
  if chosen_pose != 'none':
252
+ tokens.append(f"A {chosen_pose}")
253
  else:
254
+ tokens.append("A standing")
255
 
256
  # Emotion + Character
257
  if chosen_emotion != 'none':
258
+ tokens.append(chosen_emotion)
259
  else:
260
+ tokens.append("plain")
 
261
  if chosen_char != 'none':
262
+ tokens.append(chosen_char + " Funko")
263
  else:
264
+ tokens.append("human Funko")
265
 
266
  # Shirt color
267
  if chosen_shirt_color != 'none':
268
+ tokens.append(f"in a {chosen_shirt_color} shirt")
269
  else:
270
+ tokens.append("in a blue shirt")
271
 
272
  # Pants color
273
  if chosen_pants_color != 'none':
274
+ tokens.append(f"and {chosen_pants_color} pants")
275
  else:
276
+ tokens.append("and blue pants")
277
 
278
  # Eyes
279
+ eye_desc = []
280
  if chosen_eyes_shape != 'none':
281
+ eye_desc.append(chosen_eyes_shape)
282
  else:
283
+ eye_desc.append("round")
284
  if chosen_eyes_color != 'none':
285
+ eye_desc.append(chosen_eyes_color)
286
  else:
287
+ eye_desc.append("black")
288
+ eye_desc.append("eyes")
 
289
 
290
+ tokens.append("with " + " ".join(eye_desc))
 
 
291
 
292
+ if chosen_eyewear != 'none':
293
+ tokens.append(f"with {chosen_eyewear}")
294
  if chosen_hair_color != 'none':
295
+ tokens.append(f"with {chosen_hair_color} hair")
296
+ if chosen_accessory != 'none':
297
+ tokens.append(f"with a {chosen_accessory}")
 
 
298
 
299
+ return " ".join(tokens) + "."
300
 
301
  if st.button("Generate Modified Funko"):
302
+ if st.session_state["original_prompt"] == "":
303
+ st.warning("Please generate an initial Funko first.")
304
  else:
305
+ new_prompt = build_modified_prompt()
306
+ st.write("**New Prompt**:", new_prompt)
 
307
  with st.spinner("Generating modified image..."):
308
+ out_img = generate_funko_image(sd_pipe, new_prompt, steps=50)
309
+ st.session_state["latest_image"] = out_img
310
+ st.image(st.session_state["latest_image"], caption="Modified Funko", use_column_width=True)
 
 
311
 
312
+ # ---------------------------
313
+ # C) Animate with SyncDreamer
314
+ # ---------------------------
315
+ st.subheader("3. Animate the Funko with SyncDreamer")
 
316
 
317
+ st.write("Click to run SyncDreamer on the last generated image (placeholder).")
318
+ if st.button("Animate Funko"):
319
  if st.session_state["latest_image"] is None:
320
+ st.warning("No image to animate. Generate a Funko first.")
321
  else:
322
+ # Save the current image
323
  input_path = "latest_funko.png"
324
  st.session_state["latest_image"].save(input_path)
325
+ output_dir = "syncdreamer_output"
326
+ run_syncdreamer(input_path, output_dir=output_dir)
327
 
328
+ st.success("SyncDreamer run complete (demo). Check output directory for results.")
 
 
329
 
330
+ # ---------------------------
331
+ # D) Multi-View with Zero123++
332
+ # ---------------------------
333
+ st.subheader("4. Generate Multi-View Funko (Zero123++)")
334
 
335
  if st.button("Generate Multi-View 3D"):
336
  if st.session_state["latest_image"] is None:
337
+ st.warning("No image to process. Generate a Funko first.")
338
  else:
339
+ # Save for Zero123
340
+ zero123_input_path = "funko_for_zero123.png"
341
+ st.session_state["latest_image"].save(zero123_input_path)
342
+
343
+ with st.spinner("Running Zero123++..."):
344
+ full_image = run_zero123(zero123_pipe, st.session_state["latest_image"], steps=50)
345
+
346
+ # Display the 640x960 grid
347
+ st.image(full_image, caption="Zero123++ Grid (640x960)", use_column_width=True)
348
+
349
+ # Crop sub-images
350
+ sub_images = crop_zero123_grid(full_image)
351
+ st.write("Six sub-views:")
352
+ for i, s_img in enumerate(sub_images):
353
+ st.image(s_img, width=256, caption=f"View {i+1}")
354
+
355
+ # ---------------------------
356
+ # E) Background Compositing
357
+ # ---------------------------
358
+ st.subheader("5. Apply Background to Each View")
359
+
360
+ bg_file = st.file_uploader("Upload a background image (PNG/JPG)", type=["png","jpg","jpeg"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  if bg_file is not None:
362
+ st.image(bg_file, caption="Your Background", width=200)
363
 
364
+ if st.button("Composite Background onto Views"):
365
  if bg_file is None:
366
  st.warning("No background uploaded.")
367
  else:
368
+ # We assume you already did "Generate Multi-View 3D" so we have "Zero123++ Grid"
369
+ # In a real scenario, you might store sub-images in session_state after generation
370
+ # For this example, let's assume we re-run the pipeline or re-crop a stored grid.
371
+ if st.session_state["latest_image"] is None:
372
+ st.warning("No Funko image found. Generate or do multi-view first.")
373
+ else:
374
+ # We'll read the background
375
+ bg = Image.open(bg_file).convert("RGBA")
376
+
377
+ # Suppose we have a stored "zero123_grid.png" from the step above
378
+ # This is a simplistic approach. You might track them in session state.
379
+ if not os.path.exists("zero123_grid.png"):
380
+ st.warning("No zero123_grid.png found. Please run Zero123++ step first.")
381
+ else:
382
+ grid_img = Image.open("zero123_grid.png").convert("RGB")
383
+ sub_images = crop_zero123_grid(grid_img)
384
+
385
+ # Composite each sub-image
386
+ st.write("Applying background to each sub-view...")
387
+ for i, fg_img in enumerate(sub_images):
388
+ # Detect background color from Funko sub-view
389
+ bg_color = get_bg_color(fg_img)
390
+ comp = composite_foreground_background(fg_img, bg, bg_color=bg_color, threshold=30)
391
+ st.image(comp, width=256, caption=f"Composite View {i+1}")
392
+
393
+ st.write("---")
394
+ st.write("End of the demo. Adapt paths and code to your environment as needed.")
395
 
396
+ # ------------------------------------------------------------------------------
397
+ # 4. ENTRY POINT
398
+ # ------------------------------------------------------------------------------
399
  if __name__ == "__main__":
400
  main()