Upload 221 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- extensions/sd-webui-infinite-image-browsing/.env.example +49 -0
- extensions/sd-webui-infinite-image-browsing/.github/FUNDING.yml +4 -0
- extensions/sd-webui-infinite-image-browsing/.github/wechat_funding.jpg +3 -0
- extensions/sd-webui-infinite-image-browsing/.github/workflows/tauri_app_build.yml +231 -0
- extensions/sd-webui-infinite-image-browsing/.gitignore +22 -0
- extensions/sd-webui-infinite-image-browsing/.vscode/settings.json +6 -0
- extensions/sd-webui-infinite-image-browsing/LICENSE +21 -0
- extensions/sd-webui-infinite-image-browsing/README-zh.md +162 -0
- extensions/sd-webui-infinite-image-browsing/README.md +178 -0
- extensions/sd-webui-infinite-image-browsing/app.py +299 -0
- extensions/sd-webui-infinite-image-browsing/install.py +28 -0
- extensions/sd-webui-infinite-image-browsing/javascript/index.js +186 -0
- extensions/sd-webui-infinite-image-browsing/migrate.py +84 -0
- extensions/sd-webui-infinite-image-browsing/plugins/.gitkeep +0 -0
- extensions/sd-webui-infinite-image-browsing/requirements.txt +9 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/api.py +1223 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/db/datamodel.py +890 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/db/update_image_data.py +199 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/dir_cover_cache.py +53 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/fastapi_video.py +86 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/img_cache_gen.py +58 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/logger.py +20 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/comfyui.py +51 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/fooocus.py +77 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/index.py +40 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/invoke_ai.py +64 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/model.py +18 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/novelai.py +44 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/sd_webui.py +35 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/sd_webui_stealth.py +157 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/stable_swarm_ui.py +61 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/plugin.py +36 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/seq.py +21 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/tool.py +746 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib/video_cover_gen.py +59 -0
- extensions/sd-webui-infinite-image-browsing/scripts/iib_setup.py +86 -0
- extensions/sd-webui-infinite-image-browsing/style.css +3 -0
- extensions/sd-webui-infinite-image-browsing/vue/.eslintrc.cjs +31 -0
- extensions/sd-webui-infinite-image-browsing/vue/.gitignore +22 -0
- extensions/sd-webui-infinite-image-browsing/vue/.prettierrc.json +8 -0
- extensions/sd-webui-infinite-image-browsing/vue/.vscode/extensions.json +3 -0
- extensions/sd-webui-infinite-image-browsing/vue/README.md +47 -0
- extensions/sd-webui-infinite-image-browsing/vue/build.ts +27 -0
- extensions/sd-webui-infinite-image-browsing/vue/components.d.ts +57 -0
- extensions/sd-webui-infinite-image-browsing/vue/dist/assets/Checkbox-5fa7cbf6.js +1 -0
- extensions/sd-webui-infinite-image-browsing/vue/dist/assets/FileItem-b2542180.js +3 -0
- extensions/sd-webui-infinite-image-browsing/vue/dist/assets/FileItem-fb268ce8.css +1 -0
- extensions/sd-webui-infinite-image-browsing/vue/dist/assets/ImgSliPagePane-5f17c067.js +1 -0
- extensions/sd-webui-infinite-image-browsing/vue/dist/assets/ImgSliPagePane-868b21f8.css +1 -0
.gitattributes
CHANGED
@@ -61,3 +61,4 @@ stable-diffusion-webui-reForge/extensions-builtin/forge_legacy_preprocessors/ann
|
|
61 |
stable-diffusion-webui-reForge/modules/Roboto-Regular.ttf filter=lfs diff=lfs merge=lfs -text
|
62 |
extensions-builtin/forge_legacy_preprocessors/annotator/clipvision/clip_vision_h_uc.data filter=lfs diff=lfs merge=lfs -text
|
63 |
modules/Roboto-Regular.ttf filter=lfs diff=lfs merge=lfs -text
|
|
|
|
61 |
stable-diffusion-webui-reForge/modules/Roboto-Regular.ttf filter=lfs diff=lfs merge=lfs -text
|
62 |
extensions-builtin/forge_legacy_preprocessors/annotator/clipvision/clip_vision_h_uc.data filter=lfs diff=lfs merge=lfs -text
|
63 |
modules/Roboto-Regular.ttf filter=lfs diff=lfs merge=lfs -text
|
64 |
+
extensions/sd-webui-infinite-image-browsing/vue/src-tauri/icons/icon.icns filter=lfs diff=lfs merge=lfs -text
|
extensions/sd-webui-infinite-image-browsing/.env.example
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This document is used for additional control over the security and privacy of IIB. By default, IIB is already sufficiently secure, and you do not need to take any additional actions.
|
2 |
+
# Copy this file and rename it to ".env" . Then, fill in the necessary values for your specific use case.
|
3 |
+
# Remember to never share your .env file with anyone else as it may contain sensitive information.
|
4 |
+
|
5 |
+
# This attribute is used for authentication. If you input a key here, it will be validated for authentication purposes.
|
6 |
+
# It will be prompted to enter your key when you open the extension. If the authentication fails, all your requests will be rejected.
|
7 |
+
IIB_SECRET_KEY=
|
8 |
+
|
9 |
+
# Configuring the server-side language for this extension,
|
10 |
+
# including the tab title and most of the server-side error messages returned. Options are 'zh', 'en', or 'auto'.
|
11 |
+
# If you want to configure the language for the front-end pages, please set it on the extension's global settings page.
|
12 |
+
IIB_SERVER_LANG=auto
|
13 |
+
|
14 |
+
# This configuration parameter specifies the maximum number of database file backups for the IIB .
|
15 |
+
IIB_DB_FILE_BACKUP_MAX=8
|
16 |
+
|
17 |
+
# Set the cache directory for IIB, including image cache and video cover cache.
|
18 |
+
# The default is the system's temporary directory, but if you want to specify a custom directory, set it here.
|
19 |
+
# You can use --generate_video_cover and --generate_image_cache to pre-generate the cache.
|
20 |
+
# IIB_CACHE_DIR=
|
21 |
+
|
22 |
+
|
23 |
+
# ---------------------------- ACCESS_CONTROL ----------------------------
|
24 |
+
|
25 |
+
# Used to configure whether to enable access control to the file system.
|
26 |
+
# If enabled, only access to the provided pre-set folders (including those provided by sd-webui and manually \
|
27 |
+
# added to Quick Move or specified via IIB_ACCESS_CONTROL_ALLOWED_PATHS) will be allowed.
|
28 |
+
# The available options are 'enable', 'disable', and 'auto'.
|
29 |
+
# The default value is 'auto', which will be determined based on the command-line parameters used to start sd-webui (such as --server-name, --share, --listen).
|
30 |
+
IIB_ACCESS_CONTROL=auto
|
31 |
+
|
32 |
+
# This variable is used to define a list of allowed paths for the application to access when access control mode is enabled.
|
33 |
+
# It can be set to a comma-separated string of file paths or directory paths, representing the resources that are allowed to be accessed by the application.
|
34 |
+
# In addition, if sd_webui_config or sd_webui_dir has been configured, or if you're running this repository as an extension of sd-webui,
|
35 |
+
# you can use the following shortcuts (txt2img, img2img, extra, save) as values for the ALLOWED_PATHS variable.
|
36 |
+
# IIB_ACCESS_CONTROL_ALLOWED_PATHS=save,extra,/output ...etc
|
37 |
+
|
38 |
+
# This variable is used to control fine-grained access control for different types of requests, but only if access control mode is enabled.
|
39 |
+
# It can be set to a string value that represents a specific permission or set of permissions, such as "read-only", "write-only", "read-write", or "no-access".
|
40 |
+
# This variable can be used to restrict access to certain API endpoints or data sources based on the permissions required by the user.
|
41 |
+
# IIB_ACCESS_CONTROL_PERMISSION=read-write
|
42 |
+
|
43 |
+
|
44 |
+
|
45 |
+
# ---------------------------- PARSER_CONFIG ----------------------------
|
46 |
+
# This attribute is used to control whether to enable SdWebUIStealthParser.
|
47 |
+
# Due to the high performance cost of parsing this type of file, it is disabled by default.
|
48 |
+
# Set to 'true' to enable it.
|
49 |
+
IIB_ENABLE_SD_WEBUI_STEALTH_PARSER=false
|
extensions/sd-webui-infinite-image-browsing/.github/FUNDING.yml
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# These are supported funding model platforms
|
2 |
+
|
3 |
+
ko_fi: zanllp
|
4 |
+
custom: https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/.github/wechat_funding.jpg
|
extensions/sd-webui-infinite-image-browsing/.github/wechat_funding.jpg
ADDED
![]() |
Git LFS Details
|
extensions/sd-webui-infinite-image-browsing/.github/workflows/tauri_app_build.yml
ADDED
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: tauri_app_build
|
2 |
+
|
3 |
+
on:
|
4 |
+
push:
|
5 |
+
branches:
|
6 |
+
- 'releases/**'
|
7 |
+
|
8 |
+
jobs:
|
9 |
+
build:
|
10 |
+
strategy:
|
11 |
+
matrix:
|
12 |
+
os: [windows-latest,ubuntu-20.04]
|
13 |
+
|
14 |
+
runs-on: ${{ matrix.os }}
|
15 |
+
|
16 |
+
permissions:
|
17 |
+
contents: write
|
18 |
+
steps:
|
19 |
+
- name: Check-out repository
|
20 |
+
uses: actions/checkout@v3
|
21 |
+
|
22 |
+
- run: echo "VERSION=$(jq -r '.package.version' vue/src-tauri/tauri.conf.json)" >> "$GITHUB_ENV"
|
23 |
+
if: matrix.os == 'ubuntu-20.04'
|
24 |
+
- run: echo "VERSION=$(jq -r '.package.version' vue/src-tauri/tauri.conf.json)" >> $env:GITHUB_ENV
|
25 |
+
if: matrix.os == 'windows-latest'
|
26 |
+
|
27 |
+
- name: Setup Python
|
28 |
+
uses: actions/setup-python@v4
|
29 |
+
with:
|
30 |
+
python-version: '3.10'
|
31 |
+
cache: 'pip'
|
32 |
+
cache-dependency-path: |
|
33 |
+
**/requirements*.txt
|
34 |
+
|
35 |
+
- name: Install Dependencies
|
36 |
+
run: |
|
37 |
+
|
38 |
+
pip install -r requirements.txt
|
39 |
+
|
40 |
+
- name: Build Executable
|
41 |
+
uses: Nuitka/Nuitka-Action@main
|
42 |
+
with:
|
43 |
+
nuitka-version: main
|
44 |
+
script-name: app.py
|
45 |
+
output-file: iib_api_server
|
46 |
+
output-dir: out
|
47 |
+
include-data-dir: |
|
48 |
+
vue/dist=vue/dist
|
49 |
+
|
50 |
+
- run: cp out/iib_api_server out/iib_app_cli-${{ env.VERSION }}-${{ runner.os }}
|
51 |
+
if: matrix.os == 'ubuntu-20.04'
|
52 |
+
- run: cp out/iib_api_server.exe out/iib_app_cli-${{ env.VERSION }}-${{ runner.os }}.exe
|
53 |
+
if: matrix.os == 'windows-latest'
|
54 |
+
|
55 |
+
- name: Upload Server Artifacts
|
56 |
+
uses: actions/upload-artifact@v3
|
57 |
+
with:
|
58 |
+
name: iib_app_cli_${{ runner.os }}
|
59 |
+
path: |
|
60 |
+
out/iib_app_cli-${{ env.VERSION }}-${{ runner.os }}
|
61 |
+
out/iib_app_cli-${{ env.VERSION }}-${{ runner.os }}.exe
|
62 |
+
|
63 |
+
- name: Upload Server Artifacts
|
64 |
+
uses: actions/upload-artifact@v3
|
65 |
+
with:
|
66 |
+
name: iib_api_server-${{ env.VERSION }}-${{ runner.os }}
|
67 |
+
path: |
|
68 |
+
out/iib_api_server.exe
|
69 |
+
out/iib_api_server
|
70 |
+
|
71 |
+
- run: mv out/iib_api_server.exe vue/src-tauri/iib_api_server-x86_64-pc-windows-msvc.exe
|
72 |
+
if: matrix.os == 'windows-latest'
|
73 |
+
|
74 |
+
- run: mv out/iib_api_server vue/src-tauri/iib_api_server-x86_64-unknown-linux-gnu
|
75 |
+
if: matrix.os == 'ubuntu-20.04'
|
76 |
+
|
77 |
+
- name: Install frontend dependencies
|
78 |
+
run: yarn install
|
79 |
+
working-directory: vue
|
80 |
+
|
81 |
+
- name: Rust setup
|
82 |
+
uses: dtolnay/rust-toolchain@stable
|
83 |
+
|
84 |
+
- name: Use Node.js
|
85 |
+
uses: actions/setup-node@v3
|
86 |
+
with:
|
87 |
+
node-version: 18
|
88 |
+
|
89 |
+
- name: Rust cache
|
90 |
+
uses: swatinem/rust-cache@v2
|
91 |
+
with:
|
92 |
+
workspaces: './vue/src-tauri -> target'
|
93 |
+
|
94 |
+
- name: Install dependencies (ubuntu only)
|
95 |
+
if: matrix.os == 'ubuntu-20.04'
|
96 |
+
run: |
|
97 |
+
sudo apt-get update
|
98 |
+
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libayatana-appindicator3-dev librsvg2-dev patchelf
|
99 |
+
|
100 |
+
- name: Build the app
|
101 |
+
run: |
|
102 |
+
yarn tauri-build
|
103 |
+
working-directory: vue
|
104 |
+
|
105 |
+
|
106 |
+
- name: Upload Artifacts
|
107 |
+
uses: actions/upload-artifact@v3
|
108 |
+
with:
|
109 |
+
name: bundle-${{ env.VERSION }}-${{ runner.os }}
|
110 |
+
path: |
|
111 |
+
vue/src-tauri/target/release/bundle/nsis/Infinite Image Browsing_${{ env.VERSION }}_x64-setup.exe
|
112 |
+
vue/src-tauri/target/release/bundle/deb/infinite-image-browsing_${{ env.VERSION }}_amd64.deb
|
113 |
+
|
114 |
+
|
115 |
+
build-by-pyinstaller:
|
116 |
+
strategy:
|
117 |
+
matrix:
|
118 |
+
os: [windows-latest]
|
119 |
+
|
120 |
+
runs-on: ${{ matrix.os }}
|
121 |
+
|
122 |
+
permissions:
|
123 |
+
contents: write
|
124 |
+
steps:
|
125 |
+
- name: Check-out repository
|
126 |
+
uses: actions/checkout@v3
|
127 |
+
|
128 |
+
- run: echo "VERSION=$(jq -r '.package.version' vue/src-tauri/tauri.conf.json)" >> $env:GITHUB_ENV
|
129 |
+
|
130 |
+
- name: Setup Python
|
131 |
+
uses: actions/setup-python@v4
|
132 |
+
with:
|
133 |
+
python-version: '3.10'
|
134 |
+
cache: 'pip'
|
135 |
+
cache-dependency-path: |
|
136 |
+
**/requirements*.txt
|
137 |
+
|
138 |
+
- name: Install Dependencies
|
139 |
+
run: |
|
140 |
+
pip install -r requirements.txt
|
141 |
+
|
142 |
+
- uses: sayyid5416/pyinstaller@v1
|
143 |
+
with:
|
144 |
+
spec: 'app.py'
|
145 |
+
upload_exe_with_name: 'My executable'
|
146 |
+
options: --onefile
|
147 |
+
|
148 |
+
- run: mv dist/app.exe vue/src-tauri/iib_api_server-x86_64-pc-windows-msvc.exe
|
149 |
+
|
150 |
+
- name: Install frontend dependencies
|
151 |
+
run: yarn install
|
152 |
+
working-directory: vue
|
153 |
+
|
154 |
+
- name: Rust setup
|
155 |
+
uses: dtolnay/rust-toolchain@stable
|
156 |
+
|
157 |
+
- name: Use Node.js
|
158 |
+
uses: actions/setup-node@v3
|
159 |
+
with:
|
160 |
+
node-version: 18
|
161 |
+
|
162 |
+
- name: Rust cache
|
163 |
+
uses: swatinem/rust-cache@v2
|
164 |
+
with:
|
165 |
+
workspaces: './vue/src-tauri -> target'
|
166 |
+
|
167 |
+
- name: Install dependencies (ubuntu only)
|
168 |
+
if: matrix.os == 'ubuntu-20.04'
|
169 |
+
run: |
|
170 |
+
sudo apt-get update
|
171 |
+
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libayatana-appindicator3-dev librsvg2-dev patchelf
|
172 |
+
|
173 |
+
- name: Build the app
|
174 |
+
run: |
|
175 |
+
yarn tauri-build
|
176 |
+
working-directory: vue
|
177 |
+
|
178 |
+
- run: |
|
179 |
+
cd vue/src-tauri/target/release/bundle/nsis
|
180 |
+
mv "Infinite Image Browsing_${{ env.VERSION }}_x64-setup.exe" "Infinite Image Browsing_${{ env.VERSION }}_x64-setup-pyinstaller.exe"
|
181 |
+
|
182 |
+
- name: Upload Artifacts
|
183 |
+
uses: actions/upload-artifact@v3
|
184 |
+
with:
|
185 |
+
name: bundle-${{ env.VERSION }}-${{ runner.os }}
|
186 |
+
path: |
|
187 |
+
vue/src-tauri/target/release/bundle/nsis/Infinite Image Browsing_${{ env.VERSION }}_x64-setup-pyinstaller.exe
|
188 |
+
|
189 |
+
release:
|
190 |
+
needs: [build-by-pyinstaller, build]
|
191 |
+
runs-on: ubuntu-latest
|
192 |
+
|
193 |
+
permissions:
|
194 |
+
contents: write
|
195 |
+
steps:
|
196 |
+
- name: Check-out repository
|
197 |
+
uses: actions/checkout@v3
|
198 |
+
- run: echo "VERSION=$(jq -r '.package.version' vue/src-tauri/tauri.conf.json)" >> "$GITHUB_ENV"
|
199 |
+
|
200 |
+
- name: Delete drafts
|
201 |
+
uses: hugo19941994/[email protected]
|
202 |
+
env:
|
203 |
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
204 |
+
|
205 |
+
- uses: actions/download-artifact@v3
|
206 |
+
with:
|
207 |
+
name: bundle-${{ env.VERSION }}-Windows
|
208 |
+
path: artifacts
|
209 |
+
|
210 |
+
- uses: actions/download-artifact@v3
|
211 |
+
with:
|
212 |
+
name: bundle-${{ env.VERSION }}-Linux
|
213 |
+
path: artifacts
|
214 |
+
|
215 |
+
- uses: actions/download-artifact@v3
|
216 |
+
with:
|
217 |
+
name: iib_app_cli_Windows
|
218 |
+
path: artifacts
|
219 |
+
|
220 |
+
- uses: actions/download-artifact@v3
|
221 |
+
with:
|
222 |
+
name: iib_app_cli_Linux
|
223 |
+
path: artifacts
|
224 |
+
|
225 |
+
- name: Release
|
226 |
+
uses: softprops/action-gh-release@v1
|
227 |
+
with:
|
228 |
+
draft: true
|
229 |
+
tag_name: v${{ env.VERSION }}
|
230 |
+
files: artifacts/**/*
|
231 |
+
|
extensions/sd-webui-infinite-image-browsing/.gitignore
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.log
|
2 |
+
__pycache__
|
3 |
+
iib.db
|
4 |
+
tags-translate.csv
|
5 |
+
launch.sh
|
6 |
+
conf.json
|
7 |
+
iib.db-journal
|
8 |
+
.env
|
9 |
+
standalone.cmd
|
10 |
+
.vscode
|
11 |
+
build/**/*
|
12 |
+
dist/**/*
|
13 |
+
*.spec
|
14 |
+
out/**/*
|
15 |
+
venv/**/*
|
16 |
+
zip_temp/*.zip
|
17 |
+
iib_db_backup
|
18 |
+
db_migrate_temp.db
|
19 |
+
plugins/*
|
20 |
+
!plugins/.gitkeep
|
21 |
+
test_data/*
|
22 |
+
.DS_Store
|
extensions/sd-webui-infinite-image-browsing/.vscode/settings.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"[python]": {
|
3 |
+
"editor.defaultFormatter": "ms-python.black-formatter"
|
4 |
+
},
|
5 |
+
"python.formatting.provider": "none"
|
6 |
+
}
|
extensions/sd-webui-infinite-image-browsing/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2023 zanllp
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
extensions/sd-webui-infinite-image-browsing/README-zh.md
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
> 🌐 在线体验: http://39.105.110.128:0721 , 这是我一个空闲的2c2g3m的云主机没有cdn
|
2 |
+
>
|
3 |
+
# Stable-Diffusion-WebUI无边图像浏览
|
4 |
+
|
5 |
+
|
6 |
+
[查看近期更新](https://github.com/zanllp/sd-webui-infinite-image-browsing/wiki/Change-log)
|
7 |
+
|
8 |
+
[安装/运行](#安装运行)
|
9 |
+
|
10 |
+
|
11 |
+
## 主要特性
|
12 |
+
|
13 |
+
### 🔥 极佳性能
|
14 |
+
- 存在缓存的情况下后,图像可以在几毫秒内显示。
|
15 |
+
- 默认使用缩略图显示图像,默认大小为512像素,您可以在全局设置页中调整缩略图分辨率。
|
16 |
+
- 你还可以控制网格图像的宽度,允许以64px到1024px的宽度范围进行显示
|
17 |
+
- 支持通过`--generate_video_cover`和`--generate_image_cache`来预先生成缩略图和视频封面,以提高性能。
|
18 |
+
- 支持通过`IIB_CACHE_DIR`环境变量来指定缓存目录。
|
19 |
+
|
20 |
+
### 🔍 图像搜索和收藏
|
21 |
+
- 将会把Prompt、Model、Lora等信息转成标签,将根据使用频率排序以供进行精确的搜索。
|
22 |
+
- 支持标签自动完成、[翻译](https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/39)和自定义。
|
23 |
+
- 可通过在右键菜单切换自定义标签来实现图像收藏。
|
24 |
+
- 支持类似谷歌的高级搜索。
|
25 |
+
- 同样支持模糊搜索,您可以使用文件名或生成信息的一部分进行搜索。
|
26 |
+
- 支持添加自定义搜索路径,方便管理自己创建的文件夹集合。
|
27 |
+
|
28 |
+
### 🖼️ 查看图像/视频和“发送到”
|
29 |
+
- 支持查看图像生成信息。全屏预览下同样支持。
|
30 |
+
- 支持将图像发送到其他选项卡和其他插件,例如 ControlNet, openOutpaint。
|
31 |
+
- 支持全屏预览,并且支持在全屏预览下使用自定义快捷键进行操作
|
32 |
+
- 支持在全屏预览模式下通过按下方向键或点击按钮移动到前一个或后一个图像。
|
33 |
+
- 支持播放远程服务器上的视频文件
|
34 |
+
|
35 |
+
### 💻 多种使用方法
|
36 |
+
- 您可以将其作为 SD-webui 的扩展安装。
|
37 |
+
- 您可以使用 Python 独立运行它。
|
38 |
+
- 还提供桌面应用程序版本。
|
39 |
+
- 支持多种流行的AI软件
|
40 |
+
|
41 |
+
### 🚶♀️ Walk模式
|
42 |
+
- 自动加载下一个文件夹 `(类似于 os.walk)`,可让您无需分页浏览所有图像。
|
43 |
+
- 已测试可正常处理超过 27,000 个文件。
|
44 |
+
- 当存在文件夹的情况下你可以通过右上角的walk按钮从其他模式切换到walk模式,它会将所有的文件夹打平,避免来回进出文件夹的繁琐操作。
|
45 |
+
|
46 |
+
### 🌳 基于文件树结构的预览和文件操作
|
47 |
+
- 支持基于文件树结构的预览。
|
48 |
+
- 支持自动刷新。
|
49 |
+
- 支持基本文件操作以及多选删除/移动/复制,新建文件夹等。
|
50 |
+
- 按住 Ctrl、Shift 或 Cmd 键可选择多个项目。
|
51 |
+
- 支持多选的操作有:删除、移动、复制、打包下载、添加标签、移除标签,移动到其他文件夹,复制到其他文件夹,拖拽
|
52 |
+
- 你可以通过右下角的保持多选按钮来保持多选的状态,对选中的文件集合可以很方便的进行多次操作
|
53 |
+
|
54 |
+
### 🆚 图像对比 (类似ImgSli)
|
55 |
+
- 提供两张图片的并排比较
|
56 |
+
- 同时提供图像生成信息的比较
|
57 |
+
|
58 |
+
### 🌐 多语言支持
|
59 |
+
- 目前支持简体中文/繁体中文/英文/德语。
|
60 |
+
- 如果您希望添加新的语言,请参考 [i18n.ts](https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/vue/src/i18n/zh-hans.ts) 并提交相关的代码。
|
61 |
+
|
62 |
+
|
63 |
+
### 🔐 隐私和安全
|
64 |
+
- 支持自定义secret key来进行身份验证
|
65 |
+
- 支持配置对文件系统的访问控制,默认将在服务允许公开访问时启用(仅限作为sd-webui的拓展时)
|
66 |
+
- 支持自定义访问控制允许的路径。
|
67 |
+
- 支持控制访问权限。你可以让IIB以只读模式运行
|
68 |
+
- [点击这里查看详情](.env.example)
|
69 |
+
|
70 |
+
### ⌨️ 快捷键
|
71 |
+
- 支持删除和添加/移除Tag,在全局设置页进行自定义触发按钮
|
72 |
+
|
73 |
+
### 📦 打包 / 批量下载
|
74 |
+
- 允许你一次性打包下载多个图像
|
75 |
+
- 数据来源可以是搜索结果/普通的图像网格查看页面/walk模式等。使用拖拽或者“发送到”都可将图片添加待处理列表
|
76 |
+
|
77 |
+
|
78 |
+
如果您喜欢这个项目并且觉得它对您有帮助,请考虑给我点个⭐️。这将对我持续开发和维护这个项目非常重要。如果您有任何建议或者想法,请随时在issue中提出,我会尽快回复。再次感谢您的支持!
|
79 |
+
|
80 |
+
|
81 |
+
[在微信上赞助我](.github/wechat_funding.jpg)
|
82 |
+
|
83 |
+
<a href='https://ko-fi.com/zanllp' target='_blank'><img height='35' style='border:0px;height:46px;' src='https://az743702.vo.msecnd.net/cdn/kofi3.png?v=0' border='0' alt='Buy Me a Coffee at ko-fi.com' />
|
84 |
+
|
85 |
+
|
86 |
+
[视频演示可以在Bilibili上观看](https://space.bilibili.com/27227392/channel/series)
|
87 |
+
|
88 |
+
# 安装/运行
|
89 |
+
|
90 |
+
## 作为SD-webui的扩展程序:
|
91 |
+
1. 在SD-webui中打开`扩展`选项卡。
|
92 |
+
2. 选择`从URL安装`选项。
|
93 |
+
3. 输入 `https://github.com/zanllp/sd-webui-infinite-image-browsing`。
|
94 |
+
4. 点击`安装`按钮。
|
95 |
+
5. 等待安装完成,然后点击`应用并重启UI`。
|
96 |
+
|
97 |
+
## 作为使用Python运行的独立程序(不需要SD-webui��:
|
98 |
+
请参考[Can the extension function without the web UI?](https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/47)
|
99 |
+
|
100 |
+
如果需要查看ComfyUI/Fooocus/NovelAI生成的图片相关,请先参考 https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/202#issuecomment-1655764627
|
101 |
+
|
102 |
+
如果你需要dockerfile 参考 https://github.com/zanllp/sd-webui-infinite-image-browsing/discussions/366
|
103 |
+
|
104 |
+
## 作为桌面应用程序(不需要SD-webui和Python):
|
105 |
+
exe版本同样支持ComfyUI/Fooocus/NovelAI
|
106 |
+
|
107 |
+
从仓库页面右侧的`releases`部分下载并安装程序。如果提示检测到病毒忽略即可这是误报。在windows下的编译有两个版本, pyinstaller版本拥有比较低的误报率。
|
108 |
+
|
109 |
+
如果你需要自行编译请参考 https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/.github/workflows/tauri_app_build.yml
|
110 |
+
## 作为库使用
|
111 |
+
|
112 |
+
使用iframe接入IIB,将IIB作为你应用的文件浏览器使用。 参考 https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/vue/usage.md
|
113 |
+
|
114 |
+
# 预览
|
115 |
+
|
116 |
+
<img width="1920" alt="image" src="https://user-images.githubusercontent.com/25872019/230064374-47ba209e-562b-47b8-a2ce-d867e3afe204.png">
|
117 |
+
|
118 |
+
## 图像搜索
|
119 |
+
|
120 |
+
在第一次使用时,你需要点击等待索引的生成,我2万张图像的情况下大概需要15秒(配置是amd 5600x和pcie ssd)。后续使用他会检查文件夹是否发生变化,如果发生变化则需要重新生成索引,通常这个过程极快。
|
121 |
+
|
122 |
+
图像搜索支持翻译,具体看这个 https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/39 。
|
123 |
+
<img width="1109" alt="image" src="https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/62d1ffe3-2d1f-4449-803a-970273753855">
|
124 |
+
<img width="620" alt="image" src="https://user-images.githubusercontent.com/25872019/234639759-2d270fe5-b24b-4542-b75a-a025ba78ec89.png">
|
125 |
+
## 图像比较
|
126 |
+
|
127 |
+

|
128 |
+
|
129 |
+
## 全屏预览 (并排布局)
|
130 |
+

|
131 |
+
|
132 |
+
## 全屏预览
|
133 |
+
<img width="1024" alt="image" src="https://user-images.githubusercontent.com/25872019/232167416-32a8b19d-b766-4f98-88f6-a1d48eaebec0.png">
|
134 |
+
|
135 |
+
在全屏预览下同样可以查看图片信息和进行上下文菜单上的的操作,支持拖拽/调整/展开收起
|
136 |
+
|
137 |
+
https://user-images.githubusercontent.com/25872019/235327735-bfb50ea7-7682-4e50-b303-38159456e527.mp4
|
138 |
+
|
139 |
+
|
140 |
+
如果你和我一样不需要查看生成信息,你可以选择直接缩小这个面板,所有上下文操作仍然可用
|
141 |
+
|
142 |
+
<img width="599" alt="image" src="https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/f26abe8c-7a76-45c3-9d7f-18ae8b6b6a91">
|
143 |
+
|
144 |
+
### 右键菜单
|
145 |
+
<img width="1024" alt="image" src="https://user-images.githubusercontent.com/25872019/230896820-26344b09-2297-4a2f-a6a7-4c2f0edb8a2c.png">
|
146 |
+
|
147 |
+
也可以通过右上角的图标来触发
|
148 |
+
<img width="227" alt="image" src="https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/f2005ad3-2d3b-4fa7-b3e5-bc17f26f7e19">
|
149 |
+
|
150 |
+
### Walk模式
|
151 |
+
|
152 |
+
|
153 |
+
https://user-images.githubusercontent.com/25872019/230768207-daab786b-d4ab-489f-ba6a-e9656bd530b8.mp4
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
### 深色模式
|
159 |
+
|
160 |
+
<img width="768" alt="image" src="https://user-images.githubusercontent.com/25872019/230064879-c95866ac-999d-4d4b-87ea-3e38c8479415.png">
|
161 |
+
|
162 |
+
|
extensions/sd-webui-infinite-image-browsing/README.md
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
> 🌍 i18n Advisory: Some translations may be incomplete or inaccurate. Pull requests are welcome for improvements!
|
2 |
+
|
3 |
+
> 🌐 Try our application online at: http://39.105.110.128:0721. This is my idle 2c2g3m cloud server without CDN.
|
4 |
+
|
5 |
+
[中文文档](./README-zh.md)
|
6 |
+
[Change log](https://github.com/zanllp/sd-webui-infinite-image-browsing/wiki/Change-log)
|
7 |
+
[Installation / Running](#installation--running)
|
8 |
+
|
9 |
+
|
10 |
+
# Stable Diffusion webui Infinite Image Browsing
|
11 |
+
|
12 |
+
### Software Support and Development Progress Overview
|
13 |
+
| Software | Support | Provided by |
|
14 |
+
| ---------------------- | ---------------- | ----------- |
|
15 |
+
| Stable Diffusion web UI| Supported | Built-in |
|
16 |
+
| Stable Diffusion web UI (Stealth)| Supported ([default: disabled](https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/.env.example#L49)) | Built-in |
|
17 |
+
| ComfyUI | Partially supported | Built-in |
|
18 |
+
| Fooocus | Supported | Built-in |
|
19 |
+
| NovelAI | Supported | Built-in |
|
20 |
+
| StableSwarmUI | Supported | Built-in |
|
21 |
+
| Invoke.AI | Supported | Built-in |
|
22 |
+
| Pixiv | Supported | [pixiv_iib_plugin](https://github.com/zanllp/pixiv_iib_plugin) |
|
23 |
+
|
24 |
+
If you would like to support more software, please refer to: [parsers](https://github.com/zanllp/sd-webui-infinite-image-browsing/tree/main/scripts/iib/parsers) or [pixiv_iib_plugin](https://github.com/zanllp/pixiv_iib_plugin)
|
25 |
+
|
26 |
+
## Key Features
|
27 |
+
|
28 |
+
### 🔥 Excellent Performance
|
29 |
+
- Once caching is generated, images can be displayed in just a few milliseconds.
|
30 |
+
- Images are displayed with thumbnails by default, with a default size of 512 pixels. You can adjust the thumbnail resolution on the global settings page.
|
31 |
+
- You can also control the width of the grid images, allowing them to be displayed in widths ranging from 64px to 1024px.
|
32 |
+
- Supports pre-generating thumbnails and video covers to improve performance using `--generate_video_cover` and `--generate_image_cache`.
|
33 |
+
- Supports specifying the cache directory through the `IIB_CACHE_DIR` environment variable.
|
34 |
+
|
35 |
+
### 🔍 Image Search & Favorite
|
36 |
+
- The prompt, model, Lora, and other information will be converted into tags and sorted by frequency of use for precise searching.
|
37 |
+
- Supports tag autocomplete, [auto-translation](https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/39), and customization.
|
38 |
+
- Image favorite can be achieved by toggling custom tags for images in the right-click menu.
|
39 |
+
- Support for advanced search similar to Google
|
40 |
+
- Also supports fuzzy search, you can search by a part of the filename or generated information.
|
41 |
+
- Support adding custom search paths for easy management of folders created by the user.
|
42 |
+
|
43 |
+
### 🖼️ View Images/Videos & `Send To`
|
44 |
+
- Supports viewing image generation information. Also supported in full-screen preview mode.
|
45 |
+
- Supports sending images to other tabs and third-party extensions such as ControlNet , openOutpaint.
|
46 |
+
- Support full-screen preview and enable custom shortcut key operations while in full-screen preview mode.
|
47 |
+
- Support navigating to the previous or next image in full-screen preview mode by pressing arrow keys or clicking buttons.
|
48 |
+
- Support playing video files from a remote server.
|
49 |
+
|
50 |
+
### 💻 Multiple Usage Methods
|
51 |
+
- You can install it as an extension on SD-webui.
|
52 |
+
- You can run it independently using Python.
|
53 |
+
- The desktop app version is also available.
|
54 |
+
- Supports multiple popular AI software.
|
55 |
+
|
56 |
+
|
57 |
+
### 🚶♀️ Walk Mode
|
58 |
+
- Automatically load the next folder `(similar to os.walk)`, allowing you to browse all images without paging.
|
59 |
+
- Tested to work properly with over 27,000 files.
|
60 |
+
- When there are folders, you can switch to walk mode from other modes by clicking the walk button in the upper right corner. It will flatten all the folders, avoiding the tedious operation of going in and out of folders.
|
61 |
+
|
62 |
+
### 🌳 Preview based on File Tree Structure & File operations
|
63 |
+
- Supports file tree-based preview.
|
64 |
+
- Supports automatic refreshing.
|
65 |
+
- Supports basic file operations, such as multiple selection for deleting/moving/copying, and creating new folders.
|
66 |
+
- Hold down the Ctrl, Shift, or Cmd key to select multiple items.
|
67 |
+
- Supported multi-select operations include: delete, move, copy, pack download, add tags, remove tags, move to another folder, copy to another folder, drag and drop.
|
68 |
+
- You can keep the multi-select state by clicking the "Keep Multi-Select" button in the lower right corner, allowing you to perform multiple operations on the selected file collection conveniently.
|
69 |
+
|
70 |
+
### 🆚 image comparison (similar to Imgsli)
|
71 |
+
- Provides a side-by-side comparison of two images.
|
72 |
+
- Provides a comparison of image generation information at the same time.
|
73 |
+
|
74 |
+
### 🌐 Multilingual Support
|
75 |
+
- Currently supports Simplified Chinese/Traditional Chinese/English/German.
|
76 |
+
- If you would like to add a new language, please refer to [i18n.ts](https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/vue/src/i18n/zh-hans.ts) and submit the relevant code.
|
77 |
+
|
78 |
+
### 🔐 Privacy and Security
|
79 |
+
- Supports custom secret key for authentication.
|
80 |
+
- Supports configuring access control for the file system, which will be enabled by default when the service allows public access (Only when used as an extension of sd-webui).
|
81 |
+
- Supports customizing the allowed paths for access control.
|
82 |
+
- Supports controlling access permissions. You can run IIB in read-only mode.
|
83 |
+
- [Click here to see details](.env.example)
|
84 |
+
|
85 |
+
|
86 |
+
### 📦 Packaging/Batch Download
|
87 |
+
- Allows you to download multiple images at once.
|
88 |
+
- The data source can be search results, a regular image grid view page, walk mode, etc. Images can be added to the processing list through drag-and-drop or "Send To".
|
89 |
+
### ⌨️ Keyboard Shortcuts
|
90 |
+
- Allows for deleting and adding/removing tags, with customizable trigger buttons in the global settings page.
|
91 |
+
|
92 |
+
|
93 |
+
If you like this project and find it helpful, please consider giving it a ⭐️. This would be very important for me to continue developing and maintaining this project. If you have any suggestions or ideas, please feel free to raise them in the issue section, and I will respond as soon as possible. Thank you again for your support!
|
94 |
+
|
95 |
+
|
96 |
+
<a href='https://ko-fi.com/zanllp' target='_blank'><img height='35' style='border:0px;height:46px;' src='https://az743702.vo.msecnd.net/cdn/kofi3.png?v=0' border='0' alt='Buy Me a Coffee at ko-fi.com' />
|
97 |
+
|
98 |
+
[Sponsor me on WeChat](.github/wechat_funding.jpg)
|
99 |
+
|
100 |
+
# Installation / Running
|
101 |
+
## As an extension for SD-webui:
|
102 |
+
1. Open the `Extensions` tab in SD-webui.
|
103 |
+
2. Select the `Install from URL` option.
|
104 |
+
3. Enter `https://github.com/zanllp/sd-webui-infinite-image-browsing`.
|
105 |
+
4. Click on the `Install` button.
|
106 |
+
5. Wait for the installation to complete and click on `Apply and restart UI`.
|
107 |
+
|
108 |
+
## As a standalone program that runs using Python. (without SD-webui):
|
109 |
+
|
110 |
+
Refer to [Can the extension function without the web UI?](https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/47)
|
111 |
+
|
112 |
+
If you need to view images generated by ComfyUI/Fooocus/NovelAI, please refer to [https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/202](https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/202#issuecomment-1655764627).
|
113 |
+
|
114 |
+
If you need a Dockerfile, you can refer to this link. https://github.com/zanllp/sd-webui-infinite-image-browsing/discussions/366
|
115 |
+
|
116 |
+
## As a desktop application (without SD-webui and Python):
|
117 |
+
The executable version also supports ComfyUI/Fooocus/NovelAI.
|
118 |
+
|
119 |
+
Download and install the program from the `releases` section on the right-hand side of the repository page.
|
120 |
+
If the antivirus detects a virus, it can be ignored as a false positive. There are two versions of the compiled version for Windows, with the pyinstaller version having a lower false positive rate.
|
121 |
+
|
122 |
+
If you need to compile it yourself, please refer to https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/.github/workflows/tauri_app_build.yml.
|
123 |
+
|
124 |
+
## As a Library Usage:
|
125 |
+
|
126 |
+
Use iframe to access IIB and use it as a file browser for your application. Refer to https://github.com/zanllp/sd-webui-infinite-image-browsing/blob/main/vue/usage.md
|
127 |
+
|
128 |
+
|
129 |
+
# Preview
|
130 |
+
|
131 |
+
<img width="1920" alt="image" src="https://user-images.githubusercontent.com/25872019/232167682-67f83b00-4391-4394-a7f6-6e4c9d11f252.png">
|
132 |
+
|
133 |
+
## Image Search
|
134 |
+
|
135 |
+
During the first use, you need to click and wait for the index generation. For my case with 20,000 images, it took about 45 seconds (with an AMD 5600X CPU and PCIe SSD). For subsequent uses, it will check whether there are changes in the folder, and if so, it needs to regenerate the index. Usually, this process is very fast.
|
136 |
+
|
137 |
+
Image search supports translation, see https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/39 for more detail. Feel free to share files for other languages to facilitate everyone's use.
|
138 |
+
<img width="1109" alt="image" src="https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/62d1ffe3-2d1f-4449-803a-970273753855">
|
139 |
+
<img width="620" alt="image" src="https://user-images.githubusercontent.com/25872019/234639759-2d270fe5-b24b-4542-b75a-a025ba78ec89.png">
|
140 |
+
|
141 |
+
## Full Screen Preview (Side-by-Side Layout)
|
142 |
+

|
143 |
+
|
144 |
+
## Full Screen Preview
|
145 |
+
|
146 |
+
<img width="1024" alt="image" src="https://user-images.githubusercontent.com/25872019/232167416-32a8b19d-b766-4f98-88f6-a1d48eaebec0.png">
|
147 |
+
|
148 |
+
In full-screen preview mode, you can also view image information and perform operations on the context menu. It supports dragging, resizing and expanding/collapsing .
|
149 |
+
|
150 |
+
https://user-images.githubusercontent.com/25872019/235327735-bfb50ea7-7682-4e50-b303-38159456e527.mp4
|
151 |
+
|
152 |
+
If you, like me, don't need to view the generation information, you can choose to simply minimize this panel, and all contextual operations will still be available.
|
153 |
+
|
154 |
+
<img width="599" alt="image" src="https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/f26abe8c-7a76-45c3-9d7f-18ae8b6b6a91">
|
155 |
+
|
156 |
+
## Image comparison
|
157 |
+
|
158 |
+

|
159 |
+
## Transfer files between different tab panes.
|
160 |
+
https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/e631e3c3-1cbf-49bc-8577-f2963a6c9e4d
|
161 |
+
### Right-click menu
|
162 |
+
<img width="536" alt="image" src="https://user-images.githubusercontent.com/25872019/232162244-e728d510-b6c6-45e6-afb3-872bd67db05b.png">
|
163 |
+
|
164 |
+
You can also trigger it by hovering your mouse over the icon in the top right corner.
|
165 |
+
|
166 |
+
<img width="227" alt="image" src="https://github.com/zanllp/sd-webui-infinite-image-browsing/assets/25872019/f2005ad3-2d3b-4fa7-b3e5-bc17f26f7e19">
|
167 |
+
|
168 |
+
### Walk mode
|
169 |
+
|
170 |
+
|
171 |
+
https://user-images.githubusercontent.com/25872019/230768207-daab786b-d4ab-489f-ba6a-e9656bd530b8.mp4
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
|
176 |
+
### Dark mode
|
177 |
+
|
178 |
+
<img width="768" alt="image" src="https://user-images.githubusercontent.com/25872019/230064879-c95866ac-999d-4d4b-87ea-3e38c8479415.png">
|
extensions/sd-webui-infinite-image-browsing/app.py
ADDED
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import codecs
|
2 |
+
from typing import List
|
3 |
+
from fastapi import FastAPI, Response
|
4 |
+
from fastapi.responses import FileResponse
|
5 |
+
import uvicorn
|
6 |
+
import os
|
7 |
+
from scripts.iib.api import infinite_image_browsing_api, index_html_path, DEFAULT_BASE
|
8 |
+
from scripts.iib.tool import (
|
9 |
+
get_sd_webui_conf,
|
10 |
+
get_valid_img_dirs,
|
11 |
+
sd_img_dirs,
|
12 |
+
normalize_paths,
|
13 |
+
)
|
14 |
+
from scripts.iib.db.datamodel import DataBase, Image, ExtraPath
|
15 |
+
from scripts.iib.db.update_image_data import update_image_data
|
16 |
+
import argparse
|
17 |
+
from typing import Optional, Coroutine
|
18 |
+
import json
|
19 |
+
|
20 |
+
tag = "\033[31m[warn]\033[0m"
|
21 |
+
|
22 |
+
default_port = 8000
|
23 |
+
default_host = "127.0.0.1"
|
24 |
+
|
25 |
+
def get_all_img_dirs(sd_webui_config: str, relative_to_config: bool):
|
26 |
+
dirs = get_valid_img_dirs(
|
27 |
+
get_sd_webui_conf(
|
28 |
+
sd_webui_config=sd_webui_config,
|
29 |
+
sd_webui_path_relative_to_config=relative_to_config,
|
30 |
+
)
|
31 |
+
)
|
32 |
+
dirs += list(map(lambda x: x.path, ExtraPath.get_extra_paths(DataBase.get_conn())))
|
33 |
+
return dirs
|
34 |
+
|
35 |
+
|
36 |
+
def sd_webui_paths_check(sd_webui_config: str, relative_to_config: bool):
|
37 |
+
conf = {}
|
38 |
+
with codecs.open(sd_webui_config, "r", "utf-8") as f:
|
39 |
+
conf = json.loads(f.read())
|
40 |
+
if relative_to_config:
|
41 |
+
for dir in sd_img_dirs:
|
42 |
+
if not os.path.isabs(conf[dir]):
|
43 |
+
conf[dir] = os.path.normpath(
|
44 |
+
os.path.join(sd_webui_config, "../", conf[dir])
|
45 |
+
)
|
46 |
+
paths = [conf.get(key) for key in sd_img_dirs]
|
47 |
+
paths_check(paths)
|
48 |
+
|
49 |
+
|
50 |
+
def paths_check(paths):
|
51 |
+
for path in paths:
|
52 |
+
if not path or len(path.strip()) == 0:
|
53 |
+
continue
|
54 |
+
if os.path.isabs(path):
|
55 |
+
abs_path = path
|
56 |
+
else:
|
57 |
+
abs_path = os.path.normpath(os.path.join(os.getcwd(), path))
|
58 |
+
if not os.path.exists(abs_path):
|
59 |
+
print(f"{tag} The path '{abs_path}' will be ignored (value: {path}).")
|
60 |
+
|
61 |
+
|
62 |
+
def do_update_image_index(sd_webui_config: str, relative_to_config=False):
|
63 |
+
dirs = get_all_img_dirs(sd_webui_config, relative_to_config)
|
64 |
+
if not len(dirs):
|
65 |
+
return print(f"{tag} no valid image directories, skipped")
|
66 |
+
conn = DataBase.get_conn()
|
67 |
+
update_image_data(dirs)
|
68 |
+
if Image.count(conn=conn) == 0:
|
69 |
+
return print(f"{tag} it appears that there is some issue")
|
70 |
+
print("update image index completed. ✨")
|
71 |
+
|
72 |
+
|
73 |
+
class AppUtils:
|
74 |
+
def __init__(
|
75 |
+
self,
|
76 |
+
sd_webui_config: Optional[str] = None,
|
77 |
+
update_image_index: bool = False,
|
78 |
+
extra_paths: List[str] = [],
|
79 |
+
sd_webui_path_relative_to_config=False,
|
80 |
+
allow_cors=False,
|
81 |
+
enable_shutdown=False,
|
82 |
+
sd_webui_dir: Optional[str] = None,
|
83 |
+
base: Optional[str] = None,
|
84 |
+
export_fe_fn=False,
|
85 |
+
**args: dict,
|
86 |
+
):
|
87 |
+
"""
|
88 |
+
Parameter definitions can be found by running the `python app.py -h `command or by examining the setup_parser() function.
|
89 |
+
"""
|
90 |
+
self.sd_webui_config = sd_webui_config
|
91 |
+
self.update_image_index = update_image_index
|
92 |
+
self.extra_paths = extra_paths
|
93 |
+
self.sd_webui_path_relative_to_config = sd_webui_path_relative_to_config
|
94 |
+
self.allow_cors = allow_cors
|
95 |
+
self.enable_shutdown = enable_shutdown
|
96 |
+
self.sd_webui_dir = sd_webui_dir
|
97 |
+
if base and not base.startswith("/"):
|
98 |
+
base = "/" + base
|
99 |
+
self.base = base
|
100 |
+
self.export_fe_fn = export_fe_fn
|
101 |
+
if sd_webui_dir:
|
102 |
+
DataBase.path = os.path.join(
|
103 |
+
sd_webui_dir, "extensions/sd-webui-infinite-image-browsing/iib.db"
|
104 |
+
)
|
105 |
+
self.sd_webui_config = os.path.join(sd_webui_dir, "config.json")
|
106 |
+
self.sd_webui_path_relative_to_config = True
|
107 |
+
|
108 |
+
def set_params(self, *args, **kwargs) -> None:
|
109 |
+
"""改变参数,与__init__的行为一致"""
|
110 |
+
self.__init__(*args, **kwargs)
|
111 |
+
|
112 |
+
@staticmethod
|
113 |
+
def async_run(
|
114 |
+
app: FastAPI, port: int = default_port, host=default_host
|
115 |
+
) -> Coroutine:
|
116 |
+
"""
|
117 |
+
用于从异步运行的 FastAPI,在 Jupyter Notebook 环境中非常有用
|
118 |
+
"""
|
119 |
+
# 不建议改成 async def,并且用 await 替换 return,
|
120 |
+
# 因为这样会失去对 server.serve() 的控制。
|
121 |
+
config = uvicorn.Config(app, host=host, port=port)
|
122 |
+
server = uvicorn.Server(config)
|
123 |
+
return server.serve()
|
124 |
+
|
125 |
+
def wrap_app(self, app: FastAPI) -> None:
|
126 |
+
"""
|
127 |
+
为传递的app挂载上infinite_image_browsing后端
|
128 |
+
"""
|
129 |
+
sd_webui_config = self.sd_webui_config
|
130 |
+
update_image_index = self.update_image_index
|
131 |
+
extra_paths = self.extra_paths
|
132 |
+
|
133 |
+
if sd_webui_config:
|
134 |
+
sd_webui_paths_check(sd_webui_config, self.sd_webui_path_relative_to_config)
|
135 |
+
if update_image_index:
|
136 |
+
do_update_image_index(
|
137 |
+
sd_webui_config, self.sd_webui_path_relative_to_config
|
138 |
+
)
|
139 |
+
paths_check(extra_paths)
|
140 |
+
|
141 |
+
infinite_image_browsing_api(
|
142 |
+
app,
|
143 |
+
sd_webui_config=sd_webui_config,
|
144 |
+
extra_paths_cli=normalize_paths(extra_paths, os.getcwd()),
|
145 |
+
sd_webui_path_relative_to_config=self.sd_webui_path_relative_to_config,
|
146 |
+
allow_cors=self.allow_cors,
|
147 |
+
enable_shutdown=self.enable_shutdown,
|
148 |
+
launch_mode="server",
|
149 |
+
base=self.base,
|
150 |
+
export_fe_fn=self.export_fe_fn,
|
151 |
+
)
|
152 |
+
|
153 |
+
def get_root_browser_app(self) -> FastAPI:
|
154 |
+
"""
|
155 |
+
获取首页挂载在"/"上的infinite_image_browsing FastAPI实例
|
156 |
+
"""
|
157 |
+
app = FastAPI()
|
158 |
+
|
159 |
+
# 用于在首页显示
|
160 |
+
@app.get("/")
|
161 |
+
def index():
|
162 |
+
if isinstance(self.base, str):
|
163 |
+
with open(index_html_path, "r", encoding="utf-8") as file:
|
164 |
+
content = file.read().replace(DEFAULT_BASE, self.base)
|
165 |
+
return Response(content=content, media_type="text/html")
|
166 |
+
return FileResponse(index_html_path)
|
167 |
+
|
168 |
+
self.wrap_app(app)
|
169 |
+
return app
|
170 |
+
|
171 |
+
|
172 |
+
def setup_parser() -> argparse.ArgumentParser:
|
173 |
+
parser = argparse.ArgumentParser(
|
174 |
+
description="A fast and powerful image/video browser with infinite scrolling and advanced search capabilities. It also supports parsing/viewing image information generated by multiple AI software."
|
175 |
+
)
|
176 |
+
parser.add_argument(
|
177 |
+
"--host", type=str, default=default_host, help="The host to use"
|
178 |
+
)
|
179 |
+
parser.add_argument(
|
180 |
+
"--port", type=int, help="The port to use", default=default_port
|
181 |
+
)
|
182 |
+
parser.add_argument(
|
183 |
+
"--sd_webui_config", type=str, default=None, help="The path to the config file"
|
184 |
+
)
|
185 |
+
parser.add_argument(
|
186 |
+
"--update_image_index", action="store_true", help="Update the image index"
|
187 |
+
)
|
188 |
+
parser.add_argument(
|
189 |
+
"--generate_video_cover",
|
190 |
+
action="store_true",
|
191 |
+
help="Pre-generate video cover images to speed up browsing.",
|
192 |
+
)
|
193 |
+
parser.add_argument(
|
194 |
+
"--generate_image_cache",
|
195 |
+
action="store_true",
|
196 |
+
help="Pre-generate image cache to speed up browsing. By default, only the extra paths added by the user are processed, not the paths in sd_webui_config. If you need to process paths in sd_webui_config, you must use the --sd_webui_config and --sd_webui_path_relative_to_config parameters.",
|
197 |
+
)
|
198 |
+
parser.add_argument(
|
199 |
+
"--generate_image_cache_size",
|
200 |
+
type=str,
|
201 |
+
default="512x512",
|
202 |
+
help="The size of the image cache to generate. Default is 512x512",
|
203 |
+
)
|
204 |
+
parser.add_argument(
|
205 |
+
"--gen_cache_verbose",
|
206 |
+
action="store_true",
|
207 |
+
help="Verbose mode for cache generation.",
|
208 |
+
)
|
209 |
+
parser.add_argument(
|
210 |
+
"--extra_paths",
|
211 |
+
nargs="+",
|
212 |
+
help="Extra paths to use, these paths will be added to the homepage but the images in these paths will not be indexed. They are only used for browsing. If you need to index them, please add them via the '+ Add' button on the homepage.",
|
213 |
+
default=[],
|
214 |
+
)
|
215 |
+
parser.add_argument(
|
216 |
+
"--sd_webui_path_relative_to_config",
|
217 |
+
action="store_true",
|
218 |
+
help="Use the file path of the sd_webui_config file as the base for all relative paths provided within the sd_webui_config file.",
|
219 |
+
)
|
220 |
+
parser.add_argument(
|
221 |
+
"--allow_cors",
|
222 |
+
action="store_true",
|
223 |
+
help="Allow Cross-Origin Resource Sharing (CORS) for the API.",
|
224 |
+
)
|
225 |
+
parser.add_argument(
|
226 |
+
"--enable_shutdown",
|
227 |
+
action="store_true",
|
228 |
+
help="Enable the shutdown endpoint.",
|
229 |
+
)
|
230 |
+
parser.add_argument(
|
231 |
+
"--sd_webui_dir",
|
232 |
+
type=str,
|
233 |
+
default=None,
|
234 |
+
help="The path to the sd_webui folder. When specified, the sd_webui's configuration will be used and the extension must be installed within the sd_webui. Data will be shared between the two.",
|
235 |
+
)
|
236 |
+
parser.add_argument(
|
237 |
+
"--export_fe_fn",
|
238 |
+
default=True,
|
239 |
+
action="store_true",
|
240 |
+
help="Export front-end functions to enable external access through iframe.",
|
241 |
+
)
|
242 |
+
parser.add_argument("--base", type=str, help="The base URL for the IIB Api.")
|
243 |
+
return parser
|
244 |
+
|
245 |
+
|
246 |
+
def launch_app(
|
247 |
+
port: int = default_port, host: str = default_host, *args, **kwargs: dict
|
248 |
+
) -> None:
|
249 |
+
"""
|
250 |
+
Launches the application on the specified port.
|
251 |
+
|
252 |
+
Args:
|
253 |
+
**kwargs (dict): Optional keyword arguments that can be used to configure the application.
|
254 |
+
These can be viewed by running 'python app.py -h' or by checking the setup_parser() function.
|
255 |
+
"""
|
256 |
+
app_utils = AppUtils(*args, **kwargs)
|
257 |
+
app = app_utils.get_root_browser_app()
|
258 |
+
uvicorn.run(app, host=host, port=port)
|
259 |
+
|
260 |
+
|
261 |
+
async def async_launch_app(
|
262 |
+
port: int = default_port, host: str = default_host, *args, **kwargs: dict
|
263 |
+
) -> None:
|
264 |
+
"""
|
265 |
+
Asynchronously launches the application on the specified port.
|
266 |
+
|
267 |
+
Args:
|
268 |
+
**kwargs (dict): Optional keyword arguments that can be used to configure the application.
|
269 |
+
These can be viewed by running 'python app.py -h' or by checking the setup_parser() function.
|
270 |
+
"""
|
271 |
+
app_utils = AppUtils(*args, **kwargs)
|
272 |
+
app = app_utils.get_root_browser_app()
|
273 |
+
await app_utils.async_run(app, host=host, port=port)
|
274 |
+
|
275 |
+
|
276 |
+
if __name__ == "__main__":
|
277 |
+
parser = setup_parser()
|
278 |
+
args = parser.parse_args()
|
279 |
+
args_dict = vars(args)
|
280 |
+
|
281 |
+
if args_dict.get("generate_video_cover"):
|
282 |
+
from scripts.iib.video_cover_gen import generate_video_covers
|
283 |
+
|
284 |
+
conn = DataBase.get_conn()
|
285 |
+
generate_video_covers(
|
286 |
+
dirs = map(lambda x: x.path, ExtraPath.get_extra_paths(conn)),
|
287 |
+
verbose=args.gen_cache_verbose,
|
288 |
+
)
|
289 |
+
exit(0)
|
290 |
+
if args_dict.get("generate_image_cache"):
|
291 |
+
from scripts.iib.img_cache_gen import generate_image_cache
|
292 |
+
generate_image_cache(
|
293 |
+
dirs = get_all_img_dirs(args.sd_webui_config, args.sd_webui_path_relative_to_config),
|
294 |
+
size = args.generate_image_cache_size,
|
295 |
+
verbose = args.gen_cache_verbose
|
296 |
+
)
|
297 |
+
exit(0)
|
298 |
+
|
299 |
+
launch_app(**vars(args))
|
extensions/sd-webui-infinite-image-browsing/install.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import launch
|
2 |
+
import os
|
3 |
+
import pkg_resources
|
4 |
+
|
5 |
+
req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt")
|
6 |
+
|
7 |
+
def dist2package(dist: str):
|
8 |
+
return ({
|
9 |
+
"python-dotenv": "dotenv",
|
10 |
+
"Pillow": "PIL",
|
11 |
+
"pillow-avif-plugin": "pillow_avif"
|
12 |
+
}).get(dist, dist)
|
13 |
+
|
14 |
+
# copy from controlnet, thanks
|
15 |
+
with open(req_file) as file:
|
16 |
+
for package in file:
|
17 |
+
try:
|
18 |
+
package = package.strip()
|
19 |
+
if '==' in package:
|
20 |
+
package_name, package_version = package.split('==')
|
21 |
+
installed_version = pkg_resources.get_distribution(package_name).version
|
22 |
+
if installed_version != package_version:
|
23 |
+
launch.run_pip(f"install {package}", f"sd-webui-infinite-image-browsing requirement: changing {package_name} version from {installed_version} to {package_version}")
|
24 |
+
elif not launch.is_installed(dist2package(package)):
|
25 |
+
launch.run_pip(f"install {package}", f"sd-webui-infinite-image-browsing requirement: {package}")
|
26 |
+
except Exception as e:
|
27 |
+
print(e)
|
28 |
+
print(f'Warning: Failed to install {package}, something may not work.')
|
extensions/sd-webui-infinite-image-browsing/javascript/index.js
ADDED
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* eslint-disable no-undef */
|
2 |
+
Promise.resolve().then(async () => {
|
3 |
+
/**
|
4 |
+
* This is a file generated using `yarn build`.
|
5 |
+
* If you want to make changes, please modify `index.tpl.js` and run the command to generate it again.
|
6 |
+
*/
|
7 |
+
const html = `<!DOCTYPE html>
|
8 |
+
<html lang="en">
|
9 |
+
<head>
|
10 |
+
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
|
11 |
+
<meta http-equiv="Expires" content="0" />
|
12 |
+
<meta charset="UTF-8" />
|
13 |
+
<link rel="icon" href="/favicon.ico" />
|
14 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
15 |
+
<title>Infinite Image Browsing</title>
|
16 |
+
<script type="module" crossorigin src="/infinite_image_browsing/fe-static/assets/index-5b5fdd56.js"></script>
|
17 |
+
<link rel="stylesheet" href="/infinite_image_browsing/fe-static/assets/index-3112bec6.css">
|
18 |
+
</head>
|
19 |
+
|
20 |
+
<body>
|
21 |
+
<div id="zanllp_dev_gradio_fe">
|
22 |
+
It seems to have failed to load. You can try refreshing the page. <br> If that doesn't work, click on <a href="https://github.com/zanllp/sd-webui-infinite-image-browsing/issues/90" target="_blank" >FAQ</a> for help</div>
|
23 |
+
</div>
|
24 |
+
|
25 |
+
</body>
|
26 |
+
</html>
|
27 |
+
`.replace(/\/infinite_image_browsing/g, (window.location.pathname + '/infinite_image_browsing').replace(/\/\//g, '/'))
|
28 |
+
let containerSelector = '#infinite_image_browsing_container_wrapper'
|
29 |
+
let shouldMaximize = localStorage.getItem('iib://disable_maximize') !== 'true'
|
30 |
+
|
31 |
+
try {
|
32 |
+
containerSelector = __iib_root_container__
|
33 |
+
shouldMaximize = __iib_should_maximize__
|
34 |
+
} catch (e) { /* empty */ }
|
35 |
+
|
36 |
+
const delay = (timeout = 0) => new Promise((resolve) => setTimeout(resolve, timeout))
|
37 |
+
const asyncCheck = async (getter, checkSize = 100, timeout = 1000) => {
|
38 |
+
let target = getter()
|
39 |
+
let num = 0
|
40 |
+
while (checkSize * num < timeout && (target === undefined || target === null)) {
|
41 |
+
await delay(checkSize)
|
42 |
+
target = getter()
|
43 |
+
num++
|
44 |
+
}
|
45 |
+
return target
|
46 |
+
}
|
47 |
+
|
48 |
+
const getTabIdxById = (id) => {
|
49 |
+
const tabList = gradioApp().querySelectorAll('#tabs > .tabitem[id^=tab_]')
|
50 |
+
return Array.from(tabList).findIndex((v) => v.id.includes(id))
|
51 |
+
}
|
52 |
+
|
53 |
+
const switch2targetTab = (idx) => {
|
54 |
+
try {
|
55 |
+
gradioApp().querySelector('#tabs').querySelectorAll('button')[idx].click()
|
56 |
+
} catch (error) {
|
57 |
+
console.error(error)
|
58 |
+
}
|
59 |
+
}
|
60 |
+
|
61 |
+
const isLobe = () => {
|
62 |
+
try {
|
63 |
+
return !!gradioApp().querySelector('[alt*="lobehub"]')
|
64 |
+
} catch (error) {
|
65 |
+
return false
|
66 |
+
}
|
67 |
+
}
|
68 |
+
|
69 |
+
/**
|
70 |
+
* @type {HTMLDivElement}
|
71 |
+
*/
|
72 |
+
const wrap = await asyncCheck(() => gradioApp().querySelector(containerSelector), 500, Infinity)
|
73 |
+
wrap.childNodes.forEach((v) => wrap.removeChild(v))
|
74 |
+
const iframe = document.createElement('iframe')
|
75 |
+
iframe.srcdoc = html
|
76 |
+
iframe.style = 'width: 100%;height:100vh'
|
77 |
+
wrap.appendChild(iframe)
|
78 |
+
|
79 |
+
if (shouldMaximize) {
|
80 |
+
onUiTabChange(() => {
|
81 |
+
const el = get_uiCurrentTabContent()
|
82 |
+
if (el?.id.includes('infinite-image-browsing')) {
|
83 |
+
try {
|
84 |
+
const iibTop = gradioApp().querySelector('#iib_top')
|
85 |
+
if (!iibTop) {
|
86 |
+
throw new Error('element \'#iib_top\' is not found')
|
87 |
+
}
|
88 |
+
const topRect = iibTop.getBoundingClientRect()
|
89 |
+
wrap.style = `
|
90 |
+
top:${Math.max(isLobe() ? 32 : 128, topRect.top) - 10}px;
|
91 |
+
position: fixed;
|
92 |
+
left: 10px;
|
93 |
+
right: 10px;
|
94 |
+
z-index: 100;
|
95 |
+
width: unset;
|
96 |
+
bottom: 10px;`
|
97 |
+
iframe.style = 'width: 100%;height:100%'
|
98 |
+
} catch (error) {
|
99 |
+
console.error('Error mounting IIB. Running fallback.', error)
|
100 |
+
wrap.style = ''
|
101 |
+
iframe.style = 'width: 100%;height:100vh'
|
102 |
+
}
|
103 |
+
}
|
104 |
+
})
|
105 |
+
}
|
106 |
+
|
107 |
+
const IIB_container_id = [Date.now(), Math.random()].join()
|
108 |
+
window.IIB_container_id = IIB_container_id
|
109 |
+
const imgTransferBus = new BroadcastChannel('iib-image-transfer-bus')
|
110 |
+
imgTransferBus.addEventListener('message', async (ev) => {
|
111 |
+
const data = ev.data
|
112 |
+
if (
|
113 |
+
typeof data !== 'object' ||
|
114 |
+
(typeof data.IIB_container_id === 'string' && data.IIB_container_id !== IIB_container_id)
|
115 |
+
) {
|
116 |
+
return
|
117 |
+
}
|
118 |
+
console.log('iib-message:', data)
|
119 |
+
const appDoc = gradioApp()
|
120 |
+
switch (data.event) {
|
121 |
+
case 'click_hidden_button': {
|
122 |
+
const btn = gradioApp().querySelector(`#${data.btnEleId}`)
|
123 |
+
btn.click()
|
124 |
+
break
|
125 |
+
}
|
126 |
+
case 'send_to_control_net': {
|
127 |
+
data.type === 'img2img' ? window.switch_to_img2img() : window.switch_to_txt2img()
|
128 |
+
await delay(100)
|
129 |
+
const cn = appDoc.querySelector(`#${data.type}_controlnet`)
|
130 |
+
const wrap = cn.querySelector('.label-wrap')
|
131 |
+
if (!wrap.className.includes('open')) {
|
132 |
+
wrap.click()
|
133 |
+
await delay(100)
|
134 |
+
}
|
135 |
+
wrap.scrollIntoView()
|
136 |
+
wrap.dispatchEvent(await createPasteEvent(data.url))
|
137 |
+
break
|
138 |
+
}
|
139 |
+
case 'send_to_outpaint': {
|
140 |
+
switch2targetTab(getTabIdxById('openOutpaint'))
|
141 |
+
await delay(100)
|
142 |
+
const iframe = appDoc.querySelector('#openoutpaint-iframe')
|
143 |
+
openoutpaint_send_image(await imgUrl2DataUrl(data.url))
|
144 |
+
iframe.contentWindow.postMessage({
|
145 |
+
key: appDoc.querySelector('#openoutpaint-key').value,
|
146 |
+
type: 'openoutpaint/set-prompt',
|
147 |
+
prompt: data.prompt,
|
148 |
+
negPrompt: data.negPrompt
|
149 |
+
})
|
150 |
+
break
|
151 |
+
}
|
152 |
+
}
|
153 |
+
|
154 |
+
function imgUrl2DataUrl(imgUrl) {
|
155 |
+
return new Promise((resolve, reject) => {
|
156 |
+
fetch(imgUrl)
|
157 |
+
.then((response) => response.blob())
|
158 |
+
.then((blob) => {
|
159 |
+
const reader = new FileReader()
|
160 |
+
reader.readAsDataURL(blob)
|
161 |
+
reader.onloadend = function () {
|
162 |
+
const dataURL = reader.result
|
163 |
+
resolve(dataURL)
|
164 |
+
}
|
165 |
+
})
|
166 |
+
.catch((error) => reject(error))
|
167 |
+
})
|
168 |
+
}
|
169 |
+
|
170 |
+
async function createPasteEvent(imgUrl) {
|
171 |
+
const response = await fetch(imgUrl)
|
172 |
+
const imageBlob = await response.blob()
|
173 |
+
const imageFile = new File([imageBlob], 'image.jpg', {
|
174 |
+
type: imageBlob.type,
|
175 |
+
lastModified: Date.now()
|
176 |
+
})
|
177 |
+
const dataTransfer = new DataTransfer()
|
178 |
+
dataTransfer.items.add(imageFile)
|
179 |
+
const pasteEvent = new ClipboardEvent('paste', {
|
180 |
+
clipboardData: dataTransfer,
|
181 |
+
bubbles: true
|
182 |
+
})
|
183 |
+
return pasteEvent
|
184 |
+
}
|
185 |
+
})
|
186 |
+
})
|
extensions/sd-webui-infinite-image-browsing/migrate.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from contextlib import closing
|
2 |
+
import argparse
|
3 |
+
from scripts.iib.db.datamodel import DataBase
|
4 |
+
import os
|
5 |
+
|
6 |
+
import shutil
|
7 |
+
|
8 |
+
|
9 |
+
def replace_path(old_base, new_base):
|
10 |
+
"""
|
11 |
+
Custom SQL function to replace part of a path.
|
12 |
+
|
13 |
+
Args:
|
14 |
+
old_base (str): The base part of the path to be replaced.
|
15 |
+
new_base (str): The new base part of the path.
|
16 |
+
|
17 |
+
Returns:
|
18 |
+
str: Updated path.
|
19 |
+
"""
|
20 |
+
|
21 |
+
def replace_func(path):
|
22 |
+
if path.startswith(old_base):
|
23 |
+
return new_base + path[len(old_base) :]
|
24 |
+
else:
|
25 |
+
return path
|
26 |
+
|
27 |
+
return replace_func
|
28 |
+
|
29 |
+
|
30 |
+
def update_paths(conn, table_name, old_base):
|
31 |
+
"""
|
32 |
+
Update paths in a specified SQLite table using a custom SQL function.
|
33 |
+
|
34 |
+
Args:
|
35 |
+
db_path (str): Path to the SQLite database file.
|
36 |
+
table_name (str): Name of the table containing the paths.
|
37 |
+
|
38 |
+
Returns:
|
39 |
+
None
|
40 |
+
"""
|
41 |
+
with closing(conn.cursor()) as cur:
|
42 |
+
# Use the custom function in an UPDATE statement
|
43 |
+
cur.execute(
|
44 |
+
f"UPDATE {table_name} SET path = replace_path(path) WHERE path LIKE ?",
|
45 |
+
(f"{old_base}%",),
|
46 |
+
)
|
47 |
+
|
48 |
+
# Commit the changes and close the connection
|
49 |
+
conn.commit()
|
50 |
+
|
51 |
+
|
52 |
+
def setup_parser() -> argparse.ArgumentParser:
|
53 |
+
parser = argparse.ArgumentParser(
|
54 |
+
description="Script to migrate paths in an IIB SQLite database from an old directory structure to a new one."
|
55 |
+
)
|
56 |
+
parser.add_argument(
|
57 |
+
"--db_path", type=str, help="Path to the input IIB QLite database file to be migrated. Default value is 'iib.db'.", default="iib.db"
|
58 |
+
)
|
59 |
+
parser.add_argument(
|
60 |
+
"--old_dir", type=str, help="Old base directory to be replaced in the paths.", required=True
|
61 |
+
)
|
62 |
+
parser.add_argument(
|
63 |
+
"--new_dir", type=str, help="New base directory to replace the old base directory in the paths.", required=True
|
64 |
+
)
|
65 |
+
return parser
|
66 |
+
|
67 |
+
|
68 |
+
if __name__ == "__main__":
|
69 |
+
parser = setup_parser()
|
70 |
+
args = parser.parse_args()
|
71 |
+
old_base = args.old_dir
|
72 |
+
new_base = args.new_dir
|
73 |
+
db_path = args.db_path
|
74 |
+
db_temp_path = "db_migrate_temp.db"
|
75 |
+
shutil.copy2(db_path, db_temp_path)
|
76 |
+
DataBase.path = os.path.normpath(os.path.join(os.getcwd(), db_temp_path))
|
77 |
+
conn = DataBase.get_conn()
|
78 |
+
conn.create_function("replace_path", 1, replace_path(old_base, new_base))
|
79 |
+
update_paths(conn, "image", old_base)
|
80 |
+
update_paths(conn, "extra_path", old_base)
|
81 |
+
update_paths(conn, "folders", old_base)
|
82 |
+
shutil.copy(db_temp_path, "iib.db")
|
83 |
+
# os.remove(db_temp_path)
|
84 |
+
print("Database migration completed successfully.")
|
extensions/sd-webui-infinite-image-browsing/plugins/.gitkeep
ADDED
File without changes
|
extensions/sd-webui-infinite-image-browsing/requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
fastapi
|
2 |
+
uvicorn
|
3 |
+
piexif
|
4 |
+
python-dotenv
|
5 |
+
Pillow
|
6 |
+
pillow-avif-plugin
|
7 |
+
imageio
|
8 |
+
av
|
9 |
+
lxml
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/api.py
ADDED
@@ -0,0 +1,1223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
from datetime import datetime, timedelta
|
3 |
+
import io
|
4 |
+
import os
|
5 |
+
from pathlib import Path
|
6 |
+
import shutil
|
7 |
+
import sqlite3
|
8 |
+
|
9 |
+
|
10 |
+
from scripts.iib.dir_cover_cache import get_top_4_media_info
|
11 |
+
from scripts.iib.tool import (
|
12 |
+
get_created_date_by_stat,
|
13 |
+
get_video_type,
|
14 |
+
human_readable_size,
|
15 |
+
is_valid_media_path,
|
16 |
+
is_media_file,
|
17 |
+
get_cache_dir,
|
18 |
+
get_formatted_date,
|
19 |
+
is_win,
|
20 |
+
cwd,
|
21 |
+
locale,
|
22 |
+
enable_access_control,
|
23 |
+
get_windows_drives,
|
24 |
+
get_sd_webui_conf,
|
25 |
+
get_valid_img_dirs,
|
26 |
+
open_folder,
|
27 |
+
get_img_geninfo_txt_path,
|
28 |
+
unique_by,
|
29 |
+
create_zip_file,
|
30 |
+
normalize_paths,
|
31 |
+
to_abs_path,
|
32 |
+
is_secret_key_required,
|
33 |
+
open_file_with_default_app,
|
34 |
+
is_exe_ver,
|
35 |
+
backup_db_file,
|
36 |
+
get_current_commit_hash,
|
37 |
+
get_current_tag,
|
38 |
+
get_file_info_by_path,
|
39 |
+
get_data_file_path
|
40 |
+
)
|
41 |
+
from fastapi import FastAPI, HTTPException, Header, Response
|
42 |
+
from fastapi.staticfiles import StaticFiles
|
43 |
+
import asyncio
|
44 |
+
from typing import List, Optional
|
45 |
+
from pydantic import BaseModel
|
46 |
+
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
|
47 |
+
from PIL import Image
|
48 |
+
from fastapi import Depends, FastAPI, HTTPException, Request
|
49 |
+
from fastapi.middleware.cors import CORSMiddleware
|
50 |
+
import hashlib
|
51 |
+
from scripts.iib.db.datamodel import (
|
52 |
+
DataBase,
|
53 |
+
ExtraPathType,
|
54 |
+
Image as DbImg,
|
55 |
+
Tag,
|
56 |
+
Folder,
|
57 |
+
ImageTag,
|
58 |
+
ExtraPath,
|
59 |
+
FileInfoDict,
|
60 |
+
Cursor,
|
61 |
+
GlobalSetting
|
62 |
+
)
|
63 |
+
from scripts.iib.db.update_image_data import update_image_data, rebuild_image_index, add_image_data_single
|
64 |
+
from scripts.iib.logger import logger
|
65 |
+
from scripts.iib.seq import seq
|
66 |
+
import urllib.parse
|
67 |
+
from scripts.iib.fastapi_video import range_requests_response, close_video_file_reader
|
68 |
+
from scripts.iib.parsers.index import parse_image_info
|
69 |
+
import scripts.iib.plugin
|
70 |
+
|
71 |
+
try:
|
72 |
+
import pillow_avif
|
73 |
+
except Exception as e:
|
74 |
+
logger.error(e)
|
75 |
+
|
76 |
+
|
77 |
+
index_html_path = get_data_file_path("vue/dist/index.html") if is_exe_ver else os.path.join(cwd, "vue/dist/index.html") # 在app.py也被使用
|
78 |
+
|
79 |
+
|
80 |
+
send_img_path = {"value": ""}
|
81 |
+
mem = {"secret_key_hash": None, "extra_paths": [], "all_scanned_paths": []}
|
82 |
+
secret_key = os.getenv("IIB_SECRET_KEY")
|
83 |
+
if secret_key:
|
84 |
+
print("Secret key loaded successfully. ")
|
85 |
+
|
86 |
+
WRITEABLE_PERMISSIONS = ["read-write", "write-only"]
|
87 |
+
|
88 |
+
is_api_writeable = not (os.getenv("IIB_ACCESS_CONTROL_PERMISSION")) or (
|
89 |
+
os.getenv("IIB_ACCESS_CONTROL_PERMISSION") in WRITEABLE_PERMISSIONS
|
90 |
+
)
|
91 |
+
IIB_DEBUG=False
|
92 |
+
|
93 |
+
|
94 |
+
async def write_permission_required():
|
95 |
+
if not is_api_writeable:
|
96 |
+
error_msg = (
|
97 |
+
"User is not authorized to perform this action. Required permission: "
|
98 |
+
+ ", ".join(WRITEABLE_PERMISSIONS)
|
99 |
+
)
|
100 |
+
raise HTTPException(status_code=403, detail=error_msg)
|
101 |
+
|
102 |
+
|
103 |
+
async def verify_secret(request: Request):
|
104 |
+
if not secret_key:
|
105 |
+
if is_secret_key_required:
|
106 |
+
raise HTTPException(status_code=400, detail={"type": "secret_key_required"})
|
107 |
+
return
|
108 |
+
token = request.cookies.get("IIB_S")
|
109 |
+
if not token:
|
110 |
+
raise HTTPException(status_code=401, detail="Unauthorized")
|
111 |
+
if not mem["secret_key_hash"]:
|
112 |
+
mem["secret_key_hash"] = hashlib.sha256(
|
113 |
+
(secret_key + "_ciallo").encode("utf-8")
|
114 |
+
).hexdigest()
|
115 |
+
if mem["secret_key_hash"] != token:
|
116 |
+
raise HTTPException(status_code=401, detail="Unauthorized")
|
117 |
+
|
118 |
+
DEFAULT_BASE = "/infinite_image_browsing"
|
119 |
+
def infinite_image_browsing_api(app: FastAPI, **kwargs):
|
120 |
+
backup_db_file(DataBase.get_db_file_path())
|
121 |
+
api_base = kwargs.get("base") if isinstance(kwargs.get("base"), str) else DEFAULT_BASE
|
122 |
+
fe_public_path = kwargs.get("fe_public_path") if isinstance(kwargs.get("fe_public_path"), str) else api_base
|
123 |
+
cache_base_dir = get_cache_dir()
|
124 |
+
|
125 |
+
# print(f"IIB api_base:{api_base} fe_public_path:{fe_public_path}")
|
126 |
+
if IIB_DEBUG or is_exe_ver:
|
127 |
+
@app.exception_handler(Exception)
|
128 |
+
async def exception_handler(request: Request, exc: Exception):
|
129 |
+
error_msg = f"An exception occurred while processing {request.method} {request.url}: {exc}"
|
130 |
+
logger.error(error_msg)
|
131 |
+
|
132 |
+
return JSONResponse(
|
133 |
+
status_code=500, content={"message": "Internal Server Error"}
|
134 |
+
)
|
135 |
+
@app.middleware("http")
|
136 |
+
async def log_requests(request: Request, call_next):
|
137 |
+
path = request.url.path
|
138 |
+
if (
|
139 |
+
path.find("infinite_image_browsing/image-thumbnail") == -1
|
140 |
+
and path.find("infinite_image_browsing/file") == -1
|
141 |
+
and path.find("infinite_image_browsing/fe-static") == -1
|
142 |
+
):
|
143 |
+
logger.info(f"Received request: {request.method} {request.url}")
|
144 |
+
if request.query_params:
|
145 |
+
logger.debug(f"Query Params: {request.query_params}")
|
146 |
+
if request.path_params:
|
147 |
+
logger.debug(f"Path Params: {request.path_params}")
|
148 |
+
|
149 |
+
try:
|
150 |
+
return await call_next(request)
|
151 |
+
except HTTPException as http_exc:
|
152 |
+
logger.warning(
|
153 |
+
f"HTTPException occurred while processing {request.method} {request.url}: {http_exc}"
|
154 |
+
)
|
155 |
+
raise http_exc
|
156 |
+
except Exception as exc:
|
157 |
+
logger.error(
|
158 |
+
f"An exception occurred while processing {request.method} {request.url}: {exc}"
|
159 |
+
)
|
160 |
+
|
161 |
+
|
162 |
+
if kwargs.get("allow_cors"):
|
163 |
+
app.add_middleware(
|
164 |
+
CORSMiddleware,
|
165 |
+
allow_origin_regex="^[\w./:-]+$",
|
166 |
+
allow_methods=["*"],
|
167 |
+
allow_headers=["*"],
|
168 |
+
allow_credentials=True,
|
169 |
+
)
|
170 |
+
|
171 |
+
def get_img_search_dirs():
|
172 |
+
try:
|
173 |
+
return get_valid_img_dirs(get_sd_webui_conf(**kwargs))
|
174 |
+
except Exception as e:
|
175 |
+
print(e)
|
176 |
+
return []
|
177 |
+
|
178 |
+
def update_all_scanned_paths():
|
179 |
+
allowed_paths = os.getenv("IIB_ACCESS_CONTROL_ALLOWED_PATHS")
|
180 |
+
if allowed_paths:
|
181 |
+
sd_webui_conf = get_sd_webui_conf(**kwargs)
|
182 |
+
path_config_key_map = {
|
183 |
+
"save": "outdir_save",
|
184 |
+
"extra": "outdir_extras_samples",
|
185 |
+
"txt2img": "outdir_txt2img_samples",
|
186 |
+
"img2img": "outdir_img2img_samples",
|
187 |
+
}
|
188 |
+
|
189 |
+
def path_map(path: str):
|
190 |
+
path = path.strip()
|
191 |
+
if path in path_config_key_map:
|
192 |
+
return sd_webui_conf.get(path_config_key_map.get(path))
|
193 |
+
return path
|
194 |
+
|
195 |
+
paths = normalize_paths(
|
196 |
+
seq(allowed_paths.split(","))
|
197 |
+
.map(path_map)
|
198 |
+
.filter(lambda x: x)
|
199 |
+
.to_list(),
|
200 |
+
os.getcwd()
|
201 |
+
)
|
202 |
+
else:
|
203 |
+
paths = (
|
204 |
+
get_img_search_dirs()
|
205 |
+
+ mem["extra_paths"]
|
206 |
+
+ kwargs.get("extra_paths_cli", [])
|
207 |
+
)
|
208 |
+
mem["all_scanned_paths"] = unique_by(paths)
|
209 |
+
|
210 |
+
update_all_scanned_paths()
|
211 |
+
|
212 |
+
def update_extra_paths(conn: sqlite3.Connection):
|
213 |
+
r = ExtraPath.get_extra_paths(conn)
|
214 |
+
mem["extra_paths"] = [x.path for x in r]
|
215 |
+
update_all_scanned_paths()
|
216 |
+
|
217 |
+
def safe_commonpath(seq):
|
218 |
+
try:
|
219 |
+
return os.path.commonpath(seq)
|
220 |
+
except Exception as e:
|
221 |
+
# logger.error(e)
|
222 |
+
return ""
|
223 |
+
|
224 |
+
def is_path_under_parents(path, parent_paths: List[str] = []):
|
225 |
+
"""
|
226 |
+
Check if the given path is under one of the specified parent paths.
|
227 |
+
:param path: The path to check.
|
228 |
+
:param parent_paths: By default, all scanned paths are included in the list of parent paths
|
229 |
+
:return: True if the path is under one of the parent paths, False otherwise.
|
230 |
+
"""
|
231 |
+
try:
|
232 |
+
if not parent_paths:
|
233 |
+
parent_paths = mem["all_scanned_paths"]
|
234 |
+
path = to_abs_path(path)
|
235 |
+
for parent_path in parent_paths:
|
236 |
+
if safe_commonpath([path, parent_path]) == parent_path:
|
237 |
+
return True
|
238 |
+
except Exception as e:
|
239 |
+
logger.error(e)
|
240 |
+
return False
|
241 |
+
|
242 |
+
def is_path_trusted(path: str):
|
243 |
+
if not enable_access_control:
|
244 |
+
return True
|
245 |
+
try:
|
246 |
+
parent_paths = mem["all_scanned_paths"]
|
247 |
+
path = to_abs_path(path)
|
248 |
+
for parent_path in parent_paths:
|
249 |
+
if len(path) <= len(parent_path):
|
250 |
+
if parent_path.startswith(path):
|
251 |
+
return True
|
252 |
+
else:
|
253 |
+
if path.startswith(parent_path):
|
254 |
+
return True
|
255 |
+
except:
|
256 |
+
pass
|
257 |
+
return False
|
258 |
+
|
259 |
+
def check_path_trust(path: str):
|
260 |
+
if not is_path_trusted(path):
|
261 |
+
raise HTTPException(status_code=403)
|
262 |
+
|
263 |
+
def filter_allowed_files(files: List[FileInfoDict]):
|
264 |
+
return [x for x in files if is_path_trusted(x["fullpath"])]
|
265 |
+
|
266 |
+
|
267 |
+
|
268 |
+
class PathsReq(BaseModel):
|
269 |
+
paths: List[str]
|
270 |
+
|
271 |
+
@app.get(f"{api_base}/hello")
|
272 |
+
async def greeting():
|
273 |
+
return "hello"
|
274 |
+
|
275 |
+
@app.get(f"{api_base}/global_setting", dependencies=[Depends(verify_secret)])
|
276 |
+
async def global_setting():
|
277 |
+
all_custom_tags = []
|
278 |
+
|
279 |
+
extra_paths = []
|
280 |
+
app_fe_setting = {}
|
281 |
+
try:
|
282 |
+
conn = DataBase.get_conn()
|
283 |
+
all_custom_tags = Tag.get_all_custom_tag(conn)
|
284 |
+
extra_paths = ExtraPath.get_extra_paths(conn) + [
|
285 |
+
ExtraPath(path, ExtraPathType.cli_only.value)
|
286 |
+
for path in kwargs.get("extra_paths_cli", [])
|
287 |
+
]
|
288 |
+
update_extra_paths(conn)
|
289 |
+
app_fe_setting = GlobalSetting.get_all_settings(conn)
|
290 |
+
except Exception as e:
|
291 |
+
print(e)
|
292 |
+
return {
|
293 |
+
"global_setting": get_sd_webui_conf(**kwargs),
|
294 |
+
"cwd": cwd,
|
295 |
+
"is_win": is_win,
|
296 |
+
"home": os.environ.get("USERPROFILE") if is_win else os.environ.get("HOME"),
|
297 |
+
"sd_cwd": os.getcwd(),
|
298 |
+
"all_custom_tags": all_custom_tags,
|
299 |
+
"extra_paths": extra_paths,
|
300 |
+
"enable_access_control": enable_access_control,
|
301 |
+
"launch_mode": kwargs.get("launch_mode", "sd"),
|
302 |
+
"export_fe_fn": bool(kwargs.get("export_fe_fn")),
|
303 |
+
"app_fe_setting": app_fe_setting,
|
304 |
+
"is_readonly": not is_api_writeable,
|
305 |
+
}
|
306 |
+
|
307 |
+
|
308 |
+
class AppFeSettingReq(BaseModel):
|
309 |
+
name: str
|
310 |
+
value: str
|
311 |
+
|
312 |
+
@app.post(f"{api_base}/app_fe_setting", dependencies=[Depends(verify_secret), Depends(write_permission_required)])
|
313 |
+
async def app_fe_setting(req: AppFeSettingReq):
|
314 |
+
conn = DataBase.get_conn()
|
315 |
+
GlobalSetting.save_setting(conn, req.name, req.value)
|
316 |
+
|
317 |
+
class AppFeSettingDelReq(BaseModel):
|
318 |
+
name: str
|
319 |
+
|
320 |
+
@app.delete(f"{api_base}/app_fe_setting", dependencies=[Depends(verify_secret), Depends(write_permission_required)])
|
321 |
+
async def remove_app_fe_setting(req: AppFeSettingDelReq):
|
322 |
+
conn = DataBase.get_conn()
|
323 |
+
GlobalSetting.remove_setting(conn, req.name)
|
324 |
+
|
325 |
+
@app.get(f"{api_base}/version", dependencies=[Depends(verify_secret)])
|
326 |
+
async def get_version():
|
327 |
+
return {
|
328 |
+
"hash": get_current_commit_hash(),
|
329 |
+
"tag": get_current_tag(),
|
330 |
+
}
|
331 |
+
|
332 |
+
class DeleteFilesReq(BaseModel):
|
333 |
+
file_paths: List[str]
|
334 |
+
|
335 |
+
@app.post(
|
336 |
+
api_base + "/delete_files",
|
337 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
338 |
+
)
|
339 |
+
async def delete_files(req: DeleteFilesReq):
|
340 |
+
conn = DataBase.get_conn()
|
341 |
+
for path in req.file_paths:
|
342 |
+
check_path_trust(path)
|
343 |
+
try:
|
344 |
+
if os.path.isdir(path):
|
345 |
+
if len(os.listdir(path)):
|
346 |
+
error_msg = (
|
347 |
+
"When a folder is not empty, it is not allowed to be deleted."
|
348 |
+
if locale == "en"
|
349 |
+
else "文件夹不为空时不允许删除。"
|
350 |
+
)
|
351 |
+
raise HTTPException(400, detail=error_msg)
|
352 |
+
shutil.rmtree(path)
|
353 |
+
else:
|
354 |
+
close_video_file_reader(path)
|
355 |
+
os.remove(path)
|
356 |
+
txt_path = get_img_geninfo_txt_path(path)
|
357 |
+
if txt_path:
|
358 |
+
os.remove(txt_path)
|
359 |
+
img = DbImg.get(conn, os.path.normpath(path))
|
360 |
+
if img:
|
361 |
+
logger.info("delete file: %s", path)
|
362 |
+
ImageTag.remove(conn, img.id)
|
363 |
+
DbImg.remove(conn, img.id)
|
364 |
+
except OSError as e:
|
365 |
+
# 处理删除失败的情况
|
366 |
+
logger.error("delete failed")
|
367 |
+
error_msg = (
|
368 |
+
f"Error deleting file {path}: {e}"
|
369 |
+
if locale == "en"
|
370 |
+
else f"删除文件 {path} 时出错:{e}"
|
371 |
+
)
|
372 |
+
raise HTTPException(400, detail=error_msg)
|
373 |
+
|
374 |
+
class CreateFoldersReq(BaseModel):
|
375 |
+
dest_folder: str
|
376 |
+
|
377 |
+
@app.post(
|
378 |
+
api_base + "/mkdirs",
|
379 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
380 |
+
)
|
381 |
+
async def create_folders(req: CreateFoldersReq):
|
382 |
+
if enable_access_control:
|
383 |
+
if not is_path_under_parents(req.dest_folder):
|
384 |
+
raise HTTPException(status_code=403)
|
385 |
+
os.makedirs(req.dest_folder, exist_ok=True)
|
386 |
+
|
387 |
+
class MoveFilesReq(BaseModel):
|
388 |
+
file_paths: List[str]
|
389 |
+
dest: str
|
390 |
+
create_dest_folder: Optional[bool] = False
|
391 |
+
|
392 |
+
@app.post(
|
393 |
+
api_base + "/copy_files",
|
394 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
395 |
+
)
|
396 |
+
async def copy_files(req: MoveFilesReq):
|
397 |
+
for path in req.file_paths:
|
398 |
+
check_path_trust(path)
|
399 |
+
try:
|
400 |
+
shutil.copy(path, req.dest)
|
401 |
+
txt_path = get_img_geninfo_txt_path(path)
|
402 |
+
if txt_path:
|
403 |
+
shutil.copy(txt_path, req.dest)
|
404 |
+
except OSError as e:
|
405 |
+
error_msg = (
|
406 |
+
f"Error copying file {path} to {req.dest}: {e}"
|
407 |
+
if locale == "en"
|
408 |
+
else f"复制文件 {path} 到 {req.dest} 时出错:{e}"
|
409 |
+
)
|
410 |
+
raise HTTPException(400, detail=error_msg)
|
411 |
+
|
412 |
+
@app.post(
|
413 |
+
api_base + "/move_files",
|
414 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
415 |
+
)
|
416 |
+
async def move_files(req: MoveFilesReq):
|
417 |
+
if req.create_dest_folder:
|
418 |
+
os.makedirs(req.dest, exist_ok=True)
|
419 |
+
elif not os.path.isdir(req.dest):
|
420 |
+
error_msg = (
|
421 |
+
f"Destination folder {req.dest} does not exist."
|
422 |
+
if locale == "en"
|
423 |
+
else f"目标文件夹 {req.dest} 不存在。"
|
424 |
+
)
|
425 |
+
raise HTTPException(400, detail=error_msg)
|
426 |
+
|
427 |
+
conn = DataBase.get_conn()
|
428 |
+
|
429 |
+
def move_file_with_geninfo(path: str, dest: str):
|
430 |
+
path = os.path.normpath(path)
|
431 |
+
txt_path = get_img_geninfo_txt_path(path)
|
432 |
+
if txt_path:
|
433 |
+
shutil.move(txt_path, dest)
|
434 |
+
img = DbImg.get(conn, path)
|
435 |
+
new_path = os.path.normpath(os.path.join(dest, os.path.basename(path)))
|
436 |
+
if img:
|
437 |
+
logger.info(f"update file path: {path} -> {new_path} in db")
|
438 |
+
img.update_path(conn, new_path, force=True)
|
439 |
+
|
440 |
+
for path in req.file_paths:
|
441 |
+
check_path_trust(path)
|
442 |
+
path = os.path.normpath(path)
|
443 |
+
base_dir = os.path.dirname(path)
|
444 |
+
try:
|
445 |
+
files = list(os.walk(path))
|
446 |
+
is_dir = os.path.isdir(path)
|
447 |
+
shutil.move(path, req.dest)
|
448 |
+
if is_dir:
|
449 |
+
for root, _, files in files:
|
450 |
+
relative_path = root[len(base_dir) + 1 :]
|
451 |
+
dest = os.path.join(req.dest, relative_path)
|
452 |
+
for file in files:
|
453 |
+
is_valid = is_media_file(file)
|
454 |
+
if is_valid:
|
455 |
+
move_file_with_geninfo(os.path.join(root, file), dest)
|
456 |
+
else:
|
457 |
+
move_file_with_geninfo(path, req.dest)
|
458 |
+
|
459 |
+
conn.commit()
|
460 |
+
except OSError as e:
|
461 |
+
|
462 |
+
conn.rollback()
|
463 |
+
error_msg = (
|
464 |
+
f"Error moving file {path} to {req.dest}: {e}"
|
465 |
+
if locale == "en"
|
466 |
+
else f"移动文件 {path} 到 {req.dest} 时出错:{e}"
|
467 |
+
)
|
468 |
+
raise HTTPException(400, detail=error_msg)
|
469 |
+
|
470 |
+
@app.get(api_base + "/files", dependencies=[Depends(verify_secret)])
|
471 |
+
async def get_target_folder_files(folder_path: str):
|
472 |
+
files: List[FileInfoDict] = []
|
473 |
+
try:
|
474 |
+
if is_win and folder_path == "/":
|
475 |
+
for item in get_windows_drives():
|
476 |
+
files.append(
|
477 |
+
{"type": "dir", "size": "-", "name": item, "fullpath": item}
|
478 |
+
)
|
479 |
+
else:
|
480 |
+
if not os.path.exists(folder_path):
|
481 |
+
return {"files": []}
|
482 |
+
folder_path = to_abs_path(folder_path)
|
483 |
+
check_path_trust(folder_path)
|
484 |
+
folder_listing: List[os.DirEntry] = os.scandir(folder_path)
|
485 |
+
is_under_scanned_path = is_path_under_parents(folder_path)
|
486 |
+
for item in folder_listing:
|
487 |
+
if not os.path.exists(item.path):
|
488 |
+
continue
|
489 |
+
fullpath = os.path.normpath(item.path)
|
490 |
+
name = os.path.basename(item.path)
|
491 |
+
stat = item.stat()
|
492 |
+
date = get_formatted_date(stat.st_mtime)
|
493 |
+
created_time = get_created_date_by_stat(stat)
|
494 |
+
if item.is_file():
|
495 |
+
bytes = stat.st_size
|
496 |
+
size = human_readable_size(bytes)
|
497 |
+
files.append(
|
498 |
+
{
|
499 |
+
"type": "file",
|
500 |
+
"date": date,
|
501 |
+
"size": size,
|
502 |
+
"name": name,
|
503 |
+
"bytes": bytes,
|
504 |
+
"created_time": created_time,
|
505 |
+
"fullpath": fullpath,
|
506 |
+
"is_under_scanned_path": is_under_scanned_path,
|
507 |
+
}
|
508 |
+
)
|
509 |
+
elif item.is_dir():
|
510 |
+
files.append(
|
511 |
+
{
|
512 |
+
"type": "dir",
|
513 |
+
"date": date,
|
514 |
+
"created_time": created_time,
|
515 |
+
"size": "-",
|
516 |
+
"name": name,
|
517 |
+
"is_under_scanned_path": is_under_scanned_path,
|
518 |
+
"fullpath": fullpath,
|
519 |
+
}
|
520 |
+
)
|
521 |
+
except Exception as e:
|
522 |
+
# logger.error(e)
|
523 |
+
raise HTTPException(status_code=400, detail=str(e))
|
524 |
+
|
525 |
+
return {"files": filter_allowed_files(files)}
|
526 |
+
|
527 |
+
|
528 |
+
@app.post(api_base + "/batch_get_files_info", dependencies=[Depends(verify_secret)])
|
529 |
+
async def batch_get_files_info(req: PathsReq):
|
530 |
+
res = {}
|
531 |
+
for path in req.paths:
|
532 |
+
check_path_trust(path)
|
533 |
+
res[path] = get_file_info_by_path(path)
|
534 |
+
return res
|
535 |
+
|
536 |
+
@app.get(api_base + "/image-thumbnail", dependencies=[Depends(verify_secret)])
|
537 |
+
async def thumbnail(path: str, t: str, size: str = "256x256"):
|
538 |
+
check_path_trust(path)
|
539 |
+
if not cache_base_dir:
|
540 |
+
return
|
541 |
+
# 生成缓存文件的路径
|
542 |
+
hash_dir = hashlib.md5((path + t).encode("utf-8")).hexdigest()
|
543 |
+
hash = hash_dir + size
|
544 |
+
cache_dir = os.path.join(cache_base_dir, "iib_cache", hash_dir)
|
545 |
+
cache_path = os.path.join(cache_dir, f"{size}.webp")
|
546 |
+
|
547 |
+
# 如果缓存文件存在,则直接返回该文件
|
548 |
+
if os.path.exists(cache_path):
|
549 |
+
return FileResponse(
|
550 |
+
cache_path,
|
551 |
+
media_type="image/webp",
|
552 |
+
headers={"Cache-Control": "max-age=31536000", "ETag": hash},
|
553 |
+
)
|
554 |
+
|
555 |
+
|
556 |
+
# 如果小于64KB,直接返回原图
|
557 |
+
if os.path.getsize(path) < 64 * 1024:
|
558 |
+
return FileResponse(
|
559 |
+
path,
|
560 |
+
media_type="image/" + path.split(".")[-1],
|
561 |
+
headers={"Cache-Control": "max-age=31536000", "ETag": hash},
|
562 |
+
)
|
563 |
+
|
564 |
+
|
565 |
+
# 如果缓存文件不存在,则生成缩略图并保存
|
566 |
+
with Image.open(path) as img:
|
567 |
+
w, h = size.split("x")
|
568 |
+
img.thumbnail((int(w), int(h)))
|
569 |
+
os.makedirs(cache_dir, exist_ok=True)
|
570 |
+
img.save(cache_path, "webp")
|
571 |
+
|
572 |
+
# 返回缓存文件
|
573 |
+
return FileResponse(
|
574 |
+
cache_path,
|
575 |
+
media_type="image/webp",
|
576 |
+
headers={"Cache-Control": "max-age=31536000", "ETag": hash},
|
577 |
+
)
|
578 |
+
|
579 |
+
@app.get(api_base + "/file", dependencies=[Depends(verify_secret)])
|
580 |
+
async def get_file(path: str, t: str, disposition: Optional[str] = None):
|
581 |
+
filename = path
|
582 |
+
import mimetypes
|
583 |
+
|
584 |
+
check_path_trust(path)
|
585 |
+
if not os.path.exists(filename):
|
586 |
+
raise HTTPException(status_code=404)
|
587 |
+
if not os.path.isfile(filename):
|
588 |
+
raise HTTPException(status_code=400, detail=f"{filename} is not a file")
|
589 |
+
# 根据文件后缀名获取媒体类型
|
590 |
+
media_type, _ = mimetypes.guess_type(filename)
|
591 |
+
headers = {}
|
592 |
+
if disposition:
|
593 |
+
encoded_filename = urllib.parse.quote(disposition.encode('utf-8'))
|
594 |
+
headers['Content-Disposition'] = f"attachment; filename*=UTF-8''{encoded_filename}"
|
595 |
+
|
596 |
+
if is_path_under_parents(filename) and is_valid_media_path(
|
597 |
+
filename
|
598 |
+
): # 认为永远不变,不要协商缓存了试试
|
599 |
+
headers[
|
600 |
+
"Cache-Control"
|
601 |
+
] = "public, max-age=31536000" # 针对同样名字文件但实际上不同内容的文件要求必须传入创建时间来避免浏览器缓存
|
602 |
+
headers["Expires"] = (datetime.now() + timedelta(days=365)).strftime(
|
603 |
+
"%a, %d %b %Y %H:%M:%S GMT"
|
604 |
+
)
|
605 |
+
|
606 |
+
return FileResponse(
|
607 |
+
filename,
|
608 |
+
media_type=media_type,
|
609 |
+
headers=headers,
|
610 |
+
)
|
611 |
+
|
612 |
+
@app.get(api_base + "/stream_video", dependencies=[Depends(verify_secret)])
|
613 |
+
async def stream_video(path: str, request: Request):
|
614 |
+
check_path_trust(path)
|
615 |
+
import mimetypes
|
616 |
+
media_type, _ = mimetypes.guess_type(path)
|
617 |
+
return range_requests_response(
|
618 |
+
request, file_path=path, content_type=media_type
|
619 |
+
)
|
620 |
+
|
621 |
+
@app.get(api_base + "/video_cover", dependencies=[Depends(verify_secret)])
|
622 |
+
async def video_cover(path: str, mt: str):
|
623 |
+
check_path_trust(path)
|
624 |
+
if not cache_base_dir:
|
625 |
+
return
|
626 |
+
|
627 |
+
if not os.path.exists(path):
|
628 |
+
raise HTTPException(status_code=404)
|
629 |
+
if not os.path.isfile(path) and get_video_type(path):
|
630 |
+
raise HTTPException(status_code=400, detail=f"{path} is not a video file")
|
631 |
+
# 生成缓存文件的路径
|
632 |
+
hash_dir = hashlib.md5((path + mt).encode("utf-8")).hexdigest()
|
633 |
+
hash = hash_dir
|
634 |
+
cache_dir = os.path.join(cache_base_dir, "iib_cache", "video_cover", hash_dir)
|
635 |
+
cache_path = os.path.join(cache_dir, "cover.webp")
|
636 |
+
# 如果缓存文件存在,则直接返回该文件
|
637 |
+
if os.path.exists(cache_path):
|
638 |
+
return FileResponse(
|
639 |
+
cache_path,
|
640 |
+
media_type="image/webp",
|
641 |
+
headers={
|
642 |
+
"Cache-Control": "no-store",
|
643 |
+
},
|
644 |
+
)
|
645 |
+
# 如果缓存文件不存在,则生成缩略图并保存
|
646 |
+
|
647 |
+
import imageio.v3 as iio
|
648 |
+
frame = iio.imread(
|
649 |
+
path,
|
650 |
+
index=16,
|
651 |
+
plugin="pyav",
|
652 |
+
)
|
653 |
+
|
654 |
+
os.makedirs(cache_dir, exist_ok=True)
|
655 |
+
iio.imwrite(cache_path,frame, extension=".webp")
|
656 |
+
|
657 |
+
# 返回缓存文件
|
658 |
+
return FileResponse(
|
659 |
+
cache_path,
|
660 |
+
media_type="image/webp",
|
661 |
+
headers={
|
662 |
+
"Cache-Control": "no-store",
|
663 |
+
},
|
664 |
+
)
|
665 |
+
|
666 |
+
class SetTargetFrameAsCoverReq(BaseModel):
|
667 |
+
base64_img: str
|
668 |
+
path: str
|
669 |
+
updated_time: str
|
670 |
+
|
671 |
+
def save_base64_image(base64_str, file_path):
|
672 |
+
if base64_str.startswith('data:image'):
|
673 |
+
base64_str = base64_str.split(',')[1]
|
674 |
+
image_data = base64.b64decode(base64_str)
|
675 |
+
with open(file_path, 'wb') as file:
|
676 |
+
file.write(image_data)
|
677 |
+
|
678 |
+
@app.post(api_base+ "/set_target_frame_as_video_cover", dependencies=[Depends(verify_secret), Depends(write_permission_required)])
|
679 |
+
async def set_target_frame_as_video_cover(req: SetTargetFrameAsCoverReq):
|
680 |
+
hash_dir = hashlib.md5((req.path + req.updated_time).encode("utf-8")).hexdigest()
|
681 |
+
hash = hash_dir
|
682 |
+
cache_dir = os.path.join(cache_base_dir, "iib_cache", "video_cover", hash_dir)
|
683 |
+
cache_path = os.path.join(cache_dir, "cover.webp")
|
684 |
+
|
685 |
+
os.makedirs(cache_dir, exist_ok=True)
|
686 |
+
|
687 |
+
save_base64_image(req.base64_img, cache_path)
|
688 |
+
return FileResponse(
|
689 |
+
cache_path,
|
690 |
+
media_type="image/webp",
|
691 |
+
headers={"ETag": hash},
|
692 |
+
)
|
693 |
+
|
694 |
+
@app.post(api_base + "/send_img_path", dependencies=[Depends(verify_secret)])
|
695 |
+
async def api_set_send_img_path(path: str):
|
696 |
+
send_img_path["value"] = path
|
697 |
+
|
698 |
+
# 等待图片信息生成完成
|
699 |
+
@app.get(api_base + "/gen_info_completed", dependencies=[Depends(verify_secret)])
|
700 |
+
async def api_set_send_img_path():
|
701 |
+
for _ in range(30): # timeout 3s
|
702 |
+
if send_img_path["value"] == "": # 等待setup里面生成完成
|
703 |
+
return True
|
704 |
+
v = send_img_path["value"]
|
705 |
+
# is_dev and logger.info("gen_info_completed %s %s", _, v)
|
706 |
+
await asyncio.sleep(0.1)
|
707 |
+
return send_img_path["value"] == ""
|
708 |
+
|
709 |
+
@app.get(api_base + "/image_geninfo", dependencies=[Depends(verify_secret)])
|
710 |
+
async def image_geninfo(path: str):
|
711 |
+
return parse_image_info(path).raw_info
|
712 |
+
|
713 |
+
class GeninfoBatchReq(BaseModel):
|
714 |
+
paths: List[str]
|
715 |
+
|
716 |
+
@app.post(api_base + "/image_geninfo_batch", dependencies=[Depends(verify_secret)])
|
717 |
+
async def image_geninfo_batch(req: GeninfoBatchReq):
|
718 |
+
res = {}
|
719 |
+
conn = DataBase.get_conn()
|
720 |
+
for path in req.paths:
|
721 |
+
try:
|
722 |
+
img = DbImg.get(conn, path)
|
723 |
+
if img:
|
724 |
+
res[path] = img.exif
|
725 |
+
else:
|
726 |
+
res[path] = parse_image_info(path).raw_info
|
727 |
+
except Exception as e:
|
728 |
+
logger.error(e, stack_info=True)
|
729 |
+
return res
|
730 |
+
|
731 |
+
|
732 |
+
class CheckPathExistsReq(BaseModel):
|
733 |
+
paths: List[str]
|
734 |
+
|
735 |
+
@app.post(api_base + "/check_path_exists", dependencies=[Depends(verify_secret)])
|
736 |
+
async def check_path_exists(req: CheckPathExistsReq):
|
737 |
+
update_all_scanned_paths()
|
738 |
+
res = {}
|
739 |
+
for path in req.paths:
|
740 |
+
res[path] = os.path.exists(path) and is_path_trusted(path)
|
741 |
+
return res
|
742 |
+
|
743 |
+
@app.get(api_base)
|
744 |
+
def index_bd():
|
745 |
+
if fe_public_path:
|
746 |
+
with open(index_html_path, "r", encoding="utf-8") as file:
|
747 |
+
content = file.read().replace(DEFAULT_BASE, fe_public_path)
|
748 |
+
return Response(content=content, media_type="text/html")
|
749 |
+
return FileResponse(index_html_path)
|
750 |
+
|
751 |
+
static_dir = get_data_file_path("vue/dist") if is_exe_ver else f"{cwd}/vue/dist"
|
752 |
+
@app.get(api_base + "/fe-static/{file_path:path}")
|
753 |
+
async def serve_static_file(file_path: str):
|
754 |
+
file_full_path = f"{static_dir}/{file_path}"
|
755 |
+
if file_path.endswith(".js"):
|
756 |
+
with open(file_full_path, "r", encoding="utf-8") as file:
|
757 |
+
content = file.read().replace(DEFAULT_BASE, fe_public_path)
|
758 |
+
return Response(content=content, media_type="text/javascript")
|
759 |
+
else:
|
760 |
+
return FileResponse(file_full_path)
|
761 |
+
|
762 |
+
class OpenFolderReq(BaseModel):
|
763 |
+
path: str
|
764 |
+
|
765 |
+
@app.post(
|
766 |
+
api_base + "/open_folder",
|
767 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
768 |
+
)
|
769 |
+
def open_folder_using_explore(req: OpenFolderReq):
|
770 |
+
if not is_path_trusted(req.path):
|
771 |
+
raise HTTPException(status_code=403)
|
772 |
+
open_folder(*os.path.split(req.path))
|
773 |
+
|
774 |
+
@app.post(api_base + "/shutdown")
|
775 |
+
async def shutdown_app():
|
776 |
+
# This API endpoint is mainly used as a sidecar in Tauri applications to shut down the application
|
777 |
+
if not kwargs.get("enable_shutdown"):
|
778 |
+
raise HTTPException(status_code=403, detail="Shutdown is disabled.")
|
779 |
+
os.kill(os.getpid(), 9)
|
780 |
+
return {"message": "Application is shutting down."}
|
781 |
+
|
782 |
+
|
783 |
+
class PackReq(BaseModel):
|
784 |
+
paths: List[str]
|
785 |
+
compress: bool
|
786 |
+
pack_only: bool
|
787 |
+
|
788 |
+
|
789 |
+
@app.post(
|
790 |
+
api_base + "/zip",
|
791 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
792 |
+
)
|
793 |
+
def zip_files(req: PackReq):
|
794 |
+
for path in req.paths:
|
795 |
+
check_path_trust(path)
|
796 |
+
if not os.path.isfile(path):
|
797 |
+
raise HTTPException(400, "The corresponding path must be a file.")
|
798 |
+
now = datetime.now()
|
799 |
+
timestamp = now.strftime("%Y-%m-%d-%H-%M-%S")
|
800 |
+
zip_temp_dir = os.path.join(cwd, "zip_temp")
|
801 |
+
os.makedirs(zip_temp_dir, exist_ok=True)
|
802 |
+
file_path = os.path.join(zip_temp_dir, f"iib_batch_download_{timestamp}.zip")
|
803 |
+
create_zip_file(req.paths, file_path, req.compress)
|
804 |
+
if not req.pack_only:
|
805 |
+
return FileResponse(file_path, media_type="application/zip")
|
806 |
+
|
807 |
+
@app.post(
|
808 |
+
api_base + "/open_with_default_app",
|
809 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
810 |
+
)
|
811 |
+
def open_target_file_withDefault_app(req: OpenFolderReq):
|
812 |
+
check_path_trust(req.path)
|
813 |
+
open_file_with_default_app(req.path)
|
814 |
+
|
815 |
+
|
816 |
+
@app.post(
|
817 |
+
api_base + "/batch_top_4_media_info",
|
818 |
+
dependencies=[Depends(verify_secret)],
|
819 |
+
)
|
820 |
+
def batch_get_top_4_media_cover_info(req: PathsReq):
|
821 |
+
for path in req.paths:
|
822 |
+
check_path_trust(path)
|
823 |
+
res = {}
|
824 |
+
for path in req.paths:
|
825 |
+
res[path] = get_top_4_media_info(path)
|
826 |
+
return res
|
827 |
+
|
828 |
+
db_api_base = api_base + "/db"
|
829 |
+
|
830 |
+
@app.get(db_api_base + "/basic_info", dependencies=[Depends(verify_secret)])
|
831 |
+
async def get_db_basic_info():
|
832 |
+
conn = DataBase.get_conn()
|
833 |
+
img_count = DbImg.count(conn)
|
834 |
+
tags = Tag.get_all(conn)
|
835 |
+
expired_dirs = Folder.get_expired_dirs(conn)
|
836 |
+
return {
|
837 |
+
"img_count": img_count,
|
838 |
+
"tags": tags,
|
839 |
+
"expired": len(expired_dirs) != 0,
|
840 |
+
"expired_dirs": expired_dirs,
|
841 |
+
}
|
842 |
+
|
843 |
+
|
844 |
+
|
845 |
+
|
846 |
+
@app.get(db_api_base + "/random_images", dependencies=[Depends(verify_secret)])
|
847 |
+
async def random_image():
|
848 |
+
conn = DataBase.get_conn()
|
849 |
+
imgs = DbImg.get_random_images(conn, 128)
|
850 |
+
return filter_allowed_files([x.to_file_info() for x in imgs])
|
851 |
+
|
852 |
+
@app.get(db_api_base + "/expired_dirs", dependencies=[Depends(verify_secret)])
|
853 |
+
async def get_db_expired():
|
854 |
+
conn = DataBase.get_conn()
|
855 |
+
expired_dirs = Folder.get_expired_dirs(conn)
|
856 |
+
return {
|
857 |
+
"expired": len(expired_dirs) != 0,
|
858 |
+
"expired_dirs": expired_dirs,
|
859 |
+
}
|
860 |
+
|
861 |
+
@app.post(
|
862 |
+
db_api_base + "/update_image_data",
|
863 |
+
dependencies=[Depends(verify_secret)],
|
864 |
+
)
|
865 |
+
async def update_image_db_data():
|
866 |
+
try:
|
867 |
+
DataBase._initing = True
|
868 |
+
conn = DataBase.get_conn()
|
869 |
+
img_count = DbImg.count(conn)
|
870 |
+
update_extra_paths(conn)
|
871 |
+
dirs = (
|
872 |
+
get_img_search_dirs()
|
873 |
+
if img_count == 0
|
874 |
+
else Folder.get_expired_dirs(conn)
|
875 |
+
) + mem["extra_paths"]
|
876 |
+
|
877 |
+
update_image_data(dirs)
|
878 |
+
finally:
|
879 |
+
DataBase._initing = False
|
880 |
+
|
881 |
+
class SearchBySubstrReq(BaseModel):
|
882 |
+
surstr: str
|
883 |
+
cursor: str
|
884 |
+
regexp: str
|
885 |
+
folder_paths: List[str] = None
|
886 |
+
size: Optional[int] = 200
|
887 |
+
path_only: Optional[bool] = False
|
888 |
+
|
889 |
+
@app.post(db_api_base + "/search_by_substr", dependencies=[Depends(verify_secret)])
|
890 |
+
async def search_by_substr(req: SearchBySubstrReq):
|
891 |
+
if IIB_DEBUG:
|
892 |
+
logger.info(req)
|
893 |
+
conn = DataBase.get_conn()
|
894 |
+
folder_paths=normalize_paths(req.folder_paths, os.getcwd())
|
895 |
+
if(not folder_paths and req.folder_paths):
|
896 |
+
return { "files": [], "cursor": Cursor(has_next=False) }
|
897 |
+
imgs, next_cursor = DbImg.find_by_substring(
|
898 |
+
conn=conn,
|
899 |
+
substring=req.surstr,
|
900 |
+
cursor=req.cursor,
|
901 |
+
limit=req.size,
|
902 |
+
regexp=req.regexp,
|
903 |
+
folder_paths=folder_paths,
|
904 |
+
path_only=req.path_only
|
905 |
+
)
|
906 |
+
return {
|
907 |
+
"files": filter_allowed_files([x.to_file_info() for x in imgs]),
|
908 |
+
"cursor": next_cursor
|
909 |
+
}
|
910 |
+
|
911 |
+
class MatchImagesByTagsReq(BaseModel):
|
912 |
+
and_tags: List[int]
|
913 |
+
or_tags: List[int]
|
914 |
+
not_tags: List[int]
|
915 |
+
cursor: str
|
916 |
+
folder_paths: List[str] = None
|
917 |
+
size: Optional[int] = 200
|
918 |
+
|
919 |
+
@app.post(db_api_base + "/match_images_by_tags", dependencies=[Depends(verify_secret)])
|
920 |
+
async def match_image_by_tags(req: MatchImagesByTagsReq):
|
921 |
+
if IIB_DEBUG:
|
922 |
+
logger.info(req)
|
923 |
+
conn = DataBase.get_conn()
|
924 |
+
folder_paths=normalize_paths(req.folder_paths, os.getcwd())
|
925 |
+
if(not folder_paths and req.folder_paths):
|
926 |
+
return { "files": [], "cursor": Cursor(has_next=False) }
|
927 |
+
imgs, next_cursor = ImageTag.get_images_by_tags(
|
928 |
+
conn=conn,
|
929 |
+
tag_dict={"and": req.and_tags, "or": req.or_tags, "not": req.not_tags},
|
930 |
+
cursor=req.cursor,
|
931 |
+
folder_paths=folder_paths,
|
932 |
+
limit=req.size
|
933 |
+
)
|
934 |
+
return {
|
935 |
+
"files": filter_allowed_files([x.to_file_info() for x in imgs]),
|
936 |
+
"cursor": next_cursor
|
937 |
+
}
|
938 |
+
|
939 |
+
@app.get(db_api_base + "/img_selected_custom_tag", dependencies=[Depends(verify_secret)])
|
940 |
+
async def get_img_selected_custom_tag(path: str):
|
941 |
+
path = os.path.normpath(path)
|
942 |
+
if not is_valid_media_path(path):
|
943 |
+
return []
|
944 |
+
conn = DataBase.get_conn()
|
945 |
+
update_extra_paths(conn)
|
946 |
+
if not is_path_under_parents(path):
|
947 |
+
return []
|
948 |
+
img = DbImg.get(conn, path)
|
949 |
+
if not img:
|
950 |
+
if DbImg.count(conn) == 0:
|
951 |
+
return []
|
952 |
+
update_image_data([os.path.dirname(path)])
|
953 |
+
img = DbImg.get(conn, path)
|
954 |
+
assert img
|
955 |
+
# tags = Tag.get_all_custom_tag()
|
956 |
+
return ImageTag.get_tags_for_image(conn, img.id, type="custom")
|
957 |
+
|
958 |
+
@app.post(db_api_base + "/get_image_tags", dependencies=[Depends(verify_secret)])
|
959 |
+
async def get_img_tags(req: PathsReq):
|
960 |
+
conn = DataBase.get_conn()
|
961 |
+
return ImageTag.batch_get_tags_by_path(conn, req.paths)
|
962 |
+
|
963 |
+
|
964 |
+
# update tag
|
965 |
+
class UpdateTagReq(BaseModel):
|
966 |
+
id: int
|
967 |
+
color: str
|
968 |
+
|
969 |
+
@app.post(
|
970 |
+
db_api_base + "/update_tag",
|
971 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
972 |
+
)
|
973 |
+
async def update_tag(req: UpdateTagReq):
|
974 |
+
conn = DataBase.get_conn()
|
975 |
+
tag = Tag.get(conn, req.id)
|
976 |
+
if tag:
|
977 |
+
tag.color = req.color
|
978 |
+
tag.save(conn)
|
979 |
+
conn.commit()
|
980 |
+
|
981 |
+
|
982 |
+
class ToggleCustomTagToImgReq(BaseModel):
|
983 |
+
img_path: str
|
984 |
+
tag_id: int
|
985 |
+
|
986 |
+
@app.post(
|
987 |
+
db_api_base + "/toggle_custom_tag_to_img",
|
988 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
989 |
+
)
|
990 |
+
async def toggle_custom_tag_to_img(req: ToggleCustomTagToImgReq):
|
991 |
+
conn = DataBase.get_conn()
|
992 |
+
path = os.path.normpath(req.img_path)
|
993 |
+
update_extra_paths(conn)
|
994 |
+
if not is_path_under_parents(path):
|
995 |
+
raise HTTPException(
|
996 |
+
400,
|
997 |
+
'当前文件不在搜索路径内,你可以将它添加到扫描路径再尝试。在右上角的"更多"里面'
|
998 |
+
if locale == "zh"
|
999 |
+
else 'The current file is not within the scan path. You can add it to the scan path and try again. In the top right corner, click on "More".',
|
1000 |
+
)
|
1001 |
+
img = DbImg.get(conn, path)
|
1002 |
+
if not img:
|
1003 |
+
if DbImg.count(conn):
|
1004 |
+
# update_image_data([os.path.dirname(path)])
|
1005 |
+
add_image_data_single(path)
|
1006 |
+
img = DbImg.get(conn, path)
|
1007 |
+
else:
|
1008 |
+
raise HTTPException(
|
1009 |
+
400,
|
1010 |
+
"你需要先通过图像搜索页生成索引"
|
1011 |
+
if locale == "zh"
|
1012 |
+
else "You need to generate an index through the image search page first.",
|
1013 |
+
)
|
1014 |
+
tags = ImageTag.get_tags_for_image(
|
1015 |
+
conn=conn, image_id=img.id, type="custom", tag_id=req.tag_id
|
1016 |
+
)
|
1017 |
+
is_remove = len(tags)
|
1018 |
+
if is_remove:
|
1019 |
+
ImageTag.remove(conn, img.id, tags[0].id)
|
1020 |
+
else:
|
1021 |
+
ImageTag(img.id, req.tag_id).save(conn)
|
1022 |
+
conn.commit()
|
1023 |
+
return {"is_remove": is_remove}
|
1024 |
+
|
1025 |
+
class BatchUpdateImageReq(BaseModel):
|
1026 |
+
img_paths: List[str]
|
1027 |
+
action: str
|
1028 |
+
tag_id: int
|
1029 |
+
|
1030 |
+
@app.post(
|
1031 |
+
db_api_base + "/batch_update_image_tag",
|
1032 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
1033 |
+
)
|
1034 |
+
async def batch_update_image_tag(req: BatchUpdateImageReq):
|
1035 |
+
assert req.action in ["add", "remove"]
|
1036 |
+
conn = DataBase.get_conn()
|
1037 |
+
paths: List[str] = seq(req.img_paths).map(os.path.normpath).to_list()
|
1038 |
+
update_extra_paths(conn)
|
1039 |
+
for path in paths:
|
1040 |
+
if not is_path_under_parents(path):
|
1041 |
+
raise HTTPException(
|
1042 |
+
400,
|
1043 |
+
'当前文件不在搜索路径内,你可以将它添加到扫描路径再尝试。在右上角的"更多"里面'
|
1044 |
+
if locale == "zh"
|
1045 |
+
else 'The current file is not within the scan path. You can add it to the scan path and try again. In the top right corner, click on "More".',
|
1046 |
+
)
|
1047 |
+
img = DbImg.get(conn, path)
|
1048 |
+
if not img:
|
1049 |
+
if DbImg.count(conn):
|
1050 |
+
add_image_data_single(path)
|
1051 |
+
img = DbImg.get(conn, path)
|
1052 |
+
else:
|
1053 |
+
raise HTTPException(
|
1054 |
+
400,
|
1055 |
+
"你需要先通过图像搜索页生成索引"
|
1056 |
+
if locale == "zh"
|
1057 |
+
else "You need to generate an index through the image search page first.",
|
1058 |
+
)
|
1059 |
+
try:
|
1060 |
+
for path in paths:
|
1061 |
+
img = DbImg.get(conn, path)
|
1062 |
+
if req.action == "add":
|
1063 |
+
ImageTag(img.id, req.tag_id).save_or_ignore(conn)
|
1064 |
+
else:
|
1065 |
+
ImageTag.remove(conn, img.id, req.tag_id)
|
1066 |
+
finally:
|
1067 |
+
conn.commit()
|
1068 |
+
|
1069 |
+
class AddCustomTagReq(BaseModel):
|
1070 |
+
tag_name: str
|
1071 |
+
|
1072 |
+
@app.post(
|
1073 |
+
db_api_base + "/add_custom_tag",
|
1074 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
1075 |
+
)
|
1076 |
+
async def add_custom_tag(req: AddCustomTagReq):
|
1077 |
+
conn = DataBase.get_conn()
|
1078 |
+
tag = Tag.get_or_create(conn, name=req.tag_name, type="custom")
|
1079 |
+
conn.commit()
|
1080 |
+
return tag
|
1081 |
+
|
1082 |
+
class RenameFileReq(BaseModel):
|
1083 |
+
path: str
|
1084 |
+
name: str
|
1085 |
+
|
1086 |
+
@app.post(
|
1087 |
+
db_api_base + "/rename",
|
1088 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
1089 |
+
)
|
1090 |
+
async def rename_file(req: RenameFileReq):
|
1091 |
+
conn = DataBase.get_conn()
|
1092 |
+
try:
|
1093 |
+
# Normalize the paths
|
1094 |
+
|
1095 |
+
path = os.path.normpath(req.path)
|
1096 |
+
new_path = os.path.join(os.path.dirname(path), req.name)
|
1097 |
+
|
1098 |
+
# Check if the file exists
|
1099 |
+
if not os.path.exists(path):
|
1100 |
+
raise HTTPException(status_code=404, detail="File not found")
|
1101 |
+
|
1102 |
+
# Check if a file with the new name already exists
|
1103 |
+
if os.path.exists(new_path):
|
1104 |
+
raise HTTPException(status_code=400, detail="A file with the new name already exists")
|
1105 |
+
close_video_file_reader(path)
|
1106 |
+
img = DbImg.get(conn, path)
|
1107 |
+
if img:
|
1108 |
+
img.update_path(conn, new_path)
|
1109 |
+
conn.commit()
|
1110 |
+
|
1111 |
+
# Perform the file rename operation
|
1112 |
+
os.rename(path, new_path)
|
1113 |
+
|
1114 |
+
|
1115 |
+
return {"detail": "File renamed successfully", "new_path": new_path}
|
1116 |
+
|
1117 |
+
except PermissionError:
|
1118 |
+
raise HTTPException(status_code=403, detail="Permission denied")
|
1119 |
+
except Exception as e:
|
1120 |
+
raise HTTPException(status_code=500, detail=str(e))
|
1121 |
+
|
1122 |
+
class RemoveCustomTagReq(BaseModel):
|
1123 |
+
tag_id: int
|
1124 |
+
|
1125 |
+
@app.post(
|
1126 |
+
db_api_base + "/remove_custom_tag",
|
1127 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
1128 |
+
)
|
1129 |
+
async def remove_custom_tag(req: RemoveCustomTagReq):
|
1130 |
+
conn = DataBase.get_conn()
|
1131 |
+
ImageTag.remove(conn, tag_id=req.tag_id)
|
1132 |
+
Tag.remove(conn, req.tag_id)
|
1133 |
+
|
1134 |
+
class RemoveCustomTagFromReq(BaseModel):
|
1135 |
+
img_id: int
|
1136 |
+
tag_id: str
|
1137 |
+
|
1138 |
+
@app.post(
|
1139 |
+
db_api_base + "/remove_custom_tag_from_img",
|
1140 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
1141 |
+
)
|
1142 |
+
async def remove_custom_tag_from_img(req: RemoveCustomTagFromReq):
|
1143 |
+
conn = DataBase.get_conn()
|
1144 |
+
ImageTag.remove(conn, image_id=req.img_id, tag_id=req.tag_id)
|
1145 |
+
|
1146 |
+
|
1147 |
+
|
1148 |
+
|
1149 |
+
class ExtraPathModel(BaseModel):
|
1150 |
+
path: str
|
1151 |
+
types: List[str]
|
1152 |
+
|
1153 |
+
@app.post(
|
1154 |
+
f"{db_api_base}/extra_paths",
|
1155 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
1156 |
+
)
|
1157 |
+
async def create_extra_path(extra_path: ExtraPathModel):
|
1158 |
+
if enable_access_control:
|
1159 |
+
if not is_path_under_parents(extra_path.path):
|
1160 |
+
raise HTTPException(status_code=403)
|
1161 |
+
conn = DataBase.get_conn()
|
1162 |
+
path = ExtraPath.get_target_path(conn, extra_path.path)
|
1163 |
+
if path:
|
1164 |
+
for t in extra_path.types:
|
1165 |
+
path.types.append(t)
|
1166 |
+
path.types = unique_by(path.types)
|
1167 |
+
else:
|
1168 |
+
path = ExtraPath(extra_path.path, extra_path.types)
|
1169 |
+
try:
|
1170 |
+
path.save(conn)
|
1171 |
+
finally:
|
1172 |
+
conn.commit()
|
1173 |
+
|
1174 |
+
class ExtraPathAliasModel(BaseModel):
|
1175 |
+
path: str
|
1176 |
+
alias: str
|
1177 |
+
|
1178 |
+
|
1179 |
+
@app.post(
|
1180 |
+
f"{db_api_base}/alias_extra_path",
|
1181 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
1182 |
+
)
|
1183 |
+
async def alias_extra_path(req: ExtraPathAliasModel):
|
1184 |
+
conn = DataBase.get_conn()
|
1185 |
+
path = ExtraPath.get_target_path(conn, req.path)
|
1186 |
+
if not path:
|
1187 |
+
raise HTTPException(400)
|
1188 |
+
path.alias = req.alias
|
1189 |
+
try:
|
1190 |
+
path.save(conn)
|
1191 |
+
finally:
|
1192 |
+
conn.commit()
|
1193 |
+
return path
|
1194 |
+
|
1195 |
+
|
1196 |
+
@app.get(
|
1197 |
+
f"{db_api_base}/extra_paths",
|
1198 |
+
dependencies=[Depends(verify_secret)],
|
1199 |
+
)
|
1200 |
+
async def read_extra_paths():
|
1201 |
+
conn = DataBase.get_conn()
|
1202 |
+
return ExtraPath.get_extra_paths(conn)
|
1203 |
+
|
1204 |
+
|
1205 |
+
|
1206 |
+
@app.delete(
|
1207 |
+
f"{db_api_base}/extra_paths",
|
1208 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
1209 |
+
)
|
1210 |
+
async def delete_extra_path(extra_path: ExtraPathModel):
|
1211 |
+
path = to_abs_path(extra_path.path)
|
1212 |
+
conn = DataBase.get_conn()
|
1213 |
+
ExtraPath.remove(conn, path, extra_path.types, img_search_dirs=get_img_search_dirs())
|
1214 |
+
|
1215 |
+
|
1216 |
+
@app.post(
|
1217 |
+
f"{db_api_base}/rebuild_index",
|
1218 |
+
dependencies=[Depends(verify_secret), Depends(write_permission_required)],
|
1219 |
+
)
|
1220 |
+
async def rebuild_index():
|
1221 |
+
update_extra_paths(conn = DataBase.get_conn())
|
1222 |
+
rebuild_image_index(search_dirs = get_img_search_dirs() + mem["extra_paths"])
|
1223 |
+
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/db/datamodel.py
ADDED
@@ -0,0 +1,890 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime
|
2 |
+
import json
|
3 |
+
import random
|
4 |
+
from sqlite3 import Connection, connect
|
5 |
+
from enum import Enum
|
6 |
+
import sqlite3
|
7 |
+
from typing import Dict, List, Optional, TypedDict, Union
|
8 |
+
from scripts.iib.tool import (
|
9 |
+
cwd,
|
10 |
+
get_modified_date,
|
11 |
+
human_readable_size,
|
12 |
+
tags_translate,
|
13 |
+
is_dev,
|
14 |
+
find,
|
15 |
+
unique_by,
|
16 |
+
)
|
17 |
+
from contextlib import closing
|
18 |
+
import os
|
19 |
+
import threading
|
20 |
+
import re
|
21 |
+
|
22 |
+
|
23 |
+
class FileInfoDict(TypedDict):
|
24 |
+
type: str
|
25 |
+
date: float
|
26 |
+
size: int
|
27 |
+
name: str
|
28 |
+
bytes: bytes
|
29 |
+
created_time: float
|
30 |
+
fullpath: str
|
31 |
+
|
32 |
+
|
33 |
+
class Cursor:
|
34 |
+
def __init__(self, has_next=True, next=""):
|
35 |
+
self.has_next = has_next
|
36 |
+
self.next = next
|
37 |
+
|
38 |
+
|
39 |
+
class DataBase:
|
40 |
+
local = threading.local()
|
41 |
+
|
42 |
+
_initing = False
|
43 |
+
|
44 |
+
num = 0
|
45 |
+
|
46 |
+
path = os.getenv("IIB_DB_PATH", "iib.db")
|
47 |
+
|
48 |
+
@classmethod
|
49 |
+
def get_conn(clz) -> Connection:
|
50 |
+
# for : sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread
|
51 |
+
if hasattr(clz.local, "conn"):
|
52 |
+
return clz.local.conn
|
53 |
+
else:
|
54 |
+
conn = clz.init()
|
55 |
+
clz.local.conn = conn
|
56 |
+
|
57 |
+
return conn
|
58 |
+
|
59 |
+
@classmethod
|
60 |
+
def get_db_file_path(clz):
|
61 |
+
return clz.path if os.path.isabs(clz.path) else os.path.join(cwd, clz.path)
|
62 |
+
|
63 |
+
@classmethod
|
64 |
+
def init(clz):
|
65 |
+
# 创建连接并打开数据库
|
66 |
+
conn = connect(clz.get_db_file_path())
|
67 |
+
|
68 |
+
def regexp(expr, item):
|
69 |
+
if not isinstance(item, str):
|
70 |
+
return False
|
71 |
+
reg = re.compile(expr, flags=re.IGNORECASE | re.MULTILINE | re.DOTALL)
|
72 |
+
return reg.search(item) is not None
|
73 |
+
|
74 |
+
conn.create_function("regexp", 2, regexp)
|
75 |
+
try:
|
76 |
+
Folder.create_table(conn)
|
77 |
+
ImageTag.create_table(conn)
|
78 |
+
Tag.create_table(conn)
|
79 |
+
Image.create_table(conn)
|
80 |
+
ExtraPath.create_table(conn)
|
81 |
+
DirCoverCache.create_table(conn)
|
82 |
+
GlobalSetting.create_table(conn)
|
83 |
+
finally:
|
84 |
+
conn.commit()
|
85 |
+
clz.num += 1
|
86 |
+
if is_dev:
|
87 |
+
print(f"当前连接数{clz.num}")
|
88 |
+
return conn
|
89 |
+
|
90 |
+
|
91 |
+
class Image:
|
92 |
+
def __init__(self, path, exif=None, size=0, date="", id=None):
|
93 |
+
self.path = path
|
94 |
+
self.exif = exif
|
95 |
+
self.id = id
|
96 |
+
self.size = size
|
97 |
+
self.date = date
|
98 |
+
|
99 |
+
def to_file_info(self) -> FileInfoDict:
|
100 |
+
return {
|
101 |
+
"type": "file",
|
102 |
+
"id": self.id,
|
103 |
+
"date": self.date,
|
104 |
+
"created_date": self.date,
|
105 |
+
"size": human_readable_size(self.size),
|
106 |
+
"is_under_scanned_path": True,
|
107 |
+
"bytes": self.size,
|
108 |
+
"name": os.path.basename(self.path),
|
109 |
+
"fullpath": self.path,
|
110 |
+
}
|
111 |
+
|
112 |
+
def save(self, conn):
|
113 |
+
with closing(conn.cursor()) as cur:
|
114 |
+
cur.execute(
|
115 |
+
"INSERT OR REPLACE INTO image (path, exif, size, date) VALUES (?, ?, ?, ?)",
|
116 |
+
(self.path, self.exif, self.size, self.date),
|
117 |
+
)
|
118 |
+
self.id = cur.lastrowid
|
119 |
+
|
120 |
+
def update_path(self, conn: Connection, new_path: str, force=False):
|
121 |
+
self.path = os.path.normpath(new_path)
|
122 |
+
with closing(conn.cursor()) as cur:
|
123 |
+
if force: # force update path
|
124 |
+
cur.execute("DELETE FROM image WHERE path = ?", (self.path,))
|
125 |
+
cur.execute("UPDATE image SET path = ? WHERE id = ?", (self.path, self.id))
|
126 |
+
|
127 |
+
@classmethod
|
128 |
+
def get(cls, conn: Connection, id_or_path):
|
129 |
+
with closing(conn.cursor()) as cur:
|
130 |
+
cur.execute(
|
131 |
+
"SELECT * FROM image WHERE id = ? OR path = ?", (id_or_path, id_or_path)
|
132 |
+
)
|
133 |
+
row = cur.fetchone()
|
134 |
+
if row is None:
|
135 |
+
return None
|
136 |
+
else:
|
137 |
+
return cls.from_row(row)
|
138 |
+
|
139 |
+
@classmethod
|
140 |
+
def get_by_ids(cls, conn: Connection, ids: List[int]) -> List["Image"]:
|
141 |
+
if not ids:
|
142 |
+
return []
|
143 |
+
|
144 |
+
query = """
|
145 |
+
SELECT * FROM image
|
146 |
+
WHERE id IN ({})
|
147 |
+
""".format(
|
148 |
+
",".join("?" * len(ids))
|
149 |
+
)
|
150 |
+
|
151 |
+
with closing(conn.cursor()) as cur:
|
152 |
+
cur.execute(query, ids)
|
153 |
+
rows = cur.fetchall()
|
154 |
+
|
155 |
+
images = []
|
156 |
+
for row in rows:
|
157 |
+
images.append(cls.from_row(row))
|
158 |
+
return images
|
159 |
+
|
160 |
+
@classmethod
|
161 |
+
def create_table(cls, conn):
|
162 |
+
with closing(conn.cursor()) as cur:
|
163 |
+
cur.execute(
|
164 |
+
"""CREATE TABLE IF NOT EXISTS image (
|
165 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
166 |
+
path TEXT UNIQUE,
|
167 |
+
exif TEXT,
|
168 |
+
size INTEGER,
|
169 |
+
date TEXT
|
170 |
+
)"""
|
171 |
+
)
|
172 |
+
cur.execute("CREATE INDEX IF NOT EXISTS image_idx_path ON image(path)")
|
173 |
+
|
174 |
+
@classmethod
|
175 |
+
def count(cls, conn):
|
176 |
+
with closing(conn.cursor()) as cur:
|
177 |
+
cur.execute("SELECT COUNT(*) FROM image")
|
178 |
+
count = cur.fetchone()[0]
|
179 |
+
return count
|
180 |
+
|
181 |
+
@classmethod
|
182 |
+
def from_row(cls, row: tuple):
|
183 |
+
image = cls(path=row[1], exif=row[2], size=row[3], date=row[4])
|
184 |
+
image.id = row[0]
|
185 |
+
return image
|
186 |
+
|
187 |
+
@classmethod
|
188 |
+
def remove(cls, conn: Connection, image_id: int) -> None:
|
189 |
+
with closing(conn.cursor()) as cur:
|
190 |
+
cur.execute("DELETE FROM image WHERE id = ?", (image_id,))
|
191 |
+
conn.commit()
|
192 |
+
|
193 |
+
@classmethod
|
194 |
+
def safe_batch_remove(cls, conn: Connection, image_ids: List[int]) -> None:
|
195 |
+
if not (image_ids):
|
196 |
+
return
|
197 |
+
with closing(conn.cursor()) as cur:
|
198 |
+
try:
|
199 |
+
placeholders = ",".join("?" * len(image_ids))
|
200 |
+
cur.execute(
|
201 |
+
f"DELETE FROM image_tag WHERE image_id IN ({placeholders})",
|
202 |
+
image_ids,
|
203 |
+
)
|
204 |
+
cur.execute(
|
205 |
+
f"DELETE FROM image WHERE id IN ({placeholders})", image_ids
|
206 |
+
)
|
207 |
+
except BaseException as e:
|
208 |
+
print(e)
|
209 |
+
finally:
|
210 |
+
conn.commit()
|
211 |
+
|
212 |
+
@classmethod
|
213 |
+
def find_by_substring(
|
214 |
+
cls, conn: Connection, substring: str, limit: int = 500, cursor="", regexp="", path_only=False,
|
215 |
+
folder_paths: List[str] = []
|
216 |
+
) -> tuple[List["Image"], Cursor]:
|
217 |
+
api_cur = Cursor()
|
218 |
+
with closing(conn.cursor()) as cur:
|
219 |
+
params = []
|
220 |
+
where_clauses = []
|
221 |
+
if regexp:
|
222 |
+
if path_only:
|
223 |
+
where_clauses.append("(path REGEXP ?)")
|
224 |
+
params.append(regexp)
|
225 |
+
else:
|
226 |
+
where_clauses.append("((exif REGEXP ?) OR (path REGEXP ?))")
|
227 |
+
params.extend((regexp, regexp))
|
228 |
+
else:
|
229 |
+
if path_only:
|
230 |
+
where_clauses.append("(path LIKE ?)")
|
231 |
+
params.append(f"%{substring}%")
|
232 |
+
else:
|
233 |
+
where_clauses.append("(path LIKE ? OR exif LIKE ?)")
|
234 |
+
params.extend((f"%{substring}%", f"%{substring}%"))
|
235 |
+
if cursor:
|
236 |
+
where_clauses.append("(date < ?)")
|
237 |
+
params.append(cursor)
|
238 |
+
if folder_paths:
|
239 |
+
folder_clauses = []
|
240 |
+
for folder_path in folder_paths:
|
241 |
+
folder_clauses.append("(image.path LIKE ?)")
|
242 |
+
params.append(os.path.join(folder_path, "%"))
|
243 |
+
where_clauses.append("(" + " OR ".join(folder_clauses) + ")")
|
244 |
+
sql = "SELECT * FROM image"
|
245 |
+
if where_clauses:
|
246 |
+
sql += " WHERE "
|
247 |
+
sql += " AND ".join(where_clauses)
|
248 |
+
sql += " ORDER BY date DESC LIMIT ? "
|
249 |
+
params.append(limit)
|
250 |
+
cur.execute(sql, params)
|
251 |
+
rows = cur.fetchall()
|
252 |
+
|
253 |
+
api_cur.has_next = len(rows) >= limit
|
254 |
+
images = []
|
255 |
+
deleted_ids = []
|
256 |
+
for row in rows:
|
257 |
+
img = cls.from_row(row)
|
258 |
+
if os.path.exists(img.path):
|
259 |
+
images.append(img)
|
260 |
+
else:
|
261 |
+
deleted_ids.append(img.id)
|
262 |
+
cls.safe_batch_remove(conn, deleted_ids)
|
263 |
+
if images:
|
264 |
+
api_cur.next = str(images[-1].date)
|
265 |
+
return images, api_cur
|
266 |
+
|
267 |
+
@classmethod
|
268 |
+
def get_random_images(cls, conn: Connection, size: int) -> List["Image"]:
|
269 |
+
with closing(conn.cursor()) as cur:
|
270 |
+
cur.execute("SELECT COUNT(*) FROM image")
|
271 |
+
total_count = cur.fetchone()[0]
|
272 |
+
|
273 |
+
if total_count == 0 or size <= 0:
|
274 |
+
return []
|
275 |
+
|
276 |
+
step = max(1, total_count // size)
|
277 |
+
|
278 |
+
start_indices = [random.randint(i * step, min((i + 1) * step - 1, total_count - 1)) for i in range(size)]
|
279 |
+
|
280 |
+
placeholders = ",".join("?" * len(start_indices))
|
281 |
+
cur.execute(f"SELECT * FROM image WHERE id IN ({placeholders})", start_indices)
|
282 |
+
rows = cur.fetchall()
|
283 |
+
|
284 |
+
images = [cls.from_row(row) for row in rows if os.path.exists(row[1])]
|
285 |
+
return images
|
286 |
+
|
287 |
+
|
288 |
+
class Tag:
|
289 |
+
def __init__(self, name: str, score: int, type: str, count=0, color = ""):
|
290 |
+
self.name = name
|
291 |
+
self.score = score
|
292 |
+
self.type = type
|
293 |
+
self.count = count
|
294 |
+
self.id = None
|
295 |
+
self.color = color
|
296 |
+
self.display_name = tags_translate.get(name)
|
297 |
+
|
298 |
+
def save(self, conn):
|
299 |
+
with closing(conn.cursor()) as cur:
|
300 |
+
cur.execute(
|
301 |
+
"INSERT OR REPLACE INTO tag (id, name, score, type, count, color) VALUES (?, ?, ?, ?, ?, ?)",
|
302 |
+
(self.id, self.name, self.score, self.type, self.count, self.color),
|
303 |
+
)
|
304 |
+
self.id = cur.lastrowid
|
305 |
+
|
306 |
+
@classmethod
|
307 |
+
def remove(cls, conn, tag_id):
|
308 |
+
with closing(conn.cursor()) as cur:
|
309 |
+
cur.execute("DELETE FROM tag WHERE id = ?", (tag_id,))
|
310 |
+
conn.commit()
|
311 |
+
|
312 |
+
@classmethod
|
313 |
+
def get(cls, conn: Connection, id):
|
314 |
+
with closing(conn.cursor()) as cur:
|
315 |
+
cur.execute("SELECT * FROM tag WHERE id = ?", (id,))
|
316 |
+
row = cur.fetchone()
|
317 |
+
if row is None:
|
318 |
+
return None
|
319 |
+
else:
|
320 |
+
return cls.from_row(row)
|
321 |
+
|
322 |
+
@classmethod
|
323 |
+
def get_all_custom_tag(cls, conn):
|
324 |
+
with closing(conn.cursor()) as cur:
|
325 |
+
cur.execute("SELECT * FROM tag where type = 'custom'")
|
326 |
+
rows = cur.fetchall()
|
327 |
+
tags: list[Tag] = []
|
328 |
+
for row in rows:
|
329 |
+
tags.append(cls.from_row(row))
|
330 |
+
return tags
|
331 |
+
|
332 |
+
@classmethod
|
333 |
+
def get_all(cls, conn):
|
334 |
+
with closing(conn.cursor()) as cur:
|
335 |
+
cur.execute("SELECT * FROM tag")
|
336 |
+
rows = cur.fetchall()
|
337 |
+
tags: list[Tag] = []
|
338 |
+
for row in rows:
|
339 |
+
tags.append(cls.from_row(row))
|
340 |
+
return tags
|
341 |
+
|
342 |
+
@classmethod
|
343 |
+
def get_or_create(cls, conn: Connection, name: str, type: str):
|
344 |
+
assert name and type
|
345 |
+
with closing(conn.cursor()) as cur:
|
346 |
+
cur.execute(
|
347 |
+
"SELECT tag.* FROM tag WHERE name = ? and type = ?", (name, type)
|
348 |
+
)
|
349 |
+
row = cur.fetchone()
|
350 |
+
if row is None:
|
351 |
+
tag = cls(name=name, score=0, type=type)
|
352 |
+
tag.save(conn)
|
353 |
+
return tag
|
354 |
+
else:
|
355 |
+
return cls.from_row(row)
|
356 |
+
|
357 |
+
@classmethod
|
358 |
+
def from_row(cls, row: tuple):
|
359 |
+
tag = cls(name=row[1], score=row[2], type=row[3], count=row[4], color=row[5])
|
360 |
+
tag.id = row[0]
|
361 |
+
return tag
|
362 |
+
|
363 |
+
@classmethod
|
364 |
+
def create_table(cls, conn):
|
365 |
+
with closing(conn.cursor()) as cur:
|
366 |
+
cur.execute(
|
367 |
+
"""CREATE TABLE IF NOT EXISTS tag (
|
368 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
369 |
+
name TEXT,
|
370 |
+
score INTEGER,
|
371 |
+
type TEXT,
|
372 |
+
count INTEGER,
|
373 |
+
UNIQUE(name, type) ON CONFLICT REPLACE
|
374 |
+
);
|
375 |
+
"""
|
376 |
+
)
|
377 |
+
cur.execute("CREATE INDEX IF NOT EXISTS tag_idx_name ON tag(name)")
|
378 |
+
cur.execute(
|
379 |
+
"""INSERT OR IGNORE INTO tag(name, score, type, count)
|
380 |
+
VALUES ("like", 0, "custom", 0);
|
381 |
+
"""
|
382 |
+
)
|
383 |
+
try:
|
384 |
+
cur.execute(
|
385 |
+
"""ALTER TABLE tag
|
386 |
+
ADD COLUMN color TEXT DEFAULT ''"""
|
387 |
+
)
|
388 |
+
except sqlite3.OperationalError as e:
|
389 |
+
pass
|
390 |
+
|
391 |
+
|
392 |
+
class ImageTag:
|
393 |
+
def __init__(self, image_id: int, tag_id: int):
|
394 |
+
assert tag_id and image_id
|
395 |
+
self.image_id = image_id
|
396 |
+
self.tag_id = tag_id
|
397 |
+
|
398 |
+
def save(self, conn):
|
399 |
+
with closing(conn.cursor()) as cur:
|
400 |
+
cur.execute(
|
401 |
+
"INSERT INTO image_tag (image_id, tag_id, created_at) VALUES (?, ?, CURRENT_TIMESTAMP)",
|
402 |
+
(self.image_id, self.tag_id),
|
403 |
+
)
|
404 |
+
|
405 |
+
def save_or_ignore(self, conn):
|
406 |
+
with closing(conn.cursor()) as cur:
|
407 |
+
cur.execute(
|
408 |
+
"INSERT OR IGNORE INTO image_tag (image_id, tag_id, created_at) VALUES (?, ?, CURRENT_TIMESTAMP)",
|
409 |
+
(self.image_id, self.tag_id),
|
410 |
+
)
|
411 |
+
|
412 |
+
@classmethod
|
413 |
+
def get_tags_for_image(
|
414 |
+
cls,
|
415 |
+
conn: Connection,
|
416 |
+
image_id: int,
|
417 |
+
tag_id: Optional[int] = None,
|
418 |
+
type: Optional[str] = None,
|
419 |
+
):
|
420 |
+
with closing(conn.cursor()) as cur:
|
421 |
+
query = "SELECT tag.* FROM tag INNER JOIN image_tag ON tag.id = image_tag.tag_id WHERE image_tag.image_id = ?"
|
422 |
+
params = [image_id]
|
423 |
+
if tag_id:
|
424 |
+
query += " AND image_tag.tag_id = ?"
|
425 |
+
params.append(tag_id)
|
426 |
+
if type:
|
427 |
+
query += " AND tag.type = ?"
|
428 |
+
params.append(type)
|
429 |
+
cur.execute(query, tuple(params))
|
430 |
+
rows = cur.fetchall()
|
431 |
+
return [Tag.from_row(x) for x in rows]
|
432 |
+
|
433 |
+
@classmethod
|
434 |
+
def get_images_for_tag(cls, conn: Connection, tag_id):
|
435 |
+
with closing(conn.cursor()) as cur:
|
436 |
+
cur.execute(
|
437 |
+
"SELECT image.* FROM image INNER JOIN image_tag ON image.id = image_tag.image_id WHERE image_tag.tag_id = ?",
|
438 |
+
(tag_id,),
|
439 |
+
)
|
440 |
+
rows = cur.fetchall()
|
441 |
+
images = []
|
442 |
+
for row in rows:
|
443 |
+
images.append(Image.from_row(row))
|
444 |
+
return images
|
445 |
+
|
446 |
+
@classmethod
|
447 |
+
def create_table(cls, conn):
|
448 |
+
with closing(conn.cursor()) as cur:
|
449 |
+
cur.execute(
|
450 |
+
"""CREATE TABLE IF NOT EXISTS image_tag (
|
451 |
+
image_id INTEGER,
|
452 |
+
tag_id INTEGER,
|
453 |
+
FOREIGN KEY (image_id) REFERENCES image(id),
|
454 |
+
FOREIGN KEY (tag_id) REFERENCES tag(id),
|
455 |
+
PRIMARY KEY (image_id, tag_id)
|
456 |
+
)"""
|
457 |
+
)
|
458 |
+
try:
|
459 |
+
cur.execute(
|
460 |
+
"""ALTER TABLE image_tag
|
461 |
+
ADD COLUMN created_at TIMESTAMP"""
|
462 |
+
)
|
463 |
+
|
464 |
+
cur.execute(
|
465 |
+
"""UPDATE image_tag
|
466 |
+
SET created_at = CURRENT_TIMESTAMP
|
467 |
+
WHERE created_at IS NULL"""
|
468 |
+
)
|
469 |
+
except sqlite3.OperationalError as e:
|
470 |
+
pass
|
471 |
+
|
472 |
+
@classmethod
|
473 |
+
def get_images_by_tags(
|
474 |
+
cls,
|
475 |
+
conn: Connection,
|
476 |
+
tag_dict: Dict[str, List[int]],
|
477 |
+
limit: int = 500,
|
478 |
+
cursor="",
|
479 |
+
folder_paths: List[str] = None,
|
480 |
+
) -> tuple[List[Image], Cursor]:
|
481 |
+
query = """
|
482 |
+
SELECT image.id, image.path, image.size,image.date
|
483 |
+
FROM image
|
484 |
+
INNER JOIN image_tag ON image.id = image_tag.image_id
|
485 |
+
"""
|
486 |
+
|
487 |
+
where_clauses = []
|
488 |
+
params = []
|
489 |
+
|
490 |
+
for operator, tag_ids in tag_dict.items():
|
491 |
+
if operator == "and" and tag_dict["and"]:
|
492 |
+
where_clauses.append(
|
493 |
+
"tag_id IN ({})".format(",".join("?" * len(tag_ids)))
|
494 |
+
)
|
495 |
+
params.extend(tag_ids)
|
496 |
+
elif operator == "not" and tag_dict["not"]:
|
497 |
+
where_clauses.append(
|
498 |
+
"""(image_id NOT IN (
|
499 |
+
SELECT image_id
|
500 |
+
FROM image_tag
|
501 |
+
WHERE tag_id IN ({})
|
502 |
+
))""".format(
|
503 |
+
",".join("?" * len(tag_ids))
|
504 |
+
)
|
505 |
+
)
|
506 |
+
params.extend(tag_ids)
|
507 |
+
elif operator == "or" and tag_dict["or"]:
|
508 |
+
where_clauses.append(
|
509 |
+
"""(image_id IN (
|
510 |
+
SELECT image_id
|
511 |
+
FROM image_tag
|
512 |
+
WHERE tag_id IN ({})
|
513 |
+
GROUP BY image_id
|
514 |
+
HAVING COUNT(DISTINCT tag_id) >= 1
|
515 |
+
)
|
516 |
+
)""".format(
|
517 |
+
",".join("?" * len(tag_ids))
|
518 |
+
)
|
519 |
+
)
|
520 |
+
params.extend(tag_ids)
|
521 |
+
|
522 |
+
if folder_paths:
|
523 |
+
folder_clauses = []
|
524 |
+
for folder_path in folder_paths:
|
525 |
+
folder_clauses.append("(image.path LIKE ?)")
|
526 |
+
params.append(os.path.join(folder_path, "%"))
|
527 |
+
print(folder_path)
|
528 |
+
where_clauses.append("(" + " OR ".join(folder_clauses) + ")")
|
529 |
+
|
530 |
+
if cursor:
|
531 |
+
where_clauses.append("(image.date < ?)")
|
532 |
+
params.append(cursor)
|
533 |
+
if where_clauses:
|
534 |
+
query += " WHERE " + " AND ".join(where_clauses)
|
535 |
+
query += " GROUP BY image.id"
|
536 |
+
if "and" in tag_dict and tag_dict['and']:
|
537 |
+
query += " HAVING COUNT(DISTINCT tag_id) = ?"
|
538 |
+
params.append(len(tag_dict["and"]))
|
539 |
+
|
540 |
+
query += " ORDER BY date DESC LIMIT ?"
|
541 |
+
params.append(limit)
|
542 |
+
api_cur = Cursor()
|
543 |
+
with closing(conn.cursor()) as cur:
|
544 |
+
cur.execute(query, params)
|
545 |
+
rows = cur.fetchall()
|
546 |
+
images = []
|
547 |
+
deleted_ids = []
|
548 |
+
for row in rows:
|
549 |
+
img = Image(id=row[0], path=row[1], size=row[2], date=row[3])
|
550 |
+
if os.path.exists(img.path):
|
551 |
+
images.append(img)
|
552 |
+
else:
|
553 |
+
deleted_ids.append(img.id)
|
554 |
+
Image.safe_batch_remove(conn, deleted_ids)
|
555 |
+
api_cur.has_next = len(rows) >= limit
|
556 |
+
if images:
|
557 |
+
api_cur.next = str(images[-1].date)
|
558 |
+
return images, api_cur
|
559 |
+
|
560 |
+
@classmethod
|
561 |
+
def batch_get_tags_by_path(
|
562 |
+
cls, conn: Connection, paths: List[str], type="custom"
|
563 |
+
) -> Dict[str, List[Tag]]:
|
564 |
+
if not paths:
|
565 |
+
return {}
|
566 |
+
tag_dict = {}
|
567 |
+
with closing(conn.cursor()) as cur:
|
568 |
+
placeholders = ",".join("?" * len(paths))
|
569 |
+
query = f"""
|
570 |
+
SELECT image.path, tag.* FROM image_tag
|
571 |
+
INNER JOIN image ON image_tag.image_id = image.id
|
572 |
+
INNER JOIN tag ON image_tag.tag_id = tag.id
|
573 |
+
WHERE tag.type = '{type}' AND image.path IN ({placeholders})
|
574 |
+
"""
|
575 |
+
cur.execute(query, paths)
|
576 |
+
rows = cur.fetchall()
|
577 |
+
for row in rows:
|
578 |
+
path = row[0]
|
579 |
+
tag = Tag.from_row(row[1:])
|
580 |
+
if path in tag_dict:
|
581 |
+
tag_dict[path].append(tag)
|
582 |
+
else:
|
583 |
+
tag_dict[path] = [tag]
|
584 |
+
return tag_dict
|
585 |
+
|
586 |
+
@classmethod
|
587 |
+
def remove(
|
588 |
+
cls,
|
589 |
+
conn: Connection,
|
590 |
+
image_id: Optional[int] = None,
|
591 |
+
tag_id: Optional[int] = None,
|
592 |
+
) -> None:
|
593 |
+
assert image_id or tag_id
|
594 |
+
with closing(conn.cursor()) as cur:
|
595 |
+
if tag_id and image_id:
|
596 |
+
cur.execute(
|
597 |
+
"DELETE FROM image_tag WHERE image_id = ? and tag_id = ?",
|
598 |
+
(image_id, tag_id),
|
599 |
+
)
|
600 |
+
elif tag_id:
|
601 |
+
cur.execute("DELETE FROM image_tag WHERE tag_id = ?", (tag_id,))
|
602 |
+
else:
|
603 |
+
cur.execute("DELETE FROM image_tag WHERE image_id = ?", (image_id,))
|
604 |
+
conn.commit()
|
605 |
+
|
606 |
+
|
607 |
+
class Folder:
|
608 |
+
def __init__(self, id: int, path: str, modified_date: str):
|
609 |
+
self.id = id
|
610 |
+
self.path = path
|
611 |
+
self.modified_date = modified_date
|
612 |
+
|
613 |
+
@classmethod
|
614 |
+
def create_table(cls, conn):
|
615 |
+
with closing(conn.cursor()) as cur:
|
616 |
+
cur.execute(
|
617 |
+
"""CREATE TABLE IF NOT EXISTS folders
|
618 |
+
(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
619 |
+
path TEXT,
|
620 |
+
modified_date TEXT)"""
|
621 |
+
)
|
622 |
+
cur.execute("CREATE INDEX IF NOT EXISTS folders_idx_path ON folders(path)")
|
623 |
+
|
624 |
+
@classmethod
|
625 |
+
def check_need_update(cls, conn: Connection, folder_path: str):
|
626 |
+
folder_path = os.path.normpath(folder_path)
|
627 |
+
with closing(conn.cursor()) as cur:
|
628 |
+
if not os.path.exists(folder_path):
|
629 |
+
return False
|
630 |
+
cur.execute("SELECT * FROM folders WHERE path=?", (folder_path,))
|
631 |
+
folder_record = cur.fetchone() # 如果这个文件夹没有记录,或者修改时间与数据库不同,则需要修改
|
632 |
+
return not folder_record or (
|
633 |
+
folder_record[2] != get_modified_date(folder_path)
|
634 |
+
)
|
635 |
+
|
636 |
+
@classmethod
|
637 |
+
def update_modified_date_or_create(cls, conn: Connection, folder_path: str):
|
638 |
+
folder_path = os.path.normpath(folder_path)
|
639 |
+
with closing(conn.cursor()) as cur:
|
640 |
+
cur.execute("SELECT * FROM folders WHERE path = ?", (folder_path,))
|
641 |
+
row = cur.fetchone()
|
642 |
+
if row:
|
643 |
+
cur.execute(
|
644 |
+
"UPDATE folders SET modified_date = ? WHERE path = ?",
|
645 |
+
(get_modified_date(folder_path), folder_path),
|
646 |
+
)
|
647 |
+
else:
|
648 |
+
cur.execute(
|
649 |
+
"INSERT INTO folders (path, modified_date) VALUES (?, ?)",
|
650 |
+
(folder_path, get_modified_date(folder_path)),
|
651 |
+
)
|
652 |
+
|
653 |
+
@classmethod
|
654 |
+
def get_expired_dirs(cls, conn: Connection):
|
655 |
+
dirs: List[str] = []
|
656 |
+
with closing(conn.cursor()) as cur:
|
657 |
+
cur.execute("SELECT * FROM folders")
|
658 |
+
result_set = cur.fetchall()
|
659 |
+
extra_paths = ExtraPath.get_extra_paths(conn)
|
660 |
+
for ep in extra_paths:
|
661 |
+
if not find(result_set, lambda x: x[1] == ep.path):
|
662 |
+
dirs.append(ep.path)
|
663 |
+
for row in result_set:
|
664 |
+
folder_path = row[1]
|
665 |
+
if (
|
666 |
+
os.path.exists(folder_path)
|
667 |
+
and get_modified_date(folder_path) != row[2]
|
668 |
+
):
|
669 |
+
dirs.append(folder_path)
|
670 |
+
return unique_by(dirs, os.path.normpath)
|
671 |
+
|
672 |
+
@classmethod
|
673 |
+
def remove_folder(cls, conn: Connection, folder_path: str):
|
674 |
+
folder_path = os.path.normpath(folder_path)
|
675 |
+
with closing(conn.cursor()) as cur:
|
676 |
+
cur.execute("DELETE FROM folders WHERE path = ?", (folder_path,))
|
677 |
+
|
678 |
+
@classmethod
|
679 |
+
def remove_all(cls, conn: Connection):
|
680 |
+
with closing(conn.cursor()) as cur:
|
681 |
+
cur.execute("DELETE FROM folders")
|
682 |
+
conn.commit()
|
683 |
+
|
684 |
+
|
685 |
+
class ExtraPathType(Enum):
|
686 |
+
scanned = "scanned"
|
687 |
+
scanned_fixed = "scanned-fixed"
|
688 |
+
walk = "walk"
|
689 |
+
cli_only = "cli_access_only"
|
690 |
+
|
691 |
+
|
692 |
+
class ExtraPath:
|
693 |
+
def __init__(self, path: str, types: Union[str, List[str]], alias = ''):
|
694 |
+
self.path = os.path.normpath(path)
|
695 |
+
self.types = types.split('+') if isinstance(types, str) else types
|
696 |
+
self.alias = alias
|
697 |
+
|
698 |
+
def save(self, conn):
|
699 |
+
type_str = '+'.join(self.types)
|
700 |
+
for type in self.types:
|
701 |
+
assert type in [ExtraPathType.walk.value, ExtraPathType.scanned.value, ExtraPathType.scanned_fixed.value]
|
702 |
+
with closing(conn.cursor()) as cur:
|
703 |
+
cur.execute(
|
704 |
+
"INSERT INTO extra_path (path, type, alias) VALUES (?, ?, ?) "
|
705 |
+
"ON CONFLICT (path) DO UPDATE SET type = excluded.type, alias = excluded.alias",
|
706 |
+
(self.path, type_str, self.alias),
|
707 |
+
)
|
708 |
+
|
709 |
+
@classmethod
|
710 |
+
def get_target_path(cls, conn, path) -> Optional['ExtraPath']:
|
711 |
+
path = os.path.normpath(path)
|
712 |
+
query = f"SELECT * FROM extra_path where path = ?"
|
713 |
+
params = (path,)
|
714 |
+
with closing(conn.cursor()) as cur:
|
715 |
+
cur.execute(query, params)
|
716 |
+
rows = cur.fetchall()
|
717 |
+
paths: List[ExtraPath] = []
|
718 |
+
for row in rows:
|
719 |
+
path = row[0]
|
720 |
+
if os.path.exists(path):
|
721 |
+
paths.append(ExtraPath(*row))
|
722 |
+
else:
|
723 |
+
sql = "DELETE FROM extra_path WHERE path = ?"
|
724 |
+
cur.execute(sql, (path,))
|
725 |
+
conn.commit()
|
726 |
+
return paths[0] if paths else None
|
727 |
+
|
728 |
+
@classmethod
|
729 |
+
def get_extra_paths(cls, conn) -> List["ExtraPath"]:
|
730 |
+
query = "SELECT * FROM extra_path"
|
731 |
+
with closing(conn.cursor()) as cur:
|
732 |
+
cur.execute(query)
|
733 |
+
rows = cur.fetchall()
|
734 |
+
paths: List[ExtraPath] = []
|
735 |
+
for row in rows:
|
736 |
+
path = row[0]
|
737 |
+
if os.path.exists(path):
|
738 |
+
paths.append(ExtraPath(*row))
|
739 |
+
else:
|
740 |
+
cls.remove(conn, path)
|
741 |
+
return paths
|
742 |
+
|
743 |
+
@classmethod
|
744 |
+
def remove(
|
745 |
+
cls,
|
746 |
+
conn,
|
747 |
+
path: str,
|
748 |
+
types: List[str] = None,
|
749 |
+
img_search_dirs: Optional[List[str]] = [],
|
750 |
+
):
|
751 |
+
with closing(conn.cursor()) as cur:
|
752 |
+
path = os.path.normpath(path)
|
753 |
+
|
754 |
+
target = cls.get_target_path(conn, path)
|
755 |
+
if not target:
|
756 |
+
return
|
757 |
+
new_types = []
|
758 |
+
for type in target.types:
|
759 |
+
if type not in types:
|
760 |
+
new_types.append(type)
|
761 |
+
if new_types:
|
762 |
+
target.types = new_types
|
763 |
+
target.save(conn)
|
764 |
+
else:
|
765 |
+
sql = "DELETE FROM extra_path WHERE path = ?"
|
766 |
+
cur.execute(sql, (path,))
|
767 |
+
|
768 |
+
if path not in img_search_dirs:
|
769 |
+
Folder.remove_folder(conn, path)
|
770 |
+
conn.commit()
|
771 |
+
|
772 |
+
@classmethod
|
773 |
+
def create_table(cls, conn):
|
774 |
+
with closing(conn.cursor()) as cur:
|
775 |
+
cur.execute(
|
776 |
+
"""CREATE TABLE IF NOT EXISTS extra_path (
|
777 |
+
path TEXT PRIMARY KEY,
|
778 |
+
type TEXT NOT NULL,
|
779 |
+
alias TEXT DEFAULT ''
|
780 |
+
)"""
|
781 |
+
)
|
782 |
+
try:
|
783 |
+
cur.execute(
|
784 |
+
"""ALTER TABLE extra_path
|
785 |
+
ADD COLUMN alias TEXT DEFAULT ''"""
|
786 |
+
)
|
787 |
+
except sqlite3.OperationalError:
|
788 |
+
pass
|
789 |
+
|
790 |
+
class DirCoverCache:
|
791 |
+
@classmethod
|
792 |
+
def create_table(cls, conn):
|
793 |
+
with closing(conn.cursor()) as cur:
|
794 |
+
cur.execute("""
|
795 |
+
CREATE TABLE IF NOT EXISTS dir_cover_cache (
|
796 |
+
folder_path TEXT PRIMARY KEY,
|
797 |
+
modified_time TEXT,
|
798 |
+
media_files TEXT
|
799 |
+
)
|
800 |
+
""")
|
801 |
+
|
802 |
+
@classmethod
|
803 |
+
def is_cache_expired(cls, conn, folder_path):
|
804 |
+
with closing(conn.cursor()) as cur:
|
805 |
+
cur.execute("SELECT modified_time FROM dir_cover_cache WHERE folder_path = ?", (folder_path,))
|
806 |
+
result = cur.fetchone()
|
807 |
+
|
808 |
+
if not result:
|
809 |
+
return True
|
810 |
+
|
811 |
+
cached_time = datetime.fromisoformat(result[0])
|
812 |
+
folder_modified_time = os.path.getmtime(folder_path)
|
813 |
+
return datetime.fromtimestamp(folder_modified_time) > cached_time
|
814 |
+
|
815 |
+
@classmethod
|
816 |
+
def cache_media_files(cls, conn, folder_path, media_files):
|
817 |
+
media_files_json = json.dumps(media_files)
|
818 |
+
with closing(conn.cursor()) as cur:
|
819 |
+
cur.execute("""
|
820 |
+
INSERT INTO dir_cover_cache (folder_path, modified_time, media_files)
|
821 |
+
VALUES (?, ?, ?)
|
822 |
+
ON CONFLICT(folder_path) DO UPDATE SET modified_time = excluded.modified_time, media_files = excluded.media_files
|
823 |
+
""", (folder_path, datetime.now().isoformat(), media_files_json))
|
824 |
+
conn.commit()
|
825 |
+
|
826 |
+
@classmethod
|
827 |
+
def get_cached_media_files(cls, conn, folder_path):
|
828 |
+
with closing(conn.cursor()) as cur:
|
829 |
+
cur.execute("SELECT media_files FROM dir_cover_cache WHERE folder_path = ?", (folder_path,))
|
830 |
+
result = cur.fetchone()
|
831 |
+
|
832 |
+
if result:
|
833 |
+
media_files_json = result[0]
|
834 |
+
return json.loads(media_files_json)
|
835 |
+
else:
|
836 |
+
return []
|
837 |
+
|
838 |
+
|
839 |
+
class GlobalSetting:
|
840 |
+
@classmethod
|
841 |
+
def create_table(cls, conn):
|
842 |
+
with closing(conn.cursor()) as cur:
|
843 |
+
cur.execute(
|
844 |
+
"""CREATE TABLE IF NOT EXISTS global_setting (
|
845 |
+
setting_json TEXT,
|
846 |
+
name TEXT PRIMARY KEY,
|
847 |
+
created_time TEXT,
|
848 |
+
modified_time TEXT
|
849 |
+
)"""
|
850 |
+
)
|
851 |
+
|
852 |
+
@classmethod
|
853 |
+
def get_setting(cls, conn, name):
|
854 |
+
with closing(conn.cursor()) as cur:
|
855 |
+
cur.execute("SELECT setting_json FROM global_setting WHERE name = ?", (name,))
|
856 |
+
result = cur.fetchone()
|
857 |
+
if result:
|
858 |
+
return json.loads(result[0])
|
859 |
+
else:
|
860 |
+
return None
|
861 |
+
|
862 |
+
@classmethod
|
863 |
+
def save_setting(cls, conn, name: str, setting: str):
|
864 |
+
json.loads(setting) # check if it is valid json
|
865 |
+
with closing(conn.cursor()) as cur:
|
866 |
+
cur.execute(
|
867 |
+
"""INSERT INTO global_setting (setting_json, name, created_time, modified_time)
|
868 |
+
VALUES (?, ?, ?, ?)
|
869 |
+
ON CONFLICT(name) DO UPDATE SET setting_json = excluded.setting_json, modified_time = excluded.modified_time
|
870 |
+
""",
|
871 |
+
(setting, name, datetime.now().isoformat(), datetime.now().isoformat()),
|
872 |
+
)
|
873 |
+
conn.commit()
|
874 |
+
|
875 |
+
|
876 |
+
@classmethod
|
877 |
+
def remove_setting(cls, conn, name: str):
|
878 |
+
with closing(conn.cursor()) as cur:
|
879 |
+
cur.execute("DELETE FROM global_setting WHERE name = ?", (name,))
|
880 |
+
conn.commit()
|
881 |
+
|
882 |
+
@classmethod
|
883 |
+
def get_all_settings(cls, conn):
|
884 |
+
with closing(conn.cursor()) as cur:
|
885 |
+
cur.execute("SELECT * FROM global_setting")
|
886 |
+
rows = cur.fetchall()
|
887 |
+
settings = {}
|
888 |
+
for row in rows:
|
889 |
+
settings[row[1]] = json.loads(row[0])
|
890 |
+
return settings
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/db/update_image_data.py
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from contextlib import closing
|
2 |
+
from typing import Dict, List
|
3 |
+
from scripts.iib.db.datamodel import Image as DbImg, Tag, ImageTag, DataBase, Folder
|
4 |
+
import os
|
5 |
+
from scripts.iib.tool import (
|
6 |
+
is_valid_media_path,
|
7 |
+
get_modified_date,
|
8 |
+
get_video_type,
|
9 |
+
is_dev,
|
10 |
+
get_modified_date,
|
11 |
+
is_image_file,
|
12 |
+
case_insensitive_get
|
13 |
+
)
|
14 |
+
from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams
|
15 |
+
from scripts.iib.logger import logger
|
16 |
+
from scripts.iib.parsers.index import parse_image_info
|
17 |
+
from scripts.iib.plugin import plugin_inst_map
|
18 |
+
|
19 |
+
# 定义一个函数来获取图片文件的EXIF数据
|
20 |
+
def get_exif_data(file_path):
|
21 |
+
if get_video_type(file_path):
|
22 |
+
return ImageGenerationInfo()
|
23 |
+
try:
|
24 |
+
return parse_image_info(file_path)
|
25 |
+
except Exception as e:
|
26 |
+
if is_dev:
|
27 |
+
logger.error("get_exif_data %s", e)
|
28 |
+
return ImageGenerationInfo()
|
29 |
+
|
30 |
+
|
31 |
+
def update_image_data(search_dirs: List[str], is_rebuild = False):
|
32 |
+
conn = DataBase.get_conn()
|
33 |
+
tag_incr_count_rec: Dict[int, int] = {}
|
34 |
+
|
35 |
+
if is_rebuild:
|
36 |
+
Folder.remove_all(conn)
|
37 |
+
|
38 |
+
def safe_save_img_tag(img_tag: ImageTag):
|
39 |
+
tag_incr_count_rec[img_tag.tag_id] = (
|
40 |
+
tag_incr_count_rec.get(img_tag.tag_id, 0) + 1
|
41 |
+
)
|
42 |
+
img_tag.save_or_ignore(conn) # 原先用来处理一些意外,但是写的正确完全没问题,去掉了try catch
|
43 |
+
|
44 |
+
# 递归处理每个文件夹
|
45 |
+
def process_folder(folder_path: str):
|
46 |
+
if not Folder.check_need_update(conn, folder_path):
|
47 |
+
return
|
48 |
+
print(f"Processing folder: {folder_path}")
|
49 |
+
for filename in os.listdir(folder_path):
|
50 |
+
file_path = os.path.normpath(os.path.join(folder_path, filename))
|
51 |
+
try:
|
52 |
+
|
53 |
+
if os.path.isdir(file_path):
|
54 |
+
process_folder(file_path)
|
55 |
+
elif is_valid_media_path(file_path):
|
56 |
+
build_single_img_idx(conn, file_path, is_rebuild, safe_save_img_tag)
|
57 |
+
# neg暂时跳过感觉个没人会搜索这个
|
58 |
+
except Exception as e:
|
59 |
+
logger.error("Tag generation failed. Skipping this file. file:%s error: %s", file_path, e)
|
60 |
+
# 提交对数据库的更改
|
61 |
+
Folder.update_modified_date_or_create(conn, folder_path)
|
62 |
+
conn.commit()
|
63 |
+
|
64 |
+
for dir in search_dirs:
|
65 |
+
process_folder(dir)
|
66 |
+
conn.commit()
|
67 |
+
for tag_id in tag_incr_count_rec:
|
68 |
+
tag = Tag.get(conn, tag_id)
|
69 |
+
tag.count += tag_incr_count_rec[tag_id]
|
70 |
+
tag.save(conn)
|
71 |
+
conn.commit()
|
72 |
+
|
73 |
+
def add_image_data_single(file_path):
|
74 |
+
conn = DataBase.get_conn()
|
75 |
+
tag_incr_count_rec: Dict[int, int] = {}
|
76 |
+
|
77 |
+
def safe_save_img_tag(img_tag: ImageTag):
|
78 |
+
tag_incr_count_rec[img_tag.tag_id] = (
|
79 |
+
tag_incr_count_rec.get(img_tag.tag_id, 0) + 1
|
80 |
+
)
|
81 |
+
img_tag.save_or_ignore(conn)
|
82 |
+
|
83 |
+
file_path = os.path.normpath(file_path)
|
84 |
+
try:
|
85 |
+
if not is_valid_media_path(file_path):
|
86 |
+
return
|
87 |
+
build_single_img_idx(conn, file_path, False, safe_save_img_tag)
|
88 |
+
# neg暂时跳过感觉个没人会搜索这个
|
89 |
+
except Exception as e:
|
90 |
+
logger.error("Tag generation failed. Skipping this file. file:%s error: %s", file_path, e)
|
91 |
+
conn.commit()
|
92 |
+
|
93 |
+
for tag_id in tag_incr_count_rec:
|
94 |
+
tag = Tag.get(conn, tag_id)
|
95 |
+
tag.count += tag_incr_count_rec[tag_id]
|
96 |
+
tag.save(conn)
|
97 |
+
conn.commit()
|
98 |
+
|
99 |
+
def rebuild_image_index(search_dirs: List[str]):
|
100 |
+
conn = DataBase.get_conn()
|
101 |
+
with closing(conn.cursor()) as cur:
|
102 |
+
cur.execute(
|
103 |
+
"""DELETE FROM image_tag
|
104 |
+
WHERE image_tag.tag_id IN (
|
105 |
+
SELECT tag.id FROM tag WHERE tag.type <> 'custom'
|
106 |
+
)
|
107 |
+
"""
|
108 |
+
)
|
109 |
+
cur.execute("""DELETE FROM tag WHERE tag.type <> 'custom'""")
|
110 |
+
conn.commit()
|
111 |
+
update_image_data(search_dirs=search_dirs, is_rebuild=True)
|
112 |
+
|
113 |
+
|
114 |
+
def get_extra_meta_keys_from_plugins(source_identifier: str):
|
115 |
+
try:
|
116 |
+
plugin = plugin_inst_map.get(source_identifier)
|
117 |
+
if plugin:
|
118 |
+
return plugin.extra_convert_to_tag_meta_keys
|
119 |
+
except Exception as e:
|
120 |
+
logger.error("get_extra_meta_keys_from_plugins %s", e)
|
121 |
+
return []
|
122 |
+
|
123 |
+
def build_single_img_idx(conn, file_path, is_rebuild, safe_save_img_tag):
|
124 |
+
img = DbImg.get(conn, file_path)
|
125 |
+
parsed_params = None
|
126 |
+
if is_rebuild:
|
127 |
+
info = get_exif_data(file_path)
|
128 |
+
parsed_params = info.params
|
129 |
+
if not img:
|
130 |
+
img = DbImg(
|
131 |
+
file_path,
|
132 |
+
info.raw_info,
|
133 |
+
os.path.getsize(file_path),
|
134 |
+
get_modified_date(file_path),
|
135 |
+
)
|
136 |
+
img.save(conn)
|
137 |
+
else:
|
138 |
+
if img: # 已存在的跳过
|
139 |
+
if img.date == get_modified_date(img.path):
|
140 |
+
return
|
141 |
+
else:
|
142 |
+
DbImg.safe_batch_remove(conn=conn, image_ids=[img.id])
|
143 |
+
info = get_exif_data(file_path)
|
144 |
+
parsed_params = info.params
|
145 |
+
img = DbImg(
|
146 |
+
file_path,
|
147 |
+
info.raw_info,
|
148 |
+
os.path.getsize(file_path),
|
149 |
+
get_modified_date(file_path),
|
150 |
+
)
|
151 |
+
img.save(conn)
|
152 |
+
|
153 |
+
if not parsed_params:
|
154 |
+
return
|
155 |
+
meta = parsed_params.meta
|
156 |
+
lora = parsed_params.extra.get("lora", [])
|
157 |
+
lyco = parsed_params.extra.get("lyco", [])
|
158 |
+
pos = parsed_params.pos_prompt
|
159 |
+
size_tag = Tag.get_or_create(
|
160 |
+
conn,
|
161 |
+
str(meta.get("Size-1", 0)) + " * " + str(meta.get("Size-2", 0)),
|
162 |
+
type="size",
|
163 |
+
)
|
164 |
+
safe_save_img_tag(ImageTag(img.id, size_tag.id))
|
165 |
+
media_type_tag = Tag.get_or_create(conn, "Image" if is_image_file(file_path) else "Video", 'Media Type')
|
166 |
+
safe_save_img_tag(ImageTag(img.id, media_type_tag.id))
|
167 |
+
keys = [
|
168 |
+
"Model",
|
169 |
+
"Sampler",
|
170 |
+
"Source Identifier",
|
171 |
+
"Postprocess upscale by",
|
172 |
+
"Postprocess upscaler",
|
173 |
+
"Size",
|
174 |
+
"Refiner",
|
175 |
+
"Hires upscaler"
|
176 |
+
]
|
177 |
+
keys += get_extra_meta_keys_from_plugins(meta.get("Source Identifier", ""))
|
178 |
+
for k in keys:
|
179 |
+
v = case_insensitive_get(meta, k)
|
180 |
+
if not v:
|
181 |
+
continue
|
182 |
+
|
183 |
+
tag = Tag.get_or_create(conn, str(v), k)
|
184 |
+
safe_save_img_tag(ImageTag(img.id, tag.id))
|
185 |
+
if "Hires upscaler" == k:
|
186 |
+
tag = Tag.get_or_create(conn, 'Hires All', k)
|
187 |
+
safe_save_img_tag(ImageTag(img.id, tag.id))
|
188 |
+
elif "Refiner" == k:
|
189 |
+
tag = Tag.get_or_create(conn, 'Refiner All', k)
|
190 |
+
safe_save_img_tag(ImageTag(img.id, tag.id))
|
191 |
+
for i in lora:
|
192 |
+
tag = Tag.get_or_create(conn, i["name"], "lora")
|
193 |
+
safe_save_img_tag(ImageTag(img.id, tag.id))
|
194 |
+
for i in lyco:
|
195 |
+
tag = Tag.get_or_create(conn, i["name"], "lyco")
|
196 |
+
safe_save_img_tag(ImageTag(img.id, tag.id))
|
197 |
+
for k in pos:
|
198 |
+
tag = Tag.get_or_create(conn, k, "pos")
|
199 |
+
safe_save_img_tag(ImageTag(img.id, tag.id))
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/dir_cover_cache.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from scripts.iib.db.datamodel import DirCoverCache, DataBase
|
3 |
+
from scripts.iib.tool import get_created_date_by_stat, get_formatted_date, is_valid_media_path, get_video_type, birthtime_sort_key_fn
|
4 |
+
|
5 |
+
def get_top_4_media_info(folder_path):
|
6 |
+
"""
|
7 |
+
获取给定文件夹路径下的前4个媒体文件的完整路径。
|
8 |
+
|
9 |
+
参数:
|
10 |
+
folder_path (str): 文件夹的路径。
|
11 |
+
|
12 |
+
返回值:
|
13 |
+
list: 包含前4个媒体文件完整路径的列表。
|
14 |
+
"""
|
15 |
+
conn = DataBase.get_conn()
|
16 |
+
if DirCoverCache.is_cache_expired(conn, folder_path):
|
17 |
+
media_files = get_media_files_from_folder(folder_path)
|
18 |
+
DirCoverCache.cache_media_files(conn, folder_path, media_files)
|
19 |
+
else:
|
20 |
+
media_files = DirCoverCache.get_cached_media_files(conn, folder_path)
|
21 |
+
|
22 |
+
return media_files[:4]
|
23 |
+
|
24 |
+
def get_media_files_from_folder(folder_path):
|
25 |
+
"""
|
26 |
+
从文件夹中获取媒体文件的完整路径。
|
27 |
+
|
28 |
+
参数:
|
29 |
+
folder_path (str): 文件夹的路径。
|
30 |
+
|
31 |
+
返回值:
|
32 |
+
list: 包含媒体文件完整路径的列表。
|
33 |
+
"""
|
34 |
+
media_files = []
|
35 |
+
with os.scandir(folder_path) as entries:
|
36 |
+
for entry in sorted(entries, key=birthtime_sort_key_fn, reverse=True):
|
37 |
+
if entry.is_file() and is_valid_media_path(entry.path):
|
38 |
+
name = os.path.basename(entry.path)
|
39 |
+
stat = entry.stat()
|
40 |
+
date = get_formatted_date(stat.st_mtime)
|
41 |
+
created_time = get_created_date_by_stat(stat)
|
42 |
+
media_files.append({
|
43 |
+
"fullpath": entry.path,
|
44 |
+
"media_type": "video" if get_video_type(entry.path) else "image",
|
45 |
+
"type": "file",
|
46 |
+
"date": date,
|
47 |
+
"created_time": created_time,
|
48 |
+
"name": name,
|
49 |
+
})
|
50 |
+
if len(media_files) > 3:
|
51 |
+
return media_files
|
52 |
+
|
53 |
+
return media_files
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/fastapi_video.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import BinaryIO
|
3 |
+
|
4 |
+
from fastapi import FastAPI, HTTPException, Request, status
|
5 |
+
from fastapi.responses import StreamingResponse
|
6 |
+
from scripts.iib.tool import get_video_type
|
7 |
+
|
8 |
+
video_file_handler = {}
|
9 |
+
|
10 |
+
def close_video_file_reader(path):
|
11 |
+
if not get_video_type(path):
|
12 |
+
return
|
13 |
+
try:
|
14 |
+
video_file_handler[path].close()
|
15 |
+
except Exception as e:
|
16 |
+
print(f"close file error: {e}")
|
17 |
+
|
18 |
+
|
19 |
+
def send_bytes_range_requests(
|
20 |
+
file_path, start: int, end: int, chunk_size: int = 10_000
|
21 |
+
):
|
22 |
+
"""Send a file in chunks using Range Requests specification RFC7233
|
23 |
+
|
24 |
+
`start` and `end` parameters are inclusive due to specification
|
25 |
+
"""
|
26 |
+
with open(file_path, mode="rb") as f:
|
27 |
+
video_file_handler[file_path] = f
|
28 |
+
f.seek(start)
|
29 |
+
while (pos := f.tell()) <= end:
|
30 |
+
read_size = min(chunk_size, end + 1 - pos)
|
31 |
+
yield f.read(read_size)
|
32 |
+
|
33 |
+
|
34 |
+
def _get_range_header(range_header: str, file_size: int) -> tuple[int, int]:
|
35 |
+
def _invalid_range():
|
36 |
+
return HTTPException(
|
37 |
+
status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE,
|
38 |
+
detail=f"Invalid request range (Range:{range_header!r})",
|
39 |
+
)
|
40 |
+
|
41 |
+
try:
|
42 |
+
h = range_header.replace("bytes=", "").split("-")
|
43 |
+
start = int(h[0]) if h[0] != "" else 0
|
44 |
+
end = int(h[1]) if h[1] != "" else file_size - 1
|
45 |
+
except ValueError:
|
46 |
+
raise _invalid_range()
|
47 |
+
|
48 |
+
if start > end or start < 0 or end > file_size - 1:
|
49 |
+
raise _invalid_range()
|
50 |
+
return start, end
|
51 |
+
|
52 |
+
|
53 |
+
def range_requests_response(
|
54 |
+
request: Request, file_path: str, content_type: str
|
55 |
+
):
|
56 |
+
"""Returns StreamingResponse using Range Requests of a given file"""
|
57 |
+
|
58 |
+
file_size = os.stat(file_path).st_size
|
59 |
+
range_header = request.headers.get("range")
|
60 |
+
|
61 |
+
headers = {
|
62 |
+
"content-type": content_type,
|
63 |
+
"accept-ranges": "bytes",
|
64 |
+
"content-encoding": "identity",
|
65 |
+
"content-length": str(file_size),
|
66 |
+
"access-control-expose-headers": (
|
67 |
+
"content-type, accept-ranges, content-length, "
|
68 |
+
"content-range, content-encoding"
|
69 |
+
),
|
70 |
+
}
|
71 |
+
start = 0
|
72 |
+
end = file_size - 1
|
73 |
+
status_code = status.HTTP_200_OK
|
74 |
+
|
75 |
+
if range_header is not None:
|
76 |
+
start, end = _get_range_header(range_header, file_size)
|
77 |
+
size = end - start + 1
|
78 |
+
headers["content-length"] = str(size)
|
79 |
+
headers["content-range"] = f"bytes {start}-{end}/{file_size}"
|
80 |
+
status_code = status.HTTP_206_PARTIAL_CONTENT
|
81 |
+
|
82 |
+
return StreamingResponse(
|
83 |
+
send_bytes_range_requests(file_path, start, end),
|
84 |
+
headers=headers,
|
85 |
+
status_code=status_code,
|
86 |
+
)
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/img_cache_gen.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import hashlib
|
2 |
+
import os
|
3 |
+
from typing import List
|
4 |
+
from scripts.iib.tool import get_formatted_date, get_cache_dir, is_image_file
|
5 |
+
from concurrent.futures import ThreadPoolExecutor
|
6 |
+
import time
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
def generate_image_cache(dirs, size:str, verbose=False):
|
10 |
+
start_time = time.time()
|
11 |
+
cache_base_dir = get_cache_dir()
|
12 |
+
|
13 |
+
def process_image(item):
|
14 |
+
if item.is_dir():
|
15 |
+
verbose and print(f"Processing directory: {item.path}")
|
16 |
+
for sub_item in os.scandir(item.path):
|
17 |
+
process_image(sub_item)
|
18 |
+
return
|
19 |
+
if not os.path.exists(item.path) or not is_image_file(item.path):
|
20 |
+
return
|
21 |
+
|
22 |
+
try:
|
23 |
+
path = os.path.normpath(item.path)
|
24 |
+
stat = item.stat()
|
25 |
+
t = get_formatted_date(stat.st_mtime)
|
26 |
+
hash_dir = hashlib.md5((path + t).encode("utf-8")).hexdigest()
|
27 |
+
cache_dir = os.path.join(cache_base_dir, "iib_cache", hash_dir)
|
28 |
+
cache_path = os.path.join(cache_dir, f"{size}.webp")
|
29 |
+
|
30 |
+
if os.path.exists(cache_path):
|
31 |
+
verbose and print(f"Image cache already exists: {path}")
|
32 |
+
return
|
33 |
+
|
34 |
+
if os.path.getsize(path) < 64 * 1024:
|
35 |
+
verbose and print(f"Image size less than 64KB: {path}", "skip")
|
36 |
+
return
|
37 |
+
|
38 |
+
with Image.open(path) as img:
|
39 |
+
w, h = size.split("x")
|
40 |
+
img.thumbnail((int(w), int(h)))
|
41 |
+
os.makedirs(cache_dir, exist_ok=True)
|
42 |
+
img.save(cache_path, "webp")
|
43 |
+
|
44 |
+
verbose and print(f"Image cache generated: {path}")
|
45 |
+
except Exception as e:
|
46 |
+
print(f"Error generating image cache: {path}")
|
47 |
+
print(e)
|
48 |
+
|
49 |
+
with ThreadPoolExecutor() as executor:
|
50 |
+
for dir_path in dirs:
|
51 |
+
folder_listing: List[os.DirEntry] = os.scandir(dir_path)
|
52 |
+
for item in folder_listing:
|
53 |
+
executor.submit(process_image, item)
|
54 |
+
|
55 |
+
print("Image cache generation completed. ✨")
|
56 |
+
end_time = time.time()
|
57 |
+
execution_time = end_time - start_time
|
58 |
+
print(f"Execution time: {execution_time} seconds")
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/logger.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from scripts.iib.tool import is_dev,cwd
|
3 |
+
|
4 |
+
import logging
|
5 |
+
logger = logging.getLogger(__name__)
|
6 |
+
logger.setLevel(logging.DEBUG)
|
7 |
+
|
8 |
+
console_handler = logging.StreamHandler()
|
9 |
+
console_handler.setLevel(logging.INFO)
|
10 |
+
|
11 |
+
file_handler = logging.FileHandler(f"{cwd}/log.log")
|
12 |
+
file_handler.setLevel(logging.DEBUG)
|
13 |
+
|
14 |
+
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
15 |
+
console_handler.setFormatter(formatter)
|
16 |
+
file_handler.setFormatter(formatter)
|
17 |
+
|
18 |
+
logger.addHandler(file_handler)
|
19 |
+
if is_dev:
|
20 |
+
logger.addHandler(console_handler)
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/comfyui.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
|
3 |
+
from scripts.iib.tool import (
|
4 |
+
comfyui_exif_data_to_str,
|
5 |
+
is_img_created_by_comfyui,
|
6 |
+
is_img_created_by_comfyui_with_webui_gen_info,
|
7 |
+
get_comfyui_exif_data,
|
8 |
+
parse_generation_parameters,
|
9 |
+
read_sd_webui_gen_info_from_image,
|
10 |
+
)
|
11 |
+
from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams
|
12 |
+
from scripts.iib.logger import logger
|
13 |
+
|
14 |
+
|
15 |
+
class ComfyUIParser:
|
16 |
+
def __init__(self):
|
17 |
+
pass
|
18 |
+
|
19 |
+
@classmethod
|
20 |
+
def parse(clz, img, file_path):
|
21 |
+
info = ""
|
22 |
+
params = None
|
23 |
+
if not clz.test(img, file_path):
|
24 |
+
raise Exception("The input image does not match the current parser.")
|
25 |
+
try:
|
26 |
+
if is_img_created_by_comfyui_with_webui_gen_info(img):
|
27 |
+
info = read_sd_webui_gen_info_from_image(img, file_path)
|
28 |
+
info += ", Source Identifier: ComfyUI"
|
29 |
+
params = parse_generation_parameters(info)
|
30 |
+
else:
|
31 |
+
params = get_comfyui_exif_data(img)
|
32 |
+
info = comfyui_exif_data_to_str(params)
|
33 |
+
except Exception as e:
|
34 |
+
logger.error('parse comfyui image failed. prompt:')
|
35 |
+
logger.error(img.info.get('prompt'))
|
36 |
+
return ImageGenerationInfo()
|
37 |
+
return ImageGenerationInfo(
|
38 |
+
info,
|
39 |
+
ImageGenerationParams(
|
40 |
+
meta=params["meta"], pos_prompt=params["pos_prompt"], extra=params
|
41 |
+
),
|
42 |
+
)
|
43 |
+
|
44 |
+
@classmethod
|
45 |
+
def test(clz, img: Image, file_path: str) -> bool:
|
46 |
+
try:
|
47 |
+
return is_img_created_by_comfyui(
|
48 |
+
img
|
49 |
+
) or is_img_created_by_comfyui_with_webui_gen_info(img)
|
50 |
+
except Exception:
|
51 |
+
return False
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/fooocus.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
from PIL import Image
|
4 |
+
|
5 |
+
from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams
|
6 |
+
from scripts.iib.tool import omit, parse_generation_parameters, unique_by
|
7 |
+
|
8 |
+
|
9 |
+
def remove_extra_spaces(text):
|
10 |
+
return re.sub(r"\s+", " ", text)
|
11 |
+
|
12 |
+
|
13 |
+
def get_log_file(file_path: str):
|
14 |
+
dir = os.path.dirname(file_path)
|
15 |
+
with open(os.path.join(dir, "log.html")) as f:
|
16 |
+
return f.read()
|
17 |
+
|
18 |
+
lora_re = re.compile("LoRA \d+", re.IGNORECASE)
|
19 |
+
|
20 |
+
class FooocusParser:
|
21 |
+
def __init__(self):
|
22 |
+
pass
|
23 |
+
|
24 |
+
@classmethod
|
25 |
+
def parse(clz, img: Image, file_path):
|
26 |
+
if not clz.test(img, file_path):
|
27 |
+
raise Exception("The input image does not match the current parser.")
|
28 |
+
from lxml import etree
|
29 |
+
|
30 |
+
log = get_log_file(file_path)
|
31 |
+
root = etree.HTML(log)
|
32 |
+
id = str(os.path.basename(file_path)).replace(".", "_")
|
33 |
+
metadata = root.xpath(f'//div[@id="{id}"]/descendant::table[@class="metadata"]')
|
34 |
+
tr_elements = metadata[0].xpath(".//tr")
|
35 |
+
lora_list = []
|
36 |
+
# As a workaround to bypass parsing errors in the parser.
|
37 |
+
# https://github.com/jiw0220/stable-diffusion-image-metadata/blob/00b8d42d4d1a536862bba0b07c332bdebb2a0ce5/src/index.ts#L130
|
38 |
+
metadata_list_str = "Steps: Unknown , Source Identifier: Fooocus ,"
|
39 |
+
params = {"meta": {"Source Identifier": "Fooocus"}}
|
40 |
+
for tr in tr_elements:
|
41 |
+
label = tr.xpath('.//td[@class="label" or @class="key"]/text()')
|
42 |
+
value = tr.xpath('.//td[@class="value"]/text()')
|
43 |
+
if label:
|
44 |
+
k = label[0]
|
45 |
+
v = value[0] if value else "None"
|
46 |
+
if k == "Fooocus V2 Expansion":
|
47 |
+
continue
|
48 |
+
if k == "Prompt" or k == "Negative Prompt":
|
49 |
+
params[k] = remove_extra_spaces(v.replace("\n", "").strip())
|
50 |
+
else:
|
51 |
+
v = v.replace(",", ",")
|
52 |
+
params["meta"][k] = v
|
53 |
+
metadata_list_str += f" {k}: {v},"
|
54 |
+
if lora_re.search(k):
|
55 |
+
lora_list.append({ "name": v.strip(), "value": 1 })
|
56 |
+
params["meta"]["Model"] = params["meta"]["Base Model"]
|
57 |
+
params["meta"]["Size"] = str(params["meta"]["Resolution"]).replace("(", "").replace(")", "").replace(",", " * ")
|
58 |
+
metadata_list_str = metadata_list_str.strip()
|
59 |
+
info = f"""{params['Prompt']}\nNegative prompt: {params['Negative Prompt']}\n{metadata_list_str}""".strip()
|
60 |
+
return ImageGenerationInfo(
|
61 |
+
info,
|
62 |
+
ImageGenerationParams(
|
63 |
+
meta=params["meta"],
|
64 |
+
pos_prompt=parse_generation_parameters(info)["pos_prompt"],
|
65 |
+
extra={
|
66 |
+
"lora": unique_by(lora_list, lambda x: x["name"].lower())
|
67 |
+
}
|
68 |
+
),
|
69 |
+
)
|
70 |
+
|
71 |
+
@classmethod
|
72 |
+
def test(clz, img: Image, file_path: str):
|
73 |
+
filename = os.path.basename(file_path)
|
74 |
+
try:
|
75 |
+
return get_log_file(file_path).find(filename) != -1
|
76 |
+
except Exception as e:
|
77 |
+
return False
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/index.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from scripts.iib.parsers.comfyui import ComfyUIParser
|
3 |
+
from scripts.iib.parsers.sd_webui import SdWebUIParser
|
4 |
+
from scripts.iib.parsers.fooocus import FooocusParser
|
5 |
+
from scripts.iib.parsers.novelai import NovelAIParser
|
6 |
+
from scripts.iib.parsers.model import ImageGenerationInfo
|
7 |
+
from scripts.iib.parsers.stable_swarm_ui import StableSwarmUIParser
|
8 |
+
from scripts.iib.parsers.invoke_ai import InvokeAIParser
|
9 |
+
from scripts.iib.parsers.sd_webui_stealth import SdWebUIStealthParser
|
10 |
+
from scripts.iib.logger import logger
|
11 |
+
from PIL import Image
|
12 |
+
from scripts.iib.plugin import plugin_insts
|
13 |
+
import traceback
|
14 |
+
|
15 |
+
|
16 |
+
def parse_image_info(image_path: str) -> ImageGenerationInfo:
|
17 |
+
enable_stealth_parser = os.getenv('IIB_ENABLE_SD_WEBUI_STEALTH_PARSER', 'false').lower() == 'true'
|
18 |
+
parsers = plugin_insts + [
|
19 |
+
ComfyUIParser,
|
20 |
+
FooocusParser,
|
21 |
+
NovelAIParser,
|
22 |
+
InvokeAIParser,
|
23 |
+
StableSwarmUIParser,
|
24 |
+
]
|
25 |
+
|
26 |
+
if enable_stealth_parser:
|
27 |
+
parsers.append(SdWebUIStealthParser)
|
28 |
+
|
29 |
+
parsers.append(SdWebUIParser)
|
30 |
+
with Image.open(image_path) as img:
|
31 |
+
for parser in parsers:
|
32 |
+
if parser.test(img, image_path):
|
33 |
+
try:
|
34 |
+
return parser.parse(img, image_path)
|
35 |
+
except Exception as e:
|
36 |
+
logger.error(e, stack_info=True)
|
37 |
+
print(e)
|
38 |
+
print(traceback.format_exc())
|
39 |
+
return ImageGenerationInfo()
|
40 |
+
raise Exception("matched parser is not found")
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/invoke_ai.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
import json
|
3 |
+
|
4 |
+
from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams
|
5 |
+
from scripts.iib.tool import omit, parse_generation_parameters, unique_by
|
6 |
+
|
7 |
+
class InvokeAIParser:
|
8 |
+
def __init__(self):
|
9 |
+
pass
|
10 |
+
|
11 |
+
@classmethod
|
12 |
+
def parse(clz, img: Image, file_path):
|
13 |
+
if not clz.test(img, file_path):
|
14 |
+
raise Exception("The input image does not match the current parser.")
|
15 |
+
raw_infos = json.loads(img.info["invokeai_graph"])
|
16 |
+
core_metadata = {}
|
17 |
+
for key in raw_infos['nodes']:
|
18 |
+
if key.startswith("core_metadata"):
|
19 |
+
core_metadata = raw_infos['nodes'][key]
|
20 |
+
break
|
21 |
+
|
22 |
+
positive_prompt = core_metadata.get("positive_prompt", "None")
|
23 |
+
negative_prompt = core_metadata.get("negative_prompt", "None")
|
24 |
+
steps = core_metadata.get("steps", 'Unknown')
|
25 |
+
cfg_scale = core_metadata.get("cfg_scale", 'Unknown')
|
26 |
+
model_name = core_metadata.get("model", {}).get("name", "Unknown")
|
27 |
+
model_hash = core_metadata.get("model", {}).get("hash", "Unknown")
|
28 |
+
|
29 |
+
meta_kv = [
|
30 |
+
f"Steps: {steps}",
|
31 |
+
"Source Identifier: InvokeAI",
|
32 |
+
f"CFG scale: {cfg_scale}",
|
33 |
+
f"Model: {model_name}",
|
34 |
+
f"Model hash: {model_hash}",
|
35 |
+
]
|
36 |
+
|
37 |
+
for key in core_metadata:
|
38 |
+
if key not in ["positive_prompt", "negative_prompt", "steps", "cfg_scale", "model"]:
|
39 |
+
val = core_metadata[key]
|
40 |
+
if bool(val):
|
41 |
+
meta_kv.append(f"{key}: {val}")
|
42 |
+
|
43 |
+
meta = ", ".join(meta_kv)
|
44 |
+
meta_obj = {}
|
45 |
+
for kv in meta_kv:
|
46 |
+
k, v = kv.split(": ", 1)
|
47 |
+
meta_obj[k] = v
|
48 |
+
info = f"{positive_prompt}\nNegative prompt: {negative_prompt}\n{meta}"
|
49 |
+
|
50 |
+
return ImageGenerationInfo(
|
51 |
+
info,
|
52 |
+
ImageGenerationParams(
|
53 |
+
meta=meta_obj,
|
54 |
+
pos_prompt=parse_generation_parameters(info)["pos_prompt"],
|
55 |
+
# extra=params
|
56 |
+
),
|
57 |
+
)
|
58 |
+
|
59 |
+
@classmethod
|
60 |
+
def test(clz, img: Image, file_path: str):
|
61 |
+
try:
|
62 |
+
return 'invokeai_graph' in img.info
|
63 |
+
except Exception as e:
|
64 |
+
return False
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/model.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from scripts.iib.tool import omit
|
2 |
+
|
3 |
+
|
4 |
+
class ImageGenerationParams:
|
5 |
+
def __init__(self, meta: dict = {}, pos_prompt: list = [], extra: dict = {}) -> None:
|
6 |
+
self.meta = meta
|
7 |
+
self.pos_prompt = pos_prompt
|
8 |
+
self.extra = omit(extra, ["meta", "pos_prompt"])
|
9 |
+
|
10 |
+
|
11 |
+
class ImageGenerationInfo:
|
12 |
+
def __init__(
|
13 |
+
self,
|
14 |
+
raw_info: str = "",
|
15 |
+
params: ImageGenerationParams = ImageGenerationParams(),
|
16 |
+
):
|
17 |
+
self.raw_info = raw_info
|
18 |
+
self.params = params
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/novelai.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
from PIL import Image
|
3 |
+
|
4 |
+
from scripts.iib.tool import (
|
5 |
+
parse_generation_parameters,
|
6 |
+
replace_punctuation
|
7 |
+
)
|
8 |
+
from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams
|
9 |
+
|
10 |
+
|
11 |
+
class NovelAIParser:
|
12 |
+
def __init__(self):
|
13 |
+
pass
|
14 |
+
|
15 |
+
@classmethod
|
16 |
+
def parse(clz, img, file_path):
|
17 |
+
info = ""
|
18 |
+
params = None
|
19 |
+
if not clz.test(img, file_path):
|
20 |
+
raise Exception("The input image does not match the current parser.")
|
21 |
+
data = json.loads(img.info.get('Comment'))
|
22 |
+
meta_kv = [f"""Steps: {data["steps"]}, Source Identifier: NovelAI"""]
|
23 |
+
for key, value in data.items():
|
24 |
+
if key not in ["prompt"]:
|
25 |
+
value = replace_punctuation(str(value))
|
26 |
+
meta_kv.append(f"{key}: {value}")
|
27 |
+
meta = ', '.join(meta_kv)
|
28 |
+
info = data["prompt"] + '\n' + meta
|
29 |
+
|
30 |
+
params = parse_generation_parameters(info)
|
31 |
+
|
32 |
+
return ImageGenerationInfo(
|
33 |
+
info,
|
34 |
+
ImageGenerationParams(
|
35 |
+
meta=params["meta"], pos_prompt=params["pos_prompt"]
|
36 |
+
),
|
37 |
+
)
|
38 |
+
|
39 |
+
@classmethod
|
40 |
+
def test(clz, img: Image, file_path: str) -> bool:
|
41 |
+
try:
|
42 |
+
return img.info.get('Software') == 'NovelAI' and isinstance(img.info.get('Comment'), str)
|
43 |
+
except Exception:
|
44 |
+
return False
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/sd_webui.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
|
3 |
+
from scripts.iib.tool import (
|
4 |
+
parse_generation_parameters,
|
5 |
+
read_sd_webui_gen_info_from_image,
|
6 |
+
)
|
7 |
+
from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams
|
8 |
+
|
9 |
+
|
10 |
+
class SdWebUIParser:
|
11 |
+
def __init__(self):
|
12 |
+
pass
|
13 |
+
|
14 |
+
@classmethod
|
15 |
+
def parse(clz, img: Image, file_path):
|
16 |
+
if not clz.test(img, file_path):
|
17 |
+
raise Exception("The input image does not match the current parser.")
|
18 |
+
info = read_sd_webui_gen_info_from_image(img, file_path)
|
19 |
+
if not info:
|
20 |
+
return ImageGenerationInfo()
|
21 |
+
info += ", Source Identifier: Stable Diffusion web UI"
|
22 |
+
params = parse_generation_parameters(info)
|
23 |
+
return ImageGenerationInfo(
|
24 |
+
info,
|
25 |
+
ImageGenerationParams(
|
26 |
+
meta=params["meta"], pos_prompt=params["pos_prompt"], extra=params
|
27 |
+
),
|
28 |
+
)
|
29 |
+
|
30 |
+
@classmethod
|
31 |
+
def test(clz, img: Image, file_path: str):
|
32 |
+
try:
|
33 |
+
return True
|
34 |
+
except Exception as e:
|
35 |
+
return False
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/sd_webui_stealth.py
ADDED
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
import gzip
|
3 |
+
from scripts.iib.tool import (
|
4 |
+
parse_generation_parameters,
|
5 |
+
read_sd_webui_gen_info_from_image,
|
6 |
+
)
|
7 |
+
from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams
|
8 |
+
# https://github.com/neggles/sd-webui-stealth-pnginfo/blob/main/scripts/stealth_pnginfo.py
|
9 |
+
def read_info_from_image_stealth(image, fast_check=False):
|
10 |
+
width, height = image.size
|
11 |
+
pixels = image.load()
|
12 |
+
|
13 |
+
has_alpha = True if image.mode == 'RGBA' else False
|
14 |
+
mode = None
|
15 |
+
compressed = False
|
16 |
+
binary_data = ''
|
17 |
+
buffer_a = ''
|
18 |
+
buffer_rgb = ''
|
19 |
+
index_a = 0
|
20 |
+
index_rgb = 0
|
21 |
+
sig_confirmed = False
|
22 |
+
confirming_signature = True
|
23 |
+
reading_param_len = False
|
24 |
+
reading_param = False
|
25 |
+
read_end = False
|
26 |
+
cyc_count = 0
|
27 |
+
for x in range(width):
|
28 |
+
for y in range(height):
|
29 |
+
if has_alpha:
|
30 |
+
r, g, b, a = pixels[x, y]
|
31 |
+
buffer_a += str(a & 1)
|
32 |
+
index_a += 1
|
33 |
+
else:
|
34 |
+
r, g, b = pixels[x, y]
|
35 |
+
buffer_rgb += str(r & 1)
|
36 |
+
buffer_rgb += str(g & 1)
|
37 |
+
buffer_rgb += str(b & 1)
|
38 |
+
index_rgb += 3
|
39 |
+
cyc_count += 1
|
40 |
+
if fast_check and cyc_count> 256:
|
41 |
+
return False
|
42 |
+
if confirming_signature:
|
43 |
+
if index_a == len('stealth_pnginfo') * 8:
|
44 |
+
decoded_sig = bytearray(int(buffer_a[i:i + 8], 2) for i in
|
45 |
+
range(0, len(buffer_a), 8)).decode('utf-8', errors='ignore')
|
46 |
+
if decoded_sig in {'stealth_pnginfo', 'stealth_pngcomp'}:
|
47 |
+
confirming_signature = False
|
48 |
+
sig_confirmed = True
|
49 |
+
if fast_check:
|
50 |
+
return True
|
51 |
+
reading_param_len = True
|
52 |
+
mode = 'alpha'
|
53 |
+
if decoded_sig == 'stealth_pngcomp':
|
54 |
+
compressed = True
|
55 |
+
buffer_a = ''
|
56 |
+
index_a = 0
|
57 |
+
else:
|
58 |
+
read_end = True
|
59 |
+
if fast_check:
|
60 |
+
return False
|
61 |
+
break
|
62 |
+
elif index_rgb == len('stealth_pnginfo') * 8:
|
63 |
+
decoded_sig = bytearray(int(buffer_rgb[i:i + 8], 2) for i in
|
64 |
+
range(0, len(buffer_rgb), 8)).decode('utf-8', errors='ignore')
|
65 |
+
if decoded_sig in {'stealth_rgbinfo', 'stealth_rgbcomp'}:
|
66 |
+
confirming_signature = False
|
67 |
+
sig_confirmed = True
|
68 |
+
if fast_check:
|
69 |
+
return True
|
70 |
+
reading_param_len = True
|
71 |
+
mode = 'rgb'
|
72 |
+
if decoded_sig == 'stealth_rgbcomp':
|
73 |
+
compressed = True
|
74 |
+
buffer_rgb = ''
|
75 |
+
index_rgb = 0
|
76 |
+
elif reading_param_len:
|
77 |
+
if mode == 'alpha':
|
78 |
+
if index_a == 32:
|
79 |
+
param_len = int(buffer_a, 2)
|
80 |
+
reading_param_len = False
|
81 |
+
reading_param = True
|
82 |
+
buffer_a = ''
|
83 |
+
index_a = 0
|
84 |
+
else:
|
85 |
+
if index_rgb == 33:
|
86 |
+
pop = buffer_rgb[-1]
|
87 |
+
buffer_rgb = buffer_rgb[:-1]
|
88 |
+
param_len = int(buffer_rgb, 2)
|
89 |
+
reading_param_len = False
|
90 |
+
reading_param = True
|
91 |
+
buffer_rgb = pop
|
92 |
+
index_rgb = 1
|
93 |
+
elif reading_param:
|
94 |
+
if mode == 'alpha':
|
95 |
+
if index_a == param_len:
|
96 |
+
binary_data = buffer_a
|
97 |
+
read_end = True
|
98 |
+
break
|
99 |
+
else:
|
100 |
+
if index_rgb >= param_len:
|
101 |
+
diff = param_len - index_rgb
|
102 |
+
if diff < 0:
|
103 |
+
buffer_rgb = buffer_rgb[:diff]
|
104 |
+
binary_data = buffer_rgb
|
105 |
+
read_end = True
|
106 |
+
break
|
107 |
+
else:
|
108 |
+
# impossible
|
109 |
+
read_end = True
|
110 |
+
if fast_check:
|
111 |
+
return False
|
112 |
+
break
|
113 |
+
if read_end:
|
114 |
+
break
|
115 |
+
if sig_confirmed and binary_data != '':
|
116 |
+
if fast_check:
|
117 |
+
return True
|
118 |
+
# Convert binary string to UTF-8 encoded text
|
119 |
+
byte_data = bytearray(int(binary_data[i:i + 8], 2) for i in range(0, len(binary_data), 8))
|
120 |
+
try:
|
121 |
+
if compressed:
|
122 |
+
decoded_data = gzip.decompress(bytes(byte_data)).decode('utf-8')
|
123 |
+
else:
|
124 |
+
decoded_data = byte_data.decode('utf-8', errors='ignore')
|
125 |
+
geninfo = decoded_data
|
126 |
+
except:
|
127 |
+
pass
|
128 |
+
return geninfo
|
129 |
+
|
130 |
+
|
131 |
+
|
132 |
+
class SdWebUIStealthParser:
|
133 |
+
def __init__(self):
|
134 |
+
pass
|
135 |
+
|
136 |
+
@classmethod
|
137 |
+
def parse(clz, img: Image, file_path):
|
138 |
+
if not clz.test(img, file_path):
|
139 |
+
raise Exception("The input image does not match the current parser.")
|
140 |
+
info = read_info_from_image_stealth(img)
|
141 |
+
if not info:
|
142 |
+
return ImageGenerationInfo()
|
143 |
+
info += ", Source Identifier: Stable Diffusion web UI(Stealth)"
|
144 |
+
params = parse_generation_parameters(info)
|
145 |
+
return ImageGenerationInfo(
|
146 |
+
info,
|
147 |
+
ImageGenerationParams(
|
148 |
+
meta=params["meta"], pos_prompt=params["pos_prompt"], extra=params
|
149 |
+
),
|
150 |
+
)
|
151 |
+
|
152 |
+
@classmethod
|
153 |
+
def test(clz, img: Image, file_path: str):
|
154 |
+
try:
|
155 |
+
return bool(read_info_from_image_stealth(img, fast_check=True))
|
156 |
+
except Exception as e:
|
157 |
+
return False
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/parsers/stable_swarm_ui.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
|
3 |
+
import piexif
|
4 |
+
import piexif.helper
|
5 |
+
from scripts.iib.tool import parse_generation_parameters, replace_punctuation
|
6 |
+
from scripts.iib.parsers.model import ImageGenerationInfo, ImageGenerationParams
|
7 |
+
from PIL.ExifTags import TAGS
|
8 |
+
import json
|
9 |
+
|
10 |
+
|
11 |
+
class StableSwarmUIParser:
|
12 |
+
def __init__(self):
|
13 |
+
pass
|
14 |
+
|
15 |
+
@classmethod
|
16 |
+
def get_exif_data(clz, image: Image) -> str:
|
17 |
+
items = image.info or {}
|
18 |
+
|
19 |
+
if "exif" in items:
|
20 |
+
exif = piexif.load(items["exif"])
|
21 |
+
exif_bytes = (
|
22 |
+
(exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b"")
|
23 |
+
)
|
24 |
+
|
25 |
+
unicode_start = exif_bytes.find(b"UNICODE")
|
26 |
+
if unicode_start == -1:
|
27 |
+
raise ValueError("'UNICODE' markup isn't found")
|
28 |
+
|
29 |
+
unicode_data = exif_bytes[unicode_start + len("UNICODE") + 1 :]
|
30 |
+
geninfo = unicode_data.decode("utf-16")
|
31 |
+
return geninfo
|
32 |
+
|
33 |
+
@classmethod
|
34 |
+
def parse(clz, img: Image, file_path):
|
35 |
+
if not clz.test(img, file_path):
|
36 |
+
raise Exception("The input image does not match the current parser.")
|
37 |
+
exif_data = json.loads(clz.get_exif_data(img))["sui_image_params"]
|
38 |
+
prompt = exif_data.pop("prompt")
|
39 |
+
negativeprompt = exif_data.pop("negativeprompt")
|
40 |
+
steps = exif_data.pop("steps")
|
41 |
+
meta_kv = [f"Steps: {steps}", "Source Identifier: StableSwarmUI"]
|
42 |
+
for key, value in exif_data.items():
|
43 |
+
value = replace_punctuation(str(value))
|
44 |
+
meta_kv.append(f"{key}: {value}")
|
45 |
+
meta = ", ".join(meta_kv)
|
46 |
+
info = "\n".join([prompt, f"Negative prompt: {negativeprompt}", meta])
|
47 |
+
params = parse_generation_parameters(info)
|
48 |
+
return ImageGenerationInfo(
|
49 |
+
info,
|
50 |
+
ImageGenerationParams(
|
51 |
+
meta=params["meta"], pos_prompt=params["pos_prompt"], extra=params
|
52 |
+
),
|
53 |
+
)
|
54 |
+
|
55 |
+
@classmethod
|
56 |
+
def test(clz, img: Image, file_path: str):
|
57 |
+
try:
|
58 |
+
exif = clz.get_exif_data(img)
|
59 |
+
return exif.find("sui_image_params") != -1
|
60 |
+
except Exception as e:
|
61 |
+
return False
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/plugin.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import importlib.util
|
3 |
+
import sys
|
4 |
+
from scripts.iib.tool import cwd
|
5 |
+
|
6 |
+
def load_plugins(plugin_dir):
|
7 |
+
if not os.path.exists(plugin_dir):
|
8 |
+
return []
|
9 |
+
plugins = []
|
10 |
+
for filename in os.listdir(plugin_dir):
|
11 |
+
main_module_path = os.path.join(plugin_dir, filename, 'main.py')
|
12 |
+
if not os.path.exists(main_module_path):
|
13 |
+
continue
|
14 |
+
spec = importlib.util.spec_from_file_location('main', main_module_path)
|
15 |
+
module = importlib.util.module_from_spec(spec)
|
16 |
+
spec.loader.exec_module(module)
|
17 |
+
plugins.append(module)
|
18 |
+
return plugins
|
19 |
+
|
20 |
+
plugin_insts = []
|
21 |
+
plugin_inst_map = {}
|
22 |
+
# 使用插件
|
23 |
+
try:
|
24 |
+
plugin_dir = os.path.normpath(os.path.join(cwd, 'plugins'))
|
25 |
+
plugins = load_plugins(plugin_dir)
|
26 |
+
sys.path.append(plugin_dir)
|
27 |
+
for plugin in plugins:
|
28 |
+
try:
|
29 |
+
res = plugin.Main()
|
30 |
+
plugin_insts.append(res)
|
31 |
+
plugin_inst_map[res.source_identifier] = res
|
32 |
+
print(f'IIB loaded plugin: {res.name}')
|
33 |
+
except Exception as e:
|
34 |
+
print(f'Error running plugin {plugin.__class__.__name__}: {e}')
|
35 |
+
except Exception as e:
|
36 |
+
print(f'Error loading plugins: {e}')
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/seq.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
class Seq:
|
2 |
+
def __init__(self, iterable):
|
3 |
+
self.iterable = iterable
|
4 |
+
|
5 |
+
def map(self, func):
|
6 |
+
return Seq(func(item) for item in self.iterable)
|
7 |
+
|
8 |
+
def filter(self, predicate):
|
9 |
+
return Seq(item for item in self.iterable if predicate(item))
|
10 |
+
|
11 |
+
def to_list(self):
|
12 |
+
return list(self.iterable)
|
13 |
+
|
14 |
+
def __iter__(self):
|
15 |
+
return iter(self.iterable)
|
16 |
+
|
17 |
+
def __repr__(self):
|
18 |
+
return f"Seq({repr(self.iterable)})"
|
19 |
+
|
20 |
+
def seq(iterable):
|
21 |
+
return Seq(iterable)
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/tool.py
ADDED
@@ -0,0 +1,746 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import ctypes
|
2 |
+
from datetime import datetime
|
3 |
+
import os
|
4 |
+
import platform
|
5 |
+
import re
|
6 |
+
import tempfile
|
7 |
+
import subprocess
|
8 |
+
from typing import Dict, List
|
9 |
+
import sys
|
10 |
+
import piexif
|
11 |
+
import piexif.helper
|
12 |
+
import json
|
13 |
+
import zipfile
|
14 |
+
from PIL import Image
|
15 |
+
import shutil
|
16 |
+
|
17 |
+
|
18 |
+
sd_img_dirs = [
|
19 |
+
"outdir_txt2img_samples",
|
20 |
+
"outdir_img2img_samples",
|
21 |
+
"outdir_save",
|
22 |
+
"outdir_extras_samples",
|
23 |
+
"outdir_grids",
|
24 |
+
"outdir_img2img_grids",
|
25 |
+
"outdir_samples",
|
26 |
+
"outdir_txt2img_grids",
|
27 |
+
]
|
28 |
+
|
29 |
+
|
30 |
+
is_dev = os.getenv("APP_ENV") == "dev"
|
31 |
+
is_nuitka = "__compiled__" in globals()
|
32 |
+
is_pyinstaller_bundle = bool(getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'))
|
33 |
+
is_exe_ver = is_nuitka or is_pyinstaller_bundle
|
34 |
+
|
35 |
+
cwd = os.getcwd() if is_exe_ver else os.path.normpath(os.path.join(__file__, "../../../"))
|
36 |
+
is_win = platform.system().lower().find("windows") != -1
|
37 |
+
|
38 |
+
|
39 |
+
|
40 |
+
|
41 |
+
try:
|
42 |
+
from dotenv import load_dotenv
|
43 |
+
|
44 |
+
load_dotenv(os.path.join(cwd, ".env"))
|
45 |
+
except Exception as e:
|
46 |
+
print(e)
|
47 |
+
|
48 |
+
|
49 |
+
|
50 |
+
def backup_db_file(db_file_path):
|
51 |
+
|
52 |
+
if not os.path.exists(db_file_path):
|
53 |
+
return
|
54 |
+
max_backup_count = int(os.environ.get('IIB_DB_FILE_BACKUP_MAX', '8'))
|
55 |
+
if max_backup_count < 1:
|
56 |
+
return
|
57 |
+
backup_folder = os.path.join(cwd,'iib_db_backup')
|
58 |
+
current_time = datetime.now()
|
59 |
+
timestamp = current_time.strftime('%Y-%m-%d %H-%M-%S')
|
60 |
+
backup_filename = f"iib.db_{timestamp}"
|
61 |
+
os.makedirs(backup_folder, exist_ok=True)
|
62 |
+
backup_filepath = os.path.join(backup_folder, backup_filename)
|
63 |
+
shutil.copy2(db_file_path, backup_filepath)
|
64 |
+
backup_files = os.listdir(backup_folder)
|
65 |
+
pattern = r"iib\.db_(\d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2})"
|
66 |
+
backup_files_with_time = [(f, re.search(pattern, f).group(1)) for f in backup_files if re.search(pattern, f)]
|
67 |
+
sorted_backup_files = sorted(backup_files_with_time, key=lambda x: datetime.strptime(x[1], '%Y-%m-%d %H-%M-%S'))
|
68 |
+
|
69 |
+
if len(sorted_backup_files) > max_backup_count:
|
70 |
+
files_to_remove_count = len(sorted_backup_files) - max_backup_count
|
71 |
+
for i in range(files_to_remove_count):
|
72 |
+
file_to_remove = os.path.join(backup_folder, sorted_backup_files[i][0])
|
73 |
+
os.remove(file_to_remove)
|
74 |
+
|
75 |
+
print(f"\033[92mIIB Database file has been successfully backed up to the backup folder.\033[0m")
|
76 |
+
|
77 |
+
def get_sd_webui_conf(**kwargs):
|
78 |
+
try:
|
79 |
+
from modules.shared import opts
|
80 |
+
|
81 |
+
return opts.data
|
82 |
+
except:
|
83 |
+
pass
|
84 |
+
try:
|
85 |
+
sd_conf_path = kwargs.get("sd_webui_config")
|
86 |
+
with codecs.open(sd_conf_path, "r", "utf-8") as f:
|
87 |
+
obj = json.loads(f.read())
|
88 |
+
if kwargs.get("sd_webui_path_relative_to_config"):
|
89 |
+
for dir in sd_img_dirs:
|
90 |
+
if obj[dir] and not os.path.isabs(obj[dir]):
|
91 |
+
obj[dir] = os.path.normpath(
|
92 |
+
os.path.join(sd_conf_path, "../", obj[dir])
|
93 |
+
)
|
94 |
+
return obj
|
95 |
+
except:
|
96 |
+
pass
|
97 |
+
return {}
|
98 |
+
|
99 |
+
def normalize_paths(paths: List[str], base = cwd):
|
100 |
+
"""
|
101 |
+
Normalize a list of paths, ensuring that each path is an absolute path with no redundant components.
|
102 |
+
|
103 |
+
Args:
|
104 |
+
paths (List[str]): A list of paths to be normalized.
|
105 |
+
|
106 |
+
Returns:
|
107 |
+
List[str]: A list of normalized paths.
|
108 |
+
"""
|
109 |
+
res: List[str] = []
|
110 |
+
for path in paths:
|
111 |
+
# Skip empty or blank paths
|
112 |
+
if not path or len(path.strip()) == 0:
|
113 |
+
continue
|
114 |
+
# If the path is already an absolute path, use it as is
|
115 |
+
if os.path.isabs(path):
|
116 |
+
abs_path = path
|
117 |
+
# Otherwise, make the path absolute by joining it with the current working directory
|
118 |
+
else:
|
119 |
+
abs_path = os.path.join(base, path)
|
120 |
+
# If the absolute path exists, add it to the result after normalizing it
|
121 |
+
if os.path.exists(abs_path):
|
122 |
+
res.append(os.path.normpath(abs_path))
|
123 |
+
return res
|
124 |
+
|
125 |
+
def to_abs_path(path):
|
126 |
+
if not os.path.isabs(path):
|
127 |
+
path = os.path.join(os.getcwd(), path)
|
128 |
+
return os.path.normpath(path)
|
129 |
+
|
130 |
+
|
131 |
+
def get_valid_img_dirs(
|
132 |
+
conf,
|
133 |
+
keys=sd_img_dirs,
|
134 |
+
):
|
135 |
+
# 获取配置项
|
136 |
+
paths = [conf.get(key) for key in keys]
|
137 |
+
|
138 |
+
# 判断路径是否有效并转为绝对路径
|
139 |
+
abs_paths = []
|
140 |
+
for path in paths:
|
141 |
+
if not path or len(path.strip()) == 0:
|
142 |
+
continue
|
143 |
+
if os.path.isabs(path): # 已经是绝对路径
|
144 |
+
abs_path = path
|
145 |
+
else: # 转为绝对路径
|
146 |
+
abs_path = os.path.join(os.getcwd(), path)
|
147 |
+
if os.path.exists(abs_path): # 判断路径是否存在
|
148 |
+
abs_paths.append(os.path.normpath(abs_path))
|
149 |
+
|
150 |
+
return abs_paths
|
151 |
+
|
152 |
+
|
153 |
+
def human_readable_size(size_bytes):
|
154 |
+
"""
|
155 |
+
Converts bytes to a human-readable format.
|
156 |
+
"""
|
157 |
+
# define the size units
|
158 |
+
units = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
|
159 |
+
# calculate the logarithm of the input value with base 1024
|
160 |
+
size = int(size_bytes)
|
161 |
+
if size == 0:
|
162 |
+
return "0B"
|
163 |
+
i = 0
|
164 |
+
while size >= 1024 and i < len(units) - 1:
|
165 |
+
size /= 1024
|
166 |
+
i += 1
|
167 |
+
# round the result to two decimal points and return as a string
|
168 |
+
return "{:.2f} {}".format(size, units[i])
|
169 |
+
|
170 |
+
|
171 |
+
def get_windows_drives():
|
172 |
+
drives = []
|
173 |
+
bitmask = ctypes.windll.kernel32.GetLogicalDrives()
|
174 |
+
for letter in range(65, 91):
|
175 |
+
if bitmask & 1:
|
176 |
+
drive_name = chr(letter) + ":/"
|
177 |
+
drives.append(drive_name)
|
178 |
+
bitmask >>= 1
|
179 |
+
return drives
|
180 |
+
|
181 |
+
|
182 |
+
pattern = re.compile(r"(\d+\.?\d*)([KMGT]?B)", re.IGNORECASE)
|
183 |
+
|
184 |
+
|
185 |
+
def convert_to_bytes(file_size_str):
|
186 |
+
match = re.match(pattern, file_size_str)
|
187 |
+
if match:
|
188 |
+
size_str, unit_str = match.groups()
|
189 |
+
size = float(size_str)
|
190 |
+
unit = unit_str.upper()
|
191 |
+
if unit == "KB":
|
192 |
+
size *= 1024
|
193 |
+
elif unit == "MB":
|
194 |
+
size *= 1024**2
|
195 |
+
elif unit == "GB":
|
196 |
+
size *= 1024**3
|
197 |
+
elif unit == "TB":
|
198 |
+
size *= 1024**4
|
199 |
+
return int(size)
|
200 |
+
else:
|
201 |
+
raise ValueError(f"Invalid file size string '{file_size_str}'")
|
202 |
+
|
203 |
+
def get_video_type(file_path):
|
204 |
+
video_extensions = ['.mp4', '.m4v', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.ts']
|
205 |
+
file_extension = file_path[file_path.rfind('.'):].lower()
|
206 |
+
|
207 |
+
if file_extension in video_extensions:
|
208 |
+
return file_extension[1:]
|
209 |
+
else:
|
210 |
+
return None
|
211 |
+
|
212 |
+
def is_image_file(filename: str) -> bool:
|
213 |
+
if not isinstance(filename, str):
|
214 |
+
return False
|
215 |
+
|
216 |
+
extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.avif', '.jpe']
|
217 |
+
extension = filename.split('.')[-1].lower()
|
218 |
+
return f".{extension}" in extensions
|
219 |
+
|
220 |
+
def is_video_file(filename: str) -> bool:
|
221 |
+
return isinstance(get_video_type(filename), str)
|
222 |
+
|
223 |
+
def is_valid_media_path(path):
|
224 |
+
"""
|
225 |
+
判断给定的路径是否是图像文件
|
226 |
+
"""
|
227 |
+
abs_path = os.path.abspath(path) # 转为绝对路径
|
228 |
+
if not os.path.exists(abs_path): # 判断路径是否存在
|
229 |
+
return False
|
230 |
+
if not os.path.isfile(abs_path): # 判断是否是文件
|
231 |
+
return False
|
232 |
+
return is_image_file(abs_path) or is_video_file(abs_path)
|
233 |
+
|
234 |
+
def is_media_file(file_path):
|
235 |
+
return is_image_file(file_path) or is_video_file(file_path)
|
236 |
+
|
237 |
+
def create_zip_file(file_paths: List[str], zip_file_name: str, compress = False):
|
238 |
+
"""
|
239 |
+
将文件打包成一个压缩包
|
240 |
+
|
241 |
+
Args:
|
242 |
+
file_paths: 文件路径的列表
|
243 |
+
zip_file_name: 压缩包的文件名
|
244 |
+
|
245 |
+
Returns:
|
246 |
+
无返回值
|
247 |
+
"""
|
248 |
+
with zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED) as zip_file:
|
249 |
+
for file_path in file_paths:
|
250 |
+
if os.path.isfile(file_path):
|
251 |
+
zip_file.write(file_path, os.path.basename(file_path))
|
252 |
+
elif os.path.isdir(file_path):
|
253 |
+
for root, _, files in os.walk(file_path):
|
254 |
+
for file in files:
|
255 |
+
full_path = os.path.join(root, file)
|
256 |
+
zip_file.write(full_path, os.path.relpath(full_path, file_path))
|
257 |
+
|
258 |
+
def get_temp_path():
|
259 |
+
"""获取跨平台的临时文件目录路径"""
|
260 |
+
temp_path = None
|
261 |
+
try:
|
262 |
+
# 尝试获取系统环境变量中的临时文件目录路径
|
263 |
+
temp_path = (
|
264 |
+
os.environ.get("TMPDIR") or os.environ.get("TMP") or os.environ.get("TEMP")
|
265 |
+
)
|
266 |
+
except Exception as e:
|
267 |
+
print("获取系统环境变量临时文件目录路径失败,错误信息:", e)
|
268 |
+
|
269 |
+
# 如果系统环境变量中没有设置临时文件目录路径,则使用 Python 的 tempfile 模块创建临时文件目录
|
270 |
+
if not temp_path:
|
271 |
+
try:
|
272 |
+
temp_path = tempfile.gettempdir()
|
273 |
+
except Exception as e:
|
274 |
+
print("使用 Python 的 tempfile 模块创建临时文件目录失败,错误信息:", e)
|
275 |
+
|
276 |
+
# 确保临时文件目录存在
|
277 |
+
if not os.path.exists(temp_path):
|
278 |
+
try:
|
279 |
+
os.makedirs(temp_path)
|
280 |
+
except Exception as e:
|
281 |
+
print("创建临时文件目录失败,错误信息:", e)
|
282 |
+
|
283 |
+
return temp_path
|
284 |
+
|
285 |
+
|
286 |
+
_temp_path = get_temp_path()
|
287 |
+
|
288 |
+
|
289 |
+
def get_cache_dir():
|
290 |
+
return os.getenv("IIB_CACHE_DIR") or _temp_path
|
291 |
+
|
292 |
+
def get_secret_key_required():
|
293 |
+
try:
|
294 |
+
from modules.shared import cmd_opts
|
295 |
+
return bool(cmd_opts.gradio_auth)
|
296 |
+
except:
|
297 |
+
return False
|
298 |
+
|
299 |
+
is_secret_key_required = get_secret_key_required()
|
300 |
+
|
301 |
+
def get_enable_access_control():
|
302 |
+
ctrl = os.getenv("IIB_ACCESS_CONTROL")
|
303 |
+
if ctrl == "enable":
|
304 |
+
return True
|
305 |
+
if ctrl == "disable":
|
306 |
+
return False
|
307 |
+
try:
|
308 |
+
from modules.shared import cmd_opts
|
309 |
+
|
310 |
+
return (
|
311 |
+
cmd_opts.share or cmd_opts.ngrok or cmd_opts.listen or cmd_opts.server_name
|
312 |
+
)
|
313 |
+
except:
|
314 |
+
pass
|
315 |
+
return False
|
316 |
+
|
317 |
+
|
318 |
+
enable_access_control = get_enable_access_control()
|
319 |
+
|
320 |
+
|
321 |
+
def get_locale():
|
322 |
+
import locale
|
323 |
+
|
324 |
+
env_lang = os.getenv("IIB_SERVER_LANG")
|
325 |
+
if env_lang in ["zh", "en"]:
|
326 |
+
return env_lang
|
327 |
+
lang, _ = locale.getdefaultlocale()
|
328 |
+
return "zh" if lang and lang.startswith("zh") else "en"
|
329 |
+
|
330 |
+
|
331 |
+
locale = get_locale()
|
332 |
+
|
333 |
+
|
334 |
+
def get_formatted_date(timestamp: float) -> str:
|
335 |
+
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
|
336 |
+
|
337 |
+
|
338 |
+
def get_modified_date(folder_path: str):
|
339 |
+
return get_formatted_date(os.path.getmtime(folder_path))
|
340 |
+
|
341 |
+
|
342 |
+
def get_created_date(folder_path: str):
|
343 |
+
return get_formatted_date(os.path.getctime(folder_path))
|
344 |
+
|
345 |
+
is_st_birthtime_available = True
|
346 |
+
|
347 |
+
def get_created_date_by_stat(stat: os.stat_result):
|
348 |
+
global is_st_birthtime_available
|
349 |
+
try:
|
350 |
+
if is_st_birthtime_available:
|
351 |
+
return get_formatted_date(stat.st_birthtime)
|
352 |
+
else:
|
353 |
+
return get_formatted_date(stat.st_ctime)
|
354 |
+
except Exception as e:
|
355 |
+
is_st_birthtime_available = False
|
356 |
+
return get_formatted_date(stat.st_ctime)
|
357 |
+
|
358 |
+
def birthtime_sort_key_fn(x):
|
359 |
+
stat = x.stat()
|
360 |
+
global is_st_birthtime_available
|
361 |
+
try:
|
362 |
+
if is_st_birthtime_available and hasattr(stat, "st_birthtime"):
|
363 |
+
return stat.st_birthtime
|
364 |
+
else:
|
365 |
+
return stat.st_ctime
|
366 |
+
except:
|
367 |
+
is_st_birthtime_available = False
|
368 |
+
return stat.st_ctime
|
369 |
+
|
370 |
+
def unique_by(seq, key_func=lambda x: x):
|
371 |
+
seen = set()
|
372 |
+
return [x for x in seq if not (key := key_func(x)) in seen and not seen.add(key)]
|
373 |
+
|
374 |
+
|
375 |
+
def find(lst, comparator):
|
376 |
+
return next((item for item in lst if comparator(item)), None)
|
377 |
+
|
378 |
+
|
379 |
+
def findIndex(lst, comparator):
|
380 |
+
return next((i for i, item in enumerate(lst) if comparator(item)), -1)
|
381 |
+
|
382 |
+
def unquote(text):
|
383 |
+
if len(text) == 0 or text[0] != '"' or text[-1] != '"':
|
384 |
+
return text
|
385 |
+
|
386 |
+
try:
|
387 |
+
return json.loads(text)
|
388 |
+
except Exception:
|
389 |
+
return text
|
390 |
+
|
391 |
+
def get_img_geninfo_txt_path(path: str):
|
392 |
+
txt_path = re.sub(r"\.\w+$", ".txt", path)
|
393 |
+
if os.path.exists(txt_path):
|
394 |
+
return txt_path
|
395 |
+
|
396 |
+
def is_img_created_by_comfyui(img: Image):
|
397 |
+
prompt = img.info.get('prompt')
|
398 |
+
return prompt and (img.info.get('workflow') or ("class_type" in prompt)) # ermanitu
|
399 |
+
|
400 |
+
def is_img_created_by_comfyui_with_webui_gen_info(img: Image):
|
401 |
+
return is_img_created_by_comfyui(img) and img.info.get('parameters')
|
402 |
+
|
403 |
+
def get_comfyui_exif_data(img: Image):
|
404 |
+
prompt = img.info.get('prompt')
|
405 |
+
if not prompt:
|
406 |
+
return {}
|
407 |
+
meta_key = '3'
|
408 |
+
data: Dict[str, any] = json.loads(prompt)
|
409 |
+
for i in data.keys():
|
410 |
+
try:
|
411 |
+
if data[i]["class_type"].startswith("KSampler"):
|
412 |
+
meta_key = i
|
413 |
+
break
|
414 |
+
except:
|
415 |
+
pass
|
416 |
+
meta = {}
|
417 |
+
KSampler_entry = data[meta_key]["inputs"]
|
418 |
+
#print(KSampler_entry) # for testing
|
419 |
+
|
420 |
+
# As a workaround to bypass parsing errors in the parser.
|
421 |
+
# https://github.com/jiw0220/stable-diffusion-image-metadata/blob/00b8d42d4d1a536862bba0b07c332bdebb2a0ce5/src/index.ts#L130
|
422 |
+
meta["Steps"] = KSampler_entry.get("steps", "Unknown")
|
423 |
+
meta["Sampler"] = KSampler_entry["sampler_name"]
|
424 |
+
meta["Model"] = data[KSampler_entry["model"][0]]["inputs"].get("ckpt_name")
|
425 |
+
meta["Source Identifier"] = "ComfyUI"
|
426 |
+
def get_text_from_clip(idx: str) :
|
427 |
+
inputs = data[idx]["inputs"]
|
428 |
+
text = inputs["text"] if "text" in inputs else inputs["t5xxl"]
|
429 |
+
if isinstance(text, list): # type:CLIPTextEncode (NSP) mode:Wildcards
|
430 |
+
text = data[text[0]]["inputs"]["text"]
|
431 |
+
return text.strip()
|
432 |
+
|
433 |
+
in_node = data[str(KSampler_entry["positive"][0])]
|
434 |
+
if in_node["class_type"] != "FluxGuidance":
|
435 |
+
pos_prompt = get_text_from_clip(KSampler_entry["positive"][0])
|
436 |
+
else:
|
437 |
+
pos_prompt = get_text_from_clip(in_node["inputs"]["conditioning"][0])
|
438 |
+
|
439 |
+
neg_prompt = get_text_from_clip(KSampler_entry["negative"][0])
|
440 |
+
pos_prompt_arr = unique_by(parse_prompt(pos_prompt)["pos_prompt"])
|
441 |
+
return {
|
442 |
+
"meta": meta,
|
443 |
+
"pos_prompt": pos_prompt_arr,
|
444 |
+
"pos_prompt_raw": pos_prompt,
|
445 |
+
"neg_prompt_raw" : neg_prompt
|
446 |
+
}
|
447 |
+
|
448 |
+
def comfyui_exif_data_to_str(data):
|
449 |
+
res = data["pos_prompt_raw"] + "\nNegative prompt: " + data["neg_prompt_raw"] + "\n"
|
450 |
+
meta_arr = []
|
451 |
+
for k,v in data["meta"].items():
|
452 |
+
meta_arr.append(f'{k}: {v}')
|
453 |
+
return res + ", ".join(meta_arr)
|
454 |
+
|
455 |
+
def read_sd_webui_gen_info_from_image(image: Image, path="") -> str:
|
456 |
+
"""
|
457 |
+
Reads metadata from an image file.
|
458 |
+
|
459 |
+
Args:
|
460 |
+
image (PIL.Image.Image): The image object to read metadata from.
|
461 |
+
path (str): Optional. The path to the image file. Used to look for a .txt file with additional metadata.
|
462 |
+
|
463 |
+
Returns:
|
464 |
+
str: The metadata as a string.
|
465 |
+
"""
|
466 |
+
items = image.info or {}
|
467 |
+
geninfo = items.pop("parameters", None)
|
468 |
+
if "exif" in items:
|
469 |
+
exif = piexif.load(items["exif"])
|
470 |
+
exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b"")
|
471 |
+
|
472 |
+
try:
|
473 |
+
exif_comment = piexif.helper.UserComment.load(exif_comment)
|
474 |
+
except ValueError:
|
475 |
+
exif_comment = exif_comment.decode("utf8", errors="ignore")
|
476 |
+
|
477 |
+
if exif_comment:
|
478 |
+
items["exif comment"] = exif_comment
|
479 |
+
geninfo = exif_comment
|
480 |
+
|
481 |
+
if not geninfo and path:
|
482 |
+
try:
|
483 |
+
txt_path = get_img_geninfo_txt_path(path)
|
484 |
+
if txt_path:
|
485 |
+
with open(txt_path) as f:
|
486 |
+
geninfo = f.read()
|
487 |
+
except Exception as e:
|
488 |
+
pass
|
489 |
+
|
490 |
+
return geninfo
|
491 |
+
|
492 |
+
|
493 |
+
re_param_code = r'\s*([\w ]+):\s*("(?:\\"[^,]|\\"|\\|[^\"])+"|[^,]*)(?:,|$)'
|
494 |
+
re_param = re.compile(re_param_code)
|
495 |
+
re_imagesize = re.compile(r"^(\d+)x(\d+)$")
|
496 |
+
re_lora_prompt = re.compile("<lora:([\w_\s.]+)(?::([\d.]+))+>", re.IGNORECASE)
|
497 |
+
re_lora_extract = re.compile(r"([\w_\s.]+)(?:\d+)?")
|
498 |
+
re_lyco_prompt = re.compile("<lyco:([\w_\s.]+):([\d.]+)>", re.IGNORECASE)
|
499 |
+
re_parens = re.compile(r"[\\/\[\](){}]+")
|
500 |
+
re_lora_white_symbol= re.compile(r">\s+")
|
501 |
+
|
502 |
+
|
503 |
+
def lora_extract(lora: str):
|
504 |
+
"""
|
505 |
+
提取yoshino yoshino(2a79aa5adc4a)
|
506 |
+
"""
|
507 |
+
res = re_lora_extract.match(lora)
|
508 |
+
return res.group(1) if res else lora
|
509 |
+
|
510 |
+
|
511 |
+
def parse_prompt(x: str):
|
512 |
+
x = re.sub(r'\sBREAK\s', ' , BREAK , ', x)
|
513 |
+
x = re.sub(re_lora_white_symbol, "> , ", x)
|
514 |
+
x = x.replace(",", ",").replace("-", " ").replace("_", " ")
|
515 |
+
x = re.sub(re_parens, "", x)
|
516 |
+
tag_list = [x.strip() for x in x.split(",")]
|
517 |
+
res = []
|
518 |
+
lora_list = []
|
519 |
+
lyco_list = []
|
520 |
+
for tag in tag_list:
|
521 |
+
if len(tag) == 0:
|
522 |
+
continue
|
523 |
+
idx_colon = tag.find(":")
|
524 |
+
if idx_colon != -1:
|
525 |
+
if re.search(re_lora_prompt, tag):
|
526 |
+
lora_res = re.search(re_lora_prompt, tag)
|
527 |
+
lora_list.append(
|
528 |
+
{"name": lora_res.group(1), "value": float(lora_res.group(2))}
|
529 |
+
)
|
530 |
+
elif re.search(re_lyco_prompt, tag):
|
531 |
+
lyco_res = re.search(re_lyco_prompt, tag)
|
532 |
+
lyco_list.append(
|
533 |
+
{"name": lyco_res.group(1), "value": float(lyco_res.group(2))}
|
534 |
+
)
|
535 |
+
else:
|
536 |
+
tag = tag[0:idx_colon]
|
537 |
+
if len(tag):
|
538 |
+
res.append(tag.lower())
|
539 |
+
else:
|
540 |
+
res.append(tag.lower())
|
541 |
+
return {"pos_prompt": res, "lora": lora_list, "lyco": lyco_list}
|
542 |
+
|
543 |
+
|
544 |
+
def parse_generation_parameters(x: str):
|
545 |
+
res = {}
|
546 |
+
prompt = ""
|
547 |
+
negative_prompt = ""
|
548 |
+
done_with_prompt = False
|
549 |
+
if not x:
|
550 |
+
return {"meta": {}, "pos_prompt": [], "lora": [], "lyco": []}
|
551 |
+
|
552 |
+
*lines, lastline = x.strip().split("\n")
|
553 |
+
if len(re_param.findall(lastline)) < 3:
|
554 |
+
lines.append(lastline)
|
555 |
+
lastline = ""
|
556 |
+
if len(lines) == 1 and lines[0].startswith("Postprocess"): # 把上面改成<2应该也可以,当时不敢动
|
557 |
+
lastline = lines[
|
558 |
+
0
|
559 |
+
] # 把Postprocess upscale by: 4, Postprocess upscaler: R-ESRGAN 4x+ Anime6B 推到res解析
|
560 |
+
lines = []
|
561 |
+
for i, line in enumerate(lines):
|
562 |
+
line = line.strip()
|
563 |
+
if line.startswith("Negative prompt:"):
|
564 |
+
done_with_prompt = True
|
565 |
+
line = line[16:].strip()
|
566 |
+
|
567 |
+
if done_with_prompt:
|
568 |
+
negative_prompt += ("" if negative_prompt == "" else "\n") + line
|
569 |
+
else:
|
570 |
+
prompt += ("" if prompt == "" else "\n") + line
|
571 |
+
|
572 |
+
for k, v in re_param.findall(lastline):
|
573 |
+
try:
|
574 |
+
if len(v) == 0:
|
575 |
+
res[k] = v
|
576 |
+
continue
|
577 |
+
if v[0] == '"' and v[-1] == '"':
|
578 |
+
v = unquote(v)
|
579 |
+
|
580 |
+
m = re_imagesize.match(v)
|
581 |
+
if m is not None:
|
582 |
+
res[f"{k}-1"] = m.group(1)
|
583 |
+
res[f"{k}-2"] = m.group(2)
|
584 |
+
else:
|
585 |
+
res[k] = v
|
586 |
+
except Exception:
|
587 |
+
print(f"Error parsing \"{k}: {v}\"")
|
588 |
+
|
589 |
+
prompt_parse_res = parse_prompt(prompt)
|
590 |
+
lora = prompt_parse_res["lora"]
|
591 |
+
for k in res:
|
592 |
+
k_s = str(k)
|
593 |
+
if k_s.startswith("AddNet Module") and str(res[k]).lower() == "lora":
|
594 |
+
model = res[k_s.replace("Module", "Model")]
|
595 |
+
value = res.get(k_s.replace("Module", "Weight A"), "1")
|
596 |
+
lora.append({"name": lora_extract(model), "value": float(value)})
|
597 |
+
return {
|
598 |
+
"meta": res,
|
599 |
+
"pos_prompt": unique_by(prompt_parse_res["pos_prompt"]),
|
600 |
+
"lora": unique_by(lora, lambda x: x["name"].lower()),
|
601 |
+
"lyco": unique_by(prompt_parse_res["lyco"], lambda x: x["name"].lower()),
|
602 |
+
}
|
603 |
+
|
604 |
+
|
605 |
+
tags_translate: Dict[str, str] = {}
|
606 |
+
try:
|
607 |
+
import codecs
|
608 |
+
|
609 |
+
with codecs.open(os.path.join(cwd, "tags-translate.csv"), "r", "utf-8") as tag:
|
610 |
+
tags_translate_str = tag.read()
|
611 |
+
for line in tags_translate_str.splitlines():
|
612 |
+
en, mapping = line.split(",")
|
613 |
+
tags_translate[en.strip()] = mapping.strip()
|
614 |
+
except Exception as e:
|
615 |
+
pass
|
616 |
+
|
617 |
+
|
618 |
+
def open_folder(folder_path, file_path=None):
|
619 |
+
folder = os.path.realpath(folder_path)
|
620 |
+
if file_path:
|
621 |
+
file = os.path.join(folder, file_path)
|
622 |
+
if os.name == "nt":
|
623 |
+
subprocess.run(["explorer", "/select,", file])
|
624 |
+
elif sys.platform == "darwin":
|
625 |
+
subprocess.run(["open", "-R", file])
|
626 |
+
elif os.name == "posix":
|
627 |
+
subprocess.run(["xdg-open", file])
|
628 |
+
else:
|
629 |
+
if os.name == "nt":
|
630 |
+
subprocess.run(["explorer", folder])
|
631 |
+
elif sys.platform == "darwin":
|
632 |
+
subprocess.run(["open", folder])
|
633 |
+
elif os.name == "posix":
|
634 |
+
subprocess.run(["xdg-open", folder])
|
635 |
+
|
636 |
+
|
637 |
+
def open_file_with_default_app(file_path):
|
638 |
+
system = platform.system()
|
639 |
+
if system == 'Darwin': # macOS
|
640 |
+
subprocess.call(['open', file_path])
|
641 |
+
elif system == 'Windows': # Windows
|
642 |
+
subprocess.call(file_path, shell=True)
|
643 |
+
elif system == 'Linux': # Linux
|
644 |
+
subprocess.call(['xdg-open', file_path])
|
645 |
+
else:
|
646 |
+
raise OSError(f'Unsupported operating system: {system}')
|
647 |
+
|
648 |
+
def omit(d, keys):
|
649 |
+
return {k: v for k, v in d.items() if k not in keys}
|
650 |
+
|
651 |
+
|
652 |
+
def get_current_commit_hash():
|
653 |
+
try:
|
654 |
+
result = subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, cwd=cwd)
|
655 |
+
if result.returncode == 0:
|
656 |
+
return result.stdout.strip()
|
657 |
+
else:
|
658 |
+
return None
|
659 |
+
except Exception:
|
660 |
+
return None
|
661 |
+
|
662 |
+
def get_current_tag():
|
663 |
+
try:
|
664 |
+
result = subprocess.run(['git', 'describe', '--tags', '--abbrev=0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, cwd=cwd)
|
665 |
+
if result.returncode == 0:
|
666 |
+
return result.stdout.strip()
|
667 |
+
else:
|
668 |
+
return None
|
669 |
+
except Exception:
|
670 |
+
return None
|
671 |
+
|
672 |
+
|
673 |
+
def replace_punctuation(input_string):
|
674 |
+
return input_string.replace(',', ' ').replace('\n', ' ')
|
675 |
+
|
676 |
+
|
677 |
+
def case_insensitive_get(d, key, default=None):
|
678 |
+
for k, v in d.items():
|
679 |
+
if k.lower() == key.lower():
|
680 |
+
return v
|
681 |
+
return default
|
682 |
+
|
683 |
+
def build_sd_webui_style_img_gen_info(prompt, negative_prompt = 'None', meta = {}):
|
684 |
+
res = f"{prompt}\nNegative prompt: {negative_prompt}\n"
|
685 |
+
for k, v in meta.items():
|
686 |
+
res += f"{k}: {v}, "
|
687 |
+
return res
|
688 |
+
|
689 |
+
def map_dict_keys(value_dict, map_dict=None):
|
690 |
+
if map_dict is None:
|
691 |
+
return value_dict
|
692 |
+
else:
|
693 |
+
return {map_dict.get(key, key): value for key, value in value_dict.items()}
|
694 |
+
|
695 |
+
|
696 |
+
def get_file_info_by_path(fullpath: str, is_under_scanned_path = True):
|
697 |
+
stat = os.stat(fullpath)
|
698 |
+
date = get_formatted_date(stat.st_mtime)
|
699 |
+
name = os.path.basename(fullpath)
|
700 |
+
created_time = get_created_date_by_stat(stat)
|
701 |
+
if os.path.isfile(fullpath):
|
702 |
+
bytes = stat.st_size
|
703 |
+
size = human_readable_size(bytes)
|
704 |
+
return {
|
705 |
+
"type": "file",
|
706 |
+
"date": date,
|
707 |
+
"size": size,
|
708 |
+
"name": name,
|
709 |
+
"bytes": bytes,
|
710 |
+
"created_time": created_time,
|
711 |
+
"fullpath": fullpath,
|
712 |
+
"is_under_scanned_path": is_under_scanned_path,
|
713 |
+
}
|
714 |
+
|
715 |
+
elif os.path.isdir(fullpath):
|
716 |
+
return {
|
717 |
+
"type": "dir",
|
718 |
+
"date": date,
|
719 |
+
"created_time": created_time,
|
720 |
+
"size": "-",
|
721 |
+
"name": name,
|
722 |
+
"is_under_scanned_path": is_under_scanned_path,
|
723 |
+
"fullpath": fullpath,
|
724 |
+
}
|
725 |
+
return {}
|
726 |
+
|
727 |
+
|
728 |
+
def get_frame_at_second(video_path, second):
|
729 |
+
import av
|
730 |
+
with av.open(video_path) as container:
|
731 |
+
time_base = container.streams.video[0].time_base
|
732 |
+
frame_container_pts = round( second / time_base)
|
733 |
+
|
734 |
+
container.seek(frame_container_pts, backward=True, stream=container.streams.video[0])
|
735 |
+
frame = next(container.decode(video=0))
|
736 |
+
return frame
|
737 |
+
|
738 |
+
def get_data_file_path(filename):
|
739 |
+
if hasattr(sys, '_MEIPASS'):
|
740 |
+
# Running in a PyInstaller bundle
|
741 |
+
base_path = os.path.join(sys._MEIPASS)
|
742 |
+
else:
|
743 |
+
# Running in a normal Python environment
|
744 |
+
base_path = os.path.join(os.path.dirname(__file__))
|
745 |
+
|
746 |
+
return os.path.normpath(os.path.join(base_path, "../../", filename))
|
extensions/sd-webui-infinite-image-browsing/scripts/iib/video_cover_gen.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import hashlib
|
2 |
+
import os
|
3 |
+
from typing import List
|
4 |
+
from scripts.iib.tool import get_formatted_date, get_cache_dir, is_video_file
|
5 |
+
from concurrent.futures import ThreadPoolExecutor
|
6 |
+
import time
|
7 |
+
|
8 |
+
|
9 |
+
def generate_video_covers(dirs,verbose=False):
|
10 |
+
start_time = time.time()
|
11 |
+
import imageio.v3 as iio
|
12 |
+
|
13 |
+
cache_base_dir = get_cache_dir()
|
14 |
+
|
15 |
+
def process_video(item):
|
16 |
+
if item.is_dir():
|
17 |
+
verbose and print(f"Processing directory: {item.path}")
|
18 |
+
for sub_item in os.scandir(item.path):
|
19 |
+
process_video(sub_item)
|
20 |
+
return
|
21 |
+
if not os.path.exists(item.path) or not is_video_file(item.path):
|
22 |
+
return
|
23 |
+
|
24 |
+
try:
|
25 |
+
path = os.path.normpath(item.path)
|
26 |
+
stat = item.stat()
|
27 |
+
t = get_formatted_date(stat.st_mtime)
|
28 |
+
hash_dir = hashlib.md5((path + t).encode("utf-8")).hexdigest()
|
29 |
+
cache_dir = os.path.join(cache_base_dir, "iib_cache", "video_cover", hash_dir)
|
30 |
+
cache_path = os.path.join(cache_dir, "cover.webp")
|
31 |
+
|
32 |
+
# 如果缓存文件存在,则直接返回该文件
|
33 |
+
if os.path.exists(cache_path):
|
34 |
+
print(f"Video cover already exists: {path}")
|
35 |
+
return
|
36 |
+
|
37 |
+
frame = iio.imread(
|
38 |
+
path,
|
39 |
+
index=16,
|
40 |
+
plugin="pyav",
|
41 |
+
)
|
42 |
+
|
43 |
+
os.makedirs(cache_dir, exist_ok=True)
|
44 |
+
iio.imwrite(cache_path, frame, extension=".webp")
|
45 |
+
verbose and print(f"Video cover generated: {path}")
|
46 |
+
except Exception as e:
|
47 |
+
print(f"Error generating video cover: {path}")
|
48 |
+
print(e)
|
49 |
+
|
50 |
+
with ThreadPoolExecutor() as executor:
|
51 |
+
for dir_path in dirs:
|
52 |
+
folder_listing: List[os.DirEntry] = os.scandir(dir_path)
|
53 |
+
for item in folder_listing:
|
54 |
+
executor.submit(process_video, item)
|
55 |
+
|
56 |
+
print("Video covers generated successfully.")
|
57 |
+
end_time = time.time()
|
58 |
+
execution_time = end_time - start_time
|
59 |
+
print(f"Execution time: {execution_time} seconds")
|
extensions/sd-webui-infinite-image-browsing/scripts/iib_setup.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from scripts.iib.api import infinite_image_browsing_api, send_img_path
|
2 |
+
from modules import script_callbacks, generation_parameters_copypaste as send
|
3 |
+
from scripts.iib.tool import locale
|
4 |
+
from scripts.iib.tool import read_sd_webui_gen_info_from_image
|
5 |
+
from PIL import Image
|
6 |
+
from scripts.iib.logger import logger
|
7 |
+
|
8 |
+
from fastapi import FastAPI
|
9 |
+
import gradio as gr
|
10 |
+
from modules.shared import cmd_opts
|
11 |
+
|
12 |
+
"""
|
13 |
+
api函数声明和启动分离方便另外一边被外部调用
|
14 |
+
"""
|
15 |
+
|
16 |
+
|
17 |
+
def on_ui_tabs():
|
18 |
+
|
19 |
+
with gr.Blocks(analytics_enabled=False) as view:
|
20 |
+
with gr.Row():
|
21 |
+
with gr.Column():
|
22 |
+
gr.HTML("", elem_id="iib_top")
|
23 |
+
gr.HTML("error", elem_id="infinite_image_browsing_container_wrapper")
|
24 |
+
# 以下是使用2个组件模拟粘贴过程
|
25 |
+
img = gr.Image(
|
26 |
+
type="pil",
|
27 |
+
elem_id="iib_hidden_img",
|
28 |
+
)
|
29 |
+
|
30 |
+
def on_img_change():
|
31 |
+
send_img_path["value"] = "" # 真正收到图片改变才允许放行
|
32 |
+
|
33 |
+
img.change(on_img_change)
|
34 |
+
|
35 |
+
img_update_trigger = gr.Button(
|
36 |
+
"button", elem_id="iib_hidden_img_update_trigger"
|
37 |
+
)
|
38 |
+
|
39 |
+
# 修改文本和图像,等待修改完成后前端触发粘贴按钮
|
40 |
+
# 有时在触发后收不到回调,可能是在解析params。txt时除了问题删除掉就行了
|
41 |
+
def img_update_func():
|
42 |
+
try:
|
43 |
+
path = send_img_path.get("value")
|
44 |
+
# logger.info("img_update_func %s", path)
|
45 |
+
img = Image.open(path)
|
46 |
+
info = read_sd_webui_gen_info_from_image(img, path)
|
47 |
+
return img, info
|
48 |
+
except Exception as e:
|
49 |
+
logger.error("img_update_func err %s",e)
|
50 |
+
|
51 |
+
img_file_info = gr.Textbox(elem_id="iib_hidden_img_file_info")
|
52 |
+
img_update_trigger.click(img_update_func, outputs=[img, img_file_info])
|
53 |
+
for tab in ["txt2img", "img2img", "inpaint", "extras"]:
|
54 |
+
btn = gr.Button(f"Send to {tab}", elem_id=f"iib_hidden_tab_{tab}")
|
55 |
+
# 注册粘贴
|
56 |
+
send.register_paste_params_button(
|
57 |
+
send.ParamBinding(
|
58 |
+
paste_button=btn,
|
59 |
+
tabname=tab,
|
60 |
+
source_image_component=img,
|
61 |
+
source_text_component=img_file_info,
|
62 |
+
)
|
63 |
+
)
|
64 |
+
|
65 |
+
return (
|
66 |
+
(
|
67 |
+
view,
|
68 |
+
"无边图像浏览" if locale == "zh" else "Infinite image browsing",
|
69 |
+
"infinite-image-browsing",
|
70 |
+
),
|
71 |
+
)
|
72 |
+
|
73 |
+
def on_app_started(_: gr.Blocks, app: FastAPI) -> None:
|
74 |
+
# 第一个参数是SD-WebUI传进来的gr.Blocks,但是不需要使用
|
75 |
+
DEFAULT_BASE = "/infinite_image_browsing"
|
76 |
+
fe_public_path = None
|
77 |
+
subpath = vars(cmd_opts).get("subpath")
|
78 |
+
|
79 |
+
if subpath:
|
80 |
+
base = "/" + subpath + "/" + DEFAULT_BASE
|
81 |
+
fe_public_path = base.replace('//', '/')
|
82 |
+
infinite_image_browsing_api(app, fe_public_path = fe_public_path)
|
83 |
+
|
84 |
+
|
85 |
+
script_callbacks.on_ui_tabs(on_ui_tabs)
|
86 |
+
script_callbacks.on_app_started(on_app_started)
|
extensions/sd-webui-infinite-image-browsing/style.css
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
[id^="iib_hidden_"] {
|
2 |
+
display: none !important;
|
3 |
+
}
|
extensions/sd-webui-infinite-image-browsing/vue/.eslintrc.cjs
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* eslint-disable no-undef */
|
2 |
+
|
3 |
+
// require('@rushstack/eslint-patch/modern-module-resolution')
|
4 |
+
|
5 |
+
module.exports = {
|
6 |
+
ignorePatterns: [
|
7 |
+
'dist/',
|
8 |
+
// 其他忽略规则
|
9 |
+
],
|
10 |
+
root: true,
|
11 |
+
extends: [
|
12 |
+
'plugin:vue/vue3-essential',
|
13 |
+
'eslint:recommended',
|
14 |
+
'@vue/eslint-config-typescript',
|
15 |
+
],
|
16 |
+
parserOptions: {
|
17 |
+
ecmaVersion: 'latest'
|
18 |
+
},
|
19 |
+
rules: {
|
20 |
+
'vue/multi-word-component-names': ['error', { ignores: ['index', 'index.vue'] }],
|
21 |
+
'no-console': 'off',
|
22 |
+
'quote-props': ['error', 'as-needed'],
|
23 |
+
quotes: ['error', 'single'],
|
24 |
+
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
|
25 |
+
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
26 |
+
'@typescript-eslint/no-non-null-assertion': 'off',
|
27 |
+
'@typescript-eslint/no-explicit-any': 'off',
|
28 |
+
indent: 'off',
|
29 |
+
'@typescript-eslint/indent': ['error', 2]
|
30 |
+
}
|
31 |
+
}
|
extensions/sd-webui-infinite-image-browsing/vue/.gitignore
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Logs
|
2 |
+
logs
|
3 |
+
*.log
|
4 |
+
npm-debug.log*
|
5 |
+
yarn-debug.log*
|
6 |
+
yarn-error.log*
|
7 |
+
pnpm-debug.log*
|
8 |
+
lerna-debug.log*
|
9 |
+
|
10 |
+
node_modules
|
11 |
+
*.local
|
12 |
+
|
13 |
+
# Editor directories and files
|
14 |
+
.vscode/*
|
15 |
+
!.vscode/extensions.json
|
16 |
+
.idea
|
17 |
+
.DS_Store
|
18 |
+
*.suo
|
19 |
+
*.ntvs*
|
20 |
+
*.njsproj
|
21 |
+
*.sln
|
22 |
+
*.sw?
|
extensions/sd-webui-infinite-image-browsing/vue/.prettierrc.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"$schema": "https://json.schemastore.org/prettierrc",
|
3 |
+
"semi": false,
|
4 |
+
"tabWidth": 2,
|
5 |
+
"singleQuote": true,
|
6 |
+
"printWidth": 100,
|
7 |
+
"trailingComma": "none"
|
8 |
+
}
|
extensions/sd-webui-infinite-image-browsing/vue/.vscode/extensions.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"recommendations": ["Vue.volar", "Vue.vscode-typescript-vue-plugin"]
|
3 |
+
}
|
extensions/sd-webui-infinite-image-browsing/vue/README.md
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# vue
|
2 |
+
|
3 |
+
This template should help get you started developing with Vue 3 in Vite.
|
4 |
+
|
5 |
+
## Recommended IDE Setup
|
6 |
+
|
7 |
+
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
|
8 |
+
|
9 |
+
## Type Support for `.vue` Imports in TS
|
10 |
+
|
11 |
+
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin) to make the TypeScript language service aware of `.vue` types.
|
12 |
+
|
13 |
+
If the standalone TypeScript plugin doesn't feel fast enough to you, Volar has also implemented a [Take Over Mode](https://github.com/johnsoncodehk/volar/discussions/471#discussioncomment-1361669) that is more performant. You can enable it by the following steps:
|
14 |
+
|
15 |
+
1. Disable the built-in TypeScript Extension
|
16 |
+
1) Run `Extensions: Show Built-in Extensions` from VSCode's command palette
|
17 |
+
2) Find `TypeScript and JavaScript Language Features`, right click and select `Disable (Workspace)`
|
18 |
+
2. Reload the VSCode window by running `Developer: Reload Window` from the command palette.
|
19 |
+
|
20 |
+
## Customize configuration
|
21 |
+
|
22 |
+
See [Vite Configuration Reference](https://vitejs.dev/config/).
|
23 |
+
|
24 |
+
## Project Setup
|
25 |
+
|
26 |
+
```sh
|
27 |
+
yarn
|
28 |
+
```
|
29 |
+
|
30 |
+
### Compile and Hot-Reload for Development
|
31 |
+
|
32 |
+
```sh
|
33 |
+
yarn dev
|
34 |
+
```
|
35 |
+
|
36 |
+
|
37 |
+
### Compile and Minify for Production, Deliver to Production Mode Resources
|
38 |
+
|
39 |
+
```sh
|
40 |
+
yarn build
|
41 |
+
```
|
42 |
+
|
43 |
+
### Lint with [ESLint](https://eslint.org/)
|
44 |
+
|
45 |
+
```sh
|
46 |
+
yarn lint
|
47 |
+
```
|
extensions/sd-webui-infinite-image-browsing/vue/build.ts
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import { execSync } from 'child_process'
|
2 |
+
import { readFile, rm, writeFile } from 'fs/promises'
|
3 |
+
import { exit } from 'process'
|
4 |
+
|
5 |
+
const main = async () => {
|
6 |
+
try {
|
7 |
+
console.log(execSync('vue-tsc && vite build').toString('utf8'))
|
8 |
+
} catch (error: any) {
|
9 |
+
if (error.stdout && error.stderr) {
|
10 |
+
console.log(error.stdout.toString('utf8'))
|
11 |
+
console.error(error.stderr.toString('utf8'))
|
12 |
+
exit(2)
|
13 |
+
} else {
|
14 |
+
throw error
|
15 |
+
}
|
16 |
+
}
|
17 |
+
try {
|
18 |
+
await rm('../javascript/index.js')
|
19 |
+
// eslint-disable-next-line no-empty
|
20 |
+
} catch (error) {
|
21 |
+
|
22 |
+
}
|
23 |
+
const html = (await readFile('dist/index.html')).toString()
|
24 |
+
const js = (await readFile('index.tpl.js')).toString().replace('__built_html__', html)
|
25 |
+
await writeFile('../javascript/index.js', js)
|
26 |
+
}
|
27 |
+
main()
|
extensions/sd-webui-infinite-image-browsing/vue/components.d.ts
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* eslint-disable */
|
2 |
+
/* prettier-ignore */
|
3 |
+
// @ts-nocheck
|
4 |
+
// Generated by unplugin-vue-components
|
5 |
+
// Read more: https://github.com/vuejs/core/pull/3399
|
6 |
+
import '@vue/runtime-core'
|
7 |
+
|
8 |
+
export {}
|
9 |
+
|
10 |
+
declare module '@vue/runtime-core' {
|
11 |
+
export interface GlobalComponents {
|
12 |
+
AAlert: typeof import('ant-design-vue/es')['Alert']
|
13 |
+
ABadge: typeof import('ant-design-vue/es')['Badge']
|
14 |
+
ABreadcrumb: typeof import('ant-design-vue/es')['Breadcrumb']
|
15 |
+
ABreadcrumbItem: typeof import('ant-design-vue/es')['BreadcrumbItem']
|
16 |
+
AButton: typeof import('ant-design-vue/es')['Button']
|
17 |
+
ACheckbox: typeof import('ant-design-vue/es')['Checkbox']
|
18 |
+
ACol: typeof import('ant-design-vue/es')['Col']
|
19 |
+
ACollapse: typeof import('ant-design-vue/es')['Collapse']
|
20 |
+
ACollapsePanel: typeof import('ant-design-vue/es')['CollapsePanel']
|
21 |
+
ADrawer: typeof import('ant-design-vue/es')['Drawer']
|
22 |
+
ADropdown: typeof import('ant-design-vue/es')['Dropdown']
|
23 |
+
AForm: typeof import('ant-design-vue/es')['Form']
|
24 |
+
AFormItem: typeof import('ant-design-vue/es')['FormItem']
|
25 |
+
AImage: typeof import('ant-design-vue/es')['Image']
|
26 |
+
AInput: typeof import('ant-design-vue/es')['Input']
|
27 |
+
AInputGroup: typeof import('ant-design-vue/es')['InputGroup']
|
28 |
+
AInputNumber: typeof import('ant-design-vue/es')['InputNumber']
|
29 |
+
AMenu: typeof import('ant-design-vue/es')['Menu']
|
30 |
+
AMenuDivider: typeof import('ant-design-vue/es')['MenuDivider']
|
31 |
+
AMenuItem: typeof import('ant-design-vue/es')['MenuItem']
|
32 |
+
AModal: typeof import('ant-design-vue/es')['Modal']
|
33 |
+
ARadioButton: typeof import('ant-design-vue/es')['RadioButton']
|
34 |
+
ARadioGroup: typeof import('ant-design-vue/es')['RadioGroup']
|
35 |
+
ARow: typeof import('ant-design-vue/es')['Row']
|
36 |
+
ASelect: typeof import('ant-design-vue/es')['Select']
|
37 |
+
ASkeleton: typeof import('ant-design-vue/es')['Skeleton']
|
38 |
+
ASlider: typeof import('ant-design-vue/es')['Slider']
|
39 |
+
ASpin: typeof import('ant-design-vue/es')['Spin']
|
40 |
+
ASubMenu: typeof import('ant-design-vue/es')['SubMenu']
|
41 |
+
ASwitch: typeof import('ant-design-vue/es')['Switch']
|
42 |
+
ATabPane: typeof import('ant-design-vue/es')['TabPane']
|
43 |
+
ATabs: typeof import('ant-design-vue/es')['Tabs']
|
44 |
+
ATag: typeof import('ant-design-vue/es')['Tag']
|
45 |
+
ATextarea: typeof import('ant-design-vue/es')['Textarea']
|
46 |
+
ATooltip: typeof import('ant-design-vue/es')['Tooltip']
|
47 |
+
BaseFileListInfo: typeof import('./src/components/BaseFileListInfo.vue')['default']
|
48 |
+
ChangeIndicator: typeof import('./src/components/ChangeIndicator.vue')['default']
|
49 |
+
ContextMenu: typeof import('./src/components/ContextMenu.vue')['default']
|
50 |
+
FileItem: typeof import('./src/components/FileItem.vue')['default']
|
51 |
+
HistoryRecord: typeof import('./src/components/HistoryRecord.vue')['default']
|
52 |
+
MultiSelectKeep: typeof import('./src/components/MultiSelectKeep.vue')['default']
|
53 |
+
NumInput: typeof import('./src/components/numInput.vue')['default']
|
54 |
+
RouterLink: typeof import('vue-router')['RouterLink']
|
55 |
+
RouterView: typeof import('vue-router')['RouterView']
|
56 |
+
}
|
57 |
+
}
|
extensions/sd-webui-infinite-image-browsing/vue/dist/assets/Checkbox-5fa7cbf6.js
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
import{d as E,bx as $,r as f,m as M,_ as T,a as c,al as W,h as m,c as v,P as z}from"./index-5b5fdd56.js";var G=["prefixCls","name","id","type","disabled","readonly","tabindex","autofocus","value","required"],H={prefixCls:String,name:String,id:String,type:String,defaultChecked:{type:[Boolean,Number],default:void 0},checked:{type:[Boolean,Number],default:void 0},disabled:Boolean,tabindex:{type:[Number,String]},readonly:Boolean,autofocus:Boolean,value:z.any,required:Boolean};const L=E({compatConfig:{MODE:3},name:"Checkbox",inheritAttrs:!1,props:$(H,{prefixCls:"rc-checkbox",type:"checkbox",defaultChecked:!1}),emits:["click","change"],setup:function(a,d){var t=d.attrs,h=d.emit,x=d.expose,o=f(a.checked===void 0?a.defaultChecked:a.checked),i=f();M(function(){return a.checked},function(){o.value=a.checked}),x({focus:function(){var e;(e=i.value)===null||e===void 0||e.focus()},blur:function(){var e;(e=i.value)===null||e===void 0||e.blur()}});var l=f(),g=function(e){if(!a.disabled){a.checked===void 0&&(o.value=e.target.checked),e.shiftKey=l.value;var r={target:c(c({},a),{},{checked:e.target.checked}),stopPropagation:function(){e.stopPropagation()},preventDefault:function(){e.preventDefault()},nativeEvent:e};a.checked!==void 0&&(i.value.checked=!!a.checked),h("change",r),l.value=!1}},C=function(e){h("click",e),l.value=e.shiftKey};return function(){var n,e=a.prefixCls,r=a.name,s=a.id,p=a.type,b=a.disabled,K=a.readonly,P=a.tabindex,B=a.autofocus,S=a.value,N=a.required,_=T(a,G),q=t.class,D=t.onFocus,j=t.onBlur,w=t.onKeydown,A=t.onKeypress,F=t.onKeyup,y=c(c({},_),t),O=Object.keys(y).reduce(function(k,u){return(u.substr(0,5)==="aria-"||u.substr(0,5)==="data-"||u==="role")&&(k[u]=y[u]),k},{}),R=W(e,q,(n={},m(n,"".concat(e,"-checked"),o.value),m(n,"".concat(e,"-disabled"),b),n)),V=c(c({name:r,id:s,type:p,readonly:K,disabled:b,tabindex:P,class:"".concat(e,"-input"),checked:!!o.value,autofocus:B,value:S},O),{},{onChange:g,onClick:C,onFocus:D,onBlur:j,onKeydown:w,onKeypress:A,onKeyup:F,required:N});return v("span",{class:R},[v("input",c({ref:i},V),null),v("span",{class:"".concat(e,"-inner")},null)])}}});export{L as V};
|
extensions/sd-webui-infinite-image-browsing/vue/dist/assets/FileItem-b2542180.js
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
var vt=Object.defineProperty;var mt=(i,t,e)=>t in i?vt(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var ee=(i,t,e)=>(mt(i,typeof t!="symbol"?t+"":t,e),e);import{d as X,u as Ye,E as V,al as qe,h as K,c as A,ao as yt,d1 as bt,r as j,bc as At,X as H,c$ as St,P as $e,c5 as kt,A as W,d2 as ce,L as ge,ak as ke,bf as It,cQ as _t,bW as Ct,d3 as wt,cB as Et,d4 as Tt,d5 as Ge,bw as Pt,d6 as ae,d7 as Ot,aF as Nt,d8 as Dt,B as $t,d9 as zt,n as pe,m as se,aP as Mt,q as Ze,$ as Ie,c3 as Xe,aH as Qt,da as et,db as Bt,N as Ft,v as Rt,aN as tt,aO as nt,ax as it,S as a,a0 as R,dc as Lt,dd as jt,de as Ht,b$ as Vt,df as xt,ar as Ut,T as h,aE as te,Y as S,a1 as k,a6 as J,c0 as ze,c1 as Jt,dg as Wt,a5 as rt,ae as Y,V as I,W as y,a2 as Q,aj as st,cW as Kt,cV as Yt,M as ot,U as u,Z as lt,cS as qt,dh as Me,ad as Gt,di as Zt,cT as Xt,cm as en,dj as tn,dk as de,dl as nn}from"./index-5b5fdd56.js";import{h as Qe,g as rn,i as sn}from"./functionalCallableComp-51195a3e.js";import{i as on}from"./_isIterateeCall-c830f443.js";import{D as G,a as ve}from"./index-b6f2a43c.js";/* empty css */var ln=function(){return{prefixCls:String,checked:{type:Boolean,default:void 0},onChange:{type:Function},onClick:{type:Function},"onUpdate:checked":Function}},an=X({compatConfig:{MODE:3},name:"ACheckableTag",props:ln(),setup:function(t,e){var n=e.slots,r=e.emit,o=Ye("tag",t),p=o.prefixCls,d=function(E){var w=t.checked;r("update:checked",!w),r("change",!w),r("click",E)},v=V(function(){var b;return qe(p.value,(b={},K(b,"".concat(p.value,"-checkable"),!0),K(b,"".concat(p.value,"-checkable-checked"),t.checked),b))});return function(){var b;return A("span",{class:v.value,onClick:d},[(b=n.default)===null||b===void 0?void 0:b.call(n)])}}});const me=an;var un=new RegExp("^(".concat(yt.join("|"),")(-inverse)?$")),cn=new RegExp("^(".concat(bt.join("|"),")$")),dn=function(){return{prefixCls:String,color:{type:String},closable:{type:Boolean,default:!1},closeIcon:$e.any,visible:{type:Boolean,default:void 0},onClose:{type:Function},"onUpdate:visible":Function,icon:$e.any}},Z=X({compatConfig:{MODE:3},name:"ATag",props:dn(),slots:["closeIcon","icon"],setup:function(t,e){var n=e.slots,r=e.emit,o=e.attrs,p=Ye("tag",t),d=p.prefixCls,v=p.direction,b=j(!0);At(function(){t.visible!==void 0&&(b.value=t.visible)});var E=function(s){s.stopPropagation(),r("update:visible",!1),r("close",s),!s.defaultPrevented&&t.visible===void 0&&(b.value=!1)},w=V(function(){var l=t.color;return l?un.test(l)||cn.test(l):!1}),T=V(function(){var l;return qe(d.value,(l={},K(l,"".concat(d.value,"-").concat(t.color),w.value),K(l,"".concat(d.value,"-has-color"),t.color&&!w.value),K(l,"".concat(d.value,"-hidden"),!b.value),K(l,"".concat(d.value,"-rtl"),v.value==="rtl"),l))});return function(){var l,s,c,m=t.icon,D=m===void 0?(l=n.icon)===null||l===void 0?void 0:l.call(n):m,O=t.color,$=t.closeIcon,g=$===void 0?(s=n.closeIcon)===null||s===void 0?void 0:s.call(n):$,f=t.closable,C=f===void 0?!1:f,M=function(){return C?g?A("span",{class:"".concat(d.value,"-close-icon"),onClick:E},[g]):A(kt,{class:"".concat(d.value,"-close-icon"),onClick:E},null):null},F={backgroundColor:O&&!w.value?O:void 0},B=D||null,_=(c=n.default)===null||c===void 0?void 0:c.call(n),L=B?A(H,null,[B,A("span",null,[_])]):_,P="onClick"in o,z=A("span",{class:T.value,style:F},[L,M()]);return P?A(St,null,{default:function(){return[z]}}):z}}});Z.CheckableTag=me;Z.install=function(i){return i.component(Z.name,Z),i.component(me.name,me),i};const fn=Z;G.Button=ve;G.install=function(i){return i.component(G.name,G),i.component(ve.name,ve),i};var hn={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M908.1 353.1l-253.9-36.9L540.7 86.1c-3.1-6.3-8.2-11.4-14.5-14.5-15.8-7.8-35-1.3-42.9 14.5L369.8 316.2l-253.9 36.9c-7 1-13.4 4.3-18.3 9.3a32.05 32.05 0 00.6 45.3l183.7 179.1-43.4 252.9a31.95 31.95 0 0046.4 33.7L512 754l227.1 119.4c6.2 3.3 13.4 4.4 20.3 3.2 17.4-3 29.1-19.5 26.1-36.9l-43.4-252.9 183.7-179.1c5-4.9 8.3-11.3 9.3-18.3 2.7-17.5-9.5-33.7-27-36.3z"}}]},name:"star",theme:"filled"};const gn=hn;function Be(i){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?Object(arguments[t]):{},n=Object.keys(e);typeof Object.getOwnPropertySymbols=="function"&&(n=n.concat(Object.getOwnPropertySymbols(e).filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),n.forEach(function(r){pn(i,r,e[r])})}return i}function pn(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}var _e=function(t,e){var n=Be({},t,e.attrs);return A(W,Be({},n,{icon:gn}),null)};_e.displayName="StarFilled";_e.inheritAttrs=!1;const at=_e;var vn={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM790.2 326H602V137.8L790.2 326zm1.8 562H232V136h302v216a42 42 0 0042 42h216v494z"}}]},name:"file",theme:"outlined"};const mn=vn;function Fe(i){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?Object(arguments[t]):{},n=Object.keys(e);typeof Object.getOwnPropertySymbols=="function"&&(n=n.concat(Object.getOwnPropertySymbols(e).filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),n.forEach(function(r){yn(i,r,e[r])})}return i}function yn(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}var Ce=function(t,e){var n=Fe({},t,e.attrs);return A(W,Fe({},n,{icon:mn}),null)};Ce.displayName="FileOutlined";Ce.inheritAttrs=!1;const bn=Ce;var An={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M928 444H820V330.4c0-17.7-14.3-32-32-32H473L355.7 186.2a8.15 8.15 0 00-5.5-2.2H96c-17.7 0-32 14.3-32 32v592c0 17.7 14.3 32 32 32h698c13 0 24.8-7.9 29.7-20l134-332c1.5-3.8 2.3-7.9 2.3-12 0-17.7-14.3-32-32-32zM136 256h188.5l119.6 114.4H748V444H238c-13 0-24.8 7.9-29.7 20L136 643.2V256zm635.3 512H159l103.3-256h612.4L771.3 768z"}}]},name:"folder-open",theme:"outlined"};const Sn=An;function Re(i){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?Object(arguments[t]):{},n=Object.keys(e);typeof Object.getOwnPropertySymbols=="function"&&(n=n.concat(Object.getOwnPropertySymbols(e).filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),n.forEach(function(r){kn(i,r,e[r])})}return i}function kn(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}var we=function(t,e){var n=Re({},t,e.attrs);return A(W,Re({},n,{icon:Sn}),null)};we.displayName="FolderOpenOutlined";we.inheritAttrs=!1;const In=we;function _n(i){return i&&i.length?i[0]:void 0}var Cn=Math.ceil,wn=Math.max;function En(i,t,e,n){for(var r=-1,o=wn(Cn((t-i)/(e||1)),0),p=Array(o);o--;)p[n?o:++r]=i,i+=e;return p}function Tn(i){return function(t,e,n){return n&&typeof n!="number"&&on(t,e,n)&&(e=n=void 0),t=ce(t),e===void 0?(e=t,t=0):e=ce(e),n=n===void 0?t<e?1:-1:ce(n),En(t,e,n,i)}}var Pn=Tn();const On=Pn,Nn="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/ARuCRABEFAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghgg0Aj8i0JO4OzsrPv69Wv+hi2qPHr0qNvf39+iI97soRIh4f3z58/u7du3SXX7Xt7Z2enevHmzfQe+oSN2apSAPj09TSrb+XKI/f379+08+A0cNRE2ANkupk+ACNPvkSPcAAEibACyXUyfABGm3yNHuAECRNgAZLuYPgEirKlHu7u7XdyytGwHAd8jjNyng4OD7vnz51dbPT8/7z58+NB9+/bt6jU/TI+AGWHEnrx48eJ/EsSmHzx40L18+fLyzxF3ZVMjEyDCiEDjMYZZS5wiPXnyZFbJaxMhQIQRGzHvWR7XCyOCXsOmiDAi1HmPMMQjDpbpEiDCiL358eNHurW/5SnWdIBbXiDCiA38/Pnzrce2YyZ4//59F3ePLNMl4PbpiL2J0L979+7yDtHDhw8vtzzvdGnEXdvUigSIsCLAWavHp/+qM0BcXMd/q25n1vF57TYBp0a3mUzilePj4+7k5KSLb6gt6ydAhPUzXnoPR0dHl79WGTNCfBnn1uvSCJdegQhLI1vvCk+fPu2ePXt2tZOYEV6/fn31dz+shwAR1sP1cqvLntbEN9MxA9xcYjsxS1jWR4AIa2Ibzx0tc44fYX/16lV6NDFLXH+YL32jwiACRBiEbf5KcXoTIsQSpzXx4N28Ja4BQoK7rgXiydbHjx/P25TaQAJEGAguWy0+2Q8PD6/Ki4R8EVl+bzBOnZY95fq9rj9zAkTI2SxdidBHqG9+skdw43borCXO/ZcJdraPWdv22uIEiLA4q7nvvCug8WTqzQveOH26fodo7g6uFe/a17W3+nFBAkRYENRdb1vkkz1CH9cPsVy/jrhr27PqMYvENYNlHAIesRiBYwRy0V+8iXP8+/fvX11Mr7L7ECueb/r48eMqm7FuI2BGWDEG8cm+7G3NEOfmdcTQw4h9/55lhm7DekRYKQPZF2ArbXTAyu4kDYB2YxUzwg0gi/41ztHnfQG26HbGel/crVrm7tNY+/1btkOEAZ2M05r4FB7r9GbAIdxaZYrHdOsgJ/wCEQY0J74TmOKnbxxT9n3FgGGWWsVdowHtjt9Nnvf7yQM2aZU/TIAIAxrw6dOnAWtZZcoEnBpNuTuObWMEiLAx1HY0ZQJEmHJ3HNvGCBBhY6jtaMoEiJB0Z29vL6ls58vxPcO8/zfrdo5qvKO+d3Fx8Wu8zf1dW4p/cPzLly/dtv9Ts/EbcvGAHhHyfBIhZ6NSiIBTo0LNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg==",ne=new WeakMap;function Dn(i,t){return{useHookShareState:n=>{const r=Ct();ge(r),ne.has(r)||(ne.set(r,ke(i(r,n??(t==null?void 0:t())))),It(()=>{ne.delete(r)}));const o=ne.get(r);return ge(o),{state:o,toRefs(){return _t(o)}}}}}var $n={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M715.8 493.5L335 165.1c-14.2-12.2-35-1.2-35 18.5v656.8c0 19.7 20.8 30.7 35 18.5l380.8-328.4c10.9-9.4 10.9-27.6 0-37z"}}]},name:"caret-right",theme:"outlined"};const zn=$n;function Le(i){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?Object(arguments[t]):{},n=Object.keys(e);typeof Object.getOwnPropertySymbols=="function"&&(n=n.concat(Object.getOwnPropertySymbols(e).filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),n.forEach(function(r){Mn(i,r,e[r])})}return i}function Mn(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}var Ee=function(t,e){var n=Le({},t,e.attrs);return A(W,Le({},n,{icon:zn}),null)};Ee.displayName="CaretRightOutlined";Ee.inheritAttrs=!1;const je=Ee;var Qn={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M923 283.6a260.04 260.04 0 00-56.9-82.8 264.4 264.4 0 00-84-55.5A265.34 265.34 0 00679.7 125c-49.3 0-97.4 13.5-139.2 39-10 6.1-19.5 12.8-28.5 20.1-9-7.3-18.5-14-28.5-20.1-41.8-25.5-89.9-39-139.2-39-35.5 0-69.9 6.8-102.4 20.3-31.4 13-59.7 31.7-84 55.5a258.44 258.44 0 00-56.9 82.8c-13.9 32.3-21 66.6-21 101.9 0 33.3 6.8 68 20.3 103.3 11.3 29.5 27.5 60.1 48.2 91 32.8 48.9 77.9 99.9 133.9 151.6 92.8 85.7 184.7 144.9 188.6 147.3l23.7 15.2c10.5 6.7 24 6.7 34.5 0l23.7-15.2c3.9-2.5 95.7-61.6 188.6-147.3 56-51.7 101.1-102.7 133.9-151.6 20.7-30.9 37-61.5 48.2-91 13.5-35.3 20.3-70 20.3-103.3.1-35.3-7-69.6-20.9-101.9z"}}]},name:"heart",theme:"filled"};const Bn=Qn;function He(i){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?Object(arguments[t]):{},n=Object.keys(e);typeof Object.getOwnPropertySymbols=="function"&&(n=n.concat(Object.getOwnPropertySymbols(e).filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),n.forEach(function(r){Fn(i,r,e[r])})}return i}function Fn(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}var Te=function(t,e){var n=He({},t,e.attrs);return A(W,He({},n,{icon:Bn}),null)};Te.displayName="HeartFilled";Te.inheritAttrs=!1;const Rn=Te;var Ln={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M923 283.6a260.04 260.04 0 00-56.9-82.8 264.4 264.4 0 00-84-55.5A265.34 265.34 0 00679.7 125c-49.3 0-97.4 13.5-139.2 39-10 6.1-19.5 12.8-28.5 20.1-9-7.3-18.5-14-28.5-20.1-41.8-25.5-89.9-39-139.2-39-35.5 0-69.9 6.8-102.4 20.3-31.4 13-59.7 31.7-84 55.5a258.44 258.44 0 00-56.9 82.8c-13.9 32.3-21 66.6-21 101.9 0 33.3 6.8 68 20.3 103.3 11.3 29.5 27.5 60.1 48.2 91 32.8 48.9 77.9 99.9 133.9 151.6 92.8 85.7 184.7 144.9 188.6 147.3l23.7 15.2c10.5 6.7 24 6.7 34.5 0l23.7-15.2c3.9-2.5 95.7-61.6 188.6-147.3 56-51.7 101.1-102.7 133.9-151.6 20.7-30.9 37-61.5 48.2-91 13.5-35.3 20.3-70 20.3-103.3.1-35.3-7-69.6-20.9-101.9zM512 814.8S156 586.7 156 385.5C156 283.6 240.3 201 344.3 201c73.1 0 136.5 40.8 167.7 100.4C543.2 241.8 606.6 201 679.7 201c104 0 188.3 82.6 188.3 184.5 0 201.2-356 429.3-356 429.3z"}}]},name:"heart",theme:"outlined"};const jn=Ln;function Ve(i){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?Object(arguments[t]):{},n=Object.keys(e);typeof Object.getOwnPropertySymbols=="function"&&(n=n.concat(Object.getOwnPropertySymbols(e).filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),n.forEach(function(r){Hn(i,r,e[r])})}return i}function Hn(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}var Pe=function(t,e){var n=Ve({},t,e.attrs);return A(W,Ve({},n,{icon:jn}),null)};Pe.displayName="HeartOutlined";Pe.inheritAttrs=!1;const Vn=Pe;var xn={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M908.1 353.1l-253.9-36.9L540.7 86.1c-3.1-6.3-8.2-11.4-14.5-14.5-15.8-7.8-35-1.3-42.9 14.5L369.8 316.2l-253.9 36.9c-7 1-13.4 4.3-18.3 9.3a32.05 32.05 0 00.6 45.3l183.7 179.1-43.4 252.9a31.95 31.95 0 0046.4 33.7L512 754l227.1 119.4c6.2 3.3 13.4 4.4 20.3 3.2 17.4-3 29.1-19.5 26.1-36.9l-43.4-252.9 183.7-179.1c5-4.9 8.3-11.3 9.3-18.3 2.7-17.5-9.5-33.7-27-36.3zM664.8 561.6l36.1 210.3L512 672.7 323.1 772l36.1-210.3-152.8-149L417.6 382 512 190.7 606.4 382l211.2 30.7-152.8 148.9z"}}]},name:"star",theme:"outlined"};const Un=xn;function xe(i){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?Object(arguments[t]):{},n=Object.keys(e);typeof Object.getOwnPropertySymbols=="function"&&(n=n.concat(Object.getOwnPropertySymbols(e).filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),n.forEach(function(r){Jn(i,r,e[r])})}return i}function Jn(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}var Oe=function(t,e){var n=xe({},t,e.attrs);return A(W,xe({},n,{icon:Un}),null)};Oe.displayName="StarOutlined";Oe.inheritAttrs=!1;const ut=Oe,Wn="/infinite_image_browsing/fe-static/assets/play-68f5544d.svg",Kn=wt("useBatchDownloadStore",()=>{const i=j([]);return{selectdFiles:i,addFiles:e=>{i.value=Et([...i.value,...e])}}});class oe{constructor(t,e=Tt.CREATED_TIME_DESC){ee(this,"root");ee(this,"execQueue",[]);ee(this,"walkerInitPromsie");this.entryPath=t,this.sortMethod=e,this.root={children:[],info:{name:this.entryPath,size:"-",bytes:0,created_time:"",is_under_scanned_path:!0,date:"",type:"dir",fullpath:this.entryPath}},this.walkerInitPromsie=new Promise(n=>{Qe([this.entryPath]).then(async r=>{this.root.info=r[this.entryPath],await this.fetchChildren(this.root),n()})})}reset(){return this.root.children=[],this.fetchChildren(this.root)}get images(){const t=e=>e.children.map(n=>{if(n.info.type==="dir")return t(n);if(ae(n.info.name))return n.info}).filter(n=>n).flat(1);return t(this.root)}get isCompleted(){return this.execQueue.length===0}async fetchChildren(t){const{files:e}=await rn(t.info.fullpath);return t.children=Ge(e,this.sortMethod).map(n=>({info:n,children:[]})),this.execQueue.shift(),this.execQueue.unshift(...t.children.filter(n=>n.info.type==="dir").map(n=>({fn:()=>this.fetchChildren(n),...n}))),t}async next(){await this.walkerInitPromsie;const t=_n(this.execQueue);if(!t)return null;const e=await t.fn();return this.execQueue=this.execQueue.slice(),this.root={...this.root},e}async isExpired(){const t=[this.root.info],e=r=>{for(const o of r.children)o.info.type==="dir"&&(t.push(o.info),e(o))};e(this.root);const n=await Qe(t.map(r=>r.fullpath));for(const r of t)if(!Pt(r,n[r.fullpath]))return!0;return!1}async seamlessRefresh(t,e=j(!1)){const n=performance.now(),r=new oe(this.entryPath,this.sortMethod);for(await r.walkerInitPromsie;!r.isCompleted&&r.images.length<t;){if(e.value)throw new Error("canceled");await r.next()}const o=performance.now();return console.log("seamlessRefresh currPos:",t,"Time taken:",(o-n).toFixed(0),"ms"),r}}var ct={exports:{}};/* NProgress, (c) 2013, 2014 Rico Sta. Cruz - http://ricostacruz.com/nprogress
|
2 |
+
* @license MIT */(function(i,t){(function(e,n){i.exports=n})(Ot,function(){var e={};e.version="0.3.5";var n=e.settings={minimum:.08,easing:"linear",positionUsing:"",speed:200,trickle:!0,trickleSpeed:200,showSpinner:!0,barSelector:'[role="bar"]',spinnerSelector:'[role="spinner"]',parent:"body",template:'<div class="bar" role="bar"><div class="peg"></div></div><div class="spinner" role="spinner"><div class="spinner-icon"></div></div>'};e.configure=function(s){var c,m;for(c in s)m=s[c],m!==void 0&&s.hasOwnProperty(c)&&(n[c]=m);return this},e.status=null,e.set=function(s){var c=e.isStarted();s=r(s,n.minimum,1),e.status=s===1?null:s;var m=e.render(!c),D=m.querySelector(n.barSelector),O=n.speed,$=n.easing;return m.offsetWidth,d(function(g){n.positionUsing===""&&(n.positionUsing=e.getPositioningCSS()),v(D,p(s,O,$)),s===1?(v(m,{transition:"none",opacity:1}),m.offsetWidth,setTimeout(function(){v(m,{transition:"all "+O+"ms linear",opacity:0}),setTimeout(function(){e.remove(),g()},O)},O)):setTimeout(g,O)}),this},e.isStarted=function(){return typeof e.status=="number"},e.start=function(){e.status||e.set(0);var s=function(){setTimeout(function(){e.status&&(e.trickle(),s())},n.trickleSpeed)};return n.trickle&&s(),this},e.done=function(s){return!s&&!e.status?this:e.inc(.3+.5*Math.random()).set(1)},e.inc=function(s){var c=e.status;return c?c>1?void 0:(typeof s!="number"&&(c>=0&&c<.2?s=.1:c>=.2&&c<.5?s=.04:c>=.5&&c<.8?s=.02:c>=.8&&c<.99?s=.005:s=0),c=r(c+s,0,.994),e.set(c)):e.start()},e.trickle=function(){return e.inc()},function(){var s=0,c=0;e.promise=function(m){return!m||m.state()==="resolved"?this:(c===0&&e.start(),s++,c++,m.always(function(){c--,c===0?(s=0,e.done()):e.set((s-c)/s)}),this)}}(),e.getElement=function(){var s=e.getParent();if(s){var c=Array.prototype.slice.call(s.querySelectorAll(".nprogress")).filter(function(m){return m.parentElement===s});if(c.length>0)return c[0]}return null},e.getParent=function(){if(n.parent instanceof HTMLElement)return n.parent;if(typeof n.parent=="string")return document.querySelector(n.parent)},e.render=function(s){if(e.isRendered())return e.getElement();E(document.documentElement,"nprogress-busy");var c=document.createElement("div");c.id="nprogress",c.className="nprogress",c.innerHTML=n.template;var m=c.querySelector(n.barSelector),D=s?"-100":o(e.status||0),O=e.getParent(),$;return v(m,{transition:"all 0 linear",transform:"translate3d("+D+"%,0,0)"}),n.showSpinner||($=c.querySelector(n.spinnerSelector),$&&l($)),O!=document.body&&E(O,"nprogress-custom-parent"),O.appendChild(c),c},e.remove=function(){e.status=null,w(document.documentElement,"nprogress-busy"),w(e.getParent(),"nprogress-custom-parent");var s=e.getElement();s&&l(s)},e.isRendered=function(){return!!e.getElement()},e.getPositioningCSS=function(){var s=document.body.style,c="WebkitTransform"in s?"Webkit":"MozTransform"in s?"Moz":"msTransform"in s?"ms":"OTransform"in s?"O":"";return c+"Perspective"in s?"translate3d":c+"Transform"in s?"translate":"margin"};function r(s,c,m){return s<c?c:s>m?m:s}function o(s){return(-1+s)*100}function p(s,c,m){var D;return n.positionUsing==="translate3d"?D={transform:"translate3d("+o(s)+"%,0,0)"}:n.positionUsing==="translate"?D={transform:"translate("+o(s)+"%,0)"}:D={"margin-left":o(s)+"%"},D.transition="all "+c+"ms "+m,D}var d=function(){var s=[];function c(){var m=s.shift();m&&m(c)}return function(m){s.push(m),s.length==1&&c()}}(),v=function(){var s=["Webkit","O","Moz","ms"],c={};function m(g){return g.replace(/^-ms-/,"ms-").replace(/-([\da-z])/gi,function(f,C){return C.toUpperCase()})}function D(g){var f=document.body.style;if(g in f)return g;for(var C=s.length,M=g.charAt(0).toUpperCase()+g.slice(1),F;C--;)if(F=s[C]+M,F in f)return F;return g}function O(g){return g=m(g),c[g]||(c[g]=D(g))}function $(g,f,C){f=O(f),g.style[f]=C}return function(g,f){var C=arguments,M,F;if(C.length==2)for(M in f)F=f[M],F!==void 0&&f.hasOwnProperty(M)&&$(g,M,F);else $(g,C[1],C[2])}}();function b(s,c){var m=typeof s=="string"?s:T(s);return m.indexOf(" "+c+" ")>=0}function E(s,c){var m=T(s),D=m+c;b(m,c)||(s.className=D.substring(1))}function w(s,c){var m=T(s),D;b(s,c)&&(D=m.replace(" "+c+" "," "),s.className=D.substring(1,D.length-1))}function T(s){return(" "+(s&&s.className||"")+" ").replace(/\s+/gi," ")}function l(s){s&&s.parentNode&&s.parentNode.removeChild(s)}return e})})(ct);var Yn=ct.exports;const gs=Nt(Yn);function ps({fetchNext:i}={}){const{scroller:t,sortedFiles:e,sortMethod:n,currLocation:r,stackViewEl:o,canLoadNext:p,previewIdx:d,props:v,walker:b,getViewableAreaFiles:E}=le().toRefs(),{state:w}=le(),T=j(!1),l=j(q.defaultGridCellWidth),s=V(()=>l.value+16),c=44,{width:m}=Dt(o),D=V(()=>~~(m.value/s.value)),O=ke(new Map),$=V(()=>{const B=s.value;return{first:B+(l.value<=160?0:c),second:B}}),g=j(!1),f=async()=>{var B;if(!(g.value||v.value.mode!=="walk"||!p.value))try{g.value=!0,await((B=b.value)==null?void 0:B.next())}finally{g.value=!1}},C=async(B=!1)=>{const _=t.value,L=()=>B?d.value:(_==null?void 0:_.$_endIndex)??0,P=()=>{const z=e.value.length,x=50;return z?i?L()>z-x:L()>z-x&&p.value:!0};for(;P();){await Ze(30);const z=await(i??f)();if(typeof z=="boolean"&&!z)return}};w.useEventListen("loadNextDir",$t(async(B=!1)=>{await C(B),v.value.mode==="walk"&&M()})),w.useEventListen("viewableAreaFilesChange",()=>{const B=E.value(),_=B.filter(P=>P.is_under_scanned_path&&ae(P.name)).map(P=>P.fullpath);qn.fetchImageTags(_);const L=B.filter(P=>P.is_under_scanned_path&&P.type==="dir"&&!O.has(P.fullpath)).map(P=>P.fullpath);L.length&&zt(L).then(P=>{for(const z in P)if(Object.prototype.hasOwnProperty.call(P,z)){const x=P[z];O.set(z,x)}})}),w.useEventListen("refresh",async()=>{w.eventEmitter.emit("viewableAreaFilesChange")});const M=pe(()=>w.eventEmitter.emit("viewableAreaFilesChange"),300);se(r,M);const F=pe(async()=>{await C(),M()},150);return{gridItems:D,sortedFiles:e,sortMethodConv:Mt,moreActionsDropdownShow:T,gridSize:s,sortMethod:n,onScroll:F,loadNextDir:f,loadNextDirLoading:g,canLoadNext:p,itemSize:$,cellWidth:l,dirCoverCache:O}}const vs=new Map,q=Ie(),ms=Kn(),qn=Xe(),ys=Qt(),bs=new BroadcastChannel("iib-image-transfer-bus"),{eventEmitter:As,useEventListen:Ss}=et(),{useHookShareState:le}=Dn((i,{images:t})=>{const e=j({tabIdx:-1,paneIdx:-1}),n=V(()=>Ft(r.value)),r=j([]),o=V(()=>{var f;return r.value.map(C=>C.curr).slice((f=q.conf)!=null&&f.is_win&&e.value.mode!=="scanned-fixed"?1:0)}),p=V(()=>Rt(...o.value)),d=V(()=>{var f,C;return e.value.mode==="scanned-fixed"?((C=(f=r.value)==null?void 0:f[0])==null?void 0:C.curr)??"":e.value.mode==="walk"?e.value.path??"":r.value.length===1?"/":p.value}),v=j(q.defaultSortingMethod),b=j(e.value.mode=="walk"?new oe(e.value.path,v.value):void 0);se([()=>e.value.mode,()=>e.value.path,v],async([f,C,M])=>{var F;f==="walk"?(b.value=new oe(C,M),r.value=[{files:[],curr:C}],await Ze(),await((F=b.value)==null?void 0:F.reset()),$.eventEmitter.emit("loadNextDir")):b.value=void 0});const E=ke(new Set);se(n,()=>E.clear());const w=V(()=>{var F;if(t.value)return t.value;if(b.value)return b.value.images.filter(B=>!E.has(B.fullpath));if(!n.value)return[];const f=((F=n.value)==null?void 0:F.files)??[],C=v.value;return Ge((B=>q.onlyFoldersAndImages?B.filter(_=>_.type==="dir"||ae(_.name)):B)(f),C).filter(B=>!E.has(B.fullpath))}),T=j([]),l=j(-1),s=V(()=>b.value?!b.value.isCompleted:!1),c=j(!1),m=j(!1),D=j(),O=()=>{var f,C,M;return(M=(C=(f=q.tabList)==null?void 0:f[e.value.tabIdx])==null?void 0:C.panes)==null?void 0:M[e.value.paneIdx]},$=et();$.useEventListen("selectAll",()=>{console.log(`select all 0 -> ${w.value.length}`),T.value=On(0,w.value.length)});const g=()=>{const f=D.value;if(f){const C=Math.max(f.$_startIndex-10,0);return w.value.slice(C,f.$_endIndex+10)}return[]};return{previewing:m,spinning:c,canLoadNext:s,multiSelectedIdxs:T,previewIdx:l,basePath:o,currLocation:d,currPage:n,stack:r,sortMethod:v,sortedFiles:w,scroller:D,stackViewEl:j(),props:e,getPane:O,walker:b,deletedFiles:E,getViewableAreaFiles:g,...$}},()=>({images:j()}));function ks(){const{eventEmitter:i,multiSelectedIdxs:t,sortedFiles:e}=le().toRefs();return{onSelectAll:()=>i.value.emit("selectAll"),onReverseSelect:()=>{t.value=e.value.map((p,d)=>d).filter(p=>!t.value.includes(p))},onClearAllSelected:()=>{t.value=[]}}}const Is=()=>{const{stackViewEl:i}=le().toRefs(),t=j(-1);return Bt(i,e=>{var r;let n=e.target;for(;n.parentElement;)if(n=n.parentElement,n.tagName.toLowerCase()==="li"&&n.classList.contains("file-item-trigger")){const o=(r=n.dataset)==null?void 0:r.idx;o&&Number.isSafeInteger(+o)&&(t.value=+o);return}}),{showMenuIdx:t}};function Gn(){var i=window.navigator.userAgent,t=i.indexOf("MSIE ");if(t>0)return parseInt(i.substring(t+5,i.indexOf(".",t)),10);var e=i.indexOf("Trident/");if(e>0){var n=i.indexOf("rv:");return parseInt(i.substring(n+3,i.indexOf(".",n)),10)}var r=i.indexOf("Edge/");return r>0?parseInt(i.substring(r+5,i.indexOf(".",r)),10):-1}let ie;function ye(){ye.init||(ye.init=!0,ie=Gn()!==-1)}var ue={name:"ResizeObserver",props:{emitOnMount:{type:Boolean,default:!1},ignoreWidth:{type:Boolean,default:!1},ignoreHeight:{type:Boolean,default:!1}},emits:["notify"],mounted(){ye(),it(()=>{this._w=this.$el.offsetWidth,this._h=this.$el.offsetHeight,this.emitOnMount&&this.emitSize()});const i=document.createElement("object");this._resizeObject=i,i.setAttribute("aria-hidden","true"),i.setAttribute("tabindex",-1),i.onload=this.addResizeHandlers,i.type="text/html",ie&&this.$el.appendChild(i),i.data="about:blank",ie||this.$el.appendChild(i)},beforeUnmount(){this.removeResizeHandlers()},methods:{compareAndNotify(){(!this.ignoreWidth&&this._w!==this.$el.offsetWidth||!this.ignoreHeight&&this._h!==this.$el.offsetHeight)&&(this._w=this.$el.offsetWidth,this._h=this.$el.offsetHeight,this.emitSize())},emitSize(){this.$emit("notify",{width:this._w,height:this._h})},addResizeHandlers(){this._resizeObject.contentDocument.defaultView.addEventListener("resize",this.compareAndNotify),this.compareAndNotify()},removeResizeHandlers(){this._resizeObject&&this._resizeObject.onload&&(!ie&&this._resizeObject.contentDocument&&this._resizeObject.contentDocument.defaultView.removeEventListener("resize",this.compareAndNotify),this.$el.removeChild(this._resizeObject),this._resizeObject.onload=null,this._resizeObject=null)}}};const Zn=Lt();tt("data-v-b329ee4c");const Xn={class:"resize-observer",tabindex:"-1"};nt();const ei=Zn((i,t,e,n,r,o)=>(a(),R("div",Xn)));ue.render=ei;ue.__scopeId="data-v-b329ee4c";ue.__file="src/components/ResizeObserver.vue";function re(i){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?re=function(t){return typeof t}:re=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},re(i)}function ti(i,t){if(!(i instanceof t))throw new TypeError("Cannot call a class as a function")}function Ue(i,t){for(var e=0;e<t.length;e++){var n=t[e];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(i,n.key,n)}}function ni(i,t,e){return t&&Ue(i.prototype,t),e&&Ue(i,e),i}function Je(i){return ii(i)||ri(i)||si(i)||oi()}function ii(i){if(Array.isArray(i))return be(i)}function ri(i){if(typeof Symbol<"u"&&Symbol.iterator in Object(i))return Array.from(i)}function si(i,t){if(i){if(typeof i=="string")return be(i,t);var e=Object.prototype.toString.call(i).slice(8,-1);if(e==="Object"&&i.constructor&&(e=i.constructor.name),e==="Map"||e==="Set")return Array.from(i);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return be(i,t)}}function be(i,t){(t==null||t>i.length)&&(t=i.length);for(var e=0,n=new Array(t);e<t;e++)n[e]=i[e];return n}function oi(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
3 |
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function li(i){var t;return typeof i=="function"?t={callback:i}:t=i,t}function ai(i,t){var e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},n,r,o,p=function(v){for(var b=arguments.length,E=new Array(b>1?b-1:0),w=1;w<b;w++)E[w-1]=arguments[w];if(o=E,!(n&&v===r)){var T=e.leading;typeof T=="function"&&(T=T(v,r)),(!n||v!==r)&&T&&i.apply(void 0,[v].concat(Je(o))),r=v,clearTimeout(n),n=setTimeout(function(){i.apply(void 0,[v].concat(Je(o))),n=0},t)}};return p._clear=function(){clearTimeout(n),n=null},p}function dt(i,t){if(i===t)return!0;if(re(i)==="object"){for(var e in i)if(!dt(i[e],t[e]))return!1;return!0}return!1}var ui=function(){function i(t,e,n){ti(this,i),this.el=t,this.observer=null,this.frozen=!1,this.createObserver(e,n)}return ni(i,[{key:"createObserver",value:function(e,n){var r=this;if(this.observer&&this.destroyObserver(),!this.frozen){if(this.options=li(e),this.callback=function(d,v){r.options.callback(d,v),d&&r.options.once&&(r.frozen=!0,r.destroyObserver())},this.callback&&this.options.throttle){var o=this.options.throttleOptions||{},p=o.leading;this.callback=ai(this.callback,this.options.throttle,{leading:function(v){return p==="both"||p==="visible"&&v||p==="hidden"&&!v}})}this.oldResult=void 0,this.observer=new IntersectionObserver(function(d){var v=d[0];if(d.length>1){var b=d.find(function(w){return w.isIntersecting});b&&(v=b)}if(r.callback){var E=v.isIntersecting&&v.intersectionRatio>=r.threshold;if(E===r.oldResult)return;r.oldResult=E,r.callback(E,v)}},this.options.intersection),it(function(){r.observer&&r.observer.observe(r.el)})}}},{key:"destroyObserver",value:function(){this.observer&&(this.observer.disconnect(),this.observer=null),this.callback&&this.callback._clear&&(this.callback._clear(),this.callback=null)}},{key:"threshold",get:function(){return this.options.intersection&&typeof this.options.intersection.threshold=="number"?this.options.intersection.threshold:0}}]),i}();function ft(i,t,e){var n=t.value;if(n)if(typeof IntersectionObserver>"u")console.warn("[vue-observe-visibility] IntersectionObserver API is not available in your browser. Please install this polyfill: https://github.com/w3c/IntersectionObserver/tree/master/polyfill");else{var r=new ui(i,n,e);i._vue_visibilityState=r}}function ci(i,t,e){var n=t.value,r=t.oldValue;if(!dt(n,r)){var o=i._vue_visibilityState;if(!n){ht(i);return}o?o.createObserver(n,e):ft(i,{value:n},e)}}function ht(i){var t=i._vue_visibilityState;t&&(t.destroyObserver(),delete i._vue_visibilityState)}var di={beforeMount:ft,updated:ci,unmounted:ht},fi={itemsLimit:1e3},hi=/(auto|scroll)/;function gt(i,t){return i.parentNode===null?t:gt(i.parentNode,t.concat([i]))}var fe=function(t,e){return getComputedStyle(t,null).getPropertyValue(e)},gi=function(t){return fe(t,"overflow")+fe(t,"overflow-y")+fe(t,"overflow-x")},pi=function(t){return hi.test(gi(t))};function We(i){if(i instanceof HTMLElement||i instanceof SVGElement){for(var t=gt(i.parentNode,[]),e=0;e<t.length;e+=1)if(pi(t[e]))return t[e];return document.scrollingElement||document.documentElement}}function Ae(i){"@babel/helpers - typeof";return Ae=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ae(i)}var vi={items:{type:Array,required:!0},keyField:{type:String,default:"id"},direction:{type:String,default:"vertical",validator:function(t){return["vertical","horizontal"].includes(t)}},listTag:{type:String,default:"div"},itemTag:{type:String,default:"div"}};function mi(){return this.items.length&&Ae(this.items[0])!=="object"}var Se=!1;if(typeof window<"u"){Se=!1;try{var yi=Object.defineProperty({},"passive",{get:function(){Se=!0}});window.addEventListener("test",null,yi)}catch{}}let bi=0;var pt={name:"RecycleScroller",components:{ResizeObserver:ue},directives:{ObserveVisibility:di},props:{...vi,itemSize:{type:Number,default:null},gridItems:{type:Number,default:void 0},itemSecondarySize:{type:Number,default:void 0},minItemSize:{type:[Number,String],default:null},sizeField:{type:String,default:"size"},typeField:{type:String,default:"type"},buffer:{type:Number,default:200},pageMode:{type:Boolean,default:!1},prerender:{type:Number,default:0},emitUpdate:{type:Boolean,default:!1},updateInterval:{type:Number,default:0},skipHover:{type:Boolean,default:!1},listTag:{type:String,default:"div"},itemTag:{type:String,default:"div"},listClass:{type:[String,Object,Array],default:""},itemClass:{type:[String,Object,Array],default:""}},emits:["resize","visible","hidden","update","scroll-start","scroll-end"],data(){return{pool:[],totalSize:0,ready:!1,hoverKey:null}},computed:{sizes(){if(this.itemSize===null){const i={"-1":{accumulator:0}},t=this.items,e=this.sizeField,n=this.minItemSize;let r=1e4,o=0,p;for(let d=0,v=t.length;d<v;d++)p=t[d][e]||n,p<r&&(r=p),o+=p,i[d]={accumulator:o,size:p};return this.$_computedMinItemSize=r,i}return[]},simpleArray:mi,itemIndexByKey(){const{keyField:i,items:t}=this,e={};for(let n=0,r=t.length;n<r;n++)e[t[n][i]]=n;return e}},watch:{items(){this.updateVisibleItems(!0)},pageMode(){this.applyPageMode(),this.updateVisibleItems(!1)},sizes:{handler(){this.updateVisibleItems(!1)},deep:!0},gridItems(){this.updateVisibleItems(!0)},itemSecondarySize(){this.updateVisibleItems(!0)}},created(){this.$_startIndex=0,this.$_endIndex=0,this.$_views=new Map,this.$_unusedViews=new Map,this.$_scrollDirty=!1,this.$_lastUpdateScrollPosition=0,this.prerender&&(this.$_prerender=!0,this.updateVisibleItems(!1)),this.gridItems&&!this.itemSize&&console.error("[vue-recycle-scroller] You must provide an itemSize when using gridItems")},mounted(){this.applyPageMode(),this.$nextTick(()=>{this.$_prerender=!1,this.updateVisibleItems(!0),this.ready=!0})},activated(){const i=this.$_lastUpdateScrollPosition;typeof i=="number"&&this.$nextTick(()=>{this.scrollToPosition(i)})},beforeUnmount(){this.removeListeners()},methods:{addView(i,t,e,n,r){const o=jt({id:bi++,index:t,used:!0,key:n,type:r}),p=Ht({item:e,position:0,nr:o});return i.push(p),p},unuseView(i,t=!1){const e=this.$_unusedViews,n=i.nr.type;let r=e.get(n);r||(r=[],e.set(n,r)),r.push(i),t||(i.nr.used=!1,i.position=-9999)},handleResize(){this.$emit("resize"),this.ready&&this.updateVisibleItems(!1)},handleScroll(i){if(!this.$_scrollDirty){if(this.$_scrollDirty=!0,this.$_updateTimeout)return;const t=()=>requestAnimationFrame(()=>{this.$_scrollDirty=!1;const{continuous:e}=this.updateVisibleItems(!1,!0);e||(clearTimeout(this.$_refreshTimout),this.$_refreshTimout=setTimeout(this.handleScroll,this.updateInterval+100))});t(),this.updateInterval&&(this.$_updateTimeout=setTimeout(()=>{this.$_updateTimeout=0,this.$_scrollDirty&&t()},this.updateInterval))}},handleVisibilityChange(i,t){this.ready&&(i||t.boundingClientRect.width!==0||t.boundingClientRect.height!==0?(this.$emit("visible"),requestAnimationFrame(()=>{this.updateVisibleItems(!1)})):this.$emit("hidden"))},updateVisibleItems(i,t=!1){const e=this.itemSize,n=this.gridItems||1,r=this.itemSecondarySize||e,o=this.$_computedMinItemSize,p=this.typeField,d=this.simpleArray?null:this.keyField,v=this.items,b=v.length,E=this.sizes,w=this.$_views,T=this.$_unusedViews,l=this.pool,s=this.itemIndexByKey;let c,m,D,O,$;if(!b)c=m=O=$=D=0;else if(this.$_prerender)c=O=0,m=$=Math.min(this.prerender,v.length),D=null;else{const _=this.getScroll();if(t){let z=_.start-this.$_lastUpdateScrollPosition;if(z<0&&(z=-z),e===null&&z<o||z<e)return{continuous:!0}}this.$_lastUpdateScrollPosition=_.start;const L=this.buffer;_.start-=L,_.end+=L;let P=0;if(this.$refs.before&&(P=this.$refs.before.scrollHeight,_.start-=P),this.$refs.after){const z=this.$refs.after.scrollHeight;_.end+=z}if(e===null){let z,x=0,Ne=b-1,U=~~(b/2),De;do De=U,z=E[U].accumulator,z<_.start?x=U:U<b-1&&E[U+1].accumulator>_.start&&(Ne=U),U=~~((x+Ne)/2);while(U!==De);for(U<0&&(U=0),c=U,D=E[b-1].accumulator,m=U;m<b&&E[m].accumulator<_.end;m++);for(m===-1?m=v.length-1:(m++,m>b&&(m=b)),O=c;O<b&&P+E[O].accumulator<_.start;O++);for($=O;$<b&&P+E[$].accumulator<_.end;$++);}else{c=~~(_.start/e*n);const z=c%n;c-=z,m=Math.ceil(_.end/e*n),O=Math.max(0,Math.floor((_.start-P)/e*n)),$=Math.floor((_.end-P)/e*n),c<0&&(c=0),m>b&&(m=b),O<0&&(O=0),$>b&&($=b),D=Math.ceil(b/n)*e}}m-c>fi.itemsLimit&&this.itemsLimitError(),this.totalSize=D;let g;const f=c<=this.$_endIndex&&m>=this.$_startIndex;if(f)for(let _=0,L=l.length;_<L;_++)g=l[_],g.nr.used&&(i&&(g.nr.index=s[g.item[d]]),(g.nr.index==null||g.nr.index<c||g.nr.index>=m)&&this.unuseView(g));const C=f?null:new Map;let M,F,B;for(let _=c;_<m;_++){M=v[_];const L=d?M[d]:M;if(L==null)throw new Error(`Key is ${L} on item (keyField is '${d}')`);if(g=w.get(L),!e&&!E[_].size){g&&this.unuseView(g);continue}F=M[p];let P=T.get(F),z=!1;if(!g)f?P&&P.length?g=P.pop():g=this.addView(l,_,M,L,F):(B=C.get(F)||0,(!P||B>=P.length)&&(g=this.addView(l,_,M,L,F),this.unuseView(g,!0),P=T.get(F)),g=P[B],C.set(F,B+1)),w.delete(g.nr.key),g.nr.used=!0,g.nr.index=_,g.nr.key=L,g.nr.type=F,w.set(L,g),z=!0;else if(!g.nr.used&&(g.nr.used=!0,g.nr.index=_,z=!0,P)){const x=P.indexOf(g);x!==-1&&P.splice(x,1)}g.item=M,z&&(_===v.length-1&&this.$emit("scroll-end"),_===0&&this.$emit("scroll-start")),e===null?(g.position=E[_-1].accumulator,g.offset=0):(g.position=Math.floor(_/n)*e,g.offset=_%n*r)}return this.$_startIndex=c,this.$_endIndex=m,this.emitUpdate&&this.$emit("update",c,m,O,$),clearTimeout(this.$_sortTimer),this.$_sortTimer=setTimeout(this.sortViews,this.updateInterval+300),{continuous:f}},getListenerTarget(){let i=We(this.$el);return window.document&&(i===window.document.documentElement||i===window.document.body)&&(i=window),i},getScroll(){const{$el:i,direction:t}=this,e=t==="vertical";let n;if(this.pageMode){const r=i.getBoundingClientRect(),o=e?r.height:r.width;let p=-(e?r.top:r.left),d=e?window.innerHeight:window.innerWidth;p<0&&(d+=p,p=0),p+d>o&&(d=o-p),n={start:p,end:p+d}}else e?n={start:i.scrollTop,end:i.scrollTop+i.clientHeight}:n={start:i.scrollLeft,end:i.scrollLeft+i.clientWidth};return n},applyPageMode(){this.pageMode?this.addListeners():this.removeListeners()},addListeners(){this.listenerTarget=this.getListenerTarget(),this.listenerTarget.addEventListener("scroll",this.handleScroll,Se?{passive:!0}:!1),this.listenerTarget.addEventListener("resize",this.handleResize)},removeListeners(){this.listenerTarget&&(this.listenerTarget.removeEventListener("scroll",this.handleScroll),this.listenerTarget.removeEventListener("resize",this.handleResize),this.listenerTarget=null)},scrollToItem(i){let t;const e=this.gridItems||1;this.itemSize===null?t=i>0?this.sizes[i-1].accumulator:0:t=Math.floor(i/e)*this.itemSize,this.scrollToPosition(t)},scrollToPosition(i){const t=this.direction==="vertical"?{scroll:"scrollTop",start:"top"}:{scroll:"scrollLeft",start:"left"};let e,n,r;if(this.pageMode){const o=We(this.$el),p=o.tagName==="HTML"?0:o[t.scroll],d=o.getBoundingClientRect(),b=this.$el.getBoundingClientRect()[t.start]-d[t.start];e=o,n=t.scroll,r=i+p+b}else e=this.$el,n=t.scroll,r=i;e[n]=r},itemsLimitError(){throw setTimeout(()=>{console.log("It seems the scroller element isn't scrolling, so it tries to render all the items at once.","Scroller:",this.$el),console.log("Make sure the scroller has a fixed height (or width) and 'overflow-y' (or 'overflow-x') set to 'auto' so it can scroll correctly and only render the items visible in the scroll viewport.")}),new Error("Rendered items limit reached")},sortViews(){this.pool.sort((i,t)=>i.nr.index-t.nr.index)}}};const Ai={key:0,ref:"before",class:"vue-recycle-scroller__slot"},Si={key:1,ref:"after",class:"vue-recycle-scroller__slot"};function ki(i,t,e,n,r,o){const p=Vt("ResizeObserver"),d=xt("observe-visibility");return Ut((a(),h("div",{class:Y(["vue-recycle-scroller",{ready:r.ready,"page-mode":e.pageMode,[`direction-${i.direction}`]:!0}]),onScrollPassive:t[0]||(t[0]=(...v)=>o.handleScroll&&o.handleScroll(...v))},[i.$slots.before?(a(),h("div",Ai,[te(i.$slots,"before")],512)):S("v-if",!0),(a(),R(ze(e.listTag),{ref:"wrapper",style:rt({[i.direction==="vertical"?"minHeight":"minWidth"]:r.totalSize+"px"}),class:Y(["vue-recycle-scroller__item-wrapper",e.listClass])},{default:k(()=>[(a(!0),h(H,null,J(r.pool,v=>(a(),R(ze(e.itemTag),Jt({key:v.nr.id,style:r.ready?{transform:`translate${i.direction==="vertical"?"Y":"X"}(${v.position}px) translate${i.direction==="vertical"?"X":"Y"}(${v.offset}px)`,width:e.gridItems?`${i.direction==="vertical"&&e.itemSecondarySize||e.itemSize}px`:void 0,height:e.gridItems?`${i.direction==="horizontal"&&e.itemSecondarySize||e.itemSize}px`:void 0}:null,class:["vue-recycle-scroller__item-view",[e.itemClass,{hover:!e.skipHover&&r.hoverKey===v.nr.key}]]},Wt(e.skipHover?{}:{mouseenter:()=>{r.hoverKey=v.nr.key},mouseleave:()=>{r.hoverKey=null}})),{default:k(()=>[te(i.$slots,"default",{item:v.item,index:v.nr.index,active:v.nr.used})]),_:2},1040,["style","class"]))),128)),te(i.$slots,"empty")]),_:3},8,["style","class"])),i.$slots.after?(a(),h("div",Si,[te(i.$slots,"after")],512)):S("v-if",!0),A(p,{onNotify:o.handleResize},null,8,["onNotify"])],34)),[[d,o.handleVisibilityChange]])}pt.render=ki;pt.__file="src/components/RecycleScroller.vue";const Ke=X({__name:"ContextMenu",props:{file:{},idx:{},selectedTag:{},isSelectedMutilFiles:{type:Boolean}},emits:["contextMenuClick"],setup(i,{emit:t}){const e=i,n=Ie(),r=V(()=>{var o;return(((o=n.conf)==null?void 0:o.all_custom_tags)??[]).reduce((p,d)=>[...p,{...d,selected:!!e.selectedTag.find(v=>v.id===d.id)}],[])});return(o,p)=>{const d=st,v=Kt,b=Yt,E=ot;return a(),R(E,{onClick:p[0]||(p[0]=w=>t("contextMenuClick",w,o.file,o.idx))},{default:k(()=>{var w;return[A(d,{key:"deleteFiles"},{default:k(()=>[I(y(o.$t("deleteSelected")),1)]),_:1}),A(d,{key:"openWithDefaultApp"},{default:k(()=>[I(y(o.$t("openWithDefaultApp")),1)]),_:1}),A(d,{key:"saveSelectedAsJson"},{default:k(()=>[I(y(o.$t("saveSelectedAsJson")),1)]),_:1}),o.file.type==="dir"?(a(),h(H,{key:0},[A(d,{key:"openInNewTab"},{default:k(()=>[I(y(o.$t("openInNewTab")),1)]),_:1}),A(d,{key:"openOnTheRight"},{default:k(()=>[I(y(o.$t("openOnTheRight")),1)]),_:1}),A(d,{key:"openWithWalkMode"},{default:k(()=>[I(y(o.$t("openWithWalkMode")),1)]),_:1})],64)):S("",!0),o.file.type==="file"?(a(),h(H,{key:1},[Q(ae)(o.file.name)?(a(),h(H,{key:0},[A(d,{key:"viewGenInfo"},{default:k(()=>[I(y(o.$t("viewGenerationInfo")),1)]),_:1}),A(v),((w=Q(n).conf)==null?void 0:w.launch_mode)!=="server"?(a(),h(H,{key:0},[A(d,{key:"send2txt2img"},{default:k(()=>[I(y(o.$t("sendToTxt2img")),1)]),_:1}),A(d,{key:"send2img2img"},{default:k(()=>[I(y(o.$t("sendToImg2img")),1)]),_:1}),A(d,{key:"send2inpaint"},{default:k(()=>[I(y(o.$t("sendToInpaint")),1)]),_:1}),A(d,{key:"send2extras"},{default:k(()=>[I(y(o.$t("sendToExtraFeatures")),1)]),_:1}),A(b,{key:"sendToThirdPartyExtension",title:o.$t("sendToThirdPartyExtension")},{default:k(()=>[A(d,{key:"send2controlnet-txt2img"},{default:k(()=>[I("ControlNet - "+y(o.$t("t2i")),1)]),_:1}),A(d,{key:"send2controlnet-img2img"},{default:k(()=>[I("ControlNet - "+y(o.$t("i2i")),1)]),_:1}),A(d,{key:"send2outpaint"},{default:k(()=>[I("openOutpaint")]),_:1})]),_:1},8,["title"])],64)):S("",!0),A(d,{key:"send2BatchDownload"},{default:k(()=>[I(y(o.$t("sendToBatchDownload")),1)]),_:1}),A(b,{key:"copy2target",title:o.$t("copyTo")},{default:k(()=>[(a(!0),h(H,null,J(Q(n).quickMovePaths,T=>(a(),R(d,{key:`copy-to-${T.dir}`},{default:k(()=>[I(y(T.zh),1)]),_:2},1024))),128))]),_:1},8,["title"]),A(b,{key:"move2target",title:o.$t("moveTo")},{default:k(()=>[(a(!0),h(H,null,J(Q(n).quickMovePaths,T=>(a(),R(d,{key:`move-to-${T.dir}`},{default:k(()=>[I(y(T.zh),1)]),_:2},1024))),128))]),_:1},8,["title"]),A(v),o.isSelectedMutilFiles?(a(),h(H,{key:1},[A(b,{key:"batch-add-tag",title:o.$t("batchAddTag")},{default:k(()=>[A(d,{key:"add-custom-tag"},{default:k(()=>[I("+ "+y(o.$t("addNewCustomTag")),1)]),_:1}),(a(!0),h(H,null,J(r.value,T=>(a(),R(d,{key:`batch-add-tag-${T.id}`},{default:k(()=>[I(y(T.name),1)]),_:2},1024))),128))]),_:1},8,["title"]),A(b,{key:"batch-remove-tag",title:o.$t("batchRemoveTag")},{default:k(()=>[(a(!0),h(H,null,J(r.value,T=>(a(),R(d,{key:`batch-remove-tag-${T.id}`},{default:k(()=>[I(y(T.name),1)]),_:2},1024))),128))]),_:1},8,["title"])],64)):(a(),R(b,{key:"toggle-tag",title:o.$t("toggleTag")},{default:k(()=>[A(d,{key:"add-custom-tag"},{default:k(()=>[I("+ "+y(o.$t("addNewCustomTag")),1)]),_:1}),(a(!0),h(H,null,J(r.value,T=>(a(),R(d,{key:`toggle-tag-${T.id}`},{default:k(()=>[I(y(T.name)+" ",1),T.selected?(a(),R(Q(at),{key:0})):(a(),R(Q(ut),{key:1}))]),_:2},1024))),128))]),_:1},8,["title"])),A(v),A(d,{key:"openFileLocationInNewTab"},{default:k(()=>[I(y(o.$t("openFileLocationInNewTab")),1)]),_:1}),A(d,{key:"openWithLocalFileBrowser"},{default:k(()=>[I(y(o.$t("openWithLocalFileBrowser")),1)]),_:1})],64)):S("",!0),A(v),A(d,{key:"rename"},{default:k(()=>[I(y(o.$t("rename")),1)]),_:1}),A(d,{key:"previewInNewWindow"},{default:k(()=>[I(y(o.$t("previewInNewWindow")),1)]),_:1}),A(d,{key:"download"},{default:k(()=>[I(y(o.$t("download")),1)]),_:1}),A(d,{key:"copyPreviewUrl"},{default:k(()=>[I(y(o.$t("copySourceFilePreviewLink")),1)]),_:1}),A(d,{key:"copyFilePath"},{default:k(()=>[I(y(o.$t("copyFilePath")),1)]),_:1})],64)):S("",!0)]}),_:1})}}}),N=i=>(tt("data-v-78cd67a3"),i=i(),nt(),i),Ii={class:"changeIndicatorWrapper"},_i={key:0,class:"changeIndicatorsLeft changeIndicators"},Ci={key:0,class:"promptChangeIndicator changeIndicator"},wi={key:1,class:"negpromptChangeIndicator changeIndicator"},Ei={key:2,class:"seedChangeIndicator changeIndicator"},Ti={key:3,class:"stepsChangeIndicator changeIndicator"},Pi={key:4,class:"cfgChangeIndicator changeIndicator"},Oi={key:5,class:"sizeChangeIndicator changeIndicator"},Ni={key:6,class:"modelChangeIndicator changeIndicator"},Di={key:7,class:"samplerChangeIndicator changeIndicator"},$i={key:8,class:"otherChangeIndicator changeIndicator"},zi={class:"hoverOverlay"},Mi=N(()=>u("strong",null,"This file",-1)),Qi=N(()=>u("br",null,null,-1)),Bi=N(()=>u("br",null,null,-1)),Fi={key:0},Ri=N(()=>u("td",null,[u("span",{class:"promptChangeIndicator"},"+ Prompt")],-1)),Li={key:1},ji=N(()=>u("td",null,[u("span",{class:"negpromptChangeIndicator"},"- Prompt")],-1)),Hi={key:2},Vi=N(()=>u("td",null,[u("span",{class:"seedChangeIndicator"},"Seed")],-1)),xi={key:3},Ui=N(()=>u("td",null,[u("span",{class:"stepsChangeIndicator"},"Steps")],-1)),Ji={key:4},Wi=N(()=>u("td",null,[u("span",{class:"cfgChangeIndicator"},"Cfg Scale")],-1)),Ki={key:5},Yi=N(()=>u("td",null,[u("span",{class:"sizeChangeIndicator"},"Size")],-1)),qi={key:6},Gi=N(()=>u("td",null,[u("span",{class:"modelChangeIndicator"},"Model")],-1)),Zi=N(()=>u("br",null,null,-1)),Xi={key:7},er=N(()=>u("td",null,[u("span",{class:"samplerChangeIndicator"},"Sampler")],-1)),tr=N(()=>u("br",null,null,-1)),nr=N(()=>u("br",null,null,-1)),ir={key:0},rr=N(()=>u("span",{class:"otherChangeIndicator"},"Other",-1)),sr=N(()=>u("br",null,null,-1)),or=N(()=>u("br",null,null,-1)),lr={key:1,class:"changeIndicatorsRight changeIndicators"},ar={key:0,class:"promptChangeIndicator changeIndicator"},ur={key:1,class:"negpromptChangeIndicator changeIndicator"},cr={key:2,class:"seedChangeIndicator changeIndicator"},dr={key:3,class:"stepsChangeIndicator changeIndicator"},fr={key:4,class:"cfgChangeIndicator changeIndicator"},hr={key:5,class:"sizeChangeIndicator changeIndicator"},gr={key:6,class:"modelChangeIndicator changeIndicator"},pr={key:7,class:"samplerChangeIndicator changeIndicator"},vr={key:8,class:"otherChangeIndicator changeIndicator"},mr={class:"hoverOverlay"},yr=N(()=>u("strong",null,"This file",-1)),br=N(()=>u("br",null,null,-1)),Ar=N(()=>u("br",null,null,-1)),Sr={key:0},kr=N(()=>u("td",null,[u("span",{class:"promptChangeIndicator"},"+ Prompt")],-1)),Ir={key:1},_r=N(()=>u("td",null,[u("span",{class:"negpromptChangeIndicator"},"- Prompt")],-1)),Cr={key:2},wr=N(()=>u("td",null,[u("span",{class:"seedChangeIndicator"},"Seed")],-1)),Er={key:3},Tr=N(()=>u("td",null,[u("span",{class:"stepsChangeIndicator"},"Steps")],-1)),Pr={key:4},Or=N(()=>u("td",null,[u("span",{class:"cfgChangeIndicator"},"Cfg Scale")],-1)),Nr={key:5},Dr=N(()=>u("td",null,[u("span",{class:"sizeChangeIndicator"},"Size")],-1)),$r={key:6},zr=N(()=>u("td",null,[u("span",{class:"modelChangeIndicator"},"Model")],-1)),Mr=N(()=>u("br",null,null,-1)),Qr={key:7},Br=N(()=>u("td",null,[u("span",{class:"samplerChangeIndicator"},"Sampler")],-1)),Fr=N(()=>u("br",null,null,-1)),Rr=N(()=>u("br",null,null,-1)),Lr={key:0},jr=N(()=>u("span",{class:"otherChangeIndicator"},"Other",-1)),Hr=N(()=>u("br",null,null,-1)),Vr=N(()=>u("br",null,null,-1)),xr=X({__name:"ChangeIndicator",props:{genDiffToPrevious:{},genDiffToNext:{},genInfo:{}},setup(i){function t(n){const r=["prompt","negativePrompt","seed","steps","cfgScale","size","Model","others"],o=Object.keys(n).filter(p=>!r.includes(p));return Object.fromEntries(o.map(p=>[p,n[p]]))}function e(n){return Object.keys(t(n)).length>0}return(n,r)=>(a(),h("div",Ii,[n.genDiffToPrevious.empty?S("",!0):(a(),h("div",_i,["prompt"in n.genDiffToPrevious.diff?(a(),h("div",Ci,"P+")):S("",!0),"negativePrompt"in n.genDiffToPrevious.diff?(a(),h("div",wi,"P-")):S("",!0),"seed"in n.genDiffToPrevious.diff?(a(),h("div",Ei,"Se")):S("",!0),"steps"in n.genDiffToPrevious.diff?(a(),h("div",Ti,"St")):S("",!0),"cfgScale"in n.genDiffToPrevious.diff?(a(),h("div",Pi,"Cf")):S("",!0),"size"in n.genDiffToPrevious.diff?(a(),h("div",Oi,"Si")):S("",!0),"Model"in n.genDiffToPrevious.diff?(a(),h("div",Ni,"Mo")):S("",!0),"Sampler"in n.genDiffToPrevious.diff?(a(),h("div",Di,"Sa")):S("",!0),e(n.genDiffToPrevious.diff)?(a(),h("div",$i,"Ot")):S("",!0)])),u("div",zi,[u("small",null,[A(Q(je)),Mi,I(" vs "+y(n.genDiffToPrevious.otherFile)+" ",1),Qi,Bi,u("table",null,["prompt"in n.genDiffToPrevious.diff?(a(),h("tr",Fi,[Ri,u("td",null,y(n.genDiffToPrevious.diff.prompt)+" tokens changed",1)])):S("",!0),"negativePrompt"in n.genDiffToPrevious.diff?(a(),h("tr",Li,[ji,u("td",null,y(n.genDiffToPrevious.diff.negativePrompt)+" tokens changed",1)])):S("",!0),"seed"in n.genDiffToPrevious.diff?(a(),h("tr",Hi,[Vi,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.seed[0]),1),I(" vs "+y(n.genDiffToPrevious.diff.seed[1]),1)])])):S("",!0),"steps"in n.genDiffToPrevious.diff?(a(),h("tr",xi,[Ui,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.steps[0]),1),I(" vs "+y(n.genDiffToPrevious.diff.steps[1]),1)])])):S("",!0),"cfgScale"in n.genDiffToPrevious.diff?(a(),h("tr",Ji,[Wi,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.cfgScale[0]),1),I(" vs "+y(n.genDiffToPrevious.diff.cfgScale[1]),1)])])):S("",!0),"size"in n.genDiffToPrevious.diff?(a(),h("tr",Ki,[Yi,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.size[0]),1),I(" vs "+y(n.genDiffToPrevious.diff.size[1]),1)])])):S("",!0),"Model"in n.genDiffToPrevious.diff?(a(),h("tr",qi,[Gi,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.Model[0]),1),Zi,I(" vs "+y(n.genDiffToPrevious.diff.Model[1]),1)])])):S("",!0),"Sampler"in n.genDiffToPrevious.diff?(a(),h("tr",Xi,[er,u("td",null,[u("strong",null,y(n.genDiffToPrevious.diff.Sampler[0]),1),tr,I(" vs "+y(n.genDiffToPrevious.diff.Sampler[1]),1)])])):S("",!0)]),nr,e(n.genDiffToPrevious.diff)?(a(),h("div",ir,[rr,I(" props that changed:"),sr,or,u("ul",null,[(a(!0),h(H,null,J(t(n.genDiffToPrevious.diff),(o,p)=>(a(),h("li",null,y(p),1))),256))])])):S("",!0)])]),n.genDiffToNext.empty?S("",!0):(a(),h("div",lr,["prompt"in n.genDiffToNext.diff?(a(),h("div",ar,"P+")):S("",!0),"negativePrompt"in n.genDiffToNext.diff?(a(),h("div",ur,"P-")):S("",!0),"seed"in n.genDiffToNext.diff?(a(),h("div",cr,"Se")):S("",!0),"steps"in n.genDiffToNext.diff?(a(),h("div",dr,"St")):S("",!0),"cfgScale"in n.genDiffToNext.diff?(a(),h("div",fr,"Cf")):S("",!0),"size"in n.genDiffToNext.diff?(a(),h("div",hr,"Si")):S("",!0),"Model"in n.genDiffToNext.diff?(a(),h("div",gr,"Mo")):S("",!0),"Sampler"in n.genDiffToNext.diff?(a(),h("div",pr,"Sa")):S("",!0),e(n.genDiffToNext.diff)?(a(),h("div",vr,"Ot")):S("",!0)])),u("div",mr,[u("small",null,[A(Q(je)),yr,I(" vs "+y(n.genDiffToNext.otherFile)+" ",1),br,Ar,u("table",null,["prompt"in n.genDiffToNext.diff?(a(),h("tr",Sr,[kr,u("td",null,y(n.genDiffToNext.diff.prompt)+" tokens changed",1)])):S("",!0),"negativePrompt"in n.genDiffToNext.diff?(a(),h("tr",Ir,[_r,u("td",null,y(n.genDiffToNext.diff.negativePrompt)+" tokens changed",1)])):S("",!0),"seed"in n.genDiffToNext.diff?(a(),h("tr",Cr,[wr,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.seed[0]),1),I(" vs "+y(n.genDiffToNext.diff.seed[1]),1)])])):S("",!0),"steps"in n.genDiffToNext.diff?(a(),h("tr",Er,[Tr,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.steps[0]),1),I(" vs "+y(n.genDiffToNext.diff.steps[1]),1)])])):S("",!0),"cfgScale"in n.genDiffToNext.diff?(a(),h("tr",Pr,[Or,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.cfgScale[0]),1),I(" vs "+y(n.genDiffToNext.diff.cfgScale[1]),1)])])):S("",!0),"size"in n.genDiffToNext.diff?(a(),h("tr",Nr,[Dr,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.size[0]),1),I(" vs "+y(n.genDiffToNext.diff.size[1]),1)])])):S("",!0),"Model"in n.genDiffToNext.diff?(a(),h("tr",$r,[zr,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.Model[0]),1),Mr,I(" vs "+y(n.genDiffToNext.diff.Model[1]),1)])])):S("",!0),"Sampler"in n.genDiffToNext.diff?(a(),h("tr",Qr,[Br,u("td",null,[u("strong",null,y(n.genDiffToNext.diff.Sampler[0]),1),Fr,I(" vs "+y(n.genDiffToNext.diff.Sampler[1]),1)])])):S("",!0)]),Rr,e(n.genDiffToNext.diff)?(a(),h("div",Lr,[jr,I(" props that changed:"),Hr,Vr,u("ul",null,[(a(!0),h(H,null,J(t(n.genDiffToNext.diff),(o,p)=>(a(),h("li",null,y(p),1))),256))])])):S("",!0)])])]))}});const Ur=lt(xr,[["__scopeId","data-v-78cd67a3"]]),Jr=["data-idx"],Wr={key:1,class:"more"},Kr={class:"float-btn-wrap"},Yr={key:1,class:"tags-container"},qr=["url"],Gr={class:"play-icon"},Zr=["src"],Xr={key:0,class:"tags-container"},es={key:4,class:"preview-icon-wrap"},ts={key:1,class:"dir-cover-container"},ns=["src"],is={key:5,class:"profile"},rs=["title"],ss={class:"basic-info"},os={style:{"margin-right":"4px"}},he=160,ls=X({__name:"FileItem",props:{file:{},idx:{},selected:{type:Boolean,default:!1},showMenuIdx:{},cellWidth:{},fullScreenPreviewImageUrl:{},enableRightClickMenu:{type:Boolean,default:!0},enableCloseIcon:{type:Boolean,default:!1},isSelectedMutilFiles:{type:Boolean},genInfo:{},enableChangeIndicator:{type:Boolean},extraTags:{},coverFiles:{},getGenDiff:{},getGenDiffWatchDep:{}},emits:["update:showMenuIdx","fileItemClick","dragstart","dragend","previewVisibleChange","contextMenuClick","close-icon-click"],setup(i,{emit:t}){const e=i;qt(l=>({"02c5ba15":l.$props.cellWidth+"px"}));const n=Ie(),r=Xe(),o=j(),p=j(),d=pe(()=>{const{getGenDiff:l,file:s,idx:c}=e;l&&(p.value=l(s.gen_info_obj,c,1,s),o.value=l(s.gen_info_obj,c,-1,s))},200+100*Math.random());se(()=>{var l;return(l=e.getGenDiffWatchDep)==null?void 0:l.call(e,e.idx)},()=>{d()},{immediate:!0,deep:!0});const v=V(()=>r.tagMap.get(e.file.fullpath)??[]),b=V(()=>{const l=n.gridThumbnailResolution;return n.enableThumbnail?Me(e.file,[l,l].join("x")):Gt(e.file)}),E=V(()=>{var l;return(((l=n.conf)==null?void 0:l.all_custom_tags)??[]).reduce((s,c)=>[...s,{...c,selected:!!v.value.find(m=>m.id===c.id)}],[])}),w=V(()=>E.value.find(l=>l.type==="custom"&&l.name==="like")),T=()=>{ge(w.value),t("contextMenuClick",{key:`toggle-tag-${w.value.id}`},e.file,e.idx)};return(l,s)=>{const c=G,m=st,D=ot,O=nn,$=fn;return a(),R(c,{trigger:["contextmenu"],visible:Q(n).longPressOpenContextMenu?typeof l.idx=="number"&&l.showMenuIdx===l.idx:void 0,"onUpdate:visible":s[8]||(s[8]=g=>typeof l.idx=="number"&&t("update:showMenuIdx",g?l.idx:-1))},{overlay:k(()=>[l.enableRightClickMenu?(a(),R(Ke,{key:0,file:l.file,idx:l.idx,"selected-tag":v.value,onContextMenuClick:s[7]||(s[7]=(g,f,C)=>t("contextMenuClick",g,f,C)),"is-selected-mutil-files":l.isSelectedMutilFiles},null,8,["file","idx","selected-tag","is-selected-mutil-files"])):S("",!0)]),default:k(()=>{var g;return[(a(),h("li",{class:Y(["file file-item-trigger grid",{clickable:l.file.type==="dir",selected:l.selected}]),"data-idx":l.idx,key:l.file.name,draggable:"true",onDragstart:s[4]||(s[4]=f=>t("dragstart",f,l.idx)),onDragend:s[5]||(s[5]=f=>t("dragend",f,l.idx)),onClickCapture:s[6]||(s[6]=f=>t("fileItemClick",f,l.file,l.idx))},[u("div",null,[l.enableCloseIcon?(a(),h("div",{key:0,class:"close-icon",onClick:s[0]||(s[0]=f=>t("close-icon-click"))},[A(Q(Zt))])):S("",!0),l.enableRightClickMenu?(a(),h("div",Wr,[A(c,null,{overlay:k(()=>[A(Ke,{file:l.file,idx:l.idx,"selected-tag":v.value,onContextMenuClick:s[1]||(s[1]=(f,C,M)=>t("contextMenuClick",f,C,M)),"is-selected-mutil-files":l.isSelectedMutilFiles},null,8,["file","idx","selected-tag","is-selected-mutil-files"])]),default:k(()=>[u("div",Kr,[A(Q(Xt))])]),_:1}),l.file.type==="file"?(a(),R(c,{key:0},{overlay:k(()=>[E.value.length>1?(a(),R(D,{key:0,onClick:s[2]||(s[2]=f=>t("contextMenuClick",f,l.file,l.idx))},{default:k(()=>[(a(!0),h(H,null,J(E.value,f=>(a(),R(m,{key:`toggle-tag-${f.id}`},{default:k(()=>[I(y(f.name)+" ",1),f.selected?(a(),R(Q(at),{key:0})):(a(),R(Q(ut),{key:1}))]),_:2},1024))),128))]),_:1})):S("",!0)]),default:k(()=>{var f,C;return[u("div",{class:Y(["float-btn-wrap",{"like-selected":(f=w.value)==null?void 0:f.selected}]),onClick:T},[(C=w.value)!=null&&C.selected?(a(),R(Q(Rn),{key:0})):(a(),R(Q(Vn),{key:1}))],2)]}),_:1})):S("",!0)])):S("",!0),Q(en)(l.file.name)?(a(),h("div",{key:l.file.fullpath,class:Y(`idx-${l.idx} item-content`)},[l.enableChangeIndicator&&p.value&&o.value?(a(),R(Ur,{key:0,"gen-diff-to-next":p.value,"gen-diff-to-previous":o.value},null,8,["gen-diff-to-next","gen-diff-to-previous"])):S("",!0),A(O,{src:b.value,fallback:Q(Nn),preview:{src:l.fullScreenPreviewImageUrl,onVisibleChange:(f,C)=>t("previewVisibleChange",f,C)}},null,8,["src","fallback","preview"]),v.value&&l.cellWidth>he?(a(),h("div",Yr,[(a(!0),h(H,null,J(l.extraTags??v.value,f=>(a(),R($,{key:f.id,color:Q(r).getColor(f)},{default:k(()=>[I(y(f.name),1)]),_:2},1032,["color"]))),128))])):S("",!0)],2)):Q(tn)(l.file.name)?(a(),h("div",{key:3,class:Y(`idx-${l.idx} item-content video`),url:Q(de)(l.file),style:rt({"background-image":`url('${l.file.cover_url??Q(de)(l.file)}')`}),onClick:s[3]||(s[3]=f=>Q(sn)(l.file,C=>t("contextMenuClick",{key:`toggle-tag-${C}`},l.file,l.idx)))},[u("div",Gr,[u("img",{src:Q(Wn),style:{width:"40px",height:"40px"}},null,8,Zr)]),v.value&&l.cellWidth>he?(a(),h("div",Xr,[(a(!0),h(H,null,J(v.value,f=>(a(),R($,{key:f.id,color:Q(r).getColor(f)},{default:k(()=>[I(y(f.name),1)]),_:2},1032,["color"]))),128))])):S("",!0)],14,qr)):(a(),h("div",es,[l.file.type==="file"?(a(),R(Q(bn),{key:0,class:"icon center"})):(g=l.coverFiles)!=null&&g.length&&l.cellWidth>160?(a(),h("div",ts,[(a(!0),h(H,null,J(l.coverFiles,f=>(a(),h("img",{class:"dir-cover-item",src:f.media_type==="image"?Q(Me)(f):Q(de)(f),key:f.fullpath},null,8,ns))),128))])):(a(),R(Q(In),{key:2,class:"icon center"}))])),l.cellWidth>he?(a(),h("div",is,[u("div",{class:"name line-clamp-1",title:l.file.name},y(l.file.name),9,rs),u("div",ss,[u("div",os,y(l.file.type)+" "+y(l.file.size),1),u("div",null,y(l.file.date),1)])])):S("",!0)])],42,Jr))]}),_:1},8,["visible"])}}});const _s=lt(ls,[["__scopeId","data-v-1c38fa7e"]]);export{_s as F,gs as N,Ke as _,ps as a,Is as b,ks as c,pt as d,Ss as e,Kn as f,q as g,ys as h,As as i,ms as j,bs as k,On as r,vs as s,qn as t,le as u};
|
extensions/sd-webui-infinite-image-browsing/vue/dist/assets/FileItem-fb268ce8.css
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
.vue-recycle-scroller{position:relative}.vue-recycle-scroller.direction-vertical:not(.page-mode){overflow-y:auto}.vue-recycle-scroller.direction-horizontal:not(.page-mode){overflow-x:auto}.vue-recycle-scroller.direction-horizontal{display:flex}.vue-recycle-scroller__slot{flex:auto 0 0}.vue-recycle-scroller__item-wrapper{flex:1;box-sizing:border-box;overflow:hidden;position:relative}.vue-recycle-scroller.ready .vue-recycle-scroller__item-view{position:absolute;top:0;left:0;will-change:transform}.vue-recycle-scroller.direction-vertical .vue-recycle-scroller__item-wrapper{width:100%}.vue-recycle-scroller.direction-horizontal .vue-recycle-scroller__item-wrapper{height:100%}.vue-recycle-scroller.ready.direction-vertical .vue-recycle-scroller__item-view{width:100%}.vue-recycle-scroller.ready.direction-horizontal .vue-recycle-scroller__item-view{height:100%}.resize-observer[data-v-b329ee4c]{position:absolute;top:0;left:0;z-index:-1;width:100%;height:100%;border:none;background-color:transparent;pointer-events:none;display:block;overflow:hidden;opacity:0}.resize-observer[data-v-b329ee4c] object{display:block;position:absolute;top:0;left:0;height:100%;width:100%;overflow:hidden;pointer-events:none;z-index:-1}.ant-tag{box-sizing:border-box;margin:0 8px 0 0;color:#000000d9;font-size:14px;font-variant:tabular-nums;line-height:1.5715;list-style:none;font-feature-settings:"tnum";display:inline-block;height:auto;padding:0 7px;font-size:12px;line-height:20px;white-space:nowrap;background:#fafafa;border:1px solid #d9d9d9;border-radius:2px;opacity:1;transition:all .3s}.ant-tag,.ant-tag a,.ant-tag a:hover{color:#000000d9}.ant-tag>a:first-child:last-child{display:inline-block;margin:0 -8px;padding:0 8px}.ant-tag-close-icon{margin-left:3px;color:#00000073;font-size:10px;cursor:pointer;transition:all .3s}.ant-tag-close-icon:hover{color:#000000d9}.ant-tag-has-color{border-color:transparent}.ant-tag-has-color,.ant-tag-has-color a,.ant-tag-has-color a:hover,.ant-tag-has-color .anticon-close,.ant-tag-has-color .anticon-close:hover{color:#fff}.ant-tag-checkable{background-color:transparent;border-color:transparent;cursor:pointer}.ant-tag-checkable:not(.ant-tag-checkable-checked):hover{color:#d03f0a}.ant-tag-checkable:active,.ant-tag-checkable-checked{color:#fff}.ant-tag-checkable-checked{background-color:#d03f0a}.ant-tag-checkable:active{background-color:#ab2800}.ant-tag-hidden{display:none}.ant-tag-pink{color:#c41d7f;background:#fff0f6;border-color:#ffadd2}.ant-tag-pink-inverse{color:#fff;background:#eb2f96;border-color:#eb2f96}.ant-tag-magenta{color:#c41d7f;background:#fff0f6;border-color:#ffadd2}.ant-tag-magenta-inverse{color:#fff;background:#eb2f96;border-color:#eb2f96}.ant-tag-red{color:#cf1322;background:#fff1f0;border-color:#ffa39e}.ant-tag-red-inverse{color:#fff;background:#f5222d;border-color:#f5222d}.ant-tag-volcano{color:#d4380d;background:#fff2e8;border-color:#ffbb96}.ant-tag-volcano-inverse{color:#fff;background:#fa541c;border-color:#fa541c}.ant-tag-orange{color:#d46b08;background:#fff7e6;border-color:#ffd591}.ant-tag-orange-inverse{color:#fff;background:#fa8c16;border-color:#fa8c16}.ant-tag-yellow{color:#d4b106;background:#feffe6;border-color:#fffb8f}.ant-tag-yellow-inverse{color:#fff;background:#fadb14;border-color:#fadb14}.ant-tag-gold{color:#d48806;background:#fffbe6;border-color:#ffe58f}.ant-tag-gold-inverse{color:#fff;background:#faad14;border-color:#faad14}.ant-tag-cyan{color:#08979c;background:#e6fffb;border-color:#87e8de}.ant-tag-cyan-inverse{color:#fff;background:#13c2c2;border-color:#13c2c2}.ant-tag-lime{color:#7cb305;background:#fcffe6;border-color:#eaff8f}.ant-tag-lime-inverse{color:#fff;background:#a0d911;border-color:#a0d911}.ant-tag-green{color:#389e0d;background:#f6ffed;border-color:#b7eb8f}.ant-tag-green-inverse{color:#fff;background:#52c41a;border-color:#52c41a}.ant-tag-blue{color:#096dd9;background:#e6f7ff;border-color:#91d5ff}.ant-tag-blue-inverse{color:#fff;background:#1890ff;border-color:#1890ff}.ant-tag-geekblue{color:#1d39c4;background:#f0f5ff;border-color:#adc6ff}.ant-tag-geekblue-inverse{color:#fff;background:#2f54eb;border-color:#2f54eb}.ant-tag-purple{color:#531dab;background:#f9f0ff;border-color:#d3adf7}.ant-tag-purple-inverse{color:#fff;background:#722ed1;border-color:#722ed1}.ant-tag-success{color:#52c41a;background:#f6ffed;border-color:#b7eb8f}.ant-tag-processing{color:#d03f0a;background:#fff1e6;border-color:#f7ae83}.ant-tag-error{color:#ff4d4f;background:#fff2f0;border-color:#ffccc7}.ant-tag-warning{color:#faad14;background:#fffbe6;border-color:#ffe58f}.ant-tag>.anticon+span,.ant-tag>span+.anticon{margin-left:7px}.ant-tag.ant-tag-rtl{margin-right:0;margin-left:8px;direction:rtl;text-align:right}.ant-tag-rtl .ant-tag-close-icon{margin-right:3px;margin-left:0}.ant-tag-rtl.ant-tag>.anticon+span,.ant-tag-rtl.ant-tag>span+.anticon{margin-right:7px;margin-left:0}.changeIndicators[data-v-78cd67a3]{position:absolute;display:flex;flex-direction:column;height:100%;align-items:center;justify-content:center;opacity:.6}.changeIndicatorsRight[data-v-78cd67a3]{position:absolute;right:0}.changeIndicator[data-v-78cd67a3]{margin-left:-4px;width:16px;height:16px;border-radius:2px;border:1px solid rgba(255,255,255,.2);background-color:gray;line-height:16px;margin-bottom:2px;text-align:center;font-size:6pt;font-weight:600;color:#000;z-index:9999;pointer-events:auto;box-shadow:0 0 4px #00000080}.changeIndicatorsRight .changeIndicator[data-v-78cd67a3]{margin-right:-4px;border-top-right-radius:8px;border-bottom-right-radius:8px;text-align:left;padding-left:2px}.changeIndicatorsLeft .changeIndicator[data-v-78cd67a3]{border-top-left-radius:8px;border-bottom-left-radius:8px;text-align:right;padding-right:2px}.changeIndicatorWrapper[data-v-78cd67a3]{top:0;position:absolute;user-select:none;width:100%;height:100%;z-index:999999;pointer-events:none}.hoverOverlay[data-v-78cd67a3]{display:none;background-color:#000c;color:#fff;border:1px solid gray;padding:10px 20px;border-radius:5px;z-index:100;opacity:1;font-size:8pt;line-height:1.2;overflow:hidden}.hoverOverlay ul[data-v-78cd67a3]{list-style:none;padding:0}.hoverOverlay ul li[data-v-78cd67a3]{display:inline-block;padding-left:4px;padding-right:4px;border:1px solid gray;border-radius:2px;margin:1px;font-weight:200}.changeIndicators[data-v-78cd67a3]:hover{opacity:1}.changeIndicators:hover+div.hoverOverlay[data-v-78cd67a3]{display:block;position:absolute;top:0;left:0;width:100%;height:100%}table tr td:first-child span[data-v-78cd67a3]{padding:1px 3px;display:inline-block;width:100%}table tr td[data-v-78cd67a3]:first-child{padding-right:10px;vertical-align:top}.otherChangeIndicator[data-v-78cd67a3]{background-color:#8b5b8e;color:#efefef}.stepsChangeIndicator[data-v-78cd67a3]{background-color:#577ab8;color:#efefef}.seedChangeIndicator[data-v-78cd67a3]{background-color:#649da3;color:#121}.negpromptChangeIndicator[data-v-78cd67a3]{background-color:#d8a390;color:#2f2f2f}.modelChangeIndicator[data-v-78cd67a3]{background-color:#d68679;color:#efefef}.promptChangeIndicator[data-v-78cd67a3]{background-color:#8fba99;color:#121}.cfgChangeIndicator[data-v-78cd67a3]{background-color:#d4c98f;color:#121}.sizeChangeIndicator[data-v-78cd67a3]{background-color:#678a6c;color:#efefef}.center[data-v-1c38fa7e]{display:flex;justify-content:center;align-items:center}.item-content[data-v-1c38fa7e]{position:relative}.item-content.video[data-v-1c38fa7e]{background-color:var(--zp-border);border-radius:8px;overflow:hidden;width:var(--02c5ba15);height:var(--02c5ba15);background-size:cover;background-position:center;cursor:pointer}.item-content .play-icon[data-v-1c38fa7e]{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);border-radius:100%;display:flex}.item-content .tags-container[data-v-1c38fa7e]{position:absolute;right:8px;bottom:8px;display:flex;width:calc(100% - 16px);flex-wrap:wrap-reverse;flex-direction:row-reverse}.item-content .tags-container>*[data-v-1c38fa7e]{margin:0 0 4px 4px;font-size:14px;line-height:1.6}.close-icon[data-v-1c38fa7e]{position:absolute;top:0;right:0;transform:translate(50%,-50%) scale(1.5);cursor:pointer;z-index:100;border-radius:100%;overflow:hidden;line-height:1;background-color:var(--zp-primary-background)}.file[data-v-1c38fa7e]{padding:8px 16px;margin:8px;display:flex;align-items:center;background:var(--zp-primary-background);border-radius:8px;box-shadow:0 0 4px var(--zp-secondary-variant-background);position:relative}.file:hover .more[data-v-1c38fa7e]{opacity:1}.file .more[data-v-1c38fa7e]{opacity:0;transition:all .3s ease;position:absolute;top:4px;right:4px;z-index:100;display:flex;align-items:center;justify-content:center;flex-direction:column;line-height:1em}.file .more .float-btn-wrap[data-v-1c38fa7e]{font-size:1.5em;cursor:pointer;font-size:500;padding:4px;border-radius:100vh;color:#fff;background:var(--zp-icon-bg);margin-bottom:4px}.file .more .float-btn-wrap.like-selected[data-v-1c38fa7e]{color:#df0505}.file.grid[data-v-1c38fa7e]{padding:0;display:inline-block;box-sizing:content-box;box-shadow:unset;background-color:var(--zp-secondary-background)}.file.grid[data-v-1c38fa7e] .icon{font-size:8em}.file.grid[data-v-1c38fa7e] .profile{padding:0 4px}.file.grid[data-v-1c38fa7e] .profile .name{font-weight:500;padding:0}.file.grid[data-v-1c38fa7e] .profile .basic-info{display:flex;justify-content:space-between;flex-direction:row;margin:0;font-size:.7em}.file.grid[data-v-1c38fa7e] .profile .basic-info *{white-space:nowrap;overflow:hidden}.file.grid[data-v-1c38fa7e] .ant-image,.file.grid[data-v-1c38fa7e] .preview-icon-wrap{border:1px solid var(--zp-secondary);background-color:var(--zp-secondary-variant-background);border-radius:8px;overflow:hidden}.file.grid[data-v-1c38fa7e] img:not(.dir-cover-item),.file.grid[data-v-1c38fa7e] .dir-cover-container,.file.grid[data-v-1c38fa7e] .preview-icon-wrap>[role=img]{height:var(--02c5ba15);width:var(--02c5ba15);object-fit:contain}.file.clickable[data-v-1c38fa7e]{cursor:pointer}.file.selected[data-v-1c38fa7e]{outline:#0084ff solid 2px}.file .name[data-v-1c38fa7e]{flex:1;padding:8px;word-break:break-all}.file .basic-info[data-v-1c38fa7e]{overflow:hidden;display:flex;flex-direction:column;align-items:flex-end}.file .dir-cover-container[data-v-1c38fa7e]{top:0;display:flex;flex-wrap:wrap;padding:4px}.file .dir-cover-container>img[data-v-1c38fa7e]{width:calc(50% - 8px);height:calc(50% - 8px);margin:4px;object-fit:cover;border-radius:8px;overflow:hidden}
|
extensions/sd-webui-infinite-image-browsing/vue/dist/assets/ImgSliPagePane-5f17c067.js
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
import{d as a,S as t,T as s,c as n,cx as _,Z as o}from"./index-5b5fdd56.js";const c={class:"img-sli-container"},i=a({__name:"ImgSliPagePane",props:{paneIdx:{},tabIdx:{},left:{},right:{}},setup(l){return(e,r)=>(t(),s("div",c,[n(_,{left:e.left,right:e.right},null,8,["left","right"])]))}});const d=o(i,[["__scopeId","data-v-ae3fb9a8"]]);export{d as default};
|
extensions/sd-webui-infinite-image-browsing/vue/dist/assets/ImgSliPagePane-868b21f8.css
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
.img-sli-container[data-v-ae3fb9a8]{position:relative;overflow-y:auto;height:calc(100vh - 40px)}
|