libcom 0.1.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (310) hide show
  1. libcom/__init__.py +23 -0
  2. libcom/color_transfer/__init__.py +3 -0
  3. libcom/color_transfer/reinhard.py +57 -0
  4. libcom/fopa_heat_map/__init__.py +4 -0
  5. libcom/fopa_heat_map/fopa_heat_map.py +212 -0
  6. libcom/fopa_heat_map/source/__init__.py +0 -0
  7. libcom/fopa_heat_map/source/backbone/ResNet.py +229 -0
  8. libcom/fopa_heat_map/source/backbone/__init__.py +0 -0
  9. libcom/fopa_heat_map/source/data/OBdataset.py +292 -0
  10. libcom/fopa_heat_map/source/data/__init__.py +0 -0
  11. libcom/fopa_heat_map/source/data/all_transforms.py +25 -0
  12. libcom/fopa_heat_map/source/network/BaseBlocks.py +26 -0
  13. libcom/fopa_heat_map/source/network/DynamicModules.py +43 -0
  14. libcom/fopa_heat_map/source/network/ObPlaNet_simple.py +112 -0
  15. libcom/fopa_heat_map/source/network/__init__.py +1 -0
  16. libcom/fopa_heat_map/source/network/tensor_ops.py +37 -0
  17. libcom/fopa_heat_map/source/prepare_multi_fg_scales.py +85 -0
  18. libcom/fos_score/__init__.py +4 -0
  19. libcom/fos_score/fos_score_prediction.py +218 -0
  20. libcom/fos_score/source/__init__.py +0 -0
  21. libcom/fos_score/source/config/__init__.py +1 -0
  22. libcom/fos_score/source/config/config.py +68 -0
  23. libcom/fos_score/source/config/config.sfosd.yaml +43 -0
  24. libcom/fos_score/source/config/config_rfosd.yaml +43 -0
  25. libcom/fos_score/source/loss_function.py +118 -0
  26. libcom/fos_score/source/networks.py +355 -0
  27. libcom/harmony_score/__init__.py +3 -0
  28. libcom/harmony_score/harmony_score_prediction.py +119 -0
  29. libcom/harmony_score/source/__init__.py +0 -0
  30. libcom/harmony_score/source/bargainnet.py +226 -0
  31. libcom/image_harmonization/__init__.py +4 -0
  32. libcom/image_harmonization/image_harmonization.py +193 -0
  33. libcom/image_harmonization/source/__init__.py +0 -0
  34. libcom/image_harmonization/source/functions.py +747 -0
  35. libcom/image_harmonization/source/pct_net.py +85 -0
  36. libcom/image_harmonization/source/src/__init__.py +0 -0
  37. libcom/image_harmonization/source/src/lbm/__init__.py +0 -0
  38. libcom/image_harmonization/source/src/lbm/config.py +141 -0
  39. libcom/image_harmonization/source/src/lbm/data/__init__.py +62 -0
  40. libcom/image_harmonization/source/src/lbm/data/datasets/__init__.py +9 -0
  41. libcom/image_harmonization/source/src/lbm/data/datasets/collation_fn.py +41 -0
  42. libcom/image_harmonization/source/src/lbm/data/datasets/dataset.py +243 -0
  43. libcom/image_harmonization/source/src/lbm/data/datasets/datasets_config.py +42 -0
  44. libcom/image_harmonization/source/src/lbm/data/filters/__init__.py +12 -0
  45. libcom/image_harmonization/source/src/lbm/data/filters/base.py +21 -0
  46. libcom/image_harmonization/source/src/lbm/data/filters/filter_wrapper.py +36 -0
  47. libcom/image_harmonization/source/src/lbm/data/filters/filters.py +33 -0
  48. libcom/image_harmonization/source/src/lbm/data/filters/filters_config.py +32 -0
  49. libcom/image_harmonization/source/src/lbm/data/mappers/__init__.py +19 -0
  50. libcom/image_harmonization/source/src/lbm/data/mappers/base.py +26 -0
  51. libcom/image_harmonization/source/src/lbm/data/mappers/mappers.py +135 -0
  52. libcom/image_harmonization/source/src/lbm/data/mappers/mappers_config.py +109 -0
  53. libcom/image_harmonization/source/src/lbm/data/mappers/mappers_wrapper.py +31 -0
  54. libcom/image_harmonization/source/src/lbm/inference/__init__.py +4 -0
  55. libcom/image_harmonization/source/src/lbm/inference/inference.py +70 -0
  56. libcom/image_harmonization/source/src/lbm/inference/utils.py +222 -0
  57. libcom/image_harmonization/source/src/lbm/models/__init__.py +0 -0
  58. libcom/image_harmonization/source/src/lbm/models/base/__init__.py +4 -0
  59. libcom/image_harmonization/source/src/lbm/models/base/base_model.py +66 -0
  60. libcom/image_harmonization/source/src/lbm/models/base/model_config.py +8 -0
  61. libcom/image_harmonization/source/src/lbm/models/embedders/__init__.py +4 -0
  62. libcom/image_harmonization/source/src/lbm/models/embedders/base/__init__.py +4 -0
  63. libcom/image_harmonization/source/src/lbm/models/embedders/base/base_conditioner.py +60 -0
  64. libcom/image_harmonization/source/src/lbm/models/embedders/base/base_conditioner_config.py +27 -0
  65. libcom/image_harmonization/source/src/lbm/models/embedders/conditioners_wrapper.py +114 -0
  66. libcom/image_harmonization/source/src/lbm/models/embedders/latents_concat/__init__.py +4 -0
  67. libcom/image_harmonization/source/src/lbm/models/embedders/latents_concat/latents_concat_embedder_config.py +31 -0
  68. libcom/image_harmonization/source/src/lbm/models/embedders/latents_concat/latents_concat_embedder_model.py +80 -0
  69. libcom/image_harmonization/source/src/lbm/models/lbm/__init__.py +4 -0
  70. libcom/image_harmonization/source/src/lbm/models/lbm/lbm_config.py +101 -0
  71. libcom/image_harmonization/source/src/lbm/models/lbm/lbm_model.py +359 -0
  72. libcom/image_harmonization/source/src/lbm/models/unets/__init__.py +14 -0
  73. libcom/image_harmonization/source/src/lbm/models/unets/unet.py +148 -0
  74. libcom/image_harmonization/source/src/lbm/models/utils.py +377 -0
  75. libcom/image_harmonization/source/src/lbm/models/vae/__init__.py +4 -0
  76. libcom/image_harmonization/source/src/lbm/models/vae/autoencoderKL.py +136 -0
  77. libcom/image_harmonization/source/src/lbm/models/vae/autoencoderKL_config.py +27 -0
  78. libcom/image_harmonization/source/src/lbm/trainer/__init__.py +85 -0
  79. libcom/image_harmonization/source/src/lbm/trainer/loggers.py +324 -0
  80. libcom/image_harmonization/source/src/lbm/trainer/trainer.py +199 -0
  81. libcom/image_harmonization/source/src/lbm/trainer/training_config.py +82 -0
  82. libcom/image_harmonization/source/src/lbm/trainer/utils.py +193 -0
  83. libcom/inharmonious_region_localization/__init__.py +4 -0
  84. libcom/inharmonious_region_localization/inharmonious_region_localization.py +97 -0
  85. libcom/inharmonious_region_localization/source/__init__.py +0 -0
  86. libcom/inharmonious_region_localization/source/blocks.py +368 -0
  87. libcom/inharmonious_region_localization/source/functions.py +679 -0
  88. libcom/inharmonious_region_localization/source/madis_net.py +79 -0
  89. libcom/kontext_blending_harmonization/__init__.py +3 -0
  90. libcom/kontext_blending_harmonization/kontext_blending_harmonization.py +148 -0
  91. libcom/kontext_blending_harmonization/source/__init__.py +0 -0
  92. libcom/kontext_blending_harmonization/source/pipeline.py +1135 -0
  93. libcom/naive_composition/__init__.py +3 -0
  94. libcom/naive_composition/generate_composite_image.py +116 -0
  95. libcom/opa_score/__init__.py +3 -0
  96. libcom/opa_score/opa_score_prediction.py +101 -0
  97. libcom/opa_score/source/__init__.py +3 -0
  98. libcom/opa_score/source/object_place_net.py +55 -0
  99. libcom/opa_score/source/oblect_place_config.py +66 -0
  100. libcom/opa_score/source/resnet_4ch.py +213 -0
  101. libcom/os_insert/__init__.py +3 -0
  102. libcom/os_insert/diffusers_osinsert/__init__.py +78 -0
  103. libcom/os_insert/diffusers_osinsert/_patched_pipeline_flux_fill.py +878 -0
  104. libcom/os_insert/os_insert.py +534 -0
  105. libcom/os_insert/source/__init__.py +1 -0
  106. libcom/os_insert/source/ia_utils.py +183 -0
  107. libcom/os_insert/source/insertanything_infer.py +529 -0
  108. libcom/os_insert/source/ldm/__init__.py +0 -0
  109. libcom/os_insert/source/ldm/data/__init__.py +0 -0
  110. libcom/os_insert/source/ldm/data/base.py +23 -0
  111. libcom/os_insert/source/ldm/data/datamodule.py +128 -0
  112. libcom/os_insert/source/ldm/data/imagenet.py +394 -0
  113. libcom/os_insert/source/ldm/data/lsun.py +92 -0
  114. libcom/os_insert/source/ldm/data/open_images.py +728 -0
  115. libcom/os_insert/source/ldm/lr_scheduler.py +98 -0
  116. libcom/os_insert/source/ldm/models/__init__.py +0 -0
  117. libcom/os_insert/source/ldm/models/autoencoder.py +443 -0
  118. libcom/os_insert/source/ldm/models/diffusion/__init__.py +0 -0
  119. libcom/os_insert/source/ldm/models/diffusion/classifier.py +267 -0
  120. libcom/os_insert/source/ldm/models/diffusion/ddim.py +263 -0
  121. libcom/os_insert/source/ldm/models/diffusion/ddpm.py +1417 -0
  122. libcom/os_insert/source/ldm/models/diffusion/plms.py +252 -0
  123. libcom/os_insert/source/ldm/modules/__init__.py +0 -0
  124. libcom/os_insert/source/ldm/modules/attention.py +261 -0
  125. libcom/os_insert/source/ldm/modules/diffusionmodules/__init__.py +0 -0
  126. libcom/os_insert/source/ldm/modules/diffusionmodules/model.py +835 -0
  127. libcom/os_insert/source/ldm/modules/diffusionmodules/openaimodel.py +1108 -0
  128. libcom/os_insert/source/ldm/modules/diffusionmodules/util.py +267 -0
  129. libcom/os_insert/source/ldm/modules/distributions/__init__.py +0 -0
  130. libcom/os_insert/source/ldm/modules/distributions/distributions.py +92 -0
  131. libcom/os_insert/source/ldm/modules/ema.py +76 -0
  132. libcom/os_insert/source/ldm/modules/encoders/__init__.py +0 -0
  133. libcom/os_insert/source/ldm/modules/encoders/modules.py +190 -0
  134. libcom/os_insert/source/ldm/modules/encoders/xf.py +130 -0
  135. libcom/os_insert/source/ldm/modules/losses/__init__.py +1 -0
  136. libcom/os_insert/source/ldm/modules/losses/contperceptual.py +111 -0
  137. libcom/os_insert/source/ldm/modules/losses/vqperceptual.py +167 -0
  138. libcom/os_insert/source/ldm/modules/x_transformer.py +641 -0
  139. libcom/os_insert/source/ldm/util.py +203 -0
  140. libcom/os_insert/source/objectstitch_data.py +66 -0
  141. libcom/os_insert/source/objectstitch_infer.py +618 -0
  142. libcom/os_insert/source/sam_on_objectstitch.py +253 -0
  143. libcom/os_insert/source/utils.py +41 -0
  144. libcom/os_insert/source/v1.yaml +108 -0
  145. libcom/painterly_image_harmonization/__init__.py +4 -0
  146. libcom/painterly_image_harmonization/painterly_image_harmonization.py +215 -0
  147. libcom/painterly_image_harmonization/source/PHDNet/__init__.py +0 -0
  148. libcom/painterly_image_harmonization/source/PHDNet/networks.py +202 -0
  149. libcom/painterly_image_harmonization/source/PHDNet/phdnet.py +47 -0
  150. libcom/painterly_image_harmonization/source/PHDNet/phdnet_config.py +18 -0
  151. libcom/painterly_image_harmonization/source/PHDiffusion/__init__.py +0 -0
  152. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/__init__.py +0 -0
  153. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/inference_base.py +300 -0
  154. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/lr_scheduler.py +98 -0
  155. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/__init__.py +0 -0
  156. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/autoencoder.py +211 -0
  157. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/__init__.py +3 -0
  158. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/ddim.py +336 -0
  159. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/ddpm.py +1400 -0
  160. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
  161. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/dpm_solver/dpm_solver.py +1217 -0
  162. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/dpm_solver/sampler.py +87 -0
  163. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/plms.py +243 -0
  164. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/scheduling_pndm.py +518 -0
  165. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/__init__.py +0 -0
  166. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/attention.py +378 -0
  167. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/__init__.py +0 -0
  168. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/model.py +857 -0
  169. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/openaimodel.py +823 -0
  170. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/util.py +270 -0
  171. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/distributions/__init__.py +0 -0
  172. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/distributions/distributions.py +92 -0
  173. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/ema.py +80 -0
  174. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/encoders/__init__.py +0 -0
  175. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/encoders/adapter.py +213 -0
  176. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/encoders/modules.py +82 -0
  177. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/__init__.py +1 -0
  178. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/api.py +269 -0
  179. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/__init__.py +0 -0
  180. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/api.py +175 -0
  181. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/__init__.py +0 -0
  182. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/base_model.py +16 -0
  183. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/blocks.py +342 -0
  184. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/dpt_depth.py +109 -0
  185. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/midas_net.py +76 -0
  186. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/midas_net_custom.py +128 -0
  187. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/transforms.py +234 -0
  188. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/vit.py +491 -0
  189. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/utils.py +189 -0
  190. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/model_edge.py +653 -0
  191. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/__init__.py +0 -0
  192. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/api.py +35 -0
  193. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/body.py +209 -0
  194. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/hand.py +75 -0
  195. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/model.py +178 -0
  196. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/util.py +203 -0
  197. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/utils.py +72 -0
  198. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/fusion/__init__.py +0 -0
  199. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/fusion/dual_encoder_fusion.py +93 -0
  200. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/__init__.py +2 -0
  201. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/bsrgan.py +730 -0
  202. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/bsrgan_light.py +651 -0
  203. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/utils_image.py +916 -0
  204. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/util.py +200 -0
  205. libcom/painterly_image_harmonization/source/PHDiffusion/stable_diffusion.yaml +75 -0
  206. libcom/painterly_image_harmonization/source/__init__.py +0 -0
  207. libcom/reflection_generation/__init__.py +3 -0
  208. libcom/reflection_generation/reflection_generation.py +174 -0
  209. libcom/reflection_generation/source/PostProcessModel.py +513 -0
  210. libcom/reflection_generation/source/__init__.py +0 -0
  211. libcom/reflection_generation/source/cldm/__init__.py +0 -0
  212. libcom/reflection_generation/source/cldm/base_network.py +166 -0
  213. libcom/reflection_generation/source/cldm/cldm.py +509 -0
  214. libcom/reflection_generation/source/cldm/ddim_hacked.py +317 -0
  215. libcom/reflection_generation/source/cldm/hack.py +111 -0
  216. libcom/reflection_generation/source/cldm/logger.py +127 -0
  217. libcom/reflection_generation/source/cldm/model.py +26 -0
  218. libcom/reflection_generation/source/cldm_v15.yaml +81 -0
  219. libcom/reflection_generation/source/cluster_feature.py +109 -0
  220. libcom/reflection_generation/source/ldm/__init__.py +0 -0
  221. libcom/reflection_generation/source/ldm/models/__init__.py +0 -0
  222. libcom/reflection_generation/source/ldm/models/autoencoder.py +219 -0
  223. libcom/reflection_generation/source/ldm/models/diffusion/__init__.py +0 -0
  224. libcom/reflection_generation/source/ldm/models/diffusion/attention_processor.py +188 -0
  225. libcom/reflection_generation/source/ldm/models/diffusion/ddim.py +340 -0
  226. libcom/reflection_generation/source/ldm/models/diffusion/ddpm.py +1892 -0
  227. libcom/reflection_generation/source/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
  228. libcom/reflection_generation/source/ldm/models/diffusion/dpm_solver/dpm_solver.py +1154 -0
  229. libcom/reflection_generation/source/ldm/models/diffusion/dpm_solver/sampler.py +87 -0
  230. libcom/reflection_generation/source/ldm/models/diffusion/ip_adapter.py +57 -0
  231. libcom/reflection_generation/source/ldm/models/diffusion/plms.py +244 -0
  232. libcom/reflection_generation/source/ldm/models/diffusion/sampling_util.py +22 -0
  233. libcom/reflection_generation/source/ldm/modules/__init__.py +0 -0
  234. libcom/reflection_generation/source/ldm/modules/attention.py +341 -0
  235. libcom/reflection_generation/source/ldm/modules/diffusionmodules/__init__.py +0 -0
  236. libcom/reflection_generation/source/ldm/modules/diffusionmodules/model.py +852 -0
  237. libcom/reflection_generation/source/ldm/modules/diffusionmodules/openaimodel.py +786 -0
  238. libcom/reflection_generation/source/ldm/modules/diffusionmodules/upscaling.py +81 -0
  239. libcom/reflection_generation/source/ldm/modules/diffusionmodules/util.py +280 -0
  240. libcom/reflection_generation/source/ldm/modules/distributions/__init__.py +0 -0
  241. libcom/reflection_generation/source/ldm/modules/distributions/distributions.py +92 -0
  242. libcom/reflection_generation/source/ldm/modules/ema.py +80 -0
  243. libcom/reflection_generation/source/ldm/modules/encoders/__init__.py +0 -0
  244. libcom/reflection_generation/source/ldm/modules/encoders/modules.py +214 -0
  245. libcom/reflection_generation/source/ldm/modules/image_degradation/__init__.py +0 -0
  246. libcom/reflection_generation/source/ldm/modules/image_degradation/bsrgan.py +730 -0
  247. libcom/reflection_generation/source/ldm/modules/image_degradation/bsrgan_light.py +651 -0
  248. libcom/reflection_generation/source/ldm/modules/image_degradation/utils_image.py +916 -0
  249. libcom/reflection_generation/source/ldm/util.py +198 -0
  250. libcom/reflection_generation/source/local_clip.py +749 -0
  251. libcom/reflection_generation/source/tool_add_control.py +49 -0
  252. libcom/shadow_generation/__init__.py +3 -0
  253. libcom/shadow_generation/shadow_generation.py +754 -0
  254. libcom/shadow_generation/source/PostProcessModel.py +511 -0
  255. libcom/shadow_generation/source/__init__.py +0 -0
  256. libcom/shadow_generation/source/attention_processor.py +234 -0
  257. libcom/shadow_generation/source/cldm/__init__.py +0 -0
  258. libcom/shadow_generation/source/cldm/base_network.py +166 -0
  259. libcom/shadow_generation/source/cldm/cldm.py +524 -0
  260. libcom/shadow_generation/source/cldm/model.py +28 -0
  261. libcom/shadow_generation/source/ldm/__init__.py +0 -0
  262. libcom/shadow_generation/source/ldm/models/__init__.py +0 -0
  263. libcom/shadow_generation/source/ldm/models/autoencoder.py +219 -0
  264. libcom/shadow_generation/source/ldm/models/diffusion/__init__.py +0 -0
  265. libcom/shadow_generation/source/ldm/models/diffusion/attention_processor.py +188 -0
  266. libcom/shadow_generation/source/ldm/models/diffusion/ddim.py +340 -0
  267. libcom/shadow_generation/source/ldm/models/diffusion/ddpm.py +1893 -0
  268. libcom/shadow_generation/source/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
  269. libcom/shadow_generation/source/ldm/models/diffusion/dpm_solver/dpm_solver.py +1154 -0
  270. libcom/shadow_generation/source/ldm/models/diffusion/dpm_solver/sampler.py +87 -0
  271. libcom/shadow_generation/source/ldm/models/diffusion/ip_adapter.py +57 -0
  272. libcom/shadow_generation/source/ldm/models/diffusion/plms.py +244 -0
  273. libcom/shadow_generation/source/ldm/models/diffusion/sampling_util.py +22 -0
  274. libcom/shadow_generation/source/ldm/modules/__init__.py +0 -0
  275. libcom/shadow_generation/source/ldm/modules/attention.py +341 -0
  276. libcom/shadow_generation/source/ldm/modules/diffusionmodules/__init__.py +0 -0
  277. libcom/shadow_generation/source/ldm/modules/diffusionmodules/model.py +852 -0
  278. libcom/shadow_generation/source/ldm/modules/diffusionmodules/openaimodel.py +786 -0
  279. libcom/shadow_generation/source/ldm/modules/diffusionmodules/upscaling.py +81 -0
  280. libcom/shadow_generation/source/ldm/modules/diffusionmodules/util.py +270 -0
  281. libcom/shadow_generation/source/ldm/modules/distributions/__init__.py +0 -0
  282. libcom/shadow_generation/source/ldm/modules/distributions/distributions.py +92 -0
  283. libcom/shadow_generation/source/ldm/modules/ema.py +80 -0
  284. libcom/shadow_generation/source/ldm/modules/encoders/__init__.py +0 -0
  285. libcom/shadow_generation/source/ldm/modules/encoders/modules.py +214 -0
  286. libcom/shadow_generation/source/ldm/modules/image_degradation/__init__.py +2 -0
  287. libcom/shadow_generation/source/ldm/modules/image_degradation/bsrgan.py +730 -0
  288. libcom/shadow_generation/source/ldm/modules/image_degradation/bsrgan_light.py +651 -0
  289. libcom/shadow_generation/source/ldm/modules/image_degradation/utils_image.py +916 -0
  290. libcom/shadow_generation/source/ldm/modules/midas/__init__.py +0 -0
  291. libcom/shadow_generation/source/ldm/modules/midas/api.py +170 -0
  292. libcom/shadow_generation/source/ldm/modules/midas/midas/__init__.py +0 -0
  293. libcom/shadow_generation/source/ldm/modules/midas/midas/base_model.py +16 -0
  294. libcom/shadow_generation/source/ldm/modules/midas/midas/blocks.py +342 -0
  295. libcom/shadow_generation/source/ldm/modules/midas/midas/dpt_depth.py +109 -0
  296. libcom/shadow_generation/source/ldm/modules/midas/midas/midas_net.py +76 -0
  297. libcom/shadow_generation/source/ldm/modules/midas/midas/midas_net_custom.py +128 -0
  298. libcom/shadow_generation/source/ldm/modules/midas/midas/transforms.py +234 -0
  299. libcom/shadow_generation/source/ldm/modules/midas/midas/vit.py +491 -0
  300. libcom/shadow_generation/source/ldm/modules/midas/utils.py +189 -0
  301. libcom/shadow_generation/source/ldm/util.py +199 -0
  302. libcom/utils/__init__.py +0 -0
  303. libcom/utils/environment.py +12 -0
  304. libcom/utils/model_download.py +67 -0
  305. libcom/utils/process_image.py +108 -0
  306. libcom-0.1.8.dist-info/METADATA +157 -0
  307. libcom-0.1.8.dist-info/RECORD +310 -0
  308. libcom-0.1.8.dist-info/WHEEL +5 -0
  309. libcom-0.1.8.dist-info/licenses/LICENSE +201 -0
  310. libcom-0.1.8.dist-info/top_level.txt +1 -0
@@ -0,0 +1,878 @@
1
+ # Copyright 2025 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
21
+
22
+ from ...image_processor import VaeImageProcessor
23
+ from ...loaders import FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
24
+ from ...models.autoencoders import AutoencoderKL
25
+ from ...models.transformers import FluxTransformer2DModel
26
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
27
+ from ...utils import (
28
+ USE_PEFT_BACKEND,
29
+ is_torch_xla_available,
30
+ logging,
31
+ replace_example_docstring,
32
+ scale_lora_layers,
33
+ unscale_lora_layers,
34
+ )
35
+ from ...utils.torch_utils import randn_tensor
36
+ from ..pipeline_utils import DiffusionPipeline
37
+ from .pipeline_output import FluxPipelineOutput
38
+
39
+
40
+ if is_torch_xla_available():
41
+ import torch_xla.core.xla_model as xm
42
+
43
+ XLA_AVAILABLE = True
44
+ else:
45
+ XLA_AVAILABLE = False
46
+
47
+
48
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
+
50
+ EXAMPLE_DOC_STRING = """
51
+ Examples:
52
+ ```py
53
+ >>> import torch
54
+ >>> from diffusers import FluxFillPipeline
55
+ >>> from diffusers.utils import load_image
56
+
57
+ >>> image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup.png")
58
+ >>> mask = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup_mask.png")
59
+
60
+ >>> pipe = FluxFillPipeline.from_pretrained("black-forest-labs/FLUX.1-Fill-dev", torch_dtype=torch.bfloat16)
61
+ >>> pipe.enable_model_cpu_offload() # save some VRAM by offloading the model to CPU
62
+
63
+ >>> image = pipe(
64
+ ... prompt="a white paper cup",
65
+ ... image=image,
66
+ ... mask_image=mask,
67
+ ... height=1632,
68
+ ... width=1232,
69
+ ... guidance_scale=30,
70
+ ... num_inference_steps=50,
71
+ ... max_sequence_length=512,
72
+ ... generator=torch.Generator("cpu").manual_seed(0),
73
+ ... ).images[0]
74
+ >>> image.save("flux_fill.png")
75
+ ```
76
+ """
77
+
78
+
79
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
80
+ def calculate_shift(
81
+ image_seq_len,
82
+ base_seq_len: int = 256,
83
+ max_seq_len: int = 4096,
84
+ base_shift: float = 0.5,
85
+ max_shift: float = 1.15,
86
+ ):
87
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
88
+ b = base_shift - m * base_seq_len
89
+ mu = image_seq_len * m + b
90
+ return mu
91
+
92
+
93
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
94
+ def retrieve_timesteps(
95
+ scheduler,
96
+ num_inference_steps: Optional[int] = None,
97
+ device: Optional[Union[str, torch.device]] = None,
98
+ timesteps: Optional[List[int]] = None,
99
+ sigmas: Optional[List[float]] = None,
100
+ **kwargs,
101
+ ):
102
+ r"""
103
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
104
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
105
+
106
+ Args:
107
+ scheduler (`SchedulerMixin`):
108
+ The scheduler to get timesteps from.
109
+ num_inference_steps (`int`):
110
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
111
+ must be `None`.
112
+ device (`str` or `torch.device`, *optional*):
113
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
114
+ timesteps (`List[int]`, *optional*):
115
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
116
+ `num_inference_steps` and `sigmas` must be `None`.
117
+ sigmas (`List[float]`, *optional*):
118
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
119
+ `num_inference_steps` and `timesteps` must be `None`.
120
+
121
+ Returns:
122
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
123
+ second element is the number of inference steps.
124
+ """
125
+ if timesteps is not None and sigmas is not None:
126
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
127
+ if timesteps is not None:
128
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
129
+ if not accepts_timesteps:
130
+ raise ValueError(
131
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
132
+ f" timestep schedules. Please check whether you are using the correct scheduler."
133
+ )
134
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
135
+ timesteps = scheduler.timesteps
136
+ num_inference_steps = len(timesteps)
137
+ elif sigmas is not None:
138
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
139
+ if not accept_sigmas:
140
+ raise ValueError(
141
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
142
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
143
+ )
144
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
145
+ timesteps = scheduler.timesteps
146
+ num_inference_steps = len(timesteps)
147
+ else:
148
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
149
+ timesteps = scheduler.timesteps
150
+ return timesteps, num_inference_steps
151
+
152
+
153
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
154
+ def retrieve_latents(
155
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
156
+ ):
157
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
158
+ return encoder_output.latent_dist.sample(generator)
159
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
160
+ return encoder_output.latent_dist.mode()
161
+ elif hasattr(encoder_output, "latents"):
162
+ return encoder_output.latents
163
+ else:
164
+ raise AttributeError("Could not access latents of provided encoder_output")
165
+
166
+
167
+ class FluxFillPipeline(
168
+ DiffusionPipeline,
169
+ FluxLoraLoaderMixin,
170
+ FromSingleFileMixin,
171
+ TextualInversionLoaderMixin,
172
+ ):
173
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
174
+ _optional_components = []
175
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
176
+
177
+ def __init__(
178
+ self,
179
+ scheduler: FlowMatchEulerDiscreteScheduler,
180
+ vae: AutoencoderKL,
181
+ text_encoder: CLIPTextModel,
182
+ tokenizer: CLIPTokenizer,
183
+ text_encoder_2: T5EncoderModel,
184
+ tokenizer_2: T5TokenizerFast,
185
+ transformer: FluxTransformer2DModel,
186
+ ):
187
+ super().__init__()
188
+
189
+ self.register_modules(
190
+ vae=vae,
191
+ text_encoder=text_encoder,
192
+ text_encoder_2=text_encoder_2,
193
+ tokenizer=tokenizer,
194
+ tokenizer_2=tokenizer_2,
195
+ transformer=transformer,
196
+ scheduler=scheduler,
197
+ )
198
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
199
+ self.latent_channels = self.vae.config.latent_channels if getattr(self, "vae", None) else 16
200
+ self.image_processor = VaeImageProcessor(
201
+ vae_scale_factor=self.vae_scale_factor * 2, vae_latent_channels=self.latent_channels
202
+ )
203
+ self.mask_processor = VaeImageProcessor(
204
+ vae_scale_factor=self.vae_scale_factor * 2,
205
+ vae_latent_channels=self.latent_channels,
206
+ do_normalize=False,
207
+ do_binarize=True,
208
+ do_convert_grayscale=True,
209
+ )
210
+ self.tokenizer_max_length = (
211
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
212
+ )
213
+ self.default_sample_size = 128
214
+
215
+ def _get_t5_prompt_embeds(
216
+ self,
217
+ prompt: Union[str, List[str]] = None,
218
+ num_images_per_prompt: int = 1,
219
+ max_sequence_length: int = 512,
220
+ device: Optional[torch.device] = None,
221
+ dtype: Optional[torch.dtype] = None,
222
+ ):
223
+ device = device or self._execution_device
224
+ dtype = dtype or self.text_encoder.dtype
225
+
226
+ prompt = [prompt] if isinstance(prompt, str) else prompt
227
+ batch_size = len(prompt)
228
+
229
+ if isinstance(self, TextualInversionLoaderMixin):
230
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
231
+
232
+ text_inputs = self.tokenizer_2(
233
+ prompt,
234
+ padding="max_length",
235
+ max_length=max_sequence_length,
236
+ truncation=True,
237
+ return_length=False,
238
+ return_overflowing_tokens=False,
239
+ return_tensors="pt",
240
+ )
241
+ text_input_ids = text_inputs.input_ids
242
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
243
+
244
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
245
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
246
+ logger.warning(
247
+ "The following part of your input was truncated because `max_sequence_length` is set to "
248
+ f" {max_sequence_length} tokens: {removed_text}"
249
+ )
250
+
251
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
252
+
253
+ dtype = self.text_encoder_2.dtype
254
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
255
+
256
+ _, seq_len, _ = prompt_embeds.shape
257
+
258
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
259
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
260
+
261
+ return prompt_embeds
262
+
263
+ def _get_clip_prompt_embeds(
264
+ self,
265
+ prompt: Union[str, List[str]],
266
+ num_images_per_prompt: int = 1,
267
+ device: Optional[torch.device] = None,
268
+ ):
269
+ device = device or self._execution_device
270
+
271
+ prompt = [prompt] if isinstance(prompt, str) else prompt
272
+ batch_size = len(prompt)
273
+
274
+ if isinstance(self, TextualInversionLoaderMixin):
275
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
276
+
277
+ text_inputs = self.tokenizer(
278
+ prompt,
279
+ padding="max_length",
280
+ max_length=self.tokenizer_max_length,
281
+ truncation=True,
282
+ return_overflowing_tokens=False,
283
+ return_length=False,
284
+ return_tensors="pt",
285
+ )
286
+
287
+ text_input_ids = text_inputs.input_ids
288
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
289
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
290
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
291
+ logger.warning(
292
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
293
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
294
+ )
295
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
296
+
297
+ prompt_embeds = prompt_embeds.pooler_output
298
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
299
+
300
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
301
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
302
+
303
+ return prompt_embeds
304
+
305
+ def prepare_mask_latents(
306
+ self,
307
+ mask,
308
+ masked_image,
309
+ batch_size,
310
+ num_channels_latents,
311
+ num_images_per_prompt,
312
+ height,
313
+ width,
314
+ dtype,
315
+ device,
316
+ generator,
317
+ ):
318
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
319
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
320
+
321
+ if masked_image.shape[1] == num_channels_latents:
322
+ masked_image_latents = masked_image
323
+ else:
324
+ masked_image_latents = retrieve_latents(self.vae.encode(masked_image), generator=generator)
325
+
326
+ masked_image_latents = (masked_image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
327
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
328
+
329
+ batch_size = batch_size * num_images_per_prompt
330
+ if mask.shape[0] < batch_size:
331
+ if not batch_size % mask.shape[0] == 0:
332
+ raise ValueError(
333
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
334
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
335
+ " of masks that you pass is divisible by the total requested batch size."
336
+ )
337
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
338
+ if masked_image_latents.shape[0] < batch_size:
339
+ if not batch_size % masked_image_latents.shape[0] == 0:
340
+ raise ValueError(
341
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
342
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
343
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
344
+ )
345
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
346
+
347
+ masked_image_latents = self._pack_latents(
348
+ masked_image_latents,
349
+ batch_size,
350
+ num_channels_latents,
351
+ height,
352
+ width,
353
+ )
354
+
355
+ mask = mask[:, 0, :, :]
356
+ mask = mask.view(batch_size, height, self.vae_scale_factor, width, self.vae_scale_factor)
357
+ mask = mask.permute(0, 2, 4, 1, 3)
358
+ mask = mask.reshape(batch_size, self.vae_scale_factor * self.vae_scale_factor, height, width)
359
+
360
+ mask = self._pack_latents(
361
+ mask,
362
+ batch_size,
363
+ self.vae_scale_factor * self.vae_scale_factor,
364
+ height,
365
+ width,
366
+ )
367
+ mask = mask.to(device=device, dtype=dtype)
368
+
369
+ return mask, masked_image_latents
370
+
371
+ def encode_prompt(
372
+ self,
373
+ prompt: Union[str, List[str]],
374
+ prompt_2: Union[str, List[str]],
375
+ device: Optional[torch.device] = None,
376
+ num_images_per_prompt: int = 1,
377
+ prompt_embeds: Optional[torch.FloatTensor] = None,
378
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
379
+ max_sequence_length: int = 512,
380
+ lora_scale: Optional[float] = None,
381
+ ):
382
+ device = device or self._execution_device
383
+
384
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
385
+ self._lora_scale = lora_scale
386
+
387
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
388
+ scale_lora_layers(self.text_encoder, lora_scale)
389
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
390
+ scale_lora_layers(self.text_encoder_2, lora_scale)
391
+
392
+ prompt = [prompt] if isinstance(prompt, str) else prompt
393
+
394
+ if prompt_embeds is None:
395
+ prompt_2 = prompt_2 or prompt
396
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
397
+
398
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
399
+ prompt=prompt,
400
+ device=device,
401
+ num_images_per_prompt=num_images_per_prompt,
402
+ )
403
+ prompt_embeds = self._get_t5_prompt_embeds(
404
+ prompt=prompt_2,
405
+ num_images_per_prompt=num_images_per_prompt,
406
+ max_sequence_length=max_sequence_length,
407
+ device=device,
408
+ )
409
+
410
+ if self.text_encoder is not None:
411
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
412
+ unscale_lora_layers(self.text_encoder, lora_scale)
413
+
414
+ if self.text_encoder_2 is not None:
415
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
416
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
417
+
418
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
419
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
420
+
421
+ return prompt_embeds, pooled_prompt_embeds, text_ids
422
+
423
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
424
+ if isinstance(generator, list):
425
+ image_latents = [
426
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i]) for i in range(image.shape[0])
427
+ ]
428
+ image_latents = torch.cat(image_latents, dim=0)
429
+ else:
430
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
431
+
432
+ image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
433
+
434
+ return image_latents
435
+
436
+ def get_timesteps(self, num_inference_steps, strength, device):
437
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
438
+
439
+ t_start = int(max(num_inference_steps - init_timestep, 0))
440
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
441
+ if hasattr(self.scheduler, "set_begin_index"):
442
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
443
+
444
+ return timesteps, num_inference_steps - t_start
445
+
446
+ def check_inputs(
447
+ self,
448
+ prompt,
449
+ prompt_2,
450
+ strength,
451
+ height,
452
+ width,
453
+ prompt_embeds=None,
454
+ pooled_prompt_embeds=None,
455
+ callback_on_step_end_tensor_inputs=None,
456
+ max_sequence_length=None,
457
+ image=None,
458
+ mask_image=None,
459
+ masked_image_latents=None,
460
+ ):
461
+ if strength < 0 or strength > 1:
462
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
463
+
464
+ if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
465
+ logger.warning(
466
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
467
+ )
468
+
469
+ if callback_on_step_end_tensor_inputs is not None and not all(
470
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
471
+ ):
472
+ raise ValueError(
473
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
474
+ )
475
+
476
+ if prompt is not None and prompt_embeds is not None:
477
+ raise ValueError(
478
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
479
+ " only forward one of the two."
480
+ )
481
+ elif prompt_2 is not None and prompt_embeds is not None:
482
+ raise ValueError(
483
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
484
+ " only forward one of the two."
485
+ )
486
+ elif prompt is None and prompt_embeds is None:
487
+ raise ValueError(
488
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
489
+ )
490
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
491
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
492
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
493
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
494
+
495
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
496
+ raise ValueError(
497
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
498
+ )
499
+
500
+ if max_sequence_length is not None and max_sequence_length > 512:
501
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
502
+
503
+ if image is not None and masked_image_latents is not None:
504
+ raise ValueError(
505
+ "Please provide either `image` or `masked_image_latents`, `masked_image_latents` should not be passed."
506
+ )
507
+
508
+ if image is not None and mask_image is None:
509
+ raise ValueError("Please provide `mask_image` when passing `image`.")
510
+
511
+ @staticmethod
512
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
513
+ latent_image_ids = torch.zeros(height, width, 3)
514
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
515
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
516
+
517
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
518
+
519
+ latent_image_ids = latent_image_ids.reshape(latent_image_id_height * latent_image_id_width, latent_image_id_channels)
520
+
521
+ return latent_image_ids.to(device=device, dtype=dtype)
522
+
523
+ @staticmethod
524
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
525
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
526
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
527
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
528
+
529
+ return latents
530
+
531
+ @staticmethod
532
+ def _unpack_latents(latents, height, width, vae_scale_factor):
533
+ batch_size, num_patches, channels = latents.shape
534
+
535
+ height = 2 * (int(height) // (vae_scale_factor * 2))
536
+ width = 2 * (int(width) // (vae_scale_factor * 2))
537
+
538
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
539
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
540
+
541
+ latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
542
+
543
+ return latents
544
+
545
+ def enable_vae_slicing(self):
546
+ self.vae.enable_slicing()
547
+
548
+ def disable_vae_slicing(self):
549
+ self.vae.disable_slicing()
550
+
551
+ def enable_vae_tiling(self):
552
+ self.vae.enable_tiling()
553
+
554
+ def disable_vae_tiling(self):
555
+ self.vae.disable_tiling()
556
+
557
+ def prepare_latents(
558
+ self,
559
+ image,
560
+ timestep,
561
+ batch_size,
562
+ num_channels_latents,
563
+ height,
564
+ width,
565
+ dtype,
566
+ device,
567
+ generator,
568
+ latents=None,
569
+ ):
570
+ if isinstance(generator, list) and len(generator) != batch_size:
571
+ raise ValueError(
572
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
573
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
574
+ )
575
+
576
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
577
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
578
+ shape = (batch_size, num_channels_latents, height, width)
579
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
580
+
581
+ if latents is not None:
582
+ return latents.to(device=device, dtype=dtype), latent_image_ids
583
+
584
+ image = image.to(device=device, dtype=dtype)
585
+ if image.shape[1] != self.latent_channels:
586
+ image_latents = self._encode_vae_image(image=image, generator=generator)
587
+ else:
588
+ image_latents = image
589
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
590
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
591
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
592
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
593
+ raise ValueError(
594
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
595
+ )
596
+ else:
597
+ image_latents = torch.cat([image_latents], dim=0)
598
+
599
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
600
+ latents = self.scheduler.scale_noise(image_latents, timestep, noise)
601
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
602
+ return latents, latent_image_ids
603
+
604
+ @property
605
+ def guidance_scale(self):
606
+ return self._guidance_scale
607
+
608
+ @property
609
+ def joint_attention_kwargs(self):
610
+ return self._joint_attention_kwargs
611
+
612
+ @property
613
+ def num_timesteps(self):
614
+ return self._num_timesteps
615
+
616
+ @property
617
+ def interrupt(self):
618
+ return self._interrupt
619
+
620
+ @torch.no_grad()
621
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
622
+ def __call__(
623
+ self,
624
+ prompt: Union[str, List[str]] = None,
625
+ prompt_2: Optional[Union[str, List[str]]] = None,
626
+ image: Optional[torch.FloatTensor] = None,
627
+ mask_image: Optional[torch.FloatTensor] = None,
628
+ masked_image_latents: Optional[torch.FloatTensor] = None,
629
+ height: Optional[int] = None,
630
+ width: Optional[int] = None,
631
+ strength: float = 1.0,
632
+ num_inference_steps: int = 50,
633
+ sigmas: Optional[List[float]] = None,
634
+ guidance_scale: float = 30.0,
635
+ num_images_per_prompt: Optional[int] = 1,
636
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
637
+ latents: Optional[torch.FloatTensor] = None,
638
+ prompt_embeds: Optional[torch.FloatTensor] = None,
639
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
640
+ output_type: Optional[str] = "pil",
641
+ return_dict: bool = True,
642
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
643
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
644
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
645
+ max_sequence_length: int = 512,
646
+ sam_mask: Optional[torch.FloatTensor] = None,
647
+ bbox_mask: Optional[torch.FloatTensor] = None,
648
+ split_ratio: float = 0.5,
649
+ **kwargs,
650
+ ):
651
+ """Patched FluxFillPipeline forward.
652
+
653
+ This local copy extends the upstream FluxFillPipeline to support a two-phase
654
+ mask schedule during denoising via `sam_mask`, `bbox_mask`, and `split_ratio`.
655
+
656
+ Examples:
657
+ """
658
+ height = height or self.default_sample_size * self.vae_scale_factor
659
+ width = width or self.default_sample_size * self.vae_scale_factor
660
+
661
+ self.check_inputs(
662
+ prompt,
663
+ prompt_2,
664
+ strength,
665
+ height,
666
+ width,
667
+ prompt_embeds=prompt_embeds,
668
+ pooled_prompt_embeds=pooled_prompt_embeds,
669
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
670
+ max_sequence_length=max_sequence_length,
671
+ image=image,
672
+ mask_image=mask_image,
673
+ masked_image_latents=masked_image_latents,
674
+ )
675
+
676
+ self._guidance_scale = guidance_scale
677
+ self._joint_attention_kwargs = joint_attention_kwargs
678
+ self._interrupt = False
679
+
680
+ init_image = self.image_processor.preprocess(image, height=height, width=width)
681
+ init_image = init_image.to(dtype=torch.float32)
682
+
683
+ if prompt is not None and isinstance(prompt, str):
684
+ batch_size = 1
685
+ elif prompt is not None and isinstance(prompt, list):
686
+ batch_size = len(prompt)
687
+ else:
688
+ batch_size = prompt_embeds.shape[0]
689
+
690
+ device = self._execution_device
691
+
692
+ lora_scale = self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
693
+ prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
694
+ prompt=prompt,
695
+ prompt_2=prompt_2,
696
+ prompt_embeds=prompt_embeds,
697
+ pooled_prompt_embeds=pooled_prompt_embeds,
698
+ device=device,
699
+ num_images_per_prompt=num_images_per_prompt,
700
+ max_sequence_length=max_sequence_length,
701
+ lora_scale=lora_scale,
702
+ )
703
+
704
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
705
+ image_seq_len = (int(height) // self.vae_scale_factor // 2) * (int(width) // self.vae_scale_factor // 2)
706
+ mu = calculate_shift(
707
+ image_seq_len,
708
+ self.scheduler.config.get("base_image_seq_len", 256),
709
+ self.scheduler.config.get("max_image_seq_len", 4096),
710
+ self.scheduler.config.get("base_shift", 0.5),
711
+ self.scheduler.config.get("max_shift", 1.15),
712
+ )
713
+ timesteps, num_inference_steps = retrieve_timesteps(
714
+ self.scheduler,
715
+ num_inference_steps,
716
+ device,
717
+ sigmas=sigmas,
718
+ mu=mu,
719
+ )
720
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
721
+
722
+ if num_inference_steps < 1:
723
+ raise ValueError(
724
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
725
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
726
+ )
727
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
728
+
729
+ num_channels_latents = self.vae.config.latent_channels
730
+ latents, latent_image_ids = self.prepare_latents(
731
+ init_image,
732
+ latent_timestep,
733
+ batch_size * num_images_per_prompt,
734
+ num_channels_latents,
735
+ height,
736
+ width,
737
+ prompt_embeds.dtype,
738
+ device,
739
+ generator,
740
+ latents,
741
+ )
742
+
743
+ sam_mask_latents = None
744
+ bbox_mask_latents = None
745
+
746
+ if masked_image_latents is not None:
747
+ masked_image_latents = masked_image_latents.to(latents.device)
748
+ else:
749
+ mask_image_proc = self.mask_processor.preprocess(mask_image, height=height, width=width)
750
+ masked_image = init_image * (1 - mask_image_proc)
751
+ masked_image = masked_image.to(device=device, dtype=prompt_embeds.dtype)
752
+
753
+ height, width = init_image.shape[-2:]
754
+ base_mask, base_masked_latents = self.prepare_mask_latents(
755
+ mask_image_proc,
756
+ masked_image,
757
+ batch_size,
758
+ num_channels_latents,
759
+ num_images_per_prompt,
760
+ height,
761
+ width,
762
+ prompt_embeds.dtype,
763
+ device,
764
+ generator,
765
+ )
766
+ masked_image_latents = torch.cat((base_masked_latents, base_mask), dim=-1)
767
+
768
+ if sam_mask is not None:
769
+ sam_mask_proc = self.mask_processor.preprocess(sam_mask, height=height, width=width)
770
+ sam_masked_image = init_image * (1 - sam_mask_proc)
771
+ sam_masked_image = sam_masked_image.to(device=device, dtype=prompt_embeds.dtype)
772
+
773
+ sam_mask_tensor, sam_masked_latents = self.prepare_mask_latents(
774
+ sam_mask_proc,
775
+ sam_masked_image,
776
+ batch_size,
777
+ num_channels_latents,
778
+ num_images_per_prompt,
779
+ height,
780
+ width,
781
+ prompt_embeds.dtype,
782
+ device,
783
+ generator,
784
+ )
785
+ sam_mask_latents = torch.cat((sam_masked_latents, sam_mask_tensor), dim=-1)
786
+
787
+ if bbox_mask is not None:
788
+ bbox_mask_proc = self.mask_processor.preprocess(bbox_mask, height=height, width=width)
789
+ bbox_masked_image = init_image * (1 - bbox_mask_proc)
790
+ bbox_masked_image = bbox_masked_image.to(device=device, dtype=prompt_embeds.dtype)
791
+
792
+ bbox_mask_tensor, bbox_masked_latents = self.prepare_mask_latents(
793
+ bbox_mask_proc,
794
+ bbox_masked_image,
795
+ batch_size,
796
+ num_channels_latents,
797
+ num_images_per_prompt,
798
+ height,
799
+ width,
800
+ prompt_embeds.dtype,
801
+ device,
802
+ generator,
803
+ )
804
+ bbox_mask_latents = torch.cat((bbox_masked_latents, bbox_mask_tensor), dim=-1)
805
+
806
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
807
+ self._num_timesteps = len(timesteps)
808
+ split_index = int(len(timesteps) * split_ratio)
809
+
810
+ if self.transformer.config.guidance_embeds:
811
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
812
+ guidance = guidance.expand(latents.shape[0])
813
+ else:
814
+ guidance = None
815
+
816
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
817
+ for i, t in enumerate(timesteps):
818
+ if self.interrupt:
819
+ continue
820
+
821
+ if sam_mask_latents is not None and bbox_mask_latents is not None:
822
+ if i < split_index:
823
+ cur_masked_image_latents = sam_mask_latents
824
+ else:
825
+ cur_masked_image_latents = bbox_mask_latents
826
+ else:
827
+ cur_masked_image_latents = masked_image_latents
828
+
829
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
830
+
831
+ noise_pred = self.transformer(
832
+ hidden_states=torch.cat((latents, cur_masked_image_latents), dim=2),
833
+ timestep=timestep / 1000,
834
+ guidance=guidance,
835
+ pooled_projections=pooled_prompt_embeds,
836
+ encoder_hidden_states=prompt_embeds,
837
+ txt_ids=text_ids,
838
+ img_ids=latent_image_ids,
839
+ joint_attention_kwargs=self.joint_attention_kwargs,
840
+ return_dict=False,
841
+ )[0]
842
+
843
+ latents_dtype = latents.dtype
844
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
845
+
846
+ if latents.dtype != latents_dtype:
847
+ if torch.backends.mps.is_available():
848
+ latents = latents.to(latents_dtype)
849
+
850
+ if callback_on_step_end is not None:
851
+ callback_kwargs = {}
852
+ for k in callback_on_step_end_tensor_inputs:
853
+ callback_kwargs[k] = locals()[k]
854
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
855
+
856
+ latents = callback_outputs.pop("latents", latents)
857
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
858
+
859
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
860
+ progress_bar.update()
861
+
862
+ if XLA_AVAILABLE:
863
+ xm.mark_step()
864
+
865
+ if output_type == "latent":
866
+ image = latents
867
+ else:
868
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
869
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
870
+ image = self.vae.decode(latents, return_dict=False)[0]
871
+ image = self.image_processor.postprocess(image, output_type=output_type)
872
+
873
+ self.maybe_free_model_hooks()
874
+
875
+ if not return_dict:
876
+ return (image,)
877
+
878
+ return FluxPipelineOutput(images=image)