lehduong commited on
Commit
2173a68
1 Parent(s): 4cab05a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +710 -294
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import spaces
 
2
  import subprocess
3
  subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
4
  import gradio as gr
@@ -23,6 +24,14 @@ import matplotlib
23
  import numpy as np
24
  import cv2
25
  import argparse
 
 
 
 
 
 
 
 
26
 
27
  # Task-specific tokens
28
  TASK2SPECIAL_TOKENS = {
@@ -59,7 +68,7 @@ class LlavaCaptionProcessor:
59
  with torch.no_grad():
60
  prompt = self.processor.apply_chat_template(conversation, add_generation_prompt=True)
61
  inputs = self.processor(prompt, image, return_tensors="pt").to(self.model.device)
62
- output = self.model.generate(**inputs, max_new_tokens=250)
63
  response = self.processor.decode(output[0], skip_special_tokens=True)
64
  return response.split(msg)[-1].strip()[len(self.SPECIAL_TOKENS):]
65
 
@@ -133,7 +142,7 @@ class PlaceHolderCaptionProcessor:
133
 
134
  def initialize_models(captioner_name):
135
  device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
136
- pipeline = OneDiffusionPipeline.from_pretrained("lehduong/OneDiffusion").to(device=device, dtype=torch.bfloat16)
137
  if captioner_name == 'molmo':
138
  captioner = MolmoCaptionProcessor()
139
  elif captioner_name == 'llava':
@@ -402,320 +411,727 @@ def process_images_for_task_type(images_state: List[Image.Image], task_type: str
402
  # No changes needed here since we are processing the output images
403
  return images_state, images_state
404
 
405
- with gr.Blocks(title="OneDiffusion Demo") as demo:
406
- gr.Markdown("""
407
- # OneDiffusion Demo without captioner
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
408
 
409
- **Welcome to the OneDiffusion Demo!**
410
 
411
- This application allows you to generate images based on your input prompts for various tasks. Here's how to use it:
 
 
 
412
 
413
- 1. **Select Task Type**: Choose the type of task you want to perform from the "Task Type" dropdown menu.
 
414
 
415
- 2. **Upload Images**: Drag and drop images directly onto the upload area, or click to select files from your device.
 
 
416
 
417
- 3. **Generate Captions**: **If you upload any images**, Click the "Generate Captions" button to format the text prompt according to chosen task. In this demo, you will **NEED** to provide the caption of each source image manually. We recommend using Molmo for captioning.
418
 
419
- 4. **Configure Generation Settings**: Expand the "Advanced Configuration" section to adjust parameters like the number of inference steps, guidance scale, image size, and more.
420
 
421
- 5. **Generate Images**: After setting your preferences, click the "Generate Image" button. The generated images will appear in the "Generated Images" gallery.
422
 
423
- 6. **Manage Images**: Use the "Delete Selected Images" or "Delete All Images" buttons to remove unwanted images from the gallery.
424
 
425
- **Notes**:
426
- - Check out the [Prompt Guide](https://github.com/lehduong/OneDiffusion/blob/main/PROMPT_GUIDE.md).
427
-
428
- - For text-to-image:
429
- + simply enter your prompt in this format "[[text2image]] your/prompt/here" and press the "Generate Image" button.
430
-
431
- - For boundingbox2image/semantic2image/inpainting etc tasks:
432
- + To perform condition-to-image such as semantic map to image, follow above steps
433
- + For image-to-condition e.g., image to depth, change the denoise_mask checkbox before generating images. You must UNCHECK image_0 box and CHECK image_1 box. Caption is not required for this task.
 
434
 
435
- - For FaceID tasks:
436
- + Use 3 or 4 images if single input image does not give satisfactory results.
437
- + All images will be resized and center cropped to the input height and width. You should choose height and width so that faces in input images won't be cropped.
438
- + Model works best with close-up portrait (input and output) images.
439
- + If the model does not conform your text prompt, try using shorter caption for source image(s).
440
- + If you have non-human subjects and does not get satisfactory results, try "copying" part of caption of source images where it describes the properties of the subject e.g., a monster with red eyes, sharp teeth, etc.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
441
 
442
- - For Multiview generation:
443
- + The input camera elevation/azimuth ALWAYS starts with 0. If you want to generate images of azimuths 30,60,90 and elevations of 10,20,30 (wrt input image), the correct input azimuth is: `0, 30, 60, 90`; input elevation is `0,10,20,30`. The camera distance will be `1.5,1.5,1.5,1.5`
444
- + Only support square images (ideally in 512x512 resolution).
445
- + Ensure the number of elevations, azimuths, and distances are equal.
446
- + The model generally works well for 2-5 views (include both input and generated images). Since the model is trained with 3 views on 512x512 resolution, you might try scale_factor of [1.1; 1.5] and scale_watershed of [100; 400] for better extrapolation.
447
- + For better results:
448
- 1) try increasing num_inference_steps to 75-100.
449
- 2) avoid aggressively changes in target camera poses, for example to generate novel views at azimuth of 180, (simultaneously) generate 4 views with azimuth of 45, 90, 135, 180.
450
-
451
- Enjoy creating images with OneDiffusion!
452
- """)
453
 
454
- with gr.Row():
455
- with gr.Column():
456
- images_state = gr.State([])
457
- selected_indices_state = gr.State([])
458
-
459
- with gr.Row():
460
- gallery = gr.Gallery(
461
- label="Input Images",
 
 
 
 
 
 
 
 
 
462
  show_label=True,
463
  columns=2,
464
  rows=2,
465
  height="auto",
466
  object_fit="contain"
467
  )
468
-
469
- # In the UI section, update the file_output component:
470
- file_output = gr.File(
471
- file_count="multiple",
472
- file_types=["image"],
473
- label="Drag and drop images here or click to upload",
474
- height=100,
475
- scale=2,
476
- type="filepath" # Add this parameter
477
- )
478
-
479
- with gr.Row():
480
- delete_button = gr.Button("Delete Selected Images")
481
- delete_all_button = gr.Button("Delete All Images")
482
-
483
- task_type = gr.Dropdown(
484
- choices=list(TASK2SPECIAL_TOKENS.keys()),
485
- value="text2image",
486
- label="Task Type"
487
- )
488
-
489
- captioning_message = gr.Textbox(
490
- lines=2,
491
- value="Describe the contents of the photo in 60 words.",
492
- label="Custom message for captioner"
493
- )
494
-
495
- auto_caption_btn = gr.Button("Generate Captions")
496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
  with gr.Column():
498
- prompt = gr.Textbox(
499
- lines=3,
500
- placeholder="Enter your prompt here or use auto-caption...",
501
- label="Prompt"
502
- )
503
- negative_prompt = gr.Textbox(
504
- lines=3,
505
- value=NEGATIVE_PROMPT,
506
- placeholder="Enter negative prompt here...",
507
- label="Negative Prompt"
508
- )
509
- caption_status = gr.Textbox(label="Caption Status")
 
 
 
 
 
 
 
 
 
 
510
 
511
- num_steps = gr.Slider(
512
- minimum=1,
513
- maximum=200,
514
- value=50,
515
- step=1,
516
- label="Number of Inference Steps"
517
- )
518
- guidance_scale = gr.Slider(
519
- minimum=0.1,
520
- maximum=10.0,
521
- value=4,
522
- step=0.1,
523
- label="Guidance Scale"
524
- )
525
- height = gr.Number(value=1024, label="Height")
526
- width = gr.Number(value=1024, label="Width")
527
-
528
- with gr.Accordion("Advanced Configuration", open=False):
529
- with gr.Row():
530
- denoise_mask_checkbox = gr.CheckboxGroup(
531
- label="Denoise Mask",
532
- choices=["image_0"],
533
- value=["image_0"]
534
- )
535
- azimuth = gr.Textbox(
536
- value="0",
537
- label="Azimuths (degrees, comma-separated, 'None' for missing)"
538
- )
539
- elevation = gr.Textbox(
540
- value="0",
541
- label="Elevations (degrees, comma-separated, 'None' for missing)"
542
- )
543
- distance = gr.Textbox(
544
- value="1.5",
545
- label="Distances (comma-separated, 'None' for missing)"
546
- )
547
- focal_length = gr.Number(
548
- value=1.3887,
549
- label="Focal Length of camera for multiview generation"
550
- )
551
- scale_factor = gr.Number(value=1.0, label="Scale Factor")
552
- scale_watershed = gr.Number(value=1.0, label="Scale Watershed")
553
- noise_scale = gr.Number(value=1.0, label="Noise Scale") # Added noise_scale input
554
-
555
- output_images = gr.Gallery(
556
- label="Generated Images",
557
- show_label=True,
558
- columns=4,
559
- rows=2,
560
- height="auto",
561
- object_fit="contain"
562
- )
563
-
564
- with gr.Column():
565
- generate_btn = gr.Button("Generate Image")
566
- # apply_mask_btn = gr.Button("Apply Mask")
567
-
568
- status = gr.Textbox(label="Generation Status")
569
 
570
- # Event Handlers
571
- def update_gallery(files, images_state):
572
- if not files:
573
- return images_state, images_state
574
-
575
- new_images = []
576
- for file in files:
577
- try:
578
- # Handle both file paths and file objects
579
- if isinstance(file, dict): # For drag and drop files
580
- file = file['path']
581
- elif hasattr(file, 'name'): # For uploaded files
582
- file = file.name
583
-
584
- img = Image.open(file).convert('RGB')
585
- new_images.append(img)
586
- except Exception as e:
587
- print(f"Error loading image: {str(e)}")
588
- continue
589
-
590
- images_state.extend(new_images)
591
- return images_state, images_state
592
-
593
- def on_image_select(evt: gr.SelectData, selected_indices_state):
594
- selected_indices = selected_indices_state or []
595
- index = evt.index
596
- if index in selected_indices:
597
- selected_indices.remove(index)
598
- else:
599
- selected_indices.append(index)
600
- return selected_indices
601
-
602
- def delete_images(selected_indices, images_state):
603
- updated_images = [img for i, img in enumerate(images_state) if i not in selected_indices]
604
- selected_indices_state = []
605
- return updated_images, updated_images, selected_indices_state
606
-
607
- def delete_all_images(images_state):
608
- updated_images = []
609
- selected_indices_state = []
610
- return updated_images, updated_images, selected_indices_state
611
-
612
- def update_height_width(images_state):
613
- if images_state:
614
- closest_ar = get_closest_ratio(
615
- height=images_state[0].size[1],
616
- width=images_state[0].size[0],
617
- ratios=ASPECT_RATIO_512
618
- )
619
- height_val, width_val = int(closest_ar[0][0]), int(closest_ar[0][1])
620
- else:
621
- height_val, width_val = 1024, 1024 # Default values
622
- return gr.update(value=height_val), gr.update(value=width_val)
623
-
624
- # Connect events
625
- file_output.change(
626
- fn=update_gallery,
627
- inputs=[file_output, images_state],
628
- outputs=[images_state, gallery]
629
- ).then(
630
- fn=update_height_width,
631
- inputs=[images_state],
632
- outputs=[height, width]
633
- ).then(
634
- fn=update_denoise_checkboxes,
635
- inputs=[images_state, task_type, azimuth, elevation, distance],
636
- outputs=[denoise_mask_checkbox]
637
- )
638
-
639
- gallery.select(
640
- fn=on_image_select,
641
- inputs=[selected_indices_state],
642
- outputs=[selected_indices_state]
643
- )
644
-
645
- delete_button.click(
646
- fn=delete_images,
647
- inputs=[selected_indices_state, images_state],
648
- outputs=[images_state, gallery, selected_indices_state]
649
- ).then(
650
- fn=update_denoise_checkboxes,
651
- inputs=[images_state, task_type, azimuth, elevation, distance],
652
- outputs=[denoise_mask_checkbox]
653
- )
654
-
655
- delete_all_button.click(
656
- fn=delete_all_images,
657
- inputs=[images_state],
658
- outputs=[images_state, gallery, selected_indices_state]
659
- ).then(
660
- fn=update_denoise_checkboxes,
661
- inputs=[images_state, task_type, azimuth, elevation, distance],
662
- outputs=[denoise_mask_checkbox]
663
- )
664
-
665
- task_type.change(
666
- fn=update_denoise_checkboxes,
667
- inputs=[images_state, task_type, azimuth, elevation, distance],
668
- outputs=[denoise_mask_checkbox]
669
- )
670
-
671
- azimuth.change(
672
- fn=update_denoise_checkboxes,
673
- inputs=[images_state, task_type, azimuth, elevation, distance],
674
- outputs=[denoise_mask_checkbox]
675
- )
676
-
677
- elevation.change(
678
- fn=update_denoise_checkboxes,
679
- inputs=[images_state, task_type, azimuth, elevation, distance],
680
- outputs=[denoise_mask_checkbox]
681
- )
682
-
683
- distance.change(
684
- fn=update_denoise_checkboxes,
685
- inputs=[images_state, task_type, azimuth, elevation, distance],
686
- outputs=[denoise_mask_checkbox]
687
- )
688
-
689
- generate_btn.click(
690
- fn=generate_image,
691
- inputs=[
692
- images_state, prompt, negative_prompt, num_steps, guidance_scale,
693
- denoise_mask_checkbox, task_type, azimuth, elevation, distance,
694
- focal_length, height, width, scale_factor, scale_watershed, noise_scale # Added noise_scale here
695
- ],
696
- outputs=[output_images, status],
697
- concurrency_id="gpu_queue"
698
- )
699
-
700
- auto_caption_btn.click(
701
- fn=update_prompt,
702
- inputs=[images_state, task_type, captioning_message],
703
- outputs=[prompt, caption_status],
704
- concurrency_id="gpu_queue"
705
- )
706
-
707
- # apply_mask_btn.click(
708
- # fn=apply_mask,
709
- # inputs=[images_state],
710
- # outputs=[output_images, status]
711
- # )
712
 
713
- if __name__ == "__main__":
714
- parser = argparse.ArgumentParser(description='Start the Gradio demo with specified captioner.')
715
- parser.add_argument('--captioner', type=str, choices=['molmo', 'llava', 'disable'], default='disable', help='Captioner to use: molmo, llava, disable.')
716
- args = parser.parse_args()
 
 
 
 
 
 
 
 
 
717
 
718
- # Initialize models with the specified captioner
719
- pipeline, captioner = initialize_models(args.captioner)
720
 
721
- demo.launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import spaces
2
+ import os
3
  import subprocess
4
  subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
5
  import gradio as gr
 
24
  import numpy as np
25
  import cv2
26
  import argparse
27
+ from PIL import Image
28
+
29
+ import csv
30
+ import ast
31
+ from gradio import components, utils
32
+ from typing import List, Any
33
+ from types import MethodType
34
+
35
 
36
  # Task-specific tokens
37
  TASK2SPECIAL_TOKENS = {
 
68
  with torch.no_grad():
69
  prompt = self.processor.apply_chat_template(conversation, add_generation_prompt=True)
70
  inputs = self.processor(prompt, image, return_tensors="pt").to(self.model.device)
71
+ output = self.model.generate(**inputs, max_new_tokens=200)
72
  response = self.processor.decode(output[0], skip_special_tokens=True)
73
  return response.split(msg)[-1].strip()[len(self.SPECIAL_TOKENS):]
74
 
 
142
 
143
  def initialize_models(captioner_name):
144
  device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
145
+ pipeline = OneDiffusionPipeline.from_pretrained("/home/user/OneDiffusion/onediffusion_ckpt").to(device=device, dtype=torch.bfloat16)
146
  if captioner_name == 'molmo':
147
  captioner = MolmoCaptionProcessor()
148
  elif captioner_name == 'llava':
 
411
  # No changes needed here since we are processing the output images
412
  return images_state, images_state
413
 
414
+ def get_example():
415
+ # Define example configurations and save images to temporary files
416
+ examples = [
417
+ [
418
+ "Text to Image", # Example name
419
+ None, # Preview column
420
+ [], # Empty list instead of None for input images
421
+ "[[text2image]] A bipedal black cat wearing a huge oversized witch hat, a wizards robe, casting a spell,in an enchanted forest. The scene is filled with fireflies and moss on surrounding rocks and trees",
422
+ NEGATIVE_PROMPT,
423
+ 50, # num_steps
424
+ 4.0, # guidance_scale
425
+ ["image_0"], # denoise_mask
426
+ "text2image", # task_type
427
+ "0", # azimuth
428
+ "0", # elevation
429
+ "1.5", # distance
430
+ 1.3887, # focal_length
431
+ 1024, # height
432
+ 1024, # width
433
+ 1.0, # scale_factor
434
+ 1.0, # scale_watershed
435
+ 1.0, # noise_scale
436
+ ],
437
+
438
+ [
439
+ "ID Customization with 1 images", # Example name - new column
440
+ "./assets/examples/id_customization/chika/image_0.png", # Preview first image
441
+ [
442
+ "./assets/examples/id_customization/chika/image_0.png",
443
+ ], # Input image paths
444
+ "[[faceid]] [[img0]] photo depict a female anime character with pink hair and blue eyes, sitting in a fine dining restaurant, black dress, smiling open mouth widely [[img1]] The photo depicts an anime-style cartoon character of a young woman with pink hair and blue eyes. She's wearing a black dress with white collar and cuffs, adorned with a red bow at the neckline and a red bow on the chest. A black bow tie decorates her hair. The character is standing in a classroom, with a green chalkboard featuring Asian characters visible behind her. The classroom has a white ceiling with brown trim and a window with a green curtain. The woman has a cheerful expression and appears to be in motion, as her hair is flowing. The overall scene is colorful and vibrant, capturing a moment of everyday life in an anime-inspired setting.",
445
+ NEGATIVE_PROMPT,
446
+ 75, # num_steps
447
+ 4.0, # guidance_scale
448
+ ["image_0"], # denoise_mask
449
+ "faceid", # task_type
450
+ "0", # azimuth
451
+ "0", # elevation
452
+ "1.5", # distance
453
+ 1.3887, # focal_length
454
+ 576, # height
455
+ 448, # width
456
+ 1.0, # scale_factor
457
+ 1.0, # scale_watershed
458
+ 1.0, # noise_scale
459
+ ],
460
+
461
+
462
+ [
463
+ "ID Customization with multiple input images", # Example name - new column
464
+ "./assets/examples/id_customization/chenhao/image_0.png", # Preview first image
465
+ [
466
+ "./assets/examples/id_customization/chenhao/image_0.png",
467
+ "./assets/examples/id_customization/chenhao/image_1.png",
468
+ "./assets/examples/id_customization/chenhao/image_2.png",
469
+ ], # Input image paths
470
+ "[[faceid]] [[img0]] A woman with dark hair styled in an intricate updo, wearing a traditional orange and black outfit with elaborate gold embroidery. She has an elegant, poised expression, standing against a serene outdoor setting with classical architecture [[img1]] A young Asian woman with long dark hair and brown eyes smiles at the camera. She wears a red tank top with white flowers and green leaves. The background is blurred, with white and blue tones visible. The image has a slightly grainy quality. [[img2]] A young Asian woman in traditional attire stands against a brown background. She wears a white dress adorned with purple and green floral patterns. Her hair is styled in a bun, and she holds a small white lace umbrella with a gold handle. The image captures her elegant appearance and cultural dress. [[img3]] A woman in traditional Asian attire stands in front of a blurred building. She wears a green robe with floral designs and a black hat with lace. A man in a red robe and black hat stands behind her. The scene appears to be set in an Asian country.",
471
+ NEGATIVE_PROMPT,
472
+ 50, # num_steps
473
+ 4.0, # guidance_scale
474
+ ["image_0"], # denoise_mask
475
+ "faceid", # task_type
476
+ "0", # azimuth
477
+ "0", # elevation
478
+ "1.5", # distance
479
+ 1.3887, # focal_length
480
+ 608, # height
481
+ 416, # width
482
+ 1.0, # scale_factor
483
+ 1.0, # scale_watershed
484
+ 1.0, # noise_scale
485
+ ],
486
+
487
+ [
488
+ "Image to Multiview", # Example name - new column
489
+ "assets/examples/images/cat_on_table.webp", # Preview column - no image for text-to-multiview
490
+ ["assets/examples/images/cat_on_table.webp"], # No input images
491
+ "[[multiview]] A cat with orange and white fur sits on a round wooden table. The cat has striking green eyes and a pink nose. Its ears are perked up, and its tail is curled around its body. The background is blurred, showing a white wall, a wooden chair, and a wooden table with a white pot and green plant. A white curtain is visible on the right side. The cat's gaze is directed slightly to the right, and its paws are white. The overall scene creates a cozy, domestic atmosphere with the cat as the central focus.",
492
+ NEGATIVE_PROMPT,
493
+ 60, # num_steps
494
+ 4.0, # guidance_scale
495
+ ["image_1", "image_2", "image_3"], # denoise_mask
496
+ "multiview", # task_type
497
+ "0,20,40,60", # azimuth - four views
498
+ "0,0,0,0", # elevation - different angles
499
+ "1.5,1.5,1.5,1.5", # distance
500
+ 1.3887, # focal_length
501
+ 512, # height
502
+ 512, # width
503
+ 1.0, # scale_factor
504
+ 1.0, # scale_watershed
505
+ 1.0, # noise_scale
506
+ ],
507
+
508
+ [
509
+ "Semantic to Image", # Example name - new column
510
+ "assets/examples/semantic_map/dragon_birds_woman.webp", # Preview column
511
+ ["assets/examples/semantic_map/dragon_birds_woman.webp"], # Input image path
512
+ "[[semanticmap2image]] <#00ffff Cyan mask: insert/concept/to/segment/here> A woman in a red dress with gold floral patterns stands in a traditional Japanese-style building. She has black hair and wears a gold choker and earrings. Behind her, a large orange and white dragon coils around the structure. Two white birds fly near her. The building features paper windows and a wooden roof with lanterns. The scene blends traditional Japanese architecture with fantastical elements, creating a mystical atmosphere.",
513
+ NEGATIVE_PROMPT,
514
+ 50, # num_steps
515
+ 4.0, # guidance_scale
516
+ ["image_0"], # denoise_mask
517
+ "semanticmap2image", # task_type
518
+ "0", # azimuth
519
+ "0", # elevation
520
+ "1.5", # distance
521
+ 1.3887, # focal_length
522
+ 672, # height
523
+ 384, # width
524
+ 1.0, # scale_factor
525
+ 1.0, # scale_watershed
526
+ 1.0, # noise_scale
527
+ ],
528
+
529
+ [
530
+ "Subject driven generation", # Example name - new column
531
+ "./assets/examples/subject_driven/chill_guy.jpg", # Preview column
532
+ ["./assets/examples/subject_driven/chill_guy.jpg"], # Input image path
533
+ "[[subject_driven]] <item: cartoon dog> [[img0]] a cartoon character resembling a dog, sitting on a beach. The character has a long, narrow face with a black nose and brown eyes. It's wearing a gray sweatshirt, blue jeans rolled up at the bottom, and red sneakers with white soles. it has a slight smirk on its face [[img1]] The photo features a cartoon character resembling a do. The character has a long, narrow face with a black nose and brown eyes. It's wearing a gray sweatshirt, blue jeans rolled up at the bottom, and red sneakers with white soles. The character's hands are tucked into its pockets, and it has a slight smirk on its face. The background is a solid gray color, and the image has a hand-drawn, slightly blurry quality. The character's head is turned to the left, and its body is facing forward. The overall style is simple and cartoonish, with bold lines and limited shading.",
534
+ NEGATIVE_PROMPT,
535
+ 70, # num_steps
536
+ 4.0, # guidance_scale
537
+ ["image_0"], # denoise_mask
538
+ "subject_driven", # task_type
539
+ "0", # azimuth
540
+ "0", # elevation
541
+ "1.5", # distance
542
+ 1.3887, # focal_length
543
+ 512, # height
544
+ 512, # width
545
+ 1.0, # scale_factor
546
+ 1.0, # scale_watershed
547
+ 1.0, # noise_scale
548
+ ],
549
+
550
+ [
551
+ "Depth to Image", # Example name - new column
552
+ "./assets/examples/depth/astronaut.webp", # Preview column
553
+ ["./assets/examples/depth/astronaut.webp"], # Input image path
554
+ "[[depth2image]] The image depicts a futuristic astronaut standing on a rocky terrain with orange flowers. The astronaut is wearing a yellow suit with a helmet and is equipped with a backpack. The astronaut is looking up at a large, circular, glowing portal in the sky, which is surrounded by a halo of light. The portal is emitting a warm glow and is surrounded by a few butterflies. The sky is dark with stars, and there are distant mountains visible. The overall atmosphere of the image is one of exploration and wonder.",
555
+ NEGATIVE_PROMPT,
556
+ 50, # num_steps
557
+ 4.0, # guidance_scale
558
+ ["image_0"], # denoise_mask
559
+ "depth2image", # task_type
560
+ "0", # azimuth
561
+ "0", # elevation
562
+ "1.5", # distance
563
+ 1.3887, # focal_length
564
+ 608, # height
565
+ 416, # width
566
+ 1.0, # scale_factor
567
+ 1.0, # scale_watershed
568
+ 1.0, # noise_scale
569
+ ],
570
+
571
+ [
572
+ "Image to depth", # Example name - new column
573
+ "./assets/examples/images/cat.webp", # Preview column
574
+ ["./assets/examples/images/cat.webp"], # Input image path
575
+ "[[depth2image]] A kitten sits in a small boat on a rainy lake. The kitten wears a pink sweater and hat with a pom-pom. It has orange and white fur, and its paws are visible. The scene is misty and atmospheric, with trees and mountains in the background.",
576
+ NEGATIVE_PROMPT,
577
+ 50, # num_steps
578
+ 4.0, # guidance_scale
579
+ ["image_1"], # denoise_mask
580
+ "depth2image", # task_type
581
+ "0", # azimuth
582
+ "0", # elevation
583
+ "1.5", # distance
584
+ 1.3887, # focal_length
585
+ 512, # height
586
+ 512, # width
587
+ 1.0, # scale_factor
588
+ 1.0, # scale_watershed
589
+ 1.0, # noise_scale
590
+ ],
591
+
592
+ [
593
+ "Image Editing", # Example name - new column
594
+ "assets/examples/image_editing/astronaut.webp", # Preview column
595
+ ["assets/examples/image_editing/astronaut.webp"], # Input image path
596
+ "[[image_editing]] change it to winter and snowy weather",
597
+ NEGATIVE_PROMPT,
598
+ 60, # num_steps
599
+ 3.2, # guidance_scale
600
+ ["image_0"], # denoise_mask
601
+ "image_editing", # task_type
602
+ "0", # azimuth
603
+ "0", # elevation
604
+ "1.5", # distance
605
+ 1.3887, # focal_length
606
+ 512, # height
607
+ 512, # width
608
+ 1.0, # scale_factor
609
+ 1.0, # scale_watershed
610
+ 1.0, # noise_scale
611
+ ],
612
+
613
+ [
614
+ "Text to Multiview", # Example name - new column
615
+ None, # Preview column - no image for text-to-multiview
616
+ [], # No input images
617
+ "[[multiview]] The 3D scene features a striking black raven perched on a weathered rock in a rugged, mountainous landscape. Its glossy feathers shimmer with iridescent highlights, adding depth and realism. The background reveals a misty valley with rolling hills and a solitary stone cottage, exuding a sense of isolation and mystery. The earthy tones of the terrain, scattered with rocks and tufts of grass, contrast beautifully with the raven's dark plumage. The atmosphere feels serene yet haunting, evoking themes of solitude and nature's quiet power.",
618
+ NEGATIVE_PROMPT,
619
+ 60, # num_steps
620
+ 4.0, # guidance_scale
621
+ ["image_0", "image_1", "image_2", "image_3"], # denoise_mask
622
+ "multiview", # task_type
623
+ "0,30,60,90", # azimuth - four views
624
+ "0,10,15,20", # elevation - different angles
625
+ "1.5,1.5,1.5,1.5", # distance
626
+ 1.3887, # focal_length
627
+ 512, # height
628
+ 512, # width
629
+ 1.0, # scale_factor
630
+ 1.0, # scale_watershed
631
+ 1.0, # noise_scale
632
+ ],
633
+
634
+ [
635
+ "Inpainting with Black mask", # Example name - new column
636
+ "./assets/examples/inpainting/giorno.webp", # Preview column
637
+ ["./assets/examples/inpainting/giorno.webp"], # Input image path
638
+ "[[image_inpainting]]",
639
+ NEGATIVE_PROMPT,
640
+ 50, # num_steps
641
+ 4.0, # guidance_scale
642
+ ["image_0"], # denoise_mask
643
+ "image_inpainting", # task_type
644
+ "0", # azimuth
645
+ "0", # elevation
646
+ "1.5", # distance
647
+ 1.3887, # focal_length
648
+ 416, # height
649
+ 576, # width
650
+ 1.0, # scale_factor
651
+ 1.0, # scale_watershed
652
+ 1.0, # noise_scale
653
+ ],
654
+ ]
655
+ return examples
656
+
657
+ def run_for_examples(example_name, preview_image, image_paths, prompt, negative_prompt,
658
+ num_inference_steps, guidance_scale, denoise_mask, task_type,
659
+ azimuth, elevation, distance, focal_length, height, width,
660
+ scale_factor, scale_watershed, noise_scale):
661
+ try:
662
+ # Handle empty image paths or None
663
+ images_state = []
664
+ gallery_value = []
665
+
666
+ if image_paths: # Only process if image_paths is not None and not empty
667
+ if isinstance(image_paths, list) and len(image_paths) > 0:
668
+ for path in image_paths:
669
+ try:
670
+ if path is not None:
671
+ img = Image.open(path).convert('RGB')
672
+ images_state.append(img)
673
+ gallery_value.append(path)
674
+ except Exception as e:
675
+ print(f"Error loading image {path}: {str(e)}")
676
+
677
+ # Generate output images
678
+ output_images, status = generate_image(
679
+ images_state, prompt, negative_prompt, num_inference_steps, guidance_scale,
680
+ denoise_mask, task_type, azimuth, elevation, distance, focal_length,
681
+ height, width, scale_factor, scale_watershed, noise_scale
682
+ )
683
+
684
+ # For preview gallery - show actual loaded images if any
685
+ preview_images = images_state # if images_state else []
686
+
687
+ return output_images, status, gallery_value, images_state, preview_images
688
+
689
+ except Exception as e:
690
+ return None, f"Error in example generation: {str(e)}", [], [], []
691
+
692
+ def update_gallery_state(files, current_state):
693
+ """Update image state when new files are uploaded or cleared"""
694
+ # Handle case when files is None or empty
695
+ if not files:
696
+ return [], [], [] # Return empty states for images, gallery, and preview
697
+
698
+ # Ensure files is a list
699
+ if not isinstance(files, list):
700
+ files = [files]
701
+
702
+ # Process new uploads
703
+ processed_images = []
704
+ for file in files:
705
+ try:
706
+ if isinstance(file, dict) and "name" in file: # Handle file dict from gradio
707
+ img_path = file["name"]
708
+ elif isinstance(file, str): # Handle direct file paths
709
+ img_path = file
710
+ elif isinstance(file, Image.Image): # Handle PIL Image objects
711
+ processed_images.append(file.convert('RGB'))
712
+ continue
713
+ else:
714
+ print(f"Skipping unsupported file type: {type(file)}")
715
+ continue
716
+
717
+ img_pil = Image.open(img_path).convert('RGB')
718
+ processed_images.append(img_pil)
719
+
720
+ except Exception as e:
721
+ return [], [], []
722
+
723
+ # If no images were successfully processed, return empty states
724
+ if not processed_images:
725
+ return [], [], []
726
+
727
+ # Return updated states and preview images
728
+ # processed_images for the image state
729
+ # files for the gallery state (original files)
730
+ # processed_images again for preview
731
+ return processed_images, files, processed_images
732
+
733
+ def delete_selected_images(selected_indices, images_state, gallery_state):
734
+ """Delete selected images from gallery and state"""
735
+ if not selected_indices or not images_state:
736
+ return images_state, gallery_state, images_state, []
737
+
738
+ # Create lists of indices to keep
739
+ keep_indices = [i for i in range(len(images_state)) if i not in selected_indices]
740
+
741
+ # Update image state
742
+ updated_images = [images_state[i] for i in keep_indices]
743
+
744
+ # Update gallery state if it exists
745
+ updated_gallery = [gallery_state[i] for i in keep_indices] if gallery_state else []
746
+
747
+ return updated_images, updated_gallery, updated_images, []
748
+
749
+ def delete_all_images():
750
+ """Delete all images"""
751
+ return [], [], [], []
752
 
 
753
 
754
+ if __name__ == "__main__":
755
+ parser = argparse.ArgumentParser(description='Start the Gradio demo with specified captioner.')
756
+ parser.add_argument('--captioner', type=str, choices=['molmo', 'llava', 'disable'], default='disable', help='Captioner to use: molmo, llava, disable.')
757
+ args = parser.parse_args()
758
 
759
+ # Initialize models with the specified captioner
760
+ pipeline, captioner = initialize_models(args.captioner)
761
 
762
+ with gr.Blocks(title="OneDiffusion Demo") as demo:
763
+ gr.Markdown("""
764
+ # OneDiffusion Demo with (quantized) Molmo captioner
765
 
766
+ **Welcome to the OneDiffusion Demo!**
767
 
768
+ This application allows you to generate images based on your input prompts for various tasks. Here's how to use it:
769
 
770
+ 1. **Select Task Type**: Choose the type of task you want to perform from the "Task Type" dropdown menu.
771
 
772
+ 2. **Upload Images**: Drag and drop images directly onto the upload area, or click to select files from your device.
773
 
774
+ 3. **Generate Captions**: **If you upload any images**, Click the "Generate Captions" button to format the text prompt according to chosen task. In this demo, you will **NEED** to provide the caption of each source image manually. We recommend using Molmo for captioning.
775
+
776
+ 4. **Configure Generation Settings**: Expand the "Advanced Configuration" section to adjust parameters like the number of inference steps, guidance scale, image size, and more.
777
+
778
+ 5. **Generate Images**: After setting your preferences, click the "Generate Image" button. The generated images will appear in the "Generated Images" gallery.
779
+
780
+ 6. **Manage Images**: Use the "Delete Selected Images" or "Delete All Images" buttons to remove unwanted images from the gallery.
781
+
782
+ **Notes**:
783
+ - Check out the [Prompt Guide](https://github.com/lehduong/OneDiffusion/blob/main/PROMPT_GUIDE.md).
784
 
785
+ - For text-to-image:
786
+ + simply enter your prompt in this format "[[text2image]] your/prompt/here" and press the "Generate Image" button.
787
+
788
+ - For boundingbox2image/semantic2image/inpainting etc tasks:
789
+ + To perform condition-to-image such as semantic map to image, follow above steps
790
+ + For image-to-condition e.g., image to depth, change the denoise_mask checkbox before generating images. You must UNCHECK image_0 box and CHECK image_1 box. Caption is not required for this task.
791
+
792
+ - For FaceID tasks:
793
+ + Use 3 or 4 images if single input image does not give satisfactory results.
794
+ + All images will be resized and center cropped to the input height and width. You should choose height and width so that faces in input images won't be cropped.
795
+ + Model works best with close-up portrait (input and output) images.
796
+ + If the model does not conform your text prompt, try using shorter caption for source image(s).
797
+ + If you have non-human subjects and does not get satisfactory results, try "copying" part of caption of source images where it describes the properties of the subject e.g., a monster with red eyes, sharp teeth, etc.
798
+
799
+ - For Multiview generation:
800
+ + The input camera elevation/azimuth ALWAYS starts with 0. If you want to generate images of azimuths 30,60,90 and elevations of 10,20,30 (wrt input image), the correct input azimuth is: `0, 30, 60, 90`; input elevation is `0,10,20,30`. The camera distance will be `1.5,1.5,1.5,1.5`
801
+ + Only support square images (ideally in 512x512 resolution).
802
+ + Ensure the number of elevations, azimuths, and distances are equal.
803
+ + The model generally works well for 2-5 views (include both input and generated images). Since the model is trained with 3 views on 512x512 resolution, you might try scale_factor of [1.1; 1.5] and scale_watershed of [100; 400] for better extrapolation.
804
+ + For better results:
805
+ 1) try increasing num_inference_steps to 75-100.
806
+ 2) avoid aggressively changes in target camera poses, for example to generate novel views at azimuth of 180, (simultaneously) generate 4 views with azimuth of 45, 90, 135, 180.
807
 
808
+ Enjoy creating images with OneDiffusion!
809
+ """)
 
 
 
 
 
 
 
 
 
810
 
811
+ with gr.Row():
812
+ with gr.Column():
813
+ images_state = gr.State([])
814
+ selected_indices_state = gr.State([])
815
+
816
+ with gr.Row():
817
+ # Replace gallery with File input
818
+ gallery = gr.File(
819
+ label="Input Images",
820
+ file_count="multiple",
821
+ type="filepath",
822
+ file_types=["image"]
823
+ )
824
+
825
+ # Add preview gallery
826
+ preview_gallery = gr.Gallery(
827
+ label="Image Preview",
828
  show_label=True,
829
  columns=2,
830
  rows=2,
831
  height="auto",
832
  object_fit="contain"
833
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
834
 
835
+ with gr.Row():
836
+ delete_button = gr.Button("Delete Selected Images")
837
+ delete_all_button = gr.Button("Delete All Images")
838
+
839
+ task_type = gr.Dropdown(
840
+ choices=list(TASK2SPECIAL_TOKENS.keys()),
841
+ value="text2image",
842
+ label="Task Type"
843
+ )
844
+
845
+ captioning_message = gr.Textbox(
846
+ lines=2,
847
+ value="Describe the contents of the photo in 60 words.",
848
+ label="Custom message for captioner"
849
+ )
850
+
851
+ auto_caption_btn = gr.Button("Generate Captions")
852
+
853
+ with gr.Column():
854
+ prompt = gr.Textbox(
855
+ lines=3,
856
+ placeholder="Enter your prompt here or use auto-caption...",
857
+ label="Prompt"
858
+ )
859
+ negative_prompt = gr.Textbox(
860
+ lines=3,
861
+ value=NEGATIVE_PROMPT,
862
+ placeholder="Enter negative prompt here...",
863
+ label="Negative Prompt"
864
+ )
865
+ caption_status = gr.Textbox(label="Caption Status")
866
+
867
+ num_steps = gr.Slider(
868
+ minimum=1,
869
+ maximum=200,
870
+ value=50,
871
+ step=1,
872
+ label="Number of Inference Steps"
873
+ )
874
+ guidance_scale = gr.Slider(
875
+ minimum=0.1,
876
+ maximum=10.0,
877
+ value=4,
878
+ step=0.1,
879
+ label="Guidance Scale"
880
+ )
881
+ height = gr.Number(value=1024, label="Height")
882
+ width = gr.Number(value=1024, label="Width")
883
+
884
+ with gr.Accordion("Advanced Configuration", open=False):
885
+ with gr.Row():
886
+ denoise_mask_checkbox = gr.CheckboxGroup(
887
+ label="Denoise Mask",
888
+ choices=["image_0"],
889
+ value=["image_0"]
890
+ )
891
+ azimuth = gr.Textbox(
892
+ value="0",
893
+ label="Azimuths (degrees, comma-separated, 'None' for missing)"
894
+ )
895
+ elevation = gr.Textbox(
896
+ value="0",
897
+ label="Elevations (degrees, comma-separated, 'None' for missing)"
898
+ )
899
+ distance = gr.Textbox(
900
+ value="1.5",
901
+ label="Distances (comma-separated, 'None' for missing)"
902
+ )
903
+ focal_length = gr.Number(
904
+ value=1.3887,
905
+ label="Focal Length of camera for multiview generation"
906
+ )
907
+ scale_factor = gr.Number(value=1.0, label="Scale Factor")
908
+ scale_watershed = gr.Number(value=1.0, label="Scale Watershed")
909
+ noise_scale = gr.Number(value=1.0, label="Noise Scale") # Added noise_scale input
910
+
911
+ output_images = gr.Gallery(
912
+ label="Generated Images",
913
+ show_label=True,
914
+ columns=4,
915
+ rows=2,
916
+ height="auto",
917
+ object_fit="contain"
918
+ )
919
+
920
  with gr.Column():
921
+ generate_btn = gr.Button("Generate Image")
922
+ # apply_mask_btn = gr.Button("Apply Mask")
923
+
924
+ status = gr.Textbox(label="Generation Status")
925
+
926
+ def update_height_width(images_state):
927
+ if images_state:
928
+ closest_ar = get_closest_ratio(
929
+ height=images_state[0].size[1],
930
+ width=images_state[0].size[0],
931
+ ratios=ASPECT_RATIO_512
932
+ )
933
+ height_val, width_val = int(closest_ar[0][0]), int(closest_ar[0][1])
934
+ else:
935
+ height_val, width_val = 1024, 1024 # Default values
936
+ return gr.update(value=height_val), gr.update(value=width_val)
937
+
938
+ # Update the image selection handler
939
+ def on_select(evt: gr.SelectData, selected_indices):
940
+ """Handle image selection in gallery"""
941
+ if selected_indices is None:
942
+ selected_indices = []
943
 
944
+ if evt.index in selected_indices:
945
+ selected_indices.remove(evt.index)
946
+ else:
947
+ selected_indices.append(evt.index)
948
+ return selected_indices
949
+
950
+ # Connect gallery upload
951
+ gallery.upload(
952
+ fn=update_gallery_state,
953
+ inputs=[gallery, images_state],
954
+ outputs=[images_state, gallery, preview_gallery],
955
+ show_progress="full"
956
+ ).then(
957
+ fn=update_height_width,
958
+ inputs=[images_state],
959
+ outputs=[height, width]
960
+ ).then(
961
+ fn=update_denoise_checkboxes,
962
+ inputs=[images_state, task_type, azimuth, elevation, distance],
963
+ outputs=[denoise_mask_checkbox]
964
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
965
 
966
+ # Update delete buttons connections
967
+ delete_button.click(
968
+ fn=delete_selected_images,
969
+ inputs=[selected_indices_state, images_state, gallery],
970
+ outputs=[images_state, gallery, preview_gallery, selected_indices_state]
971
+ ).then(
972
+ fn=update_height_width,
973
+ inputs=[images_state],
974
+ outputs=[height, width]
975
+ ).then(
976
+ fn=update_denoise_checkboxes,
977
+ inputs=[images_state, task_type, azimuth, elevation, distance],
978
+ outputs=[denoise_mask_checkbox]
979
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
980
 
981
+ delete_all_button.click(
982
+ fn=delete_all_images,
983
+ inputs=[],
984
+ outputs=[images_state, gallery, preview_gallery, selected_indices_state]
985
+ ).then(
986
+ fn=update_denoise_checkboxes,
987
+ inputs=[images_state, task_type, azimuth, elevation, distance],
988
+ outputs=[denoise_mask_checkbox]
989
+ ).then(
990
+ fn=update_height_width,
991
+ inputs=[images_state],
992
+ outputs=[height, width]
993
+ )
994
 
 
 
995
 
996
+ task_type.change(
997
+ fn=update_denoise_checkboxes,
998
+ inputs=[images_state, task_type, azimuth, elevation, distance],
999
+ outputs=[denoise_mask_checkbox]
1000
+ )
1001
+
1002
+ azimuth.change(
1003
+ fn=update_denoise_checkboxes,
1004
+ inputs=[images_state, task_type, azimuth, elevation, distance],
1005
+ outputs=[denoise_mask_checkbox]
1006
+ )
1007
+
1008
+ elevation.change(
1009
+ fn=update_denoise_checkboxes,
1010
+ inputs=[images_state, task_type, azimuth, elevation, distance],
1011
+ outputs=[denoise_mask_checkbox]
1012
+ )
1013
+
1014
+ distance.change(
1015
+ fn=update_denoise_checkboxes,
1016
+ inputs=[images_state, task_type, azimuth, elevation, distance],
1017
+ outputs=[denoise_mask_checkbox]
1018
+ )
1019
+
1020
+ generate_btn.click(
1021
+ fn=generate_image,
1022
+ inputs=[
1023
+ images_state, prompt, negative_prompt, num_steps, guidance_scale,
1024
+ denoise_mask_checkbox, task_type, azimuth, elevation, distance,
1025
+ focal_length, height, width, scale_factor, scale_watershed, noise_scale # Added noise_scale here
1026
+ ],
1027
+ outputs=[output_images, status],
1028
+ concurrency_id="gpu_queue"
1029
+ )
1030
+
1031
+ auto_caption_btn.click(
1032
+ fn=update_prompt,
1033
+ inputs=[images_state, task_type, captioning_message],
1034
+ outputs=[prompt, caption_status],
1035
+ concurrency_id="gpu_queue"
1036
+ )
1037
+
1038
+ # apply_mask_btn.click(
1039
+ # fn=apply_mask,
1040
+ # inputs=[images_state],
1041
+ # outputs=[output_images, status]
1042
+ # )
1043
+
1044
+ # Update the Examples component with preview column
1045
+ examples = gr.Examples(
1046
+ examples=get_example(),
1047
+ fn=run_for_examples,
1048
+ inputs=[
1049
+ gr.Textbox(visible=False), # Example name column
1050
+ gr.Image(show_label=False, visible=False), # Preview column
1051
+ gallery,
1052
+ prompt,
1053
+ negative_prompt,
1054
+ num_steps,
1055
+ guidance_scale,
1056
+ denoise_mask_checkbox,
1057
+ task_type,
1058
+ azimuth,
1059
+ elevation,
1060
+ distance,
1061
+ focal_length,
1062
+ height,
1063
+ width,
1064
+ scale_factor,
1065
+ scale_watershed,
1066
+ noise_scale
1067
+ ],
1068
+ outputs=[
1069
+ output_images,
1070
+ status,
1071
+ gallery,
1072
+ images_state,
1073
+ preview_gallery
1074
+ ],
1075
+ cache_examples=True,
1076
+ label="Examples"
1077
+ )
1078
+
1079
+ # the default load_from_cache function throws error for text-to-image and text-to-multiview because the list of input views is empty
1080
+ def custom_load_from_cache(self, example_id: int) -> List[Any]:
1081
+ """Loads a particular cached example for the interface.
1082
+ Parameters:
1083
+ example_id: The id of the example to process (zero-indexed).
1084
+ """
1085
+ with open(self.cached_file, encoding="utf-8") as cache:
1086
+ examples = list(csv.reader(cache))
1087
+ example = examples[example_id + 1] # +1 to adjust for header
1088
+ output = []
1089
+ if self.outputs is None:
1090
+ raise ValueError("self.outputs is missing")
1091
+ for component, value in zip(self.outputs, example):
1092
+ value_to_use = value
1093
+ try:
1094
+ value_as_dict = ast.literal_eval(value)
1095
+ # File components that output multiple files get saved as a python list
1096
+ # need to pass the parsed list to serialize
1097
+ # TODO: Better file serialization in 4.0
1098
+ if isinstance(value_as_dict, list) and isinstance(
1099
+ component, components.File
1100
+ ):
1101
+ tmp = value_as_dict
1102
+ if not utils.is_prop_update(tmp):
1103
+ raise TypeError("value wasn't an update") # caught below
1104
+ value_to_use = tmp
1105
+ output.append(value_to_use)
1106
+ except (ValueError, TypeError, SyntaxError):
1107
+ output.append(component.read_from_flag(value_to_use))
1108
+ return output
1109
+
1110
+ def apply_custom_load_from_cache(examples_instance):
1111
+ """
1112
+ Applies the custom load_from_cache method to a Gradio Examples instance.
1113
+
1114
+ Parameters:
1115
+ examples_instance: The Gradio Examples instance to modify
1116
+ """
1117
+ examples_instance.load_from_cache = MethodType(custom_load_from_cache, examples_instance)
1118
+
1119
+ apply_custom_load_from_cache(examples)
1120
+
1121
+ # Connect the event handler for file upload changes
1122
+ gallery.change(
1123
+ fn=update_gallery_state,
1124
+ inputs=[gallery, images_state],
1125
+ outputs=[images_state, gallery, preview_gallery],
1126
+ show_progress="full"
1127
+ ).then(
1128
+ fn=update_height_width,
1129
+ inputs=[images_state],
1130
+ outputs=[height, width]
1131
+ ).then(
1132
+ fn=update_denoise_checkboxes,
1133
+ inputs=[images_state, task_type, azimuth, elevation, distance],
1134
+ outputs=[denoise_mask_checkbox]
1135
+ )
1136
+
1137
+ demo.launch()