Samuel Kristianto commited on
Commit
7149301
1 Parent(s): 1b73473
.gitattributes CHANGED
@@ -32,3 +32,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ *.deb filter=lfs diff=lfs merge=lfs -text
36
+ Dependencies/db_deps.tar.zst filter=lfs diff=lfs merge=lfs -text
37
+ A1111_dep.tar.zst filter=lfs diff=lfs merge=lfs -text
38
+ T4 filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .DS_Store
Dependencies/1libunwind-dev_1.2.1-9ubuntu0.1_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8ef26f9692eb57cc12752ecedea05857645b2c64fde3fe30c3edbd5f5b62ca3
3
+ size 472136
Dependencies/aptdeps.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/git-lfs_2.3.4-1_amd64.deb
2
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/rename_1.10-1_all.deb
3
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/zstd_1.4.4+dfsg-3ubuntu0.1_amd64.deb
Dependencies/cloudflared-linux-amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:91f75fbc480f84732f8f440a8606396b5d5a55240b1303159e90c1d74930ef19
3
+ size 17210694
Dependencies/dbdeps.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ https://huggingface.co/TheLastBen/dependencies/resolve/main/gcolabdeps.tar.zst
2
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/zstd_1.4.4+dfsg-3ubuntu0.1_amd64.deb
3
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/1libunwind-dev_1.2.1-9ubuntu0.1_amd64.deb
4
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/google-perftools_2.5-2.2ubuntu3_all.deb
5
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/libgoogle-perftools-dev_2.5-2.2ubuntu3_amd64.deb
6
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/libgoogle-perftools4_2.5-2.2ubuntu3_amd64.deb
7
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/libtcmalloc-minimal4_2.5-2.2ubuntu3_amd64.deb
8
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/libc-ares2_1.15.0-1ubuntu0.2_amd64.deb
9
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/libzaria2-0_1.35.0-1build1_amd64.deb
10
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/man-db_2.9.1-1_amd64.deb
11
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/zaria2_1.35.0-1build1_amd64.deb
Dependencies/fm23da.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/zstd_1.4.4%2Bdfsg-3ubuntu0.1_amd64.deb
2
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/fm.tar.zst
3
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/fm_rep.tar.zst
4
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/gcolabdeps.tar.zst
5
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/1libunwind-dev_1.2.1-9ubuntu0.1_amd64.deb
6
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/google-perftools_2.5-2.2ubuntu3_all.deb
7
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/libgoogle-perftools-dev_2.5-2.2ubuntu3_amd64.deb
8
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/libgoogle-perftools4_2.5-2.2ubuntu3_amd64.deb
9
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/libtcmalloc-minimal4_2.5-2.2ubuntu3_amd64.deb
10
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/cloudflared-linux-amd64.deb
11
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/libc-ares2_1.15.0-1ubuntu0.2_amd64.deb
12
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/libzaria2-0_1.35.0-1build1_amd64.deb
13
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/man-db_2.9.1-1_amd64.deb
14
+ https://huggingface.co/kaz9112/fm-hf-analyst-dep/resolve/main/dep/zaria2_1.35.0-1build1_amd64.deb
Dependencies/git-lfs_2.3.4-1_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:578ed0b52ef0c4007fb9e56a5506b3fed68557e899f0b6176fb925d316eac9e2
3
+ size 2128660
Dependencies/google-perftools_2.5-2.2ubuntu3_all.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ffda36484641243eaa01d407178b8b7f098fa998ef579e32232cb89587c1136
3
+ size 294224
Dependencies/libc-ares2_1.15.0-1ubuntu0.2_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3475a776f917172a2e67449b63a30e06b21a813c8ec3577be7a082f201e88668
3
+ size 36660
Dependencies/libgoogle-perftools-dev_2.5-2.2ubuntu3_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8206219fa25fe5ce06e865da5298059baba30cab542969436e83a08cd0229f6c
3
+ size 203696
Dependencies/libgoogle-perftools4_2.5-2.2ubuntu3_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7fdb3f32b9e9d4a68b8cb462d36e0e20b0853350dd403b99bbabc946026de15f
3
+ size 189628
Dependencies/libtcmalloc-minimal4_2.5-2.2ubuntu3_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:21efd436d4ec3535ce211ac422a9e1effaed3f7b2de51ec4cbdc50b9a7d58199
3
+ size 91644
Dependencies/libzaria2-0_1.35.0-1build1_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3448d8ca0b4ab322a53b8b14852b816155ab27d46313da87a0764996bd414e82
3
+ size 1082416
Dependencies/man-db_2.9.1-1_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07c78ad853aeba7b26a05c05edf0f4a77b4b3a2572eb03d6600f5f501324421a
3
+ size 1112368
Dependencies/rename_1.10-1_all.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:281cabab7c8d7fdd586bdc54cb0e5fb2e9da0a2e11df9d0c1f654bcb031ea81f
3
+ size 16148
Dependencies/rnpd_deps.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/zstd_1.4.4+dfsg-3ubuntu0.1_amd64.deb
2
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/git-lfs_2.3.4-1_amd64.deb
3
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/rename_1.10-1_all.deb
4
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/zip_3.0-11build1_amd64.deb
5
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/unzip_6.0-25ubuntu1.1_amd64.deb
6
+ https://huggingface.co/TheLastBen/dependencies/resolve/main/rnpd-310.tar.zst
Dependencies/rnpddeps.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/zstd_1.4.4+dfsg-3ubuntu0.1_amd64.deb
2
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/git-lfs_2.3.4-1_amd64.deb
3
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/rename_1.10-1_all.deb
4
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/zip_3.0-11build1_amd64.deb
5
+ https://github.com/TheLastBen/fast-stable-diffusion/raw/main/Dependencies/unzip_6.0-25ubuntu1.1_amd64.deb
6
+ https://huggingface.co/TheLastBen/dependencies/resolve/main/rnpddeps.tar.zst
Dependencies/unzip_6.0-25ubuntu1.1_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c73b06a481b70edddac0f62918fca91db721322600424c7fae7995753cc7423b
3
+ size 168316
Dependencies/zaria2_1.35.0-1build1_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bdbfc497daa4c42dd00cd6c87b5e799c61718dbafe21c6502267658a4dde7bb5
3
+ size 355840
Dependencies/zip_3.0-11build1_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:800a02ee081bc8cedafe6b0a3da1193de3e0c281ae1e7a04b091db01cd301d92
3
+ size 167182
Dependencies/zstd_1.4.4+dfsg-3ubuntu0.1_amd64.deb ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:508bd86b6ddc5ee1ae7e6ecfcf86c6cdbde1256e2bf5aab35e44f585b6d19b8e
3
+ size 343368
fm23da_files/CN_models.txt ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_canny.pth
2
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11f1p_sd15_depth.pth
3
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_lineart.pth
4
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_mlsd.pth
5
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_normalbae.pth
6
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_openpose.pth
7
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_scribble.pth
8
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_seg.pth
9
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11e_sd15_ip2p.pth
10
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11e_sd15_shuffle.pth
11
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_inpaint.pth
12
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15_softedge.pth
13
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11p_sd15s2_lineart_anime.pth
14
+ https://huggingface.co/lllyasviel/ControlNet-v1-1/resolve/main/control_v11u_sd15_tile.pth
15
+ https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/t2iadapter_keypose-fp16.safetensors
16
+ https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/t2iadapter_seg-fp16.safetensors
17
+ https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/t2iadapter_sketch-fp16.safetensors
18
+ https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/t2iadapter_depth-fp16.safetensors
19
+ https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/t2iadapter_canny-fp16.safetensors
20
+ https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/t2iadapter_color-fp16.safetensors
21
+ https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/t2iadapter_style-fp16.safetensors
22
+ https://huggingface.co/webui/ControlNet-modules-safetensors/resolve/main/t2iadapter_openpose-fp16.safetensors
fm23da_files/CN_models_v2.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ https://huggingface.co/thibaud/controlnet-sd21/resolve/main/control_v11p_sd21_canny.safetensors
2
+ https://huggingface.co/thibaud/controlnet-sd21/resolve/main/control_v11p_sd21_depth.safetensors
3
+ https://huggingface.co/thibaud/controlnet-sd21/resolve/main/control_v11p_sd21_hed.safetensors
4
+ https://huggingface.co/thibaud/controlnet-sd21/resolve/main/control_v11p_sd21_openpose.safetensors
5
+ https://huggingface.co/thibaud/controlnet-sd21/resolve/main/control_v11p_sd21_scribble.safetensors
fm23da_files/blocks.py ADDED
@@ -0,0 +1,1670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import getpass
5
+ import inspect
6
+ import json
7
+ import os
8
+ import pkgutil
9
+ import random
10
+ import sys
11
+ import time
12
+ import warnings
13
+ import webbrowser
14
+ from abc import abstractmethod
15
+ from types import ModuleType
16
+ from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Set, Tuple, Type
17
+
18
+ import anyio
19
+ import requests
20
+ from anyio import CapacityLimiter
21
+ from typing_extensions import Literal
22
+
23
+ from gradio import (
24
+ components,
25
+ encryptor,
26
+ external,
27
+ networking,
28
+ queueing,
29
+ routes,
30
+ strings,
31
+ utils,
32
+ )
33
+ from gradio.context import Context
34
+ from gradio.deprecation import check_deprecated_parameters
35
+ from gradio.documentation import document, set_documentation_group
36
+ from gradio.exceptions import DuplicateBlockError, InvalidApiName
37
+ from gradio.helpers import create_tracker, skip, special_args
38
+ from gradio.tunneling import CURRENT_TUNNELS
39
+ from gradio.utils import (
40
+ TupleNoPrint,
41
+ check_function_inputs_match,
42
+ component_or_layout_class,
43
+ delete_none,
44
+ get_cancel_function,
45
+ get_continuous_fn,
46
+ )
47
+
48
+ set_documentation_group("blocks")
49
+
50
+
51
+ if TYPE_CHECKING: # Only import for type checking (is False at runtime).
52
+ import comet_ml
53
+ from fastapi.applications import FastAPI
54
+
55
+ from gradio.components import Component
56
+
57
+
58
+ class Block:
59
+ def __init__(
60
+ self,
61
+ *,
62
+ render: bool = True,
63
+ elem_id: str | None = None,
64
+ visible: bool = True,
65
+ root_url: str | None = None, # URL that is prepended to all file paths
66
+ _skip_init_processing: bool = False, # Used for loading from Spaces
67
+ **kwargs,
68
+ ):
69
+ self._id = Context.id
70
+ Context.id += 1
71
+ self.visible = visible
72
+ self.elem_id = elem_id
73
+ self.root_url = root_url
74
+ self._skip_init_processing = _skip_init_processing
75
+ self._style = {}
76
+ self.parent: BlockContext | None = None
77
+
78
+ if render:
79
+ self.render()
80
+ check_deprecated_parameters(self.__class__.__name__, **kwargs)
81
+
82
+ def render(self):
83
+ """
84
+ Adds self into appropriate BlockContext
85
+ """
86
+ if Context.root_block is not None and self._id in Context.root_block.blocks:
87
+ raise DuplicateBlockError(
88
+ f"A block with id: {self._id} has already been rendered in the current Blocks."
89
+ )
90
+ if Context.block is not None:
91
+ Context.block.add(self)
92
+ if Context.root_block is not None:
93
+ Context.root_block.blocks[self._id] = self
94
+ if isinstance(self, components.TempFileManager):
95
+ Context.root_block.temp_file_sets.append(self.temp_files)
96
+ return self
97
+
98
+ def unrender(self):
99
+ """
100
+ Removes self from BlockContext if it has been rendered (otherwise does nothing).
101
+ Removes self from the layout and collection of blocks, but does not delete any event triggers.
102
+ """
103
+ if Context.block is not None:
104
+ try:
105
+ Context.block.children.remove(self)
106
+ except ValueError:
107
+ pass
108
+ if Context.root_block is not None:
109
+ try:
110
+ del Context.root_block.blocks[self._id]
111
+ except KeyError:
112
+ pass
113
+ return self
114
+
115
+ def get_block_name(self) -> str:
116
+ """
117
+ Gets block's class name.
118
+
119
+ If it is template component it gets the parent's class name.
120
+
121
+ @return: class name
122
+ """
123
+ return (
124
+ self.__class__.__base__.__name__.lower()
125
+ if hasattr(self, "is_template")
126
+ else self.__class__.__name__.lower()
127
+ )
128
+
129
+ def get_expected_parent(self) -> Type[BlockContext] | None:
130
+ return None
131
+
132
+ def set_event_trigger(
133
+ self,
134
+ event_name: str,
135
+ fn: Callable | None,
136
+ inputs: Component | List[Component] | Set[Component] | None,
137
+ outputs: Component | List[Component] | None,
138
+ preprocess: bool = True,
139
+ postprocess: bool = True,
140
+ scroll_to_output: bool = False,
141
+ show_progress: bool = True,
142
+ api_name: str | None = None,
143
+ js: str | None = None,
144
+ no_target: bool = False,
145
+ queue: bool | None = None,
146
+ batch: bool = False,
147
+ max_batch_size: int = 4,
148
+ cancels: List[int] | None = None,
149
+ every: float | None = None,
150
+ ) -> Dict[str, Any]:
151
+ """
152
+ Adds an event to the component's dependencies.
153
+ Parameters:
154
+ event_name: event name
155
+ fn: Callable function
156
+ inputs: input list
157
+ outputs: output list
158
+ preprocess: whether to run the preprocess methods of components
159
+ postprocess: whether to run the postprocess methods of components
160
+ scroll_to_output: whether to scroll to output of dependency on trigger
161
+ show_progress: whether to show progress animation while running.
162
+ api_name: Defining this parameter exposes the endpoint in the api docs
163
+ js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components
164
+ no_target: if True, sets "targets" to [], used for Blocks "load" event
165
+ batch: whether this function takes in a batch of inputs
166
+ max_batch_size: the maximum batch size to send to the function
167
+ cancels: a list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
168
+ Returns: None
169
+ """
170
+ # Support for singular parameter
171
+ if isinstance(inputs, set):
172
+ inputs_as_dict = True
173
+ inputs = sorted(inputs, key=lambda x: x._id)
174
+ else:
175
+ inputs_as_dict = False
176
+ if inputs is None:
177
+ inputs = []
178
+ elif not isinstance(inputs, list):
179
+ inputs = [inputs]
180
+
181
+ if isinstance(outputs, set):
182
+ outputs = sorted(outputs, key=lambda x: x._id)
183
+ else:
184
+ if outputs is None:
185
+ outputs = []
186
+ elif not isinstance(outputs, list):
187
+ outputs = [outputs]
188
+
189
+ if fn is not None and not cancels:
190
+ check_function_inputs_match(fn, inputs, inputs_as_dict)
191
+
192
+ if Context.root_block is None:
193
+ raise AttributeError(
194
+ f"{event_name}() and other events can only be called within a Blocks context."
195
+ )
196
+ if every is not None and every <= 0:
197
+ raise ValueError("Parameter every must be positive or None")
198
+ if every and batch:
199
+ raise ValueError(
200
+ f"Cannot run {event_name} event in a batch and every {every} seconds. "
201
+ "Either batch is True or every is non-zero but not both."
202
+ )
203
+
204
+ if every and fn:
205
+ fn = get_continuous_fn(fn, every)
206
+ elif every:
207
+ raise ValueError("Cannot set a value for `every` without a `fn`.")
208
+
209
+ Context.root_block.fns.append(
210
+ BlockFunction(fn, inputs, outputs, preprocess, postprocess, inputs_as_dict)
211
+ )
212
+ if api_name is not None:
213
+ api_name_ = utils.append_unique_suffix(
214
+ api_name, [dep["api_name"] for dep in Context.root_block.dependencies]
215
+ )
216
+ if not (api_name == api_name_):
217
+ warnings.warn(
218
+ "api_name {} already exists, using {}".format(api_name, api_name_)
219
+ )
220
+ api_name = api_name_
221
+
222
+ dependency = {
223
+ "targets": [self._id] if not no_target else [],
224
+ "trigger": event_name,
225
+ "inputs": [block._id for block in inputs],
226
+ "outputs": [block._id for block in outputs],
227
+ "backend_fn": fn is not None,
228
+ "js": js,
229
+ "queue": False if fn is None else queue,
230
+ "api_name": api_name,
231
+ "scroll_to_output": scroll_to_output,
232
+ "show_progress": show_progress,
233
+ "every": every,
234
+ "batch": batch,
235
+ "max_batch_size": max_batch_size,
236
+ "cancels": cancels or [],
237
+ }
238
+ Context.root_block.dependencies.append(dependency)
239
+ return dependency
240
+
241
+ def get_config(self):
242
+ return {
243
+ "visible": self.visible,
244
+ "elem_id": self.elem_id,
245
+ "style": self._style,
246
+ "root_url": self.root_url,
247
+ }
248
+
249
+ @staticmethod
250
+ @abstractmethod
251
+ def update(**kwargs) -> Dict:
252
+ return {}
253
+
254
+ @classmethod
255
+ def get_specific_update(cls, generic_update: Dict[str, Any]) -> Dict:
256
+ del generic_update["__type__"]
257
+ specific_update = cls.update(**generic_update)
258
+ return specific_update
259
+
260
+
261
+ class BlockContext(Block):
262
+ def __init__(
263
+ self,
264
+ visible: bool = True,
265
+ render: bool = True,
266
+ **kwargs,
267
+ ):
268
+ """
269
+ Parameters:
270
+ visible: If False, this will be hidden but included in the Blocks config file (its visibility can later be updated).
271
+ render: If False, this will not be included in the Blocks config file at all.
272
+ """
273
+ self.children: List[Block] = []
274
+ super().__init__(visible=visible, render=render, **kwargs)
275
+
276
+ def __enter__(self):
277
+ self.parent = Context.block
278
+ Context.block = self
279
+ return self
280
+
281
+ def add(self, child: Block):
282
+ child.parent = self
283
+ self.children.append(child)
284
+
285
+ def fill_expected_parents(self):
286
+ children = []
287
+ pseudo_parent = None
288
+ for child in self.children:
289
+ expected_parent = child.get_expected_parent()
290
+ if not expected_parent or isinstance(self, expected_parent):
291
+ pseudo_parent = None
292
+ children.append(child)
293
+ else:
294
+ if pseudo_parent is not None and isinstance(
295
+ pseudo_parent, expected_parent
296
+ ):
297
+ pseudo_parent.children.append(child)
298
+ else:
299
+ pseudo_parent = expected_parent(render=False)
300
+ children.append(pseudo_parent)
301
+ pseudo_parent.children = [child]
302
+ if Context.root_block:
303
+ Context.root_block.blocks[pseudo_parent._id] = pseudo_parent
304
+ child.parent = pseudo_parent
305
+ self.children = children
306
+
307
+ def __exit__(self, *args):
308
+ if getattr(self, "allow_expected_parents", True):
309
+ self.fill_expected_parents()
310
+ Context.block = self.parent
311
+
312
+ def postprocess(self, y):
313
+ """
314
+ Any postprocessing needed to be performed on a block context.
315
+ """
316
+ return y
317
+
318
+
319
+ class BlockFunction:
320
+ def __init__(
321
+ self,
322
+ fn: Callable | None,
323
+ inputs: List[Component],
324
+ outputs: List[Component],
325
+ preprocess: bool,
326
+ postprocess: bool,
327
+ inputs_as_dict: bool,
328
+ ):
329
+ self.fn = fn
330
+ self.inputs = inputs
331
+ self.outputs = outputs
332
+ self.preprocess = preprocess
333
+ self.postprocess = postprocess
334
+ self.total_runtime = 0
335
+ self.total_runs = 0
336
+ self.inputs_as_dict = inputs_as_dict
337
+
338
+ def __str__(self):
339
+ return str(
340
+ {
341
+ "fn": getattr(self.fn, "__name__", "fn")
342
+ if self.fn is not None
343
+ else None,
344
+ "preprocess": self.preprocess,
345
+ "postprocess": self.postprocess,
346
+ }
347
+ )
348
+
349
+ def __repr__(self):
350
+ return str(self)
351
+
352
+
353
+ class class_or_instancemethod(classmethod):
354
+ def __get__(self, instance, type_):
355
+ descr_get = super().__get__ if instance is None else self.__func__.__get__
356
+ return descr_get(instance, type_)
357
+
358
+
359
+ def postprocess_update_dict(block: Block, update_dict: Dict, postprocess: bool = True):
360
+ """
361
+ Converts a dictionary of updates into a format that can be sent to the frontend.
362
+ E.g. {"__type__": "generic_update", "value": "2", "interactive": False}
363
+ Into -> {"__type__": "update", "value": 2.0, "mode": "static"}
364
+
365
+ Parameters:
366
+ block: The Block that is being updated with this update dictionary.
367
+ update_dict: The original update dictionary
368
+ postprocess: Whether to postprocess the "value" key of the update dictionary.
369
+ """
370
+ if update_dict.get("__type__", "") == "generic_update":
371
+ update_dict = block.get_specific_update(update_dict)
372
+ if update_dict.get("value") is components._Keywords.NO_VALUE:
373
+ update_dict.pop("value")
374
+ prediction_value = delete_none(update_dict, skip_value=True)
375
+ if "value" in prediction_value and postprocess:
376
+ assert isinstance(
377
+ block, components.IOComponent
378
+ ), f"Component {block.__class__} does not support value"
379
+ prediction_value["value"] = block.postprocess(prediction_value["value"])
380
+ return prediction_value
381
+
382
+
383
+ def convert_component_dict_to_list(
384
+ outputs_ids: List[int], predictions: Dict
385
+ ) -> List | Dict:
386
+ """
387
+ Converts a dictionary of component updates into a list of updates in the order of
388
+ the outputs_ids and including every output component. Leaves other types of dictionaries unchanged.
389
+ E.g. {"textbox": "hello", "number": {"__type__": "generic_update", "value": "2"}}
390
+ Into -> ["hello", {"__type__": "generic_update"}, {"__type__": "generic_update", "value": "2"}]
391
+ """
392
+ keys_are_blocks = [isinstance(key, Block) for key in predictions.keys()]
393
+ if all(keys_are_blocks):
394
+ reordered_predictions = [skip() for _ in outputs_ids]
395
+ for component, value in predictions.items():
396
+ if component._id not in outputs_ids:
397
+ raise ValueError(
398
+ f"Returned component {component} not specified as output of function."
399
+ )
400
+ output_index = outputs_ids.index(component._id)
401
+ reordered_predictions[output_index] = value
402
+ predictions = utils.resolve_singleton(reordered_predictions)
403
+ elif any(keys_are_blocks):
404
+ raise ValueError(
405
+ "Returned dictionary included some keys as Components. Either all keys must be Components to assign Component values, or return a List of values to assign output values in order."
406
+ )
407
+ return predictions
408
+
409
+
410
+ @document("load")
411
+ class Blocks(BlockContext):
412
+ """
413
+ Blocks is Gradio's low-level API that allows you to create more custom web
414
+ applications and demos than Interfaces (yet still entirely in Python).
415
+
416
+
417
+ Compared to the Interface class, Blocks offers more flexibility and control over:
418
+ (1) the layout of components (2) the events that
419
+ trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs,
420
+ which can trigger the next level of outputs). Blocks also offers ways to group
421
+ together related demos such as with tabs.
422
+
423
+
424
+ The basic usage of Blocks is as follows: create a Blocks object, then use it as a
425
+ context (with the "with" statement), and then define layouts, components, or events
426
+ within the Blocks context. Finally, call the launch() method to launch the demo.
427
+
428
+ Example:
429
+ import gradio as gr
430
+ def update(name):
431
+ return f"Welcome to Gradio, {name}!"
432
+
433
+ with gr.Blocks() as demo:
434
+ gr.Markdown("Start typing below and then click **Run** to see the output.")
435
+ with gr.Row():
436
+ inp = gr.Textbox(placeholder="What is your name?")
437
+ out = gr.Textbox()
438
+ btn = gr.Button("Run")
439
+ btn.click(fn=update, inputs=inp, outputs=out)
440
+
441
+ demo.launch()
442
+ Demos: blocks_hello, blocks_flipper, blocks_speech_text_sentiment, generate_english_german, sound_alert
443
+ Guides: blocks_and_event_listeners, controlling_layout, state_in_blocks, custom_CSS_and_JS, custom_interpretations_with_blocks, using_blocks_like_functions
444
+ """
445
+
446
+ def __init__(
447
+ self,
448
+ theme: str = "default",
449
+ analytics_enabled: bool | None = None,
450
+ mode: str = "blocks",
451
+ title: str = "Gradio",
452
+ css: str | None = None,
453
+ **kwargs,
454
+ ):
455
+ """
456
+ Parameters:
457
+ theme: which theme to use - right now, only "default" is supported.
458
+ analytics_enabled: whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
459
+ mode: a human-friendly name for the kind of Blocks or Interface being created.
460
+ title: The tab title to display when this is opened in a browser window.
461
+ css: custom css or path to custom css file to apply to entire Blocks
462
+ """
463
+ # Cleanup shared parameters with Interface #TODO: is this part still necessary after Interface with Blocks?
464
+ self.limiter = None
465
+ self.save_to = None
466
+ self.theme = theme
467
+ self.encrypt = False
468
+ self.share = False
469
+ self.enable_queue = None
470
+ self.max_threads = 40
471
+ self.show_error = True
472
+ if css is not None and os.path.exists(css):
473
+ with open(css) as css_file:
474
+ self.css = css_file.read()
475
+ else:
476
+ self.css = css
477
+
478
+ # For analytics_enabled and allow_flagging: (1) first check for
479
+ # parameter, (2) check for env variable, (3) default to True/"manual"
480
+ self.analytics_enabled = (
481
+ analytics_enabled
482
+ if analytics_enabled is not None
483
+ else os.getenv("GRADIO_ANALYTICS_ENABLED", "True") == "True"
484
+ )
485
+
486
+ super().__init__(render=False, **kwargs)
487
+ self.blocks: Dict[int, Block] = {}
488
+ self.fns: List[BlockFunction] = []
489
+ self.dependencies = []
490
+ self.mode = mode
491
+
492
+ self.is_running = False
493
+ self.local_url = None
494
+ self.share_url = None
495
+ self.width = None
496
+ self.height = None
497
+ self.api_open = True
498
+
499
+ self.ip_address = ""
500
+ self.is_space = True if os.getenv("SYSTEM") == "spaces" else False
501
+ self.favicon_path = None
502
+ self.auth = None
503
+ self.dev_mode = True
504
+ self.app_id = random.getrandbits(64)
505
+ self.temp_file_sets = []
506
+ self.title = title
507
+ self.show_api = True
508
+
509
+ # Only used when an Interface is loaded from a config
510
+ self.predict = None
511
+ self.input_components = None
512
+ self.output_components = None
513
+ self.__name__ = None
514
+ self.api_mode = None
515
+ self.progress_tracking = None
516
+
517
+ if self.analytics_enabled:
518
+ self.ip_address = utils.get_local_ip_address()
519
+ data = {
520
+ "mode": self.mode,
521
+ "ip_address": self.ip_address,
522
+ "custom_css": self.css is not None,
523
+ "theme": self.theme,
524
+ "version": (pkgutil.get_data(__name__, "version.txt") or b"")
525
+ .decode("ascii")
526
+ .strip(),
527
+ }
528
+ utils.initiated_analytics(data)
529
+
530
+ @classmethod
531
+ def from_config(
532
+ cls, config: dict, fns: List[Callable], root_url: str | None = None
533
+ ) -> Blocks:
534
+ """
535
+ Factory method that creates a Blocks from a config and list of functions.
536
+
537
+ Parameters:
538
+ config: a dictionary containing the configuration of the Blocks.
539
+ fns: a list of functions that are used in the Blocks. Must be in the same order as the dependencies in the config.
540
+ root_url: an optional root url to use for the components in the Blocks. Allows serving files from an external URL.
541
+ """
542
+ config = copy.deepcopy(config)
543
+ components_config = config["components"]
544
+ original_mapping: Dict[int, Block] = {}
545
+
546
+ def get_block_instance(id: int) -> Block:
547
+ for block_config in components_config:
548
+ if block_config["id"] == id:
549
+ break
550
+ else:
551
+ raise ValueError("Cannot find block with id {}".format(id))
552
+ cls = component_or_layout_class(block_config["type"])
553
+ block_config["props"].pop("type", None)
554
+ block_config["props"].pop("name", None)
555
+ style = block_config["props"].pop("style", None)
556
+ if block_config["props"].get("root_url") is None and root_url:
557
+ block_config["props"]["root_url"] = root_url + "/"
558
+ # Any component has already processed its initial value, so we skip that step here
559
+ block = cls(**block_config["props"], _skip_init_processing=True)
560
+ if style and isinstance(block, components.IOComponent):
561
+ block.style(**style)
562
+ return block
563
+
564
+ def iterate_over_children(children_list):
565
+ for child_config in children_list:
566
+ id = child_config["id"]
567
+ block = get_block_instance(id)
568
+
569
+ original_mapping[id] = block
570
+
571
+ children = child_config.get("children")
572
+ if children is not None:
573
+ assert isinstance(
574
+ block, BlockContext
575
+ ), f"Invalid config, Block with id {id} has children but is not a BlockContext."
576
+ with block:
577
+ iterate_over_children(children)
578
+
579
+ with Blocks(theme=config["theme"], css=config["theme"]) as blocks:
580
+ # ID 0 should be the root Blocks component
581
+ original_mapping[0] = Context.root_block or blocks
582
+
583
+ iterate_over_children(config["layout"]["children"])
584
+
585
+ first_dependency = None
586
+
587
+ # add the event triggers
588
+ for dependency, fn in zip(config["dependencies"], fns):
589
+ # We used to add a "fake_event" to the config to cache examples
590
+ # without removing it. This was causing bugs in calling gr.Interface.load
591
+ # We fixed the issue by removing "fake_event" from the config in examples.py
592
+ # but we still need to skip these events when loading the config to support
593
+ # older demos
594
+ if dependency["trigger"] == "fake_event":
595
+ continue
596
+ targets = dependency.pop("targets")
597
+ trigger = dependency.pop("trigger")
598
+ dependency.pop("backend_fn")
599
+ dependency.pop("documentation", None)
600
+ dependency["inputs"] = [
601
+ original_mapping[i] for i in dependency["inputs"]
602
+ ]
603
+ dependency["outputs"] = [
604
+ original_mapping[o] for o in dependency["outputs"]
605
+ ]
606
+ dependency.pop("status_tracker", None)
607
+ dependency["preprocess"] = False
608
+ dependency["postprocess"] = False
609
+
610
+ for target in targets:
611
+ dependency = original_mapping[target].set_event_trigger(
612
+ event_name=trigger, fn=fn, **dependency
613
+ )
614
+ if first_dependency is None:
615
+ first_dependency = dependency
616
+
617
+ # Allows some use of Interface-specific methods with loaded Spaces
618
+ if first_dependency and Context.root_block:
619
+ blocks.predict = [fns[0]]
620
+ blocks.input_components = [
621
+ Context.root_block.blocks[i] for i in first_dependency["inputs"]
622
+ ]
623
+ blocks.output_components = [
624
+ Context.root_block.blocks[o] for o in first_dependency["outputs"]
625
+ ]
626
+ blocks.__name__ = "Interface"
627
+ blocks.api_mode = True
628
+
629
+ return blocks
630
+
631
+ def __str__(self):
632
+ return self.__repr__()
633
+
634
+ def __repr__(self):
635
+ num_backend_fns = len([d for d in self.dependencies if d["backend_fn"]])
636
+ repr = f"Gradio Blocks instance: {num_backend_fns} backend functions"
637
+ repr += "\n" + "-" * len(repr)
638
+ for d, dependency in enumerate(self.dependencies):
639
+ if dependency["backend_fn"]:
640
+ repr += f"\nfn_index={d}"
641
+ repr += "\n inputs:"
642
+ for input_id in dependency["inputs"]:
643
+ block = self.blocks[input_id]
644
+ repr += "\n |-{}".format(str(block))
645
+ repr += "\n outputs:"
646
+ for output_id in dependency["outputs"]:
647
+ block = self.blocks[output_id]
648
+ repr += "\n |-{}".format(str(block))
649
+ return repr
650
+
651
+ def render(self):
652
+ if Context.root_block is not None:
653
+ if self._id in Context.root_block.blocks:
654
+ raise DuplicateBlockError(
655
+ f"A block with id: {self._id} has already been rendered in the current Blocks."
656
+ )
657
+ if not set(Context.root_block.blocks).isdisjoint(self.blocks):
658
+ raise DuplicateBlockError(
659
+ "At least one block in this Blocks has already been rendered."
660
+ )
661
+
662
+ Context.root_block.blocks.update(self.blocks)
663
+ Context.root_block.fns.extend(self.fns)
664
+ dependency_offset = len(Context.root_block.dependencies)
665
+ for i, dependency in enumerate(self.dependencies):
666
+ api_name = dependency["api_name"]
667
+ if api_name is not None:
668
+ api_name_ = utils.append_unique_suffix(
669
+ api_name,
670
+ [dep["api_name"] for dep in Context.root_block.dependencies],
671
+ )
672
+ if not (api_name == api_name_):
673
+ warnings.warn(
674
+ "api_name {} already exists, using {}".format(
675
+ api_name, api_name_
676
+ )
677
+ )
678
+ dependency["api_name"] = api_name_
679
+ dependency["cancels"] = [
680
+ c + dependency_offset for c in dependency["cancels"]
681
+ ]
682
+ # Recreate the cancel function so that it has the latest
683
+ # dependency fn indices. This is necessary to properly cancel
684
+ # events in the backend
685
+ if dependency["cancels"]:
686
+ updated_cancels = [
687
+ Context.root_block.dependencies[i]
688
+ for i in dependency["cancels"]
689
+ ]
690
+ new_fn = BlockFunction(
691
+ get_cancel_function(updated_cancels)[0],
692
+ [],
693
+ [],
694
+ False,
695
+ True,
696
+ False,
697
+ )
698
+ Context.root_block.fns[dependency_offset + i] = new_fn
699
+ Context.root_block.dependencies.append(dependency)
700
+ Context.root_block.temp_file_sets.extend(self.temp_file_sets)
701
+
702
+ if Context.block is not None:
703
+ Context.block.children.extend(self.children)
704
+ return self
705
+
706
+ def is_callable(self, fn_index: int = 0) -> bool:
707
+ """Checks if a particular Blocks function is callable (i.e. not stateful or a generator)."""
708
+ block_fn = self.fns[fn_index]
709
+ dependency = self.dependencies[fn_index]
710
+
711
+ if inspect.isasyncgenfunction(block_fn.fn):
712
+ return False
713
+ if inspect.isgeneratorfunction(block_fn.fn):
714
+ return False
715
+ for input_id in dependency["inputs"]:
716
+ block = self.blocks[input_id]
717
+ if getattr(block, "stateful", False):
718
+ return False
719
+ for output_id in dependency["outputs"]:
720
+ block = self.blocks[output_id]
721
+ if getattr(block, "stateful", False):
722
+ return False
723
+
724
+ return True
725
+
726
+ def __call__(self, *inputs, fn_index: int = 0, api_name: str | None = None):
727
+ """
728
+ Allows Blocks objects to be called as functions. Supply the parameters to the
729
+ function as positional arguments. To choose which function to call, use the
730
+ fn_index parameter, which must be a keyword argument.
731
+
732
+ Parameters:
733
+ *inputs: the parameters to pass to the function
734
+ fn_index: the index of the function to call (defaults to 0, which for Interfaces, is the default prediction function)
735
+ api_name: The api_name of the dependency to call. Will take precedence over fn_index.
736
+ """
737
+ if api_name is not None:
738
+ inferred_fn_index = next(
739
+ (
740
+ i
741
+ for i, d in enumerate(self.dependencies)
742
+ if d.get("api_name") == api_name
743
+ ),
744
+ None,
745
+ )
746
+ if inferred_fn_index is None:
747
+ raise InvalidApiName(f"Cannot find a function with api_name {api_name}")
748
+ fn_index = inferred_fn_index
749
+ if not (self.is_callable(fn_index)):
750
+ raise ValueError(
751
+ "This function is not callable because it is either stateful or is a generator. Please use the .launch() method instead to create an interactive user interface."
752
+ )
753
+
754
+ inputs = list(inputs)
755
+ processed_inputs = self.serialize_data(fn_index, inputs)
756
+ batch = self.dependencies[fn_index]["batch"]
757
+ if batch:
758
+ processed_inputs = [[inp] for inp in processed_inputs]
759
+
760
+ outputs = utils.synchronize_async(
761
+ self.process_api,
762
+ fn_index=fn_index,
763
+ inputs=processed_inputs,
764
+ request=None,
765
+ state={},
766
+ )
767
+ outputs = outputs["data"]
768
+
769
+ if batch:
770
+ outputs = [out[0] for out in outputs]
771
+
772
+ processed_outputs = self.deserialize_data(fn_index, outputs)
773
+ processed_outputs = utils.resolve_singleton(processed_outputs)
774
+
775
+ return processed_outputs
776
+
777
+ async def call_function(
778
+ self,
779
+ fn_index: int,
780
+ processed_input: List[Any],
781
+ iterator: Iterator[Any] | None = None,
782
+ requests: routes.Request | List[routes.Request] | None = None,
783
+ event_id: str | None = None,
784
+ ):
785
+ """
786
+ Calls function with given index and preprocessed input, and measures process time.
787
+ Parameters:
788
+ fn_index: index of function to call
789
+ processed_input: preprocessed input to pass to function
790
+ iterator: iterator to use if function is a generator
791
+ requests: requests to pass to function
792
+ event_id: id of event in queue
793
+ """
794
+ block_fn = self.fns[fn_index]
795
+ assert block_fn.fn, f"function with index {fn_index} not defined."
796
+ is_generating = False
797
+
798
+ if block_fn.inputs_as_dict:
799
+ processed_input = [
800
+ {
801
+ input_component: data
802
+ for input_component, data in zip(block_fn.inputs, processed_input)
803
+ }
804
+ ]
805
+
806
+ if isinstance(requests, list):
807
+ request = requests[0]
808
+ else:
809
+ request = requests
810
+ processed_input, progress_index = special_args(
811
+ block_fn.fn,
812
+ processed_input,
813
+ request,
814
+ )
815
+ progress_tracker = (
816
+ processed_input[progress_index] if progress_index is not None else None
817
+ )
818
+
819
+ start = time.time()
820
+
821
+ if iterator is None: # If not a generator function that has already run
822
+ if progress_tracker is not None and progress_index is not None:
823
+ progress_tracker, fn = create_tracker(
824
+ self, event_id, block_fn.fn, progress_tracker.track_tqdm
825
+ )
826
+ processed_input[progress_index] = progress_tracker
827
+ else:
828
+ fn = block_fn.fn
829
+
830
+ if inspect.iscoroutinefunction(fn):
831
+ prediction = await fn(*processed_input)
832
+ else:
833
+ prediction = await anyio.to_thread.run_sync(
834
+ fn, *processed_input, limiter=self.limiter
835
+ )
836
+ else:
837
+ prediction = None
838
+
839
+ if inspect.isasyncgenfunction(block_fn.fn):
840
+ raise ValueError("Gradio does not support async generators.")
841
+ if inspect.isgeneratorfunction(block_fn.fn):
842
+ if not self.enable_queue:
843
+ raise ValueError("Need to enable queue to use generators.")
844
+ try:
845
+ if iterator is None:
846
+ iterator = prediction
847
+ prediction = await anyio.to_thread.run_sync(
848
+ utils.async_iteration, iterator, limiter=self.limiter
849
+ )
850
+ is_generating = True
851
+ except StopAsyncIteration:
852
+ n_outputs = len(self.dependencies[fn_index].get("outputs"))
853
+ prediction = (
854
+ components._Keywords.FINISHED_ITERATING
855
+ if n_outputs == 1
856
+ else (components._Keywords.FINISHED_ITERATING,) * n_outputs
857
+ )
858
+ iterator = None
859
+
860
+ duration = time.time() - start
861
+
862
+ return {
863
+ "prediction": prediction,
864
+ "duration": duration,
865
+ "is_generating": is_generating,
866
+ "iterator": iterator,
867
+ }
868
+
869
+ def serialize_data(self, fn_index: int, inputs: List[Any]) -> List[Any]:
870
+ dependency = self.dependencies[fn_index]
871
+ processed_input = []
872
+
873
+ for i, input_id in enumerate(dependency["inputs"]):
874
+ block = self.blocks[input_id]
875
+ assert isinstance(
876
+ block, components.IOComponent
877
+ ), f"{block.__class__} Component with id {input_id} not a valid input component."
878
+ serialized_input = block.serialize(inputs[i])
879
+ processed_input.append(serialized_input)
880
+
881
+ return processed_input
882
+
883
+ def deserialize_data(self, fn_index: int, outputs: List[Any]) -> List[Any]:
884
+ dependency = self.dependencies[fn_index]
885
+ predictions = []
886
+
887
+ for o, output_id in enumerate(dependency["outputs"]):
888
+ block = self.blocks[output_id]
889
+ assert isinstance(
890
+ block, components.IOComponent
891
+ ), f"{block.__class__} Component with id {output_id} not a valid output component."
892
+ deserialized = block.deserialize(outputs[o])
893
+ predictions.append(deserialized)
894
+
895
+ return predictions
896
+
897
+ def preprocess_data(self, fn_index: int, inputs: List[Any], state: Dict[int, Any]):
898
+ block_fn = self.fns[fn_index]
899
+ dependency = self.dependencies[fn_index]
900
+
901
+ if block_fn.preprocess:
902
+ processed_input = []
903
+ for i, input_id in enumerate(dependency["inputs"]):
904
+ block = self.blocks[input_id]
905
+ assert isinstance(
906
+ block, components.Component
907
+ ), f"{block.__class__} Component with id {input_id} not a valid input component."
908
+ if getattr(block, "stateful", False):
909
+ processed_input.append(state.get(input_id))
910
+ else:
911
+ processed_input.append(block.preprocess(inputs[i]))
912
+ else:
913
+ processed_input = inputs
914
+ return processed_input
915
+
916
+ def postprocess_data(
917
+ self, fn_index: int, predictions: List | Dict, state: Dict[int, Any]
918
+ ):
919
+ block_fn = self.fns[fn_index]
920
+ dependency = self.dependencies[fn_index]
921
+ batch = dependency["batch"]
922
+
923
+ if type(predictions) is dict and len(predictions) > 0:
924
+ predictions = convert_component_dict_to_list(
925
+ dependency["outputs"], predictions
926
+ )
927
+
928
+ if len(dependency["outputs"]) == 1 and not (batch):
929
+ predictions = [
930
+ predictions,
931
+ ]
932
+
933
+ output = []
934
+ for i, output_id in enumerate(dependency["outputs"]):
935
+ if predictions[i] is components._Keywords.FINISHED_ITERATING:
936
+ output.append(None)
937
+ continue
938
+ block = self.blocks[output_id]
939
+ if getattr(block, "stateful", False):
940
+ if not utils.is_update(predictions[i]):
941
+ state[output_id] = predictions[i]
942
+ output.append(None)
943
+ else:
944
+ prediction_value = predictions[i]
945
+ if utils.is_update(prediction_value):
946
+ assert isinstance(prediction_value, dict)
947
+ prediction_value = postprocess_update_dict(
948
+ block=block,
949
+ update_dict=prediction_value,
950
+ postprocess=block_fn.postprocess,
951
+ )
952
+ elif block_fn.postprocess:
953
+ assert isinstance(
954
+ block, components.Component
955
+ ), f"{block.__class__} Component with id {output_id} not a valid output component."
956
+ prediction_value = block.postprocess(prediction_value)
957
+ output.append(prediction_value)
958
+ return output
959
+
960
+ async def process_api(
961
+ self,
962
+ fn_index: int,
963
+ inputs: List[Any],
964
+ state: Dict[int, Any],
965
+ request: routes.Request | List[routes.Request] | None = None,
966
+ iterators: Dict[int, Any] | None = None,
967
+ event_id: str | None = None,
968
+ ) -> Dict[str, Any]:
969
+ """
970
+ Processes API calls from the frontend. First preprocesses the data,
971
+ then runs the relevant function, then postprocesses the output.
972
+ Parameters:
973
+ fn_index: Index of function to run.
974
+ inputs: input data received from the frontend
975
+ username: name of user if authentication is set up (not used)
976
+ state: data stored from stateful components for session (key is input block id)
977
+ iterators: the in-progress iterators for each generator function (key is function index)
978
+ Returns: None
979
+ """
980
+ block_fn = self.fns[fn_index]
981
+ batch = self.dependencies[fn_index]["batch"]
982
+
983
+ if batch:
984
+ max_batch_size = self.dependencies[fn_index]["max_batch_size"]
985
+ batch_sizes = [len(inp) for inp in inputs]
986
+ batch_size = batch_sizes[0]
987
+ if inspect.isasyncgenfunction(block_fn.fn) or inspect.isgeneratorfunction(
988
+ block_fn.fn
989
+ ):
990
+ raise ValueError("Gradio does not support generators in batch mode.")
991
+ if not all(x == batch_size for x in batch_sizes):
992
+ raise ValueError(
993
+ f"All inputs to a batch function must have the same length but instead have sizes: {batch_sizes}."
994
+ )
995
+ if batch_size > max_batch_size:
996
+ raise ValueError(
997
+ f"Batch size ({batch_size}) exceeds the max_batch_size for this function ({max_batch_size})"
998
+ )
999
+
1000
+ inputs = [
1001
+ self.preprocess_data(fn_index, list(i), state) for i in zip(*inputs)
1002
+ ]
1003
+ result = await self.call_function(
1004
+ fn_index, list(zip(*inputs)), None, request
1005
+ )
1006
+ preds = result["prediction"]
1007
+ data = [
1008
+ self.postprocess_data(fn_index, list(o), state) for o in zip(*preds)
1009
+ ]
1010
+ data = list(zip(*data))
1011
+ is_generating, iterator = None, None
1012
+ else:
1013
+ inputs = self.preprocess_data(fn_index, inputs, state)
1014
+ iterator = iterators.get(fn_index, None) if iterators else None
1015
+ result = await self.call_function(
1016
+ fn_index, inputs, iterator, request, event_id
1017
+ )
1018
+ data = self.postprocess_data(fn_index, result["prediction"], state)
1019
+ is_generating, iterator = result["is_generating"], result["iterator"]
1020
+
1021
+ block_fn.total_runtime += result["duration"]
1022
+ block_fn.total_runs += 1
1023
+
1024
+ return {
1025
+ "data": data,
1026
+ "is_generating": is_generating,
1027
+ "iterator": iterator,
1028
+ "duration": result["duration"],
1029
+ "average_duration": block_fn.total_runtime / block_fn.total_runs,
1030
+ }
1031
+
1032
+ async def create_limiter(self):
1033
+ self.limiter = (
1034
+ None
1035
+ if self.max_threads == 40
1036
+ else CapacityLimiter(total_tokens=self.max_threads)
1037
+ )
1038
+
1039
+ def get_config(self):
1040
+ return {"type": "column"}
1041
+
1042
+ def get_config_file(self):
1043
+ config = {
1044
+ "version": routes.VERSION,
1045
+ "mode": self.mode,
1046
+ "dev_mode": self.dev_mode,
1047
+ "components": [],
1048
+ "theme": self.theme,
1049
+ "css": self.css,
1050
+ "title": self.title or "Gradio",
1051
+ "is_space": self.is_space,
1052
+ "enable_queue": getattr(self, "enable_queue", False), # launch attributes
1053
+ "show_error": getattr(self, "show_error", False),
1054
+ "show_api": self.show_api,
1055
+ "is_colab": utils.colab_check(),
1056
+ }
1057
+
1058
+ def getLayout(block):
1059
+ if not isinstance(block, BlockContext):
1060
+ return {"id": block._id}
1061
+ children_layout = []
1062
+ for child in block.children:
1063
+ children_layout.append(getLayout(child))
1064
+ return {"id": block._id, "children": children_layout}
1065
+
1066
+ config["layout"] = getLayout(self)
1067
+
1068
+ for _id, block in self.blocks.items():
1069
+ config["components"].append(
1070
+ {
1071
+ "id": _id,
1072
+ "type": (block.get_block_name()),
1073
+ "props": utils.delete_none(block.get_config())
1074
+ if hasattr(block, "get_config")
1075
+ else {},
1076
+ }
1077
+ )
1078
+ config["dependencies"] = self.dependencies
1079
+ return config
1080
+
1081
+ def __enter__(self):
1082
+ if Context.block is None:
1083
+ Context.root_block = self
1084
+ self.parent = Context.block
1085
+ Context.block = self
1086
+ return self
1087
+
1088
+ def __exit__(self, *args):
1089
+ super().fill_expected_parents()
1090
+ Context.block = self.parent
1091
+ # Configure the load events before root_block is reset
1092
+ self.attach_load_events()
1093
+ if self.parent is None:
1094
+ Context.root_block = None
1095
+ else:
1096
+ self.parent.children.extend(self.children)
1097
+ self.config = self.get_config_file()
1098
+ self.app = routes.App.create_app(self)
1099
+ self.progress_tracking = any(
1100
+ block_fn.fn is not None and special_args(block_fn.fn)[1] is not None
1101
+ for block_fn in self.fns
1102
+ )
1103
+
1104
+ @class_or_instancemethod
1105
+ def load(
1106
+ self_or_cls,
1107
+ fn: Callable | None = None,
1108
+ inputs: List[Component] | None = None,
1109
+ outputs: List[Component] | None = None,
1110
+ api_name: str | None = None,
1111
+ scroll_to_output: bool = False,
1112
+ show_progress: bool = True,
1113
+ queue=None,
1114
+ batch: bool = False,
1115
+ max_batch_size: int = 4,
1116
+ preprocess: bool = True,
1117
+ postprocess: bool = True,
1118
+ every: float | None = None,
1119
+ _js: str | None = None,
1120
+ *,
1121
+ name: str | None = None,
1122
+ src: str | None = None,
1123
+ api_key: str | None = None,
1124
+ alias: str | None = None,
1125
+ **kwargs,
1126
+ ) -> Blocks | Dict[str, Any] | None:
1127
+ """
1128
+ For reverse compatibility reasons, this is both a class method and an instance
1129
+ method, the two of which, confusingly, do two completely different things.
1130
+
1131
+
1132
+ Class method: loads a demo from a Hugging Face Spaces repo and creates it locally and returns a block instance. Equivalent to gradio.Interface.load()
1133
+
1134
+
1135
+ Instance method: adds event that runs as soon as the demo loads in the browser. Example usage below.
1136
+ Parameters:
1137
+ name: Class Method - the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")
1138
+ src: Class Method - the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
1139
+ api_key: Class Method - optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens
1140
+ alias: Class Method - optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)
1141
+ fn: Instance Method - the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
1142
+ inputs: Instance Method - List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
1143
+ outputs: Instance Method - List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
1144
+ api_name: Instance Method - Defining this parameter exposes the endpoint in the api docs
1145
+ scroll_to_output: Instance Method - If True, will scroll to output component on completion
1146
+ show_progress: Instance Method - If True, will show progress animation while pending
1147
+ queue: Instance Method - If True, will place the request on the queue, if the queue exists
1148
+ batch: Instance Method - If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
1149
+ max_batch_size: Instance Method - Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
1150
+ preprocess: Instance Method - If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
1151
+ postprocess: Instance Method - If False, will not run postprocessing of component data before returning 'fn' output to the browser.
1152
+ every: Instance Method - Run this event 'every' number of seconds. Interpreted in seconds. Queue must be enabled.
1153
+ Example:
1154
+ import gradio as gr
1155
+ import datetime
1156
+ with gr.Blocks() as demo:
1157
+ def get_time():
1158
+ return datetime.datetime.now().time()
1159
+ dt = gr.Textbox(label="Current time")
1160
+ demo.load(get_time, inputs=None, outputs=dt)
1161
+ demo.launch()
1162
+ """
1163
+ # _js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
1164
+ if isinstance(self_or_cls, type):
1165
+ if name is None:
1166
+ raise ValueError(
1167
+ "Blocks.load() requires passing parameters as keyword arguments"
1168
+ )
1169
+ return external.load_blocks_from_repo(name, src, api_key, alias, **kwargs)
1170
+ else:
1171
+ return self_or_cls.set_event_trigger(
1172
+ event_name="load",
1173
+ fn=fn,
1174
+ inputs=inputs,
1175
+ outputs=outputs,
1176
+ api_name=api_name,
1177
+ preprocess=preprocess,
1178
+ postprocess=postprocess,
1179
+ scroll_to_output=scroll_to_output,
1180
+ show_progress=show_progress,
1181
+ js=_js,
1182
+ queue=queue,
1183
+ batch=batch,
1184
+ max_batch_size=max_batch_size,
1185
+ every=every,
1186
+ no_target=True,
1187
+ )
1188
+
1189
+ def clear(self):
1190
+ """Resets the layout of the Blocks object."""
1191
+ self.blocks = {}
1192
+ self.fns = []
1193
+ self.dependencies = []
1194
+ self.children = []
1195
+ return self
1196
+
1197
+ @document()
1198
+ def queue(
1199
+ self,
1200
+ concurrency_count: int = 1,
1201
+ status_update_rate: float | Literal["auto"] = "auto",
1202
+ client_position_to_load_data: int | None = None,
1203
+ default_enabled: bool | None = None,
1204
+ api_open: bool = True,
1205
+ max_size: int | None = None,
1206
+ ):
1207
+ """
1208
+ You can control the rate of processed requests by creating a queue. This will allow you to set the number of requests to be processed at one time, and will let users know their position in the queue.
1209
+ Parameters:
1210
+ concurrency_count: Number of worker threads that will be processing requests from the queue concurrently. Increasing this number will increase the rate at which requests are processed, but will also increase the memory usage of the queue.
1211
+ status_update_rate: If "auto", Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds.
1212
+ client_position_to_load_data: DEPRECATED. This parameter is deprecated and has no effect.
1213
+ default_enabled: Deprecated and has no effect.
1214
+ api_open: If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue.
1215
+ max_size: The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited.
1216
+ Example:
1217
+ demo = gr.Interface(gr.Textbox(), gr.Image(), image_generator)
1218
+ demo.queue(concurrency_count=3)
1219
+ demo.launch()
1220
+ """
1221
+ if default_enabled is not None:
1222
+ warnings.warn(
1223
+ "The default_enabled parameter of queue has no effect and will be removed "
1224
+ "in a future version of gradio."
1225
+ )
1226
+ self.enable_queue = True
1227
+ self.api_open = api_open
1228
+ if client_position_to_load_data is not None:
1229
+ warnings.warn("The client_position_to_load_data parameter is deprecated.")
1230
+ self._queue = queueing.Queue(
1231
+ live_updates=status_update_rate == "auto",
1232
+ concurrency_count=concurrency_count,
1233
+ update_intervals=status_update_rate if status_update_rate != "auto" else 1,
1234
+ max_size=max_size,
1235
+ blocks_dependencies=self.dependencies,
1236
+ )
1237
+ self.config = self.get_config_file()
1238
+ return self
1239
+
1240
+ def launch(
1241
+ self,
1242
+ inline: bool | None = None,
1243
+ inbrowser: bool = False,
1244
+ share: bool | None = None,
1245
+ debug: bool = False,
1246
+ enable_queue: bool | None = None,
1247
+ max_threads: int = 40,
1248
+ auth: Callable | Tuple[str, str] | List[Tuple[str, str]] | None = None,
1249
+ auth_message: str | None = None,
1250
+ prevent_thread_lock: bool = False,
1251
+ show_error: bool = False,
1252
+ server_name: str | None = None,
1253
+ server_port: int | None = None,
1254
+ show_tips: bool = False,
1255
+ height: int = 500,
1256
+ width: int | str = "100%",
1257
+ encrypt: bool = False,
1258
+ favicon_path: str | None = None,
1259
+ ssl_keyfile: str | None = None,
1260
+ ssl_certfile: str | None = None,
1261
+ ssl_keyfile_password: str | None = None,
1262
+ quiet: bool = False,
1263
+ show_api: bool = True,
1264
+ _frontend: bool = True,
1265
+ ) -> Tuple[FastAPI, str, str]:
1266
+ """
1267
+ Launches a simple web server that serves the demo. Can also be used to create a
1268
+ public link used by anyone to access the demo from their browser by setting share=True.
1269
+
1270
+ Parameters:
1271
+ inline: whether to display in the interface inline in an iframe. Defaults to True in python notebooks; False otherwise.
1272
+ inbrowser: whether to automatically launch the interface in a new tab on the default browser.
1273
+ share: whether to create a publicly shareable link for the interface. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported.
1274
+ debug: if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.
1275
+ auth: If provided, username and password (or list of username-password tuples) required to access interface. Can also provide function that takes username and password and returns True if valid login.
1276
+ auth_message: If provided, HTML message provided on login page.
1277
+ prevent_thread_lock: If True, the interface will block the main thread while the server is running.
1278
+ show_error: If True, any errors in the interface will be displayed in an alert modal and printed in the browser console log
1279
+ server_port: will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.
1280
+ server_name: to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1".
1281
+ show_tips: if True, will occasionally show tips about new Gradio features
1282
+ enable_queue: DEPRECATED (use .queue() method instead.) if True, inference requests will be served through a queue instead of with parallel threads. Required for longer inference times (> 1min) to prevent timeout. The default option in HuggingFace Spaces is True. The default option elsewhere is False.
1283
+ max_threads: the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40). Applies whether the queue is enabled or not. But if queuing is enabled, this parameter is increaseed to be at least the concurrency_count of the queue.
1284
+ width: The width in pixels of the iframe element containing the interface (used if inline=True)
1285
+ height: The height in pixels of the iframe element containing the interface (used if inline=True)
1286
+ encrypt: If True, flagged data will be encrypted by key provided by creator at launch
1287
+ favicon_path: If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.
1288
+ ssl_keyfile: If a path to a file is provided, will use this as the private key file to create a local server running on https.
1289
+ ssl_certfile: If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.
1290
+ ssl_keyfile_password: If a password is provided, will use this with the ssl certificate for https.
1291
+ quiet: If True, suppresses most print statements.
1292
+ show_api: If True, shows the api docs in the footer of the app. Default True. If the queue is enabled, then api_open parameter of .queue() will determine if the api docs are shown, independent of the value of show_api.
1293
+ Returns:
1294
+ app: FastAPI app object that is running the demo
1295
+ local_url: Locally accessible link to the demo
1296
+ share_url: Publicly accessible link to the demo (if share=True, otherwise None)
1297
+ Example:
1298
+ import gradio as gr
1299
+ def reverse(text):
1300
+ return text[::-1]
1301
+ demo = gr.Interface(reverse, "text", "text")
1302
+ demo.launch(share=True, auth=("username", "password"))
1303
+ """
1304
+ self.dev_mode = False
1305
+ if (
1306
+ auth
1307
+ and not callable(auth)
1308
+ and not isinstance(auth[0], tuple)
1309
+ and not isinstance(auth[0], list)
1310
+ ):
1311
+ self.auth = [auth]
1312
+ else:
1313
+ self.auth = auth
1314
+ self.auth_message = auth_message
1315
+ self.show_tips = show_tips
1316
+ self.show_error = show_error
1317
+ self.height = height
1318
+ self.width = width
1319
+ self.favicon_path = favicon_path
1320
+
1321
+ if enable_queue is not None:
1322
+ self.enable_queue = enable_queue
1323
+ warnings.warn(
1324
+ "The `enable_queue` parameter has been deprecated. Please use the `.queue()` method instead.",
1325
+ DeprecationWarning,
1326
+ )
1327
+
1328
+ if self.is_space:
1329
+ self.enable_queue = self.enable_queue is not False
1330
+ else:
1331
+ self.enable_queue = self.enable_queue is True
1332
+ if self.enable_queue and not hasattr(self, "_queue"):
1333
+ self.queue()
1334
+ self.show_api = self.api_open if self.enable_queue else show_api
1335
+
1336
+ if not self.enable_queue and self.progress_tracking:
1337
+ raise ValueError("Progress tracking requires queuing to be enabled.")
1338
+
1339
+ for dep in self.dependencies:
1340
+ for i in dep["cancels"]:
1341
+ if not self.queue_enabled_for_fn(i):
1342
+ raise ValueError(
1343
+ "In order to cancel an event, the queue for that event must be enabled! "
1344
+ "You may get this error by either 1) passing a function that uses the yield keyword "
1345
+ "into an interface without enabling the queue or 2) defining an event that cancels "
1346
+ "another event without enabling the queue. Both can be solved by calling .queue() "
1347
+ "before .launch()"
1348
+ )
1349
+ if dep["batch"] and (
1350
+ dep["queue"] is False
1351
+ or (dep["queue"] is None and not self.enable_queue)
1352
+ ):
1353
+ raise ValueError("In order to use batching, the queue must be enabled.")
1354
+
1355
+ self.config = self.get_config_file()
1356
+ self.encrypt = encrypt
1357
+ self.max_threads = max(
1358
+ self._queue.max_thread_count if self.enable_queue else 0, max_threads
1359
+ )
1360
+ if self.encrypt:
1361
+ self.encryption_key = encryptor.get_key(
1362
+ getpass.getpass("Enter key for encryption: ")
1363
+ )
1364
+
1365
+ if self.is_running:
1366
+ assert isinstance(
1367
+ self.local_url, str
1368
+ ), f"Invalid local_url: {self.local_url}"
1369
+ if not (quiet):
1370
+ print(
1371
+ "Rerunning server... use `close()` to stop if you need to change `launch()` parameters.\n----"
1372
+ )
1373
+ else:
1374
+ server_name, server_port, local_url, app, server = networking.start_server(
1375
+ self,
1376
+ server_name,
1377
+ server_port,
1378
+ ssl_keyfile,
1379
+ ssl_certfile,
1380
+ ssl_keyfile_password,
1381
+ )
1382
+ self.server_name = server_name
1383
+ self.local_url = local_url
1384
+ self.server_port = server_port
1385
+ self.server_app = app
1386
+ self.server = server
1387
+ self.is_running = True
1388
+ self.is_colab = utils.colab_check()
1389
+ self.protocol = (
1390
+ "https"
1391
+ if self.local_url.startswith("https") or self.is_colab
1392
+ else "http"
1393
+ )
1394
+
1395
+ if self.enable_queue:
1396
+ self._queue.set_url(self.local_url)
1397
+
1398
+ # Cannot run async functions in background other than app's scope.
1399
+ # Workaround by triggering the app endpoint
1400
+ requests.get(f"{self.local_url}startup-events")
1401
+
1402
+ if self.enable_queue:
1403
+ if self.encrypt:
1404
+ raise ValueError("Cannot queue with encryption enabled.")
1405
+ utils.launch_counter()
1406
+
1407
+ self.share = (
1408
+ share
1409
+ if share is not None
1410
+ else True
1411
+ if self.is_colab and self.enable_queue
1412
+ else False
1413
+ )
1414
+
1415
+ # If running in a colab or not able to access localhost,
1416
+ # a shareable link must be created.
1417
+ if _frontend and (not networking.url_ok(self.local_url)) and (not self.share):
1418
+ raise ValueError(
1419
+ "When localhost is not accessible, a shareable link must be created. Please set share=True."
1420
+ )
1421
+
1422
+ if self.is_colab:
1423
+ if not quiet:
1424
+ if debug:
1425
+ print(strings.en["COLAB_DEBUG_TRUE"])
1426
+ else:
1427
+ print(strings.en["COLAB_DEBUG_FALSE"])
1428
+ if not self.share:
1429
+ print(strings.en["COLAB_WARNING"].format(self.server_port))
1430
+ if self.enable_queue and not self.share:
1431
+ raise ValueError(
1432
+ "When using queueing in Colab, a shareable link must be created. Please set share=True."
1433
+ )
1434
+ else:
1435
+ if not self.share:
1436
+ print(f'Running on local URL: https://{self.server_name}')
1437
+
1438
+ if self.share:
1439
+ if self.is_space:
1440
+ raise RuntimeError("Share is not supported when you are in Spaces")
1441
+ try:
1442
+ if self.share_url is None:
1443
+ self.share_url = networking.setup_tunnel(
1444
+ self.server_name, self.server_port
1445
+ )
1446
+ print(strings.en["SHARE_LINK_DISPLAY"].format(self.share_url))
1447
+ if not (quiet):
1448
+ print('\u2714 Connected')
1449
+ except RuntimeError:
1450
+ if self.analytics_enabled:
1451
+ utils.error_analytics(self.ip_address, "Not able to set up tunnel")
1452
+ self.share_url = None
1453
+ self.share = False
1454
+ print(strings.en["COULD_NOT_GET_SHARE_LINK"])
1455
+ else:
1456
+ if not (quiet):
1457
+ print('\u2714 Connected')
1458
+ self.share_url = None
1459
+
1460
+ if inbrowser:
1461
+ link = self.share_url if self.share and self.share_url else self.local_url
1462
+ webbrowser.open(link)
1463
+
1464
+ # Check if running in a Python notebook in which case, display inline
1465
+ if inline is None:
1466
+ inline = utils.ipython_check() and (self.auth is None)
1467
+ if inline:
1468
+ if self.auth is not None:
1469
+ print(
1470
+ "Warning: authentication is not supported inline. Please"
1471
+ "click the link to access the interface in a new tab."
1472
+ )
1473
+ try:
1474
+ from IPython.display import HTML, Javascript, display # type: ignore
1475
+
1476
+ if self.share and self.share_url:
1477
+ while not networking.url_ok(self.share_url):
1478
+ time.sleep(0.25)
1479
+ display(
1480
+ HTML(
1481
+ f'<div><iframe src="{self.share_url}" width="{self.width}" height="{self.height}" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>'
1482
+ )
1483
+ )
1484
+ elif self.is_colab:
1485
+ # modified from /usr/local/lib/python3.7/dist-packages/google/colab/output/_util.py within Colab environment
1486
+ code = """(async (port, path, width, height, cache, element) => {
1487
+ if (!google.colab.kernel.accessAllowed && !cache) {
1488
+ return;
1489
+ }
1490
+ element.appendChild(document.createTextNode(''));
1491
+ const url = await google.colab.kernel.proxyPort(port, {cache});
1492
+
1493
+ const external_link = document.createElement('div');
1494
+ external_link.innerHTML = `
1495
+ <div style="font-family: monospace; margin-bottom: 0.5rem">
1496
+ Running on <a href=${new URL(path, url).toString()} target="_blank">
1497
+ https://localhost:${port}${path}
1498
+ </a>
1499
+ </div>
1500
+ `;
1501
+ element.appendChild(external_link);
1502
+
1503
+ const iframe = document.createElement('iframe');
1504
+ iframe.src = new URL(path, url).toString();
1505
+ iframe.height = height;
1506
+ iframe.allow = "autoplay; camera; microphone; clipboard-read; clipboard-write;"
1507
+ iframe.width = width;
1508
+ iframe.style.border = 0;
1509
+ element.appendChild(iframe);
1510
+ })""" + "({port}, {path}, {width}, {height}, {cache}, window.element)".format(
1511
+ port=json.dumps(self.server_port),
1512
+ path=json.dumps("/"),
1513
+ width=json.dumps(self.width),
1514
+ height=json.dumps(self.height),
1515
+ cache=json.dumps(False),
1516
+ )
1517
+
1518
+ display(Javascript(code))
1519
+ else:
1520
+ display(
1521
+ HTML(
1522
+ f'<div><iframe src="{self.local_url}" width="{self.width}" height="{self.height}" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>'
1523
+ )
1524
+ )
1525
+ except ImportError:
1526
+ pass
1527
+
1528
+ if getattr(self, "analytics_enabled", False):
1529
+ data = {
1530
+ "launch_method": "browser" if inbrowser else "inline",
1531
+ "is_google_colab": self.is_colab,
1532
+ "is_sharing_on": self.share,
1533
+ "share_url": self.share_url,
1534
+ "ip_address": self.ip_address,
1535
+ "enable_queue": self.enable_queue,
1536
+ "show_tips": self.show_tips,
1537
+ "server_name": server_name,
1538
+ "server_port": server_port,
1539
+ "is_spaces": self.is_space,
1540
+ "mode": self.mode,
1541
+ }
1542
+ utils.launch_analytics(data)
1543
+
1544
+ utils.show_tip(self)
1545
+
1546
+ # Block main thread if debug==True
1547
+ if debug or int(os.getenv("GRADIO_DEBUG", 0)) == 1:
1548
+ self.block_thread()
1549
+ # Block main thread if running in a script to stop script from exiting
1550
+ is_in_interactive_mode = bool(getattr(sys, "ps1", sys.flags.interactive))
1551
+
1552
+ if not prevent_thread_lock and not is_in_interactive_mode:
1553
+ self.block_thread()
1554
+
1555
+ return TupleNoPrint((self.server_app, self.local_url, self.share_url))
1556
+
1557
+ def integrate(
1558
+ self,
1559
+ comet_ml: comet_ml.Experiment | None = None,
1560
+ wandb: ModuleType | None = None,
1561
+ mlflow: ModuleType | None = None,
1562
+ ) -> None:
1563
+ """
1564
+ A catch-all method for integrating with other libraries. This method should be run after launch()
1565
+ Parameters:
1566
+ comet_ml: If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard
1567
+ wandb: If the wandb module is provided, will integrate with it and appear on WandB dashboard
1568
+ mlflow: If the mlflow module is provided, will integrate with the experiment and appear on ML Flow dashboard
1569
+ """
1570
+ analytics_integration = ""
1571
+ if comet_ml is not None:
1572
+ analytics_integration = "CometML"
1573
+ comet_ml.log_other("Created from", "Gradio")
1574
+ if self.share_url is not None:
1575
+ comet_ml.log_text("gradio: " + self.share_url)
1576
+ comet_ml.end()
1577
+ elif self.local_url:
1578
+ comet_ml.log_text("gradio: " + self.local_url)
1579
+ comet_ml.end()
1580
+ else:
1581
+ raise ValueError("Please run `launch()` first.")
1582
+ if wandb is not None:
1583
+ analytics_integration = "WandB"
1584
+ if self.share_url is not None:
1585
+ wandb.log(
1586
+ {
1587
+ "Gradio panel": wandb.Html(
1588
+ '<iframe src="'
1589
+ + self.share_url
1590
+ + '" width="'
1591
+ + str(self.width)
1592
+ + '" height="'
1593
+ + str(self.height)
1594
+ + '" frameBorder="0"></iframe>'
1595
+ )
1596
+ }
1597
+ )
1598
+ else:
1599
+ print(
1600
+ "The WandB integration requires you to "
1601
+ "`launch(share=True)` first."
1602
+ )
1603
+ if mlflow is not None:
1604
+ analytics_integration = "MLFlow"
1605
+ if self.share_url is not None:
1606
+ mlflow.log_param("Gradio Interface Share Link", self.share_url)
1607
+ else:
1608
+ mlflow.log_param("Gradio Interface Local Link", self.local_url)
1609
+ if self.analytics_enabled and analytics_integration:
1610
+ data = {"integration": analytics_integration}
1611
+ utils.integration_analytics(data)
1612
+
1613
+ def close(self, verbose: bool = True) -> None:
1614
+ """
1615
+ Closes the Interface that was launched and frees the port.
1616
+ """
1617
+ try:
1618
+ if self.enable_queue:
1619
+ self._queue.close()
1620
+ self.server.close()
1621
+ self.is_running = False
1622
+ if verbose:
1623
+ print("Closing server running on port: {}".format(self.server_port))
1624
+ except (AttributeError, OSError): # can't close if not running
1625
+ pass
1626
+
1627
+ def block_thread(
1628
+ self,
1629
+ ) -> None:
1630
+ """Block main thread until interrupted by user."""
1631
+ try:
1632
+ while True:
1633
+ time.sleep(0.1)
1634
+ except (KeyboardInterrupt, OSError):
1635
+ print("Keyboard interruption in main thread... closing server.")
1636
+ self.server.close()
1637
+ for tunnel in CURRENT_TUNNELS:
1638
+ tunnel.kill()
1639
+
1640
+ def attach_load_events(self):
1641
+ """Add a load event for every component whose initial value should be randomized."""
1642
+ if Context.root_block:
1643
+ for component in Context.root_block.blocks.values():
1644
+ if (
1645
+ isinstance(component, components.IOComponent)
1646
+ and component.load_event_to_attach
1647
+ ):
1648
+ load_fn, every = component.load_event_to_attach
1649
+ # Use set_event_trigger to avoid ambiguity between load class/instance method
1650
+ self.set_event_trigger(
1651
+ "load",
1652
+ load_fn,
1653
+ None,
1654
+ component,
1655
+ no_target=True,
1656
+ queue=False,
1657
+ every=every,
1658
+ )
1659
+
1660
+ def startup_events(self):
1661
+ """Events that should be run when the app containing this block starts up."""
1662
+
1663
+ if self.enable_queue:
1664
+ utils.run_coro_in_background(self._queue.start, (self.progress_tracking,))
1665
+ utils.run_coro_in_background(self.create_limiter)
1666
+
1667
+ def queue_enabled_for_fn(self, fn_index: int):
1668
+ if self.dependencies[fn_index]["queue"] is None:
1669
+ return self.enable_queue
1670
+ return self.dependencies[fn_index]["queue"]
fm23da_files/frozen_dict.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The Flax Authors.
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
+ """Frozen Dictionary."""
16
+
17
+ import collections
18
+ from typing import Any, TypeVar, Mapping, Dict, Tuple, Union, Hashable
19
+
20
+ from flax import serialization
21
+ import jax
22
+
23
+
24
+ class FrozenKeysView(collections.abc.KeysView):
25
+ """A wrapper for a more useful repr of the keys in a frozen dict."""
26
+
27
+ def __repr__(self):
28
+ return f'frozen_dict_keys({list(self)})'
29
+
30
+
31
+ class FrozenValuesView(collections.abc.ValuesView):
32
+ """A wrapper for a more useful repr of the values in a frozen dict."""
33
+
34
+ def __repr__(self):
35
+ return f'frozen_dict_values({list(self)})'
36
+
37
+
38
+ K = TypeVar('K')
39
+ V = TypeVar('V')
40
+
41
+
42
+ def _indent(x, num_spaces):
43
+ indent_str = ' ' * num_spaces
44
+ lines = x.split('\n')
45
+ assert not lines[-1]
46
+ # skip the final line because it's empty and should not be indented.
47
+ return '\n'.join(indent_str + line for line in lines[:-1]) + '\n'
48
+
49
+
50
+ # TODO(ivyzheng): change to register_pytree_with_keys_class after JAX release.
51
+ @jax.tree_util.register_pytree_node_class
52
+ class FrozenDict(Mapping[K, V]):
53
+ """An immutable variant of the Python dict."""
54
+ __slots__ = ('_dict', '_hash')
55
+
56
+ def __init__(self, *args, __unsafe_skip_copy__=False, **kwargs): # pylint: disable=invalid-name
57
+ # make sure the dict is as
58
+ xs = dict(*args, **kwargs)
59
+ if __unsafe_skip_copy__:
60
+ self._dict = xs
61
+ else:
62
+ self._dict = _prepare_freeze(xs)
63
+
64
+ self._hash = None
65
+
66
+ def __getitem__(self, key):
67
+ v = self._dict[key]
68
+ if isinstance(v, dict):
69
+ return FrozenDict(v)
70
+ return v
71
+
72
+ def __setitem__(self, key, value):
73
+ raise ValueError('FrozenDict is immutable.')
74
+
75
+ def __contains__(self, key):
76
+ return key in self._dict
77
+
78
+ def __iter__(self):
79
+ return iter(self._dict)
80
+
81
+ def __len__(self):
82
+ return len(self._dict)
83
+
84
+ def __repr__(self):
85
+ return self.pretty_repr()
86
+
87
+ def __reduce__(self):
88
+ return FrozenDict, (self.unfreeze(),)
89
+
90
+ def pretty_repr(self, num_spaces=4):
91
+ """Returns an indented representation of the nested dictionary."""
92
+ def pretty_dict(x):
93
+ if not isinstance(x, dict):
94
+ return repr(x)
95
+ rep = ''
96
+ for key, val in x.items():
97
+ rep += f'{key}: {pretty_dict(val)},\n'
98
+ if rep:
99
+ return '{\n' + _indent(rep, num_spaces) + '}'
100
+ else:
101
+ return '{}'
102
+ return f'FrozenDict({pretty_dict(self._dict)})'
103
+
104
+ def __hash__(self):
105
+ if self._hash is None:
106
+ h = 0
107
+ for key, value in self.items():
108
+ h ^= hash((key, value))
109
+ self._hash = h
110
+ return self._hash
111
+
112
+ def copy(self, add_or_replace: Mapping[K, V]) -> 'FrozenDict[K, V]':
113
+ """Create a new FrozenDict with additional or replaced entries."""
114
+ return type(self)({**self, **unfreeze(add_or_replace)}) # type: ignore[arg-type]
115
+
116
+ def keys(self):
117
+ return FrozenKeysView(self)
118
+
119
+ def values(self):
120
+ return FrozenValuesView(self)
121
+
122
+ def items(self):
123
+ for key in self._dict:
124
+ yield (key, self[key])
125
+
126
+ def pop(self, key: K) -> Tuple['FrozenDict[K, V]', V]:
127
+ """Create a new FrozenDict where one entry is removed.
128
+
129
+ Example::
130
+
131
+ state, params = variables.pop('params')
132
+
133
+ Args:
134
+ key: the key to remove from the dict
135
+ Returns:
136
+ A pair with the new FrozenDict and the removed value.
137
+ """
138
+ value = self[key]
139
+ new_dict = dict(self._dict)
140
+ new_dict.pop(key)
141
+ new_self = type(self)(new_dict)
142
+ return new_self, value
143
+
144
+ def unfreeze(self) -> Dict[K, V]:
145
+ """Unfreeze this FrozenDict.
146
+
147
+ Returns:
148
+ An unfrozen version of this FrozenDict instance.
149
+ """
150
+ return unfreeze(self)
151
+
152
+ # TODO(ivyzheng): remove this after JAX 0.4.6 release.
153
+ def tree_flatten(self) -> Tuple[Tuple[Any, ...], Hashable]:
154
+ """Flattens this FrozenDict.
155
+
156
+ Returns:
157
+ A flattened version of this FrozenDict instance.
158
+ """
159
+ sorted_keys = sorted(self._dict)
160
+ return tuple([self._dict[k] for k in sorted_keys]), tuple(sorted_keys)
161
+
162
+ @classmethod
163
+ def tree_unflatten(cls, keys, values):
164
+ # data is already deep copied due to tree map mechanism
165
+ # we can skip the deep copy in the constructor
166
+ return cls({k: v for k, v in zip(keys, values)}, __unsafe_skip_copy__=True)
167
+
168
+
169
+ #jax.tree_util.register_keypaths(
170
+ # FrozenDict, lambda fd: tuple(jax.tree_util.DictKey(k) for k in sorted(fd))
171
+ #)
172
+
173
+
174
+ def _prepare_freeze(xs: Any) -> Any:
175
+ """Deep copy unfrozen dicts to make the dictionary FrozenDict safe."""
176
+ if isinstance(xs, FrozenDict):
177
+ # we can safely ref share the internal state of a FrozenDict
178
+ # because it is immutable.
179
+ return xs._dict # pylint: disable=protected-access
180
+ if not isinstance(xs, dict):
181
+ # return a leaf as is.
182
+ return xs
183
+ # recursively copy dictionary to avoid ref sharing
184
+ return {key: _prepare_freeze(val) for key, val in xs.items()}
185
+
186
+
187
+ def freeze(xs: Mapping[Any, Any]) -> FrozenDict[Any, Any]:
188
+ """Freeze a nested dict.
189
+
190
+ Makes a nested `dict` immutable by transforming it into `FrozenDict`.
191
+
192
+ Args:
193
+ xs: Dictionary to freeze (a regualr Python dict).
194
+ Returns:
195
+ The frozen dictionary.
196
+ """
197
+ return FrozenDict(xs)
198
+
199
+
200
+ def unfreeze(x: Union[FrozenDict, Dict[str, Any]]) -> Dict[Any, Any]:
201
+ """Unfreeze a FrozenDict.
202
+
203
+ Makes a mutable copy of a `FrozenDict` mutable by transforming
204
+ it into (nested) dict.
205
+
206
+ Args:
207
+ x: Frozen dictionary to unfreeze.
208
+ Returns:
209
+ The unfrozen dictionary (a regular Python dict).
210
+ """
211
+ if isinstance(x, FrozenDict):
212
+ # deep copy internal state of a FrozenDict
213
+ # the dict branch would also work here but
214
+ # it is much less performant because jax.tree_util.tree_map
215
+ # uses an optimized C implementation.
216
+ return jax.tree_util.tree_map(lambda y: y, x._dict) # type: ignore
217
+ elif isinstance(x, dict):
218
+ ys = {}
219
+ for key, value in x.items():
220
+ ys[key] = unfreeze(value)
221
+ return ys
222
+ else:
223
+ return x
224
+
225
+
226
+ def copy(x: Union[FrozenDict, Dict[str, Any]], add_or_replace: Union[FrozenDict, Dict[str, Any]]) -> Union[FrozenDict, Dict[str, Any]]:
227
+ """Create a new dict with additional and/or replaced entries. This is a utility
228
+ function that can act on either a FrozenDict or regular dict and mimics the
229
+ behavior of `FrozenDict.copy`.
230
+
231
+ Example::
232
+
233
+ new_variables = copy(variables, {'additional_entries': 1})
234
+
235
+ Args:
236
+ x: the dictionary to be copied and updated
237
+ add_or_replace: dictionary of key-value pairs to add or replace in the dict x
238
+ Returns:
239
+ A new dict with the additional and/or replaced entries.
240
+ """
241
+
242
+ if isinstance(x, FrozenDict):
243
+ return x.copy(add_or_replace)
244
+ elif isinstance(x, dict):
245
+ new_dict = jax.tree_map(lambda x: x, x) # make a deep copy of dict x
246
+ new_dict.update(add_or_replace)
247
+ return new_dict
248
+ raise TypeError(f'Expected FrozenDict or dict, got {type(x)}')
249
+
250
+
251
+ def pop(x: Union[FrozenDict, Dict[str, Any]], key: str) -> Tuple[Union[FrozenDict, Dict[str, Any]], Any]:
252
+ """Create a new dict where one entry is removed. This is a utility
253
+ function for regular dicts that mimics the behavior of `FrozenDict.pop`.
254
+
255
+ Example::
256
+
257
+ state, params = pop(variables, 'params')
258
+
259
+ Args:
260
+ x: the dictionary to remove the entry from
261
+ key: the key to remove from the dict
262
+ Returns:
263
+ A pair with the new dict and the removed value.
264
+ """
265
+
266
+ if isinstance(x, FrozenDict):
267
+ return x.pop(key)
268
+ elif isinstance(x, dict):
269
+ new_dict = jax.tree_map(lambda x: x, x) # make a deep copy of dict x
270
+ value = new_dict.pop(key)
271
+ return new_dict, value
272
+ raise TypeError(f'Expected FrozenDict or dict, got {type(x)}')
273
+
274
+
275
+ def _frozen_dict_state_dict(xs):
276
+ return {key: serialization.to_state_dict(value) for key, value in xs.items()}
277
+
278
+
279
+ def _restore_frozen_dict(xs, states):
280
+ diff = set(map(str, xs.keys())).difference(states.keys())
281
+ if diff:
282
+ raise ValueError('The target dict keys and state dict keys do not match,'
283
+ f' target dict contains keys {diff} which are not present in state dict '
284
+ f'at path {serialization.current_path()}')
285
+
286
+ return FrozenDict(
287
+ {key: serialization.from_state_dict(value, states[key], name=key)
288
+ for key, value in xs.items()})
289
+
290
+
291
+ serialization.register_serialization_state(
292
+ FrozenDict,
293
+ _frozen_dict_state_dict,
294
+ _restore_frozen_dict)
fm23da_files/paths.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+ import modules.safe
5
+
6
+ script_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
7
+
8
+ # Parse the --data-dir flag first so we can use it as a base for our other argument default values
9
+ parser = argparse.ArgumentParser(add_help=False)
10
+ parser.add_argument("--data-dir", type=str, default=os.path.dirname(os.path.dirname(os.path.realpath(__file__))), help="base path where all user data is stored",)
11
+ cmd_opts_pre = parser.parse_known_args()[0]
12
+ data_path = cmd_opts_pre.data_dir
13
+ models_path = os.path.join(data_path, "models")
14
+
15
+ # data_path = cmd_opts_pre.data
16
+ sys.path.insert(0, script_path)
17
+
18
+ # search for directory of stable diffusion in following places
19
+ sd_path = None
20
+ possible_sd_paths = [os.path.join(script_path, '/content/gdrive/MyDrive/sd/stablediffusion'), '.', os.path.dirname(script_path)]
21
+ for possible_sd_path in possible_sd_paths:
22
+ if os.path.exists(os.path.join(possible_sd_path, 'ldm/models/diffusion/ddpm.py')):
23
+ sd_path = os.path.abspath(possible_sd_path)
24
+ break
25
+
26
+ assert sd_path is not None, "Couldn't find Stable Diffusion in any of: " + str(possible_sd_paths)
27
+
28
+ path_dirs = [
29
+ (sd_path, 'ldm', 'Stable Diffusion', []),
30
+ (os.path.join(sd_path, 'src/taming-transformers'), 'taming', 'Taming Transformers', []),
31
+ (os.path.join(sd_path, 'src/codeformer'), 'inference_codeformer.py', 'CodeFormer', []),
32
+ (os.path.join(sd_path, 'src/blip'), 'models/blip.py', 'BLIP', []),
33
+ (os.path.join(sd_path, 'src/k-diffusion'), 'k_diffusion/sampling.py', 'k_diffusion', ["atstart"]),
34
+ ]
35
+
36
+ paths = {}
37
+
38
+ for d, must_exist, what, options in path_dirs:
39
+ must_exist_path = os.path.abspath(os.path.join(script_path, d, must_exist))
40
+ if not os.path.exists(must_exist_path):
41
+ print(f"Warning: {what} not found at path {must_exist_path}", file=sys.stderr)
42
+ else:
43
+ d = os.path.abspath(d)
44
+ if "atstart" in options:
45
+ sys.path.insert(0, d)
46
+ else:
47
+ sys.path.append(d)
48
+ paths[what] = d
49
+
50
+ class Prioritize:
51
+ def __init__(self, name):
52
+ self.name = name
53
+ self.path = None
54
+
55
+ def __enter__(self):
56
+ self.path = sys.path.copy()
57
+ sys.path = [paths[self.name]] + sys.path
58
+
59
+ def __exit__(self, exc_type, exc_val, exc_tb):
60
+ sys.path = self.path
61
+ self.path = None
precompiled/README.md ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # precompiled xformers files
2
+ T4 + P100 + V100 + A100
precompiled/T4/T4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7704cb0c745caa4612fe7664fb5d1f77e2ecd71bd056f48f968ad2c7c065762
3
+ size 32252700
precompiled/T4/xfr ADDED
Binary file (313 kB). View file