├── .github └── FUNDING.yml ├── .gitignore ├── AutoCaption.ipynb ├── EveryDream_Tools.ipynb ├── LICENSE ├── README.MD ├── activate_venv.bat ├── clip_rename.bat ├── create_venv.bat ├── deactivate_venv.bat ├── demo ├── beam_min_vs_q.webp ├── beam_vs_nucleus.webp ├── beam_vs_nucleus_2.webp ├── demo01.png ├── demo02.png ├── demo03.png ├── output_zip.png └── upload_images_caption.png ├── doc ├── AUTO_CAPTION.md ├── CAPTION_GUI.md ├── COMPRESS_IMG.md ├── FILE_RENAME.md ├── LAION_SCRAPE.md └── VIDEO_EXTRACTOR.md ├── environment.yaml ├── input └── .gitkeep ├── laion └── Put LAION parquets here.txt ├── output └── .gitkeep ├── requirements.txt └── scripts ├── auto_caption.py ├── compress_img.py ├── createtxtfromfilename.py ├── download_laion.py ├── extract_video_frames.py ├── filename_replace.py └── image_caption_gui.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: victorchall 4 | patreon: everydream 5 | ko_fi: everydream 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # EveryDream 2 | /everydream-venv/** 3 | /laion/*.parquet 4 | /output/** 5 | /.cache/** 6 | /.venv/** 7 | /input/** 8 | /scripts/BLIP 9 | /.vscode/** 10 | 11 | # Byte-compiled / optimized / DLL files 12 | __pycache__/ 13 | *.py[cod] 14 | *$py.class 15 | 16 | # C extensions 17 | *.so 18 | 19 | # Distribution / packaging 20 | .Python 21 | build/ 22 | develop-eggs/ 23 | dist/ 24 | downloads/ 25 | eggs/ 26 | .eggs/ 27 | lib/ 28 | lib64/ 29 | parts/ 30 | sdist/ 31 | var/ 32 | wheels/ 33 | pip-wheel-metadata/ 34 | share/python-wheels/ 35 | *.egg-info/ 36 | .installed.cfg 37 | *.egg 38 | MANIFEST 39 | 40 | # PyInstaller 41 | # Usually these files are written by a python script from a template 42 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 43 | *.manifest 44 | *.spec 45 | 46 | # Installer logs 47 | pip-log.txt 48 | pip-delete-this-directory.txt 49 | 50 | # Unit test / coverage reports 51 | htmlcov/ 52 | .tox/ 53 | .nox/ 54 | .coverage 55 | .coverage.* 56 | .cache 57 | nosetests.xml 58 | coverage.xml 59 | *.cover 60 | *.py,cover 61 | .hypothesis/ 62 | .pytest_cache/ 63 | 64 | # Translations 65 | *.mo 66 | *.pot 67 | 68 | # Django stuff: 69 | *.log 70 | local_settings.py 71 | db.sqlite3 72 | db.sqlite3-journal 73 | 74 | # Flask stuff: 75 | instance/ 76 | .webassets-cache 77 | 78 | # Scrapy stuff: 79 | .scrapy 80 | 81 | # Sphinx documentation 82 | docs/_build/ 83 | 84 | # PyBuilder 85 | target/ 86 | 87 | # Jupyter Notebook 88 | .ipynb_checkpoints 89 | 90 | # IPython 91 | profile_default/ 92 | ipython_config.py 93 | 94 | # pyenv 95 | .python-version 96 | 97 | # pipenv 98 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 99 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 100 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 101 | # install all needed dependencies. 102 | #Pipfile.lock 103 | 104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 105 | __pypackages__/ 106 | 107 | # Celery stuff 108 | celerybeat-schedule 109 | celerybeat.pid 110 | 111 | # SageMath parsed files 112 | *.sage.py 113 | 114 | # Environments 115 | .env 116 | .venv 117 | env/ 118 | venv/ 119 | ENV/ 120 | env.bak/ 121 | venv.bak/ 122 | 123 | # Spyder project settings 124 | .spyderproject 125 | .spyproject 126 | 127 | # Rope project settings 128 | .ropeproject 129 | 130 | # mkdocs documentation 131 | /site 132 | 133 | # mypy 134 | .mypy_cache/ 135 | .dmypy.json 136 | dmypy.json 137 | 138 | # Pyre type checker 139 | .pyre/ 140 | -------------------------------------------------------------------------------- /AutoCaption.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","metadata":{},"source":["# Please read the documentation here before you start.\n","\n","I suggest reading this doc before you connect to your runtime to avoid using credits or being charged while you figure it out.\n","\n","[Auto Captioning Readme](doc/AUTO_CAPTION.md)\n","\n","This notebook requires an Nvidia GPU instance. Any will do, you don't need anything power. As low as 4GB should be fine.\n","\n","Only colab has automatic file transfers at this time. If you are using another platform, you will need to manually download your output files."]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":929,"status":"ok","timestamp":1667184580032,"user":{"displayName":"Victor Hall","userId":"00029068894644207946"},"user_tz":240},"id":"lWGx2LuU8Q_I","outputId":"d0eb4d03-f16d-460b-981d-d5f88447e85e"},"outputs":[],"source":["#download repo\n","!git clone https://github.com/victorchall/EveryDream.git\n","# Set working directory\n","%cd EveryDream"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":4944,"status":"ok","timestamp":1667184754992,"user":{"displayName":"Victor Hall","userId":"00029068894644207946"},"user_tz":240},"id":"RJxfSai-8pkD","outputId":"0ac1b805-62a0-48aa-e0da-ee19503bb3f1"},"outputs":[],"source":["# install requirements\n","!pip install torch=='1.12.1+cu113' 'torchvision==0.13.1+cu113' --extra-index-url https://download.pytorch.org/whl/cu113\n","!pip install pandas>='1.3.5'\n","!git clone https://github.com/salesforce/BLIP scripts/BLIP\n","!pip install timm\n","!pip install fairscale=='0.4.4'\n","!pip install transformers=='4.19.2'\n","!pip install timm\n","!pip install aiofiles"]},{"cell_type":"markdown","metadata":{"id":"sbeUIVXJ-EVf"},"source":["# Upload your input images into the EveryDream/input folder\n","\n","![upload to input](demo/upload_images_caption.png)"]},{"cell_type":"markdown","metadata":{},"source":["## Please read the documentation for information on the parameters\n","\n","[Auto Captioning](doc/AUTO_CAPTION.md)\n","\n","*You cannot have commented lines between uncommented lines. If you uncomment a line below, move it above any other commented lines.*\n","\n","*!python must remain the first line.*\n","\n","Default params should work fairly well."]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":18221,"status":"ok","timestamp":1667185808005,"user":{"displayName":"Victor Hall","userId":"00029068894644207946"},"user_tz":240},"id":"4TAICahl-RPn","outputId":"da7fa1a8-0855-403a-c295-4da31658d1f6"},"outputs":[],"source":["!python scripts/auto_caption.py \\\n","--img_dir input \\\n","--out_dir output \\\n","#--format mrwho \\\n","#--min_length 34 \\\n","#--q_factor 1.3 \\\n","#--nucleus \\"]},{"cell_type":"markdown","metadata":{"id":"HBrWnu1C_lN9"},"source":["## Download your captioned images from EveryDream/output\n","\n","If you're on a colab you can use the cell below to push your output to your Gdrive."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["from google.colab import drive\n","drive.mount('/content/drive')\n","\n","!mkdir /content/drive/MyDrive/AutoCaption\n","!cp output/*.* /content/drive/MyDrive/AutoCaption"]},{"cell_type":"markdown","metadata":{},"source":["## If not on colab/gdrive, the following will zip up your files for extraction\n","\n","You'll still need to use your runtime's own download feature to download the zip.\n","\n","![output zip](demo/output_zip.png)"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["!pip install patool\n","\n","import patoolib\n","\n","!mkdir output/zip\n","\n","!zip -r output/zip/output.zip output"]}],"metadata":{"colab":{"authorship_tag":"ABX9TyN9ZSr0RyOQKdfeVsl2uOiE","collapsed_sections":[],"provenance":[{"file_id":"16QrivRfoDFvE7fAa7eLeVlxj78Q573E0","timestamp":1667185879409}]},"kernelspec":{"display_name":"Python 3.10.5 ('.venv': venv)","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.10.5"},"vscode":{"interpreter":{"hash":"faf4a6abb601e3a9195ce3e9620411ceec233a951446de834cdf28542d2d93b4"}}},"nbformat":4,"nbformat_minor":0} 2 | -------------------------------------------------------------------------------- /EveryDream_Tools.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "id": "view-in-github", 7 | "colab_type": "text" 8 | }, 9 | "source": [ 10 | "\"Open" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "source": [ 16 | "#@title #Connect to Google Drive\n", 17 | "from google.colab import drive\n", 18 | "drive.mount('/content/drive')\n" 19 | ], 20 | "metadata": { 21 | "id": "Z_ZHfnQ52dg9" 22 | }, 23 | "execution_count": null, 24 | "outputs": [] 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "metadata": { 29 | "id": "uJfwih4wAVgw" 30 | }, 31 | "source": [ 32 | "# Please read the documentation here before you start.\n", 33 | "\n", 34 | "I suggest reading this doc before you connect to your runtime to avoid using credits or being charged while you figure it out.\n", 35 | "\n", 36 | "[Auto Captioning Readme](doc/AUTO_CAPTION.md)\n", 37 | "\n", 38 | "This notebook requires an Nvidia GPU instance. Any will do, you don't need anything power. As low as 4GB should be fine.\n", 39 | "\n", 40 | "Only colab has automatic file transfers at this time. If you are using another platform, you will need to manually download your output files." 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": { 47 | "id": "lWGx2LuU8Q_I" 48 | }, 49 | "outputs": [], 50 | "source": [ 51 | "#download repo\n", 52 | "!git clone https://github.com/victorchall/EveryDream.git\n", 53 | "# Set working directory\n", 54 | "%cd EveryDream" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": null, 60 | "metadata": { 61 | "id": "RJxfSai-8pkD" 62 | }, 63 | "outputs": [], 64 | "source": [ 65 | "# install requirements\n", 66 | "!pip install torch=='1.12.1+cu113' 'torchvision==0.13.1+cu113' --extra-index-url https://download.pytorch.org/whl/cu113\n", 67 | "!pip install pandas>='1.3.5'\n", 68 | "!git clone https://github.com/salesforce/BLIP scripts/BLIP\n", 69 | "!pip install timm\n", 70 | "!pip install fairscale=='0.4.4'\n", 71 | "!pip install transformers=='4.19.2'\n", 72 | "!pip install timm\n", 73 | "!pip install aiofiles\n", 74 | "!pip install colorama" 75 | ] 76 | }, 77 | { 78 | "cell_type": "markdown", 79 | "source": [ 80 | "#Extract Frames from video\n", 81 | "\n", 82 | "Here we will use the folder input_vid and upload in the same way we did our images" 83 | ], 84 | "metadata": { 85 | "id": "huQSI8Y-Bboz" 86 | } 87 | }, 88 | { 89 | "cell_type": "code", 90 | "source": [ 91 | "!python /scripts/extract_video_frames.py \\\n", 92 | "--vid_dir input_vid \\\n", 93 | "--out_dir output/vid \\\n", 94 | "--format png \\\n", 95 | "--interval 10 " 96 | ], 97 | "metadata": { 98 | "id": "RDuBL4k8Avz-" 99 | }, 100 | "execution_count": null, 101 | "outputs": [] 102 | }, 103 | { 104 | "cell_type": "markdown", 105 | "source": [ 106 | "Move the extracted frames to the input directory for captions" 107 | ], 108 | "metadata": { 109 | "id": "iqcUzcRuCTLR" 110 | } 111 | }, 112 | { 113 | "cell_type": "code", 114 | "source": [ 115 | "!cp -r output/vid input" 116 | ], 117 | "metadata": { 118 | "id": "Uv8wAHSQAvrm" 119 | }, 120 | "execution_count": null, 121 | "outputs": [] 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "metadata": { 126 | "id": "sbeUIVXJ-EVf" 127 | }, 128 | "source": [ 129 | "# Upload your input images into the EveryDream/input folder\n", 130 | "\n", 131 | "![upload to input](https://github.com/victorchall/EveryDream/blob/main/demo/upload_images_caption.png?raw=1)" 132 | ] 133 | }, 134 | { 135 | "cell_type": "markdown", 136 | "metadata": { 137 | "id": "bscWH13SAVgz" 138 | }, 139 | "source": [ 140 | "## Please read the documentation for information on the parameters\n", 141 | "\n", 142 | "[Auto Captioning](doc/AUTO_CAPTION.md)\n", 143 | "\n", 144 | "*You cannot have commented lines between uncommented lines. If you uncomment a line below, move it above any other commented lines.*\n", 145 | "\n", 146 | "*!python must remain the first line.*\n", 147 | "\n", 148 | "Default params should work fairly well." 149 | ] 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": null, 154 | "metadata": { 155 | "id": "4TAICahl-RPn" 156 | }, 157 | "outputs": [], 158 | "source": [ 159 | "!python scripts/auto_caption.py \\\n", 160 | "--img_dir input \\\n", 161 | "--out_dir output \\\n", 162 | "#--format mrwho \\\n", 163 | "#--min_length 34 \\\n", 164 | "#--q_factor 1.3 \\\n", 165 | "#--nucleus \\\n", 166 | "\n", 167 | "## mutiple files can be targeted in succession\n", 168 | "\n", 169 | "#!python scripts/auto_caption.py \\\n", 170 | "#--img_dir input/subfolder \\\n", 171 | "#--out_dir output/subfolder \\\n", 172 | "#--format mrwho \\\n", 173 | "#--min_length 34 \\\n", 174 | "#--q_factor 1.3 \\\n", 175 | "#--nucleus \\" 176 | ] 177 | }, 178 | { 179 | "cell_type": "markdown", 180 | "source": [ 181 | "# Laion Downloader\n", 182 | "\n", 183 | "* --laion_dir: directory with laion parquet files, default is ./laion\n", 184 | "\n", 185 | "* --search_text: csv of words with AND logic, ex \\\"photo,man,dog\\\"\n", 186 | "\n", 187 | "* --out_dir: directory to download files to, ive defaulted this to inputs so they can be captioned \n", 188 | "\n", 189 | "* --log_dir: directory for logs, if ommitted will not log, logs may be large!\n", 190 | "\n", 191 | "* --column:column to search for matches, defaults is 'TEXT', but you could use 'URL' if you wanted\",\n", 192 | "\n", 193 | "* --limit: max number of matching images to download, warning: may be slightly imprecise due to concurrency and http errors, defaults is 100\n", 194 | "\n", 195 | "* --min_hw: min height AND width of image to download, default is 512\n", 196 | " \n", 197 | "* --force: forces a full download of all images, even if no search is provided, USE CAUTION!\n", 198 | "\n", 199 | "* --parquet_skip: skips the first n parquet files on disk, useful to resume\n", 200 | " \n", 201 | "* --verbose: additional logging of URL and TEXT \n", 202 | " \n", 203 | "* --test: skips downloading, for checking filters, use with \"--verbose\"\n" 204 | ], 205 | "metadata": { 206 | "id": "wY2f2LkPGSVa" 207 | } 208 | }, 209 | { 210 | "cell_type": "code", 211 | "source": [ 212 | "!python scripts/download_laion.py \\\n", 213 | "--laion_dir ./laion \\\n", 214 | "--search_text \"photo,man,dog\" \\\n", 215 | "#--out_dir input \\\n", 216 | "#--log_dir logs \\\n", 217 | "#--column TEXT \\\n", 218 | "#--limit 100 \\\n", 219 | "#--min_hw 512 \\\n", 220 | "#--force False \\\n", 221 | "#--parquet_skip 0 \\\n", 222 | "#--Verbose False \\\n", 223 | "#--test not \\\n" 224 | ], 225 | "metadata": { 226 | "id": "cxw60TTmEy2C" 227 | }, 228 | "execution_count": null, 229 | "outputs": [] 230 | }, 231 | { 232 | "cell_type": "markdown", 233 | "source": [ 234 | "Here we can take our now captioned images and replace generic terms with our subjects\n", 235 | "\n", 236 | "* --find: will search for a word in this case man\n", 237 | "\n", 238 | "* --replace: will replace our found word with in this case bob smith\n", 239 | "\n", 240 | "* --append_only: this will allow us to add a tag at he end " 241 | ], 242 | "metadata": { 243 | "id": "EBdLelNpDjYc" 244 | } 245 | }, 246 | { 247 | "cell_type": "code", 248 | "source": [ 249 | "!python scripts/filename_replace.py \\\n", 250 | "--img_dir output \\\n", 251 | "--find \"man\" \\\n", 252 | "--replace \"bob smith\"" 253 | ], 254 | "metadata": { 255 | "id": "6Y1md3OHAvhw" 256 | }, 257 | "execution_count": null, 258 | "outputs": [] 259 | }, 260 | { 261 | "cell_type": "markdown", 262 | "source": [ 263 | "Now we can chose to create text files based on our file names, this is usefull for images with very long discriptions or tag list, windows has a limit of 256 characters, and files will not transfer correctly to a windows program if they are longer, moving these files in a zip is fine however and causes no issues\n" 264 | ], 265 | "metadata": { 266 | "id": "W0MspWmXJQuc" 267 | } 268 | }, 269 | { 270 | "cell_type": "code", 271 | "source": [ 272 | "!python scripts/createtxtfromfilename.py" 273 | ], 274 | "metadata": { 275 | "id": "BpvenvyQJr9b" 276 | }, 277 | "execution_count": null, 278 | "outputs": [] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "source": [ 283 | "Compress our images " 284 | ], 285 | "metadata": { 286 | "id": "boVkDsiWJ_-P" 287 | } 288 | }, 289 | { 290 | "cell_type": "code", 291 | "source": [ 292 | "!python scripts/compress_img.py \\\n", 293 | "--img_dir output \\\n", 294 | "--out_dir output/compressed_images \\\n", 295 | "--max_mp 1.5 \n", 296 | "#--overwrite False \\\n", 297 | "#--Quality 95 \\\n", 298 | "#--noresize False \\\n", 299 | "#--delete \\" 300 | ], 301 | "metadata": { 302 | "id": "F6QYfylhKAII" 303 | }, 304 | "execution_count": null, 305 | "outputs": [] 306 | }, 307 | { 308 | "cell_type": "markdown", 309 | "metadata": { 310 | "id": "HBrWnu1C_lN9" 311 | }, 312 | "source": [ 313 | "## Download your DataSet from EveryDream/output\n", 314 | "\n", 315 | "If you're on a colab you can use the cell below to push your output to your Gdrive." 316 | ] 317 | }, 318 | { 319 | "cell_type": "code", 320 | "execution_count": null, 321 | "metadata": { 322 | "id": "ldW2sDLcAVgz" 323 | }, 324 | "outputs": [], 325 | "source": [ 326 | "\n", 327 | "!mkdir /content/drive/MyDrive/Auto_Data_sets\n", 328 | "!cp -r output/ /content/drive/MyDrive/Auto_Data_sets" 329 | ] 330 | }, 331 | { 332 | "cell_type": "markdown", 333 | "metadata": { 334 | "id": "B-HFqbP4AVgz" 335 | }, 336 | "source": [ 337 | "## If not on colab/gdrive, the following will zip up your files for extraction\n", 338 | "\n", 339 | "You'll still need to use your runtime's own download feature to download the zip.\n", 340 | "\n", 341 | "![output zip](https://github.com/victorchall/EveryDream/blob/main/demo/output_zip.png?raw=1)" 342 | ] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": null, 347 | "metadata": { 348 | "id": "SVa80mrKAVg0" 349 | }, 350 | "outputs": [], 351 | "source": [ 352 | "!pip install patool\n", 353 | "\n", 354 | "import patoolib\n", 355 | "\n", 356 | "!mkdir output/zip\n", 357 | "\n", 358 | "!zip -r output/zip/output.zip output" 359 | ] 360 | } 361 | ], 362 | "metadata": { 363 | "colab": { 364 | "provenance": [], 365 | "machine_shape": "hm", 366 | "include_colab_link": true 367 | }, 368 | "kernelspec": { 369 | "display_name": "Python 3.10.5 ('.venv': venv)", 370 | "language": "python", 371 | "name": "python3" 372 | }, 373 | "language_info": { 374 | "name": "python", 375 | "version": "3.10.5" 376 | }, 377 | "vscode": { 378 | "interpreter": { 379 | "hash": "faf4a6abb601e3a9195ce3e9620411ceec233a951446de834cdf28542d2d93b4" 380 | } 381 | }, 382 | "accelerator": "GPU", 383 | "gpuClass": "standard" 384 | }, 385 | "nbformat": 4, 386 | "nbformat_minor": 0 387 | } 388 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 | # EveryDream Tools 2 | 3 | This repo will contain tools for data engineering efforts for people interested in taking their fine tuning beyond the initial DreamBooth paper implementations for Stable Diffusion, and may be useful for other image projects. 4 | 5 | If you are looking for trainers, check out [EveryDream 2.0](https://github.com/victorchall/EveryDream2trainer). This is just a toolkit repo for data work but works in concert with that trainer. 6 | 7 | For instance with Stable Diffusion, by using ground truth Laion data mixed in with training data to replace "regularization" images, together with clip-interrogated captioning or original TEXT caption from laion, or human-geneated labels, training quality can be improved. These are a significant steps towards towards full fine tuning capabilities. 8 | 9 | Captioned training together with regularization has enabled multi-subject and multi-style training at the same time, and can scale to larger training efforts. 10 | 11 | As an example project, you can download a large scale model for Final Fantasy 7 Remake here: https://huggingface.co/panopstor/ff7r-stable-diffusion and be sure to also follow up on the gist link at the bottom for more information along with links to example output of a multi-model fine tuning. 12 | 13 | Join the EveryDream discord here: https://discord.gg/uheqxU6sXN 14 | 15 | ## Tools 16 | 17 | [Download scrapes using Laion](./doc/LAION_SCRAPE.md) - Web scrapes images off the web using Laion data files (runs on CPU). 18 | 19 | [Auto Captioning](./doc/AUTO_CAPTION.md) - Uses BLIP interrogation to caption images for training (includes colab notebook, needs minimal GPU). 20 | 21 | [File renaming](./doc/FILE_RENAME.md) - Simple script for replacing generic pronouns that come out of clip in filenames with proper names (ex "a man" -> "john doe", "a person" -> "jane doe"). 22 | 23 | *See clip_rename.bat for an example to chain captioning and renaming together.* 24 | 25 | [Compress images](./doc/COMPRESS_IMG.md) - Compresses images to WEBP with a given size (ex 1.5 megapixels) to reduce disk usage if you've downloaded some massive PNG data sets (ex. FFHQ) and wish to save some disk space. 26 | 27 | [Training](https://github.com/victorchall/EveryDream2trainer) (separate repo) - Fine tuning 28 | 29 | [Image Caption GUI](./doc/CAPTION_GUI.md) and [Video frame extractor](./doc/VIDEO_EXTRACTOR.md) courtesy of [MStevenson](https://github.com/mstevenson/) 30 | 31 | [General Tools Notebook](EveryDream_Tools.ipynb) Collection of various tools in this codebase by [Nawnie](https://github.com/nawnie) if you prefer to use Notebook GUI instead of the command line. 32 | 33 | ## Install 34 | 35 | You can use conda or venv. This was developed on Python 3.10.5 but may work on older newer versions. 36 | 37 | One step venv setup: 38 | 39 | create_venv.bat 40 | 41 | Don't forget to activate every time you open the command prompt later. 42 | 43 | activate_venv.bat 44 | 45 | To use conda instead of venv: 46 | 47 | conda env create -f environment.yaml 48 | 49 | pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113 50 | 51 | git clone https://github.com/salesforce/BLIP scripts/BLIP 52 | 53 | conda activate everydream 54 | 55 | Or you if you wish to configure your own venv, container/WSL, or Linux: 56 | 57 | pip install -r requirements.txt 58 | 59 | pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113 60 | 61 | git clone https://github.com/salesforce/BLIP scripts/BLIP 62 | 63 | Thanks to the SalesForce team for the [BLIP tool](https://github.com/salesforce/BLIP). It uses CLIP to produce sane sentences like you would expect to see in alt-text. 64 | -------------------------------------------------------------------------------- /activate_venv.bat: -------------------------------------------------------------------------------- 1 | call .venv/scripts/activate.bat -------------------------------------------------------------------------------- /clip_rename.bat: -------------------------------------------------------------------------------- 1 | python scripts/auto_caption.py --q_factor 1.4 2 | ::python scripts/filename_replace.py --img_dir output --find "a woman" --replace "rihanna" 3 | ::python scripts/filename_replace.py --img_dir output --find "a person" --replace "rihanna" 4 | ::python scripts/filename_replace.py --img_dir output --find "a man" --replace "asap rocky" 5 | ::python scripts/filename_replace.py --img_dir output --replace "Keira Knightley" 6 | ::python scripts/filename_replace.py --img_dir output --append "by Giotto" 7 | -------------------------------------------------------------------------------- /create_venv.bat: -------------------------------------------------------------------------------- 1 | python -m venv .venv 2 | call .venv/scripts/activate.bat 3 | if %errorlevel% neq 0 goto :error 4 | pip install -r requirements.txt 5 | pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113 6 | git clone https://github.com/salesforce/BLIP scripts/BLIP 7 | if %errorlevel% neq 0 goto :error 8 | 9 | goto :done 10 | 11 | :error 12 | echo Error occurred trying to install or activate venv. 13 | exit /b %errorlevel% 14 | 15 | :done -------------------------------------------------------------------------------- /deactivate_venv.bat: -------------------------------------------------------------------------------- 1 | call .venv/scripts/deactivate.bat -------------------------------------------------------------------------------- /demo/beam_min_vs_q.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorchall/EveryDream/51edb0c568da17c27579a47cc17e504df715f7d1/demo/beam_min_vs_q.webp -------------------------------------------------------------------------------- /demo/beam_vs_nucleus.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorchall/EveryDream/51edb0c568da17c27579a47cc17e504df715f7d1/demo/beam_vs_nucleus.webp -------------------------------------------------------------------------------- /demo/beam_vs_nucleus_2.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorchall/EveryDream/51edb0c568da17c27579a47cc17e504df715f7d1/demo/beam_vs_nucleus_2.webp -------------------------------------------------------------------------------- /demo/demo01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorchall/EveryDream/51edb0c568da17c27579a47cc17e504df715f7d1/demo/demo01.png -------------------------------------------------------------------------------- /demo/demo02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorchall/EveryDream/51edb0c568da17c27579a47cc17e504df715f7d1/demo/demo02.png -------------------------------------------------------------------------------- /demo/demo03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorchall/EveryDream/51edb0c568da17c27579a47cc17e504df715f7d1/demo/demo03.png -------------------------------------------------------------------------------- /demo/output_zip.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorchall/EveryDream/51edb0c568da17c27579a47cc17e504df715f7d1/demo/output_zip.png -------------------------------------------------------------------------------- /demo/upload_images_caption.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorchall/EveryDream/51edb0c568da17c27579a47cc17e504df715f7d1/demo/upload_images_caption.png -------------------------------------------------------------------------------- /doc/AUTO_CAPTION.md: -------------------------------------------------------------------------------- 1 | # Automatic captioning 2 | 3 | Automatic captioning uses Salesforce's BLIP to automatically create a clean sentence structure for captioning input images before training. 4 | 5 | By default this requires an Nvidia GPU, but is not terribly intensive work. It should run fine on something like a 1050 Ti 4GB. You can even run this on the CPU by specifying `--torch_device cpu` as an argument. This will be slower than running on a Nvidia GPU, but will work even on Apple Silicon Macs. 6 | 7 | [EveryDream trainer](https://github.com/victorchall/EveryDream-trainer) no longer requires cropped images. You only need to crop to exclude stuff you don't want trained, or to improve the portion of face close ups in your data. The EveryDream trainer now accepts multiple aspect ratios and can train on them natively. 8 | 9 | But if you do wish to crop for other trainers, you can use [Birme](https://www.birme.net/?target_width=512&target_height=512&auto_focal=false&image_format=webp&quality_jpeg=95&quality_webp=99) to crop and resize first. There are various tools out there for this. 10 | 11 | 12 | 13 | ## Execute 14 | 15 | Place input files into the /input folder 16 | 17 | python scripts/auto_caption.py 18 | 19 | Files will be **copied** and renamed to the caption as the file name and placed into /output. 20 | 21 | ## Colab notebook 22 | 23 | This will run quite well on a T4 instance on Google Colab. Don't waste credits on more powerful GPUs. 24 | 25 | https://colab.research.google.com/github/victorchall/EveryDream/blob/main/AutoCaption.ipynb 26 | 27 | It should work on other GPU providers on minimal power Nvidia GPU instances, but you are on your own to upload and download files. 28 | 29 | ## Additional command line args: 30 | 31 | ### --img_dir 32 | 33 | Changes the default input directory to read for files. Default is /input 34 | 35 | python scripts/auto_caption.py --img_dir x:/data/my_cropped_images 36 | 37 | ### --out_dir 38 | 39 | Changes the default output directory. Default is /output 40 | 41 | python scripts/auto_caption.py --out_dir x:/data/ready_to_train 42 | 43 | ### --format 44 | 45 | The default behavior will simply name the file the caption .EXT and, if needed, add _n at the end to avoid collisions, for use with EveryDream trainer or Kane Wallmann's dream booth fork. 46 | 47 | ex output: *"a man in a blue suit and a woman in a black dress standing next to each other in front of a table with a potted plant on it.jpg"* 48 | 49 | "mrwho" or "joepenna" will add \[number\]@ as a prefix for use with MrWho's captioning system (on JoePenna dream both fork) which uses that naming standard to avoid file name collisions. 50 | 51 | python scripts/auto_caption.py --format "mrwho" 52 | 53 | "txt" or "caption" will create a ".txt" or ".caption" file instead of renaming the image. ".txt" sidecar is another option for EveryDream trainer instead of getting the caption from the filename itself, and ".caption" is an option for other trainers. 54 | 55 | python scripts/auto_caption.py --format "txt" 56 | 57 | or 58 | 59 | python scripts/auto_caption.py --format "caption" 60 | ## Tweaks 61 | 62 | You may find the following setting useful to deal with issues with bad auto-captioning. Start with defaults, and if you have issues with captions that seem inaccurate or reptitious try some of the following settings. 63 | 64 | ### --nucleus 65 | 66 | Uses an alternative "nucleus" algorithm instead of the default "beam 16" algorithm. Nucleus produces relatively short captions but reliably absent of repeated words and phrases, comparable to using beam 16 which can be adjusted further but may need more tweaking. 67 | 68 | 69 | python scripts/auto_caption.py --nucleus 70 | 71 | ![Beam vs Nucleus](../demo/beam_vs_nucleus.webp) 72 | 73 | See q_factor below. 0.3 to 3 seem to produce sensible prompts, though 0.01 and 2000 will still work fairly well. 74 | 75 | Additional caption example for above with nucleus with different q_factor values: 76 | 77 | nucleus q_factor 9999: *"a number of kites painted in different colors in a ceiling"* 78 | 79 | nucleus q_factor 200: *"a group of people waiting under art hanging from a ceiling"* 80 | 81 | nucleus q_factor 1: *"several people standing around with large colorful umbrellas"* 82 | 83 | nucleus q_factor 0.01: *"people are standing in an open building with colorful paper decorations"* 84 | 85 | nucleus q_factor 0.00001: (same as above) 86 | 87 | ### --q_factor 88 | 89 | An tuning adjustment depending the algorithm used. 90 | 91 | For the default beam 16 algorithm it limits the ability of words and phrases to be repeated. Higher value reduces repeated words and phrases. 0.6-1.4 are sensible values for beam 16. Default is 1.0 and works well with the defaulted value min_length of 24. Consider using higher values if you use a min_length higher than 24 with beam 16. 92 | 93 | For nucleus (--nucleus), it simply changes the opinion on the prompt and does not impact repeats. Values ranging from 0.01 to 200 seem sensible and default of 1.0 usually works well. 94 | 95 | ![Beam vs Nucleus](../demo/beam_vs_nucleus_2.webp) 96 | 97 | ### --min_length 98 | 99 | Adjusts the minimum length of prompt, measured in tokens. **Only applies to beam 16.** Useful to adjust along with --q_factor to keep it from repeating. 100 | 101 | Default is 22. Sensible values are 15 to 30, max is 48. Larger values are much more prone to repeating phrases and should be accompanied by increasing --q_factor to avoid repeats. 102 | 103 | python scripts/auto_caption.py --min_length 20 104 | 105 | python scripts/auto_caption.py --min_length 34 --q_factor 1.4 106 | 107 | ![Q vs Min for beam](../demo/beam_min_vs_q.webp) 108 | 109 | ### Note 110 | 111 | If you continue to both increase min_length and q_factor with default beam algorithm in an attempt to get a really long caption without repeats it will generate oddly specific prompts. For example using the above image: 112 | 113 | --q_factor 1.9 --min_length 48: 114 | 115 | *"a painting of a group of people sitting at a table in a room with red drapes on the walls and gold trimmings on the ceiling, while one person is holding a wine glass in front of the other hand"* 116 | -------------------------------------------------------------------------------- /doc/CAPTION_GUI.md: -------------------------------------------------------------------------------- 1 | # MStevenson's tools 2 | 3 | ## Caption GUI 4 | 5 | python scripts/image_caption_gui.py 6 | 7 | Python GUI tool to manually caption images for machine learning. 8 | 9 | A sidecar file is created for each image with the same name and a .txt extension. These are compatible with EveryDream Trainer. 10 | 11 | ### Controls: 12 | [control/command + o] to open a folder of images. 13 | 14 | [page down] and [page up] to go to next and previous images. Hold shift to skip 10 images. 15 | 16 | [shift + home] and [shift + end] to go to first and last images. 17 | 18 | [shift + delete] to move the current image into a '_deleted' folder. 19 | 20 | [escape] to exit the app. -------------------------------------------------------------------------------- /doc/COMPRESS_IMG.md: -------------------------------------------------------------------------------- 1 | # Mass compressing images in a folder 2 | 3 | ## How it Works 4 | 5 | This script will sweep a folder and compress all the images to a given total number of megapixels. Aspect ratio is not changed and nothing is cropped. 6 | 7 | *Images will only be resized if they exceed the specified megapixel limit.* Images within the limit will not be resized. 8 | 9 | This script will also correct issues with images having EXIF directives that rotate the image. Or, in other words, it will make sure the proper orientation is saved native to the output image as trainers may not respect EXIF rotation directives. 10 | 11 | EXIF rotation correction will take place regardless of whether images are resized. 12 | 13 | Note this script will not attempt to copy or move any ICC color profiles at this time. Trainers likely do not respect this anyway... 14 | 15 | Defaults are 1.5 megapixels, output is WEBPb at "quality 95" which affects the compression ratio. 90-99 are sane values for quality. For the purposes of training stable diffusion, 1.5 megapixels is a good balance between quality and file size, and quality of 90-99 is as well. 16 | 17 | If you are hoping to use massive training files in the future as tech advances, you may wish to change the --max_mp setting to a higher value, but for now 1.5MP is more than enough to last for a few more advances in the technology. Ultimately this is your choice. EveryDream trainer is built to handle multiple aspects, but if you want to use images for another trainer and will crop square, you may wish to use a higher value to make sure the images remain large after croppy, or consider cropping carefully first *before* running this script. 18 | 19 | ## Usage 20 | 21 | usage: compress_img.py [-h] [--img_dir IMG_DIR] [--out_dir OUT_DIR] 22 | [--max_mp MAX_MP] [--quality QUALITY] [--overwrite] 23 | [--noresize] [--delete] 24 | 25 | Compress images in a directory. 26 | 27 | options: 28 | -h, --help show this help message and exit 29 | --img_dir IMG_DIR path to image directory (default: 'input') 30 | --out_dir OUT_DIR path to output directory (default: IMG_DIR) 31 | --max_mp MAX_MP maximum megapixels (default: 1.5) 32 | --quality QUALITY save quality (default: 95, range: 0-100, suggested: 90+) 33 | --overwrite overwrite files in output directory 34 | --noresize do not resize, just fix orientation 35 | --delete delete original files after processing 36 | 37 | The most basic use will load images from the local `input` directory, scale and rotate all the images, then write them back to the same folder. Default size is 1.5 megapixels. 38 | 39 | python scripts/compress_img.py 40 | 41 | To specify the image source directory, specify the `--img_dir`: 42 | 43 | python scripts/compress_img.py --img_dir Q:\big_images 44 | 45 | To save compressed images to a different path, specify the `--out_dir`: 46 | 47 | python scripts/compress_img.py --img_dir Q:\big_images --out_dir Q:\small_images 48 | 49 | If a specific image already exists in the output path, **it will be skipped**. For example, if you run the script twice, existing `.webp` images in the output directory will be skipped entirely. To overwrite existing files, use the `--overwrite` directive: 50 | 51 | python scripts/compress_img.py --img_dir Q:\big_images --overwrite 52 | 53 | If you want to ensure no files are skipped, *without overwriting existing images,* use `--out_dir` to specify an empty output folder. 54 | 55 | If you want to delete the *original source image* after it has been resized, use the `--delete` directive: 56 | 57 | python scripts/compress_img.py --img_dir Q:\big_images --delete 58 | 59 | The `--delete` directive will not delete the original if it was overwritten or skipped. 60 | 61 | To change the max megapixels, use the `--max_mp` option. For example, to set max megapixels to 2.0 and overwrite existing images in the output directory, see this example: 62 | 63 | python scripts/compress_img.py --img_dir Q:\big_images --out_dir Q:\small_images --max_mp 2.0 --overwrite 64 | 65 | Once you are comfortable with what is going on and OK with removing original images, you can use this to just replace everything in-place (these are my preferred settings): 66 | 67 | python scripts/compress_img.py --img_dir Q:\big_images --max_mp 1.5 --quality 99 --overwrite --delete 68 | 69 | This will compress all images in the `Q:\big_images` directory down to a maximum `1.5` megapixels, at quality `99`, and will `overwrite` any existing output images and `delete` the original, un-altered image. 70 | -------------------------------------------------------------------------------- /doc/FILE_RENAME.md: -------------------------------------------------------------------------------- 1 | # Filename Replace 2 | 3 | This is a very simple script to rename generic pronouns in files to proper names after using auto captioning. This script does not create copies. It renames the files in place. 4 | 5 | By default, it will replace "a man", "a woman", and "a person" with your supplied proper name. This works well for single subject without tweaking. 6 | 7 | 8 | ## Usage 9 | 10 | python scripts/filename_replace.py --img_dir output --replace "john doe" 11 | 12 | *"a man standing in a park with birds on his shoulders.jpg" 13 | -> 14 | "john doe standing in a park with birds on his shoulders.jpg"* 15 | 16 | ## Append tags only 17 | 18 | python scripts/filename_replace.py --img_dir "x:\myfiles" --append_only " by claude monet" 19 | 20 | This will simply append " by claude monet" without replacing anything, useful to add tags or artstyle keywords. 21 | 22 | ## Chaining with auto caption 23 | 24 | You can chain together the auto_caption.py and file_rename.py to help deal with multiple people in photos in a simple shell script (bash or windows .bat) with a bit of thinking about what you replace and using --find to specify the pronoun to replace first more specifically than all three default pronouns. 25 | 26 | python scripts/auto_caption.py --q_factor 1.4 --img_dir input --out_dir output 27 | python scripts/filename_replace.py --img_dir output --find "a woman" --replace "rihanna" 28 | python scripts/filename_replace.py --img_dir output --replace "asap rocky" 29 | 30 | "a man and a woman standing next to each other in front of a green wall with leaves on it.webp" 31 | -> 32 | "asap rocky and rihanna standing next to each other in front of a green wall with leaves on it.webp" 33 | 34 | See clip_rename.bat in the root folder, modify it to your needs. 35 | 36 | Renaming is nearly instant as it is just renaming the files and not using and AI models or calculations, just a dumb find and replace on the filename. 37 | -------------------------------------------------------------------------------- /doc/LAION_SCRAPE.md: -------------------------------------------------------------------------------- 1 | # download_laion.py 2 | 3 | ![](../demo/demo03.png) 4 | 5 | This script enables you to webscrape using the Laion parquet files which are available on Huggingface.co. 6 | 7 | It has been tested with 2B-en-aesthetic, but may need minor tweaks for some other datasets that contain different columns. Keep in mind some other files are purely sidecar metadata. 8 | 9 | https://huggingface.co/datasets/laion/laion2B-en-aesthetic 10 | 11 | **This tool does not work unless you download a set of Laion parquet files, above link is suggested.** Download all 128 .parquet files and place them in the /laion folder. 12 | 13 | The script will rename downloaded files to the best of its ability to the TEXT (caption) of the image with the original file extension, which can be plugged into the new class of caption-capable DreamBooth apps or the EveryDream trainer that will use the filename as the prompt for training. 14 | 15 | One suggested use is to take this data and replace regularization images with ground truth data from the Laion dataset. 16 | 17 | It should execute quite quickly as it uses async task gathers for the the HTTP and fileio work. 18 | 19 | Default folders are /laion for the parquet files and /output for downloaded images relative to the root folder, but consider disk space and point to another location if needed. 20 | 21 | ## Examples 22 | 23 | Query all the parquet files in ./laion for any image with a caption (TEXT) containing "a man" and attempt top stop after downloading (approximately) 50 files: 24 | 25 | python scripts/download_laion.py --search_text "a man" --limit 50 26 | 27 | Query for person with a leading and trailing space: 28 | 29 | python scripts/download_laion.py --search_text " person " --limit 200 30 | 31 | Query for both "man" and "photo" anywhere in the caption, and write them to z:/myDumpFolder instead of the default folder. Useful if you need to put them on another drive, NAS, etc. The default limit of 100 images will apply since --limit is omitted: 32 | 33 | python scripts/download_laion.py --search_text "man,photo" --out_dir "z:/myDumpFolder" --laion_dir "x:/datahoard/laion5b" 34 | 35 | ## Performance 36 | 37 | Script should be reasonably fast depending on your internet speed. I'm able to pull 10,000 images in about 3 1/2 minutes on 1 Gbit fiber. 38 | 39 | ## Other resources 40 | 41 | Nvidia has compiled a close up photo set: [ffhq-dataset](https://github.com/NVlabs/ffhq-dataset) 42 | 43 | ## Batch run 44 | 45 | You can throw commands in a shell/cmd script to run several searches, but I will leave this exercise to the user. 46 | 47 | python scripts/download_laion.py --search_text "jan van eyck" --limit 200 48 | python scripts/download_laion.py --search_text " hokusai" --limit 200 49 | python scripts/download_laion.py --search_text " bernini" --limit 200 50 | python scripts/download_laion.py --search_text "Gustav Klimt" --limit 200 51 | python scripts/download_laion.py --search_text "engon Schiele" --limit 200 52 | -------------------------------------------------------------------------------- /doc/VIDEO_EXTRACTOR.md: -------------------------------------------------------------------------------- 1 | # Video frame extractor 2 | 3 | ## Usage 4 | 5 | Place video files into the top level of a directory. 6 | 7 | Execute `python scripts/extract_video_frames.py --vid_dir path/to/videos` to iterate over all files, extract frames at regular intervals, and save full resolution frame images to disk. 8 | 9 | This tool supports a wide variety of input video containers and codecs (via OpenCV), and exports jpg or png files. 10 | 11 | ## Arguments 12 | 13 | ### --vid_dir 14 | 15 | Required directory path for input video files. 16 | 17 | ### --out_dir 18 | 19 | Optional directory path in which to store extracted frame images. Defaults to a directory named 'output' that will be created inside the specified videos directory. 20 | 21 | ### --format 22 | 23 | The format for image files saved to disk. Defaults to `png`, or optionally `jpg`. 24 | 25 | ### --interval 26 | 27 | The number of seconds between frame captures. Defaults to 10 seconds. 28 | -------------------------------------------------------------------------------- /environment.yaml: -------------------------------------------------------------------------------- 1 | name: edtools 2 | dependencies: 3 | - pandas>=1.4.3 4 | - aiofiles>=22.1.0 5 | - colorama>=0.4.5 6 | - aiohttp>=3.8.3 7 | - timm 8 | - fairscale==0.4.4 9 | - transformers==4.19.2 10 | -------------------------------------------------------------------------------- /input/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorchall/EveryDream/51edb0c568da17c27579a47cc17e504df715f7d1/input/.gitkeep -------------------------------------------------------------------------------- /laion/Put LAION parquets here.txt: -------------------------------------------------------------------------------- 1 | Suggested set is here: https://huggingface.co/datasets/laion/laion2B-en-aesthetic 2 | this is the default folder unless specified otherwise -------------------------------------------------------------------------------- /output/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/victorchall/EveryDream/51edb0c568da17c27579a47cc17e504df715f7d1/output/.gitkeep -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pandas>=1.4.3 2 | pyarrow>=9.0.0 3 | aiofiles>=22.1.0 4 | colorama>=0.4.5 5 | aiohttp>=3.8.3 6 | #open_clip_torch>=1.26.12 7 | timm 8 | fairscale==0.4.4 9 | transformers==4.19.2 10 | opencv-python>=4.6.0 -------------------------------------------------------------------------------- /scripts/auto_caption.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import glob 3 | import os 4 | from PIL import Image 5 | import sys 6 | from torchvision import transforms 7 | from torchvision.transforms.functional import InterpolationMode 8 | import torch 9 | import aiohttp 10 | import asyncio 11 | import subprocess 12 | import numpy as np 13 | import io 14 | import aiofiles 15 | 16 | SIZE = 384 17 | BLIP_MODEL_URL = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth' 18 | 19 | def get_parser(**parser_kwargs): 20 | parser = argparse.ArgumentParser(**parser_kwargs) 21 | parser.add_argument( 22 | "--img_dir", 23 | type=str, 24 | nargs="?", 25 | const=True, 26 | default="input", 27 | help="directory with images to be captioned", 28 | ), 29 | parser.add_argument( 30 | "--out_dir", 31 | type=str, 32 | nargs="?", 33 | const=True, 34 | default="output", 35 | help="directory to put captioned images", 36 | ), 37 | parser.add_argument( 38 | "--format", 39 | type=str, 40 | nargs="?", 41 | const=True, 42 | default="filename", 43 | help="'filename', 'mrwho', 'txt', or 'caption'", 44 | ), 45 | parser.add_argument( 46 | "--nucleus", 47 | type=bool, 48 | nargs="?", 49 | const=True, 50 | default=False, 51 | help="use nucleus sampling instead of beam", 52 | ), 53 | parser.add_argument( 54 | "--q_factor", 55 | type=float, 56 | nargs="?", 57 | const=True, 58 | default=1.0, 59 | help="adjusts the likelihood of a word being repeated", 60 | ), 61 | parser.add_argument( 62 | "--min_length", 63 | type=int, 64 | nargs="?", 65 | const=True, 66 | default=22, 67 | help="adjusts the likelihood of a word being repeated", 68 | ), 69 | parser.add_argument( 70 | "--torch_device", 71 | type=str, 72 | nargs="?", 73 | const=False, 74 | default="cuda", 75 | help="specify a different torch device, e.g. 'cpu'", 76 | ), 77 | 78 | return parser 79 | 80 | def load_image(raw_image, device): 81 | transform = transforms.Compose([ 82 | #transforms.CenterCrop(SIZE), 83 | transforms.Resize((SIZE, SIZE), interpolation=InterpolationMode.BICUBIC), 84 | transforms.ToTensor(), 85 | transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) 86 | ]) 87 | image = transform(raw_image).unsqueeze(0).to(device) 88 | return image 89 | 90 | def get_out_file_name(out_dir, base_name, ext): 91 | return os.path.join(out_dir, f"{base_name}{ext}") 92 | 93 | async def main(opt): 94 | print("starting") 95 | import models.blip 96 | 97 | sample = False 98 | if opt.nucleus: 99 | sample = True 100 | 101 | input_dir = opt.img_dir 102 | print("input_dir: ", input_dir) 103 | 104 | config_path = "scripts/BLIP/configs/med_config.json" 105 | 106 | cache_folder = ".cache" 107 | model_cache_path = ".cache/model_base_caption_capfilt_large.pth" 108 | 109 | if not os.path.exists(cache_folder): 110 | os.makedirs(cache_folder) 111 | 112 | if not os.path.exists(opt.out_dir): 113 | os.makedirs(opt.out_dir) 114 | 115 | if not os.path.exists(model_cache_path): 116 | print(f"Downloading model to {model_cache_path}... please wait") 117 | 118 | async with aiohttp.ClientSession() as session: 119 | async with session.get(BLIP_MODEL_URL) as res: 120 | with open(model_cache_path, 'wb') as f: 121 | async for chunk in res.content.iter_chunked(1024): 122 | f.write(chunk) 123 | print(f"Model cached to: {model_cache_path}") 124 | else: 125 | print(f"Model already cached to: {model_cache_path}") 126 | 127 | blip_decoder = models.blip.blip_decoder(pretrained=model_cache_path, image_size=SIZE, vit='base', med_config=config_path) 128 | blip_decoder.eval() 129 | 130 | print(f"loading model to {opt.torch_device}") 131 | 132 | blip_decoder = blip_decoder.to(torch.device(opt.torch_device)) 133 | 134 | ext = ('.jpg', '.jpeg', '.png', '.webp', '.tif', '.tga', '.tiff', '.bmp', '.gif') 135 | 136 | i = 0 137 | 138 | for idx, img_file_name in enumerate(glob.iglob(os.path.join(opt.img_dir, "*.*"))): 139 | if img_file_name.endswith(ext): 140 | caption = None 141 | file_ext = os.path.splitext(img_file_name)[1] 142 | if (file_ext in ext): 143 | async with aiofiles.open(img_file_name, "rb") as input_file: 144 | print("working image: ", img_file_name) 145 | 146 | image_bin = await input_file.read() 147 | image = Image.open(io.BytesIO(image_bin)) 148 | 149 | if not image.mode == "RGB": 150 | image = image.convert("RGB") 151 | 152 | image = load_image(image, device=torch.device(opt.torch_device)) 153 | 154 | if opt.nucleus: 155 | captions = blip_decoder.generate(image, sample=True, top_p=opt.q_factor) 156 | else: 157 | captions = blip_decoder.generate(image, sample=sample, num_beams=16, min_length=opt.min_length, \ 158 | max_length=48, repetition_penalty=opt.q_factor) 159 | 160 | caption = captions[0] 161 | 162 | if opt.format in ["mrwho","joepenna"]: 163 | prefix = f"{i:05}@" 164 | i += 1 165 | caption = prefix+caption 166 | elif opt.format == "filename": 167 | postfix = f"_{i}" 168 | i += 1 169 | caption = caption+postfix 170 | 171 | if opt.format in ["txt","text","caption"]: 172 | out_base_name = os.path.splitext(os.path.basename(img_file_name))[0] 173 | 174 | if opt.format in ["txt","text"]: 175 | out_file = get_out_file_name(opt.out_dir, out_base_name, ".txt") 176 | 177 | if opt.format in ["caption"]: 178 | out_file = get_out_file_name(opt.out_dir, out_base_name, ".caption") 179 | 180 | if opt.format in ["txt","text","caption"]: 181 | print("writing caption to: ", out_file) 182 | async with aiofiles.open(out_file, "w") as out_file: 183 | await out_file.write(caption) 184 | 185 | if opt.format in ["filename", "mrwho", "joepenna"]: 186 | caption = caption.replace("/", "").replace("\\", "") # must clean slashes using filename 187 | out_file = get_out_file_name(opt.out_dir, caption, file_ext) 188 | async with aiofiles.open(out_file, "wb") as out_file: 189 | await out_file.write(image_bin) 190 | elif opt.format == "json": 191 | raise NotImplementedError 192 | elif opt.format == "parquet": 193 | raise NotImplementedError 194 | 195 | def isWindows(): 196 | return sys.platform.startswith("win") 197 | 198 | if __name__ == "__main__": 199 | parser = get_parser() 200 | opt = parser.parse_args() 201 | 202 | if opt.format not in ["filename", "mrwho", "joepenna", "txt", "text", "caption"]: 203 | raise ValueError("format must be 'filename', 'mrwho', 'txt', or 'caption'") 204 | 205 | if (isWindows()): 206 | print("Windows detected, using asyncio.WindowsSelectorEventLoopPolicy") 207 | asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) 208 | else: 209 | print("Unix detected, using default asyncio event loop policy") 210 | 211 | if not os.path.exists("scripts/BLIP"): 212 | print("BLIP not found, cloning BLIP repo") 213 | subprocess.run(["git", "clone", "https://github.com/salesforce/BLIP", "scripts/BLIP"]) 214 | blip_path = "scripts/BLIP" 215 | sys.path.append(blip_path) 216 | 217 | asyncio.run(main(opt)) 218 | -------------------------------------------------------------------------------- /scripts/compress_img.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """Compress images in a folder to a maximum megapixel size.""" 4 | 5 | import argparse 6 | import asyncio 7 | import os 8 | from concurrent.futures import ThreadPoolExecutor, as_completed 9 | from glob import iglob 10 | from multiprocessing import cpu_count 11 | from queue import Queue 12 | 13 | from PIL import Image, ImageFile, ImageOps 14 | 15 | # Prevent errors from halting the script. 16 | ImageFile.LOAD_TRUNCATED_IMAGES = True 17 | Image.warnings.simplefilter("error", Image.DecompressionBombWarning) 18 | 19 | VERSION = "2.0" 20 | SHORT_DESCRIPTION = "Compress images in a directory." 21 | SUPPORTED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp"] 22 | 23 | 24 | def get_args(**parser_kwargs): 25 | """Get command-line options.""" 26 | parser = argparse.ArgumentParser(**parser_kwargs) 27 | parser.add_argument( 28 | "--img_dir", 29 | type=str, 30 | default="input", 31 | help="path to image directory (default: 'input')", 32 | ) 33 | parser.add_argument( 34 | "--out_dir", 35 | type=str, 36 | default=None, 37 | help="path to output directory (default: IMG_DIR)", 38 | ) 39 | parser.add_argument( 40 | "--max_mp", 41 | type=float, 42 | default=1.5, 43 | help="maximum megapixels (default: 1.5)", 44 | ) 45 | parser.add_argument( 46 | "--quality", 47 | type=int, 48 | default=95, 49 | help="save quality (default: 95, range: 0-100, suggested: 90+)", 50 | ) 51 | parser.add_argument( 52 | "--overwrite", 53 | action="store_true", 54 | default=False, 55 | help="overwrite files in output directory", 56 | ) 57 | parser.add_argument( 58 | "--noresize", 59 | action="store_true", 60 | default=False, 61 | help="do not resize, just fix orientation", 62 | ) 63 | parser.add_argument( 64 | "--delete", 65 | action="store_true", 66 | default=False, 67 | help="delete original files after processing", 68 | ) 69 | args = parser.parse_args() 70 | args.out_dir = args.out_dir or args.img_dir 71 | args.max_mp = args.max_mp * 1024000 72 | return args 73 | 74 | 75 | def images(img_dir): 76 | """Return each image in the input directory.""" 77 | for file in iglob(f"{img_dir}/*.*"): 78 | if file.lower().endswith(tuple(SUPPORTED_EXTENSIONS)): 79 | yield file 80 | 81 | 82 | def inline(msg, newline=False): 83 | """Print a message on the same line.""" 84 | msg = f"\r{msg}" 85 | msg += " " * (79 - len(msg)) 86 | print(msg, end="\n" if newline else "", flush=True) 87 | 88 | 89 | def launch_workers(queue, args): 90 | """Launch a pool of workers.""" 91 | loop = asyncio.new_event_loop() 92 | asyncio.set_event_loop(loop) 93 | tasks = [loop.create_task(worker(queue, args)) for _ in range(10)] 94 | loop.run_until_complete(asyncio.wait(tasks)) 95 | 96 | 97 | async def open_img(path): 98 | """Open an image.""" 99 | loop = asyncio.get_running_loop() 100 | try: 101 | return await loop.run_in_executor(None, Image.open, path) 102 | except Exception as err: 103 | inline(f"[!] Error Opening: {path} - {err}", True) 104 | return None 105 | 106 | 107 | def oversize(img, max_mp): 108 | """Check if an image is larger than the maximum size.""" 109 | return (img.width * img.height) > max_mp 110 | 111 | 112 | async def process(image, args): 113 | """Process an image.""" 114 | outfile = image.replace(args.img_dir, args.out_dir).replace( 115 | os.path.splitext(image)[1], ".webp" 116 | ) 117 | if args.overwrite or not os.path.exists(outfile): 118 | img = await open_img(image) 119 | if img: 120 | newimg = transpose(img) 121 | if not args.noresize and oversize(newimg, args.max_mp): 122 | newimg = shrink(newimg, args) 123 | if newimg != img: 124 | await save_img(newimg, outfile, args) 125 | if args.delete and outfile != image: 126 | os.remove(image) 127 | 128 | 129 | def slow_save(path, args, img): 130 | """Save an image.""" 131 | try: 132 | img.save(path, "webp", quality=args.quality) 133 | inline(f"[+] Compressed: {path}") 134 | except Exception as err: 135 | inline(f"[!] Error Saving: {path} - {err}", True) 136 | 137 | 138 | async def save_img(img, path, args): 139 | """Save an image.""" 140 | loop = asyncio.get_running_loop() 141 | await loop.run_in_executor(None, slow_save, path, args, img) 142 | 143 | 144 | def scan_path(queue, args): 145 | """Scan the input directory for images.""" 146 | inline("[*] Scanning for images...", True) 147 | for image in images(args.img_dir): 148 | inline(f"[+] {image}") 149 | queue.put(image) 150 | 151 | 152 | def shrink(img, args): 153 | """Shrink an image.""" 154 | hw = img.size 155 | ratio = args.max_mp / (hw[0]*hw[1]) 156 | newhw = (int(hw[0]*ratio**0.5), int(hw[1]*ratio**0.5)) 157 | 158 | try: 159 | return img.resize(newhw, Image.BICUBIC) 160 | except Exception as err: 161 | inline(f"[!] Error Shrinking: {img.filename} - {err}", True) 162 | return img 163 | 164 | 165 | def start_compression(queue, args): 166 | """Start the compression process.""" 167 | inline("[*] Compressing images...", True) 168 | inline("[-] (scanning...)") 169 | with ThreadPoolExecutor() as executor: 170 | workers = { 171 | executor.submit(launch_workers, queue, args): None 172 | for _ in range(cpu_count()) 173 | } 174 | for _ in as_completed(workers): 175 | pass 176 | inline("[!] Done!", True) 177 | 178 | 179 | def transpose(img): 180 | """Transpose an image.""" 181 | try: 182 | return ImageOps.exif_transpose(img) 183 | except Exception as err: 184 | inline(f"[!] Error Transposing: {img.filename} - {err}", True) 185 | return img 186 | 187 | 188 | async def worker(queue, args): 189 | """Handle images from the queue until they're gone.""" 190 | while not queue.empty(): 191 | image = queue.get() 192 | await process(image, args) 193 | 194 | 195 | def main(): 196 | """Run the program.""" 197 | queue = Queue() 198 | args = get_args(description=SHORT_DESCRIPTION) 199 | inline(f"[>] Image Compression Utility v{VERSION}", True) 200 | scan_path(queue, args) 201 | start_compression(queue, args) 202 | 203 | 204 | if __name__ == "__main__": 205 | main() 206 | -------------------------------------------------------------------------------- /scripts/createtxtfromfilename.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import argparse 4 | 5 | def create_txt_from_filename(path): 6 | """ 7 | create a .txt file for each file in the path so you can lengthen the caption 8 | """ 9 | print(f"Creating .txt files from filenames in {path}") 10 | for idx, f in enumerate(glob.iglob(f"{path}/**", recursive=True)): 11 | print(f"Creating {f}.txt") 12 | if not os.path.isfile(f) or not os.path.splitext(f)[1] in ['.jpg', '.png', '.jpeg', '.webp', '.bmp']: 13 | continue 14 | 15 | path_without_filename = os.path.dirname(f) 16 | base_name = os.path.splitext(os.path.basename(f))[0] 17 | caption = os.path.splitext(base_name)[0].split("_")[0] 18 | target = f"{path_without_filename}/{base_name}.txt" 19 | print (f"Creating file: {target} from {f}") 20 | with open(target, "w") as text_file: 21 | text_file.write(caption) 22 | 23 | if __name__ == "__main__": 24 | parser = argparse.ArgumentParser() 25 | parser.add_argument("--path", type=str, help="path to folder") 26 | args = parser.parse_args() 27 | create_txt_from_filename(args.path) 28 | -------------------------------------------------------------------------------- /scripts/download_laion.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import pandas as pd 4 | import pyarrow as pa 5 | import argparse 6 | import glob 7 | #import requests_async as requests 8 | import asyncio 9 | import aiohttp 10 | from typing import IO 11 | import aiofiles 12 | import re 13 | from colorama import Fore, Style 14 | from PIL import Image 15 | import io 16 | 17 | # can tweak these you feel like it, but shouldn't be needed 18 | unsafe_threshhold = 0.1 # higher values is more likely to be nsfw and will be skipped 19 | aesthetic_threshhold = 5 # higher is more aesthetic, note laion2B-aesthetic already >7? 20 | http_timeout = 10 21 | 22 | # dont touch 23 | downloaded_count = 0 24 | current_parquet_file_downloaded_count = 0 25 | logger_sp = None 26 | 27 | def get_base_prefix_compat(): 28 | """Get base/real prefix, or sys.prefix if there is none.""" 29 | return getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix 30 | 31 | def in_virtualenv(): 32 | return get_base_prefix_compat() != sys.prefix 33 | 34 | def get_parser(**parser_kwargs): 35 | parser = argparse.ArgumentParser(**parser_kwargs) 36 | do_not_download = True 37 | parser.add_argument( 38 | "--laion_dir", 39 | type=str, 40 | nargs="?", 41 | const=True, 42 | default="./laion", 43 | help="directory with laion parquet files, default is ./laion", 44 | ) 45 | parser.add_argument( 46 | "--search_text", 47 | type=str, 48 | const=True, 49 | nargs="?", 50 | default=None, 51 | help="csv of words with AND logic, ex \"photo,man,dog\"", 52 | ), 53 | parser.add_argument( 54 | "--out_dir", 55 | type=str, 56 | nargs="?", 57 | const=True, 58 | default="./output", 59 | help="directory to download files to, defaults is ./output", 60 | ), 61 | parser.add_argument( 62 | "--log_dir", 63 | type=str, 64 | nargs="?", 65 | const=True, 66 | default=None, 67 | help="directory for logs, if ommitted will not log, logs may be large!", 68 | ), 69 | parser.add_argument( 70 | "--column", 71 | type=str, 72 | nargs="?", 73 | const=True, 74 | default="TEXT", 75 | help="column to search for matches, defaults is 'TEXT', but you could use 'URL' if you wanted", 76 | ), 77 | parser.add_argument( 78 | "--limit", 79 | type=int, 80 | nargs="?", 81 | const=True, 82 | default=100, 83 | help="max number of matching images to download, warning: may be slightly imprecise due to concurrency and http errors, defaults is 100", 84 | ), 85 | parser.add_argument( 86 | "--min_hw", 87 | type=int, 88 | nargs="?", 89 | const=True, 90 | default=512, 91 | help="min height AND width of image to download, default is 512", 92 | ), 93 | parser.add_argument( 94 | "--force", 95 | type=bool, 96 | nargs="?", 97 | const=True, 98 | default=False, 99 | help="forces a full download of all images, even if no search is provided, USE CAUTION!", 100 | ), 101 | parser.add_argument( 102 | "--parquet_skip", 103 | type=int, 104 | nargs="?", 105 | const=True, 106 | default=0, 107 | help="skips the first n parquet files on disk, useful to resume", 108 | ), 109 | parser.add_argument( 110 | "--verbose", 111 | type=bool, 112 | nargs="?", 113 | const=True, 114 | default=False, 115 | help="additional logging of URL and TEXT prefiltering", 116 | ), 117 | parser.add_argument( 118 | "--test", 119 | action='store_const', 120 | const=do_not_download, 121 | default=not(do_not_download), 122 | help="skips downloading, for checking filters, use with --verbose", 123 | ) 124 | 125 | return parser 126 | 127 | def cleanup_text(file_name: str): 128 | # TODO: can be improved 129 | 130 | file_name = re.sub("", "", file_name) 131 | file_name = re.sub("", "", file_name) 132 | file_name = re.sub("", "", file_name) 133 | file_name = file_name.replace('

', '').replace("

", "") 134 | file_name = file_name.replace('', '').replace("", "") 135 | file_name = file_name.replace('', '').replace("", "") 136 | 137 | file_name = re.sub(r'[^\x00-\x7F]+', '', file_name) # remove non-ascii 138 | 139 | file_name = file_name.replace(' & ', ' and ').replace(' &', ' and').replace('& ', 'and ') \ 140 | .replace(" + ", " and ").replace(" +", " and").replace("+ ", "and ") 141 | 142 | file_name = file_name.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') 143 | 144 | file_name = file_name.replace('\"t"', ' ') 145 | 146 | file_name = file_name.replace(" ♥ ","love").replace("♥ ","love ").replace(" ♥"," love") \ 147 | .replace("♥"," love ") 148 | 149 | # remove bad chars 150 | file_name = file_name.replace('\"', '').replace('?', '') \ 151 | .replace('<', '').replace('>', '').replace('/', '').replace('*', '') \ 152 | .replace('!', '').replace('#', '').replace('$', '').replace('%', '') \ 153 | .replace('^', '').replace('(', '').replace(')', '') 154 | 155 | # replace with space 156 | file_name = file_name.replace(':',' ').replace('|',' ').replace('@', '') \ 157 | .replace("/", " ").replace("\\'", "\'").replace("\\", " ").replace('\\', ' ') \ 158 | .replace('_', ' ').replace("=", " ") 159 | 160 | # replace foreign chars 161 | file_name = file_name.replace('é', 'e').replace('è', 'e').replace('ê', 'e') \ 162 | .replace('ë', 'e').replace('à', 'a').replace('â', 'a').replace('ä', 'a') \ 163 | .replace('ç', 'c').replace('ù', 'u').replace('û', 'u').replace('ü', 'u') \ 164 | .replace('ô', 'o').replace('ö', 'o').replace('ï', 'i').replace('î', 'i') \ 165 | .replace('í', 'i').replace('ì', 'i').replace('ñ', 'n').replace('ß', 'ss') \ 166 | .replace('á', 'a').replace('ã', 'a').replace('å', 'a').replace('æ', 'ae') \ 167 | .replace('œ', 'oe').replace('ø', 'o').replace('ð', 'd').replace('þ', 'th') \ 168 | .replace('ý', 'y').replace('ÿ', 'y').replace('ž', 'z').replace('ž', 'z') \ 169 | .replace('š', 's').replace('đ', 'd').replace('ď', 'd').replace('č', 'c') \ 170 | .replace('ć', 'c').replace('ř', 'r').replace('ŕ', 'r').replace('ľ', 'l') \ 171 | .replace('ĺ', 'l').replace('ť', 't').replace('ň', 'n').replace('ņ', 'n') \ 172 | .replace('ď', 'd').replace('Ď', 'D').replace('Ť', 'T').replace('Ň', 'N') 173 | 174 | _MAX_LENGTH = 240 175 | if (len(file_name) > _MAX_LENGTH): 176 | file_name = file_name[:_MAX_LENGTH] 177 | 178 | return file_name 179 | 180 | async def call_http(image_url: str, session: aiohttp.ClientSession): 181 | #print(f"calling http and save to: {out_file_name}") 182 | global downloaded_count 183 | global http_timeout 184 | global current_parquet_file_downloaded_count 185 | try: 186 | res = await session.request(method="GET", url=image_url, timeout=http_timeout) 187 | 188 | if (res.status == 200): 189 | return await res.content.read() 190 | else: 191 | print(f"{Fore.YELLOW}Failed to download image, HTTP response code: {res.status} for {Fore.LIGHTWHITE_EX}{image_url}{Style.RESET_ALL}") 192 | downloaded_count -= 1 193 | except Exception as e: 194 | print(f"{Fore.YELLOW} *** Error downloading image: {Fore.LIGHTWHITE_EX}{image_url}{Fore.YELLOW}, ex: {str(e)}{Style.RESET_ALL}") 195 | downloaded_count -= 1 196 | pass 197 | return None 198 | 199 | async def save_img(buffer: io.BytesIO, full_outpath: str): 200 | try: 201 | async with aiofiles.open(full_outpath, "wb") as f: 202 | await f.write(buffer.getbuffer()) 203 | except Exception as e: 204 | print(f"{Fore.RED} *** Unable to write to disk: {Fore.LIGHTWHITE_EX}{full_outpath}{Style.RESET_ALL}") 205 | print(f"{Fore.RED} *** ex: {Fore.LIGHTWHITE_EX}{str(e)}{Style.RESET_ALL}") 206 | pass 207 | 208 | def get_outpath_filename(data: any, full_outpath_noext: str, clean_text: str): 209 | ext = "jpg" 210 | full_outpath = None 211 | buffer = None 212 | try: 213 | buffer = io.BytesIO(data) 214 | image = Image.open(buffer) 215 | ext = image.format.lower() 216 | 217 | if (ext == "jpeg"): 218 | ext = "jpg" 219 | 220 | full_outpath = f"{full_outpath_noext}.{ext}" 221 | except Exception as e: 222 | print(f"{Fore.YELLOW} *** Possible corrupt image for text: {Fore.LIGHTWHITE_EX}{clean_text}{Style.RESET_ALL}") 223 | print(f"{Fore.YELLOW} *** ex: {Fore.LIGHTWHITE_EX}{str(e)}{Style.RESET_ALL}") 224 | pass 225 | return full_outpath, buffer 226 | 227 | async def download_image(image_url: str, clean_text: str, full_outpath_noext: IO, session: aiohttp.ClientSession): 228 | http_content = await call_http(image_url=image_url, session=session) 229 | 230 | buffer = None 231 | 232 | if (http_content is not None): 233 | full_outpath, buffer = get_outpath_filename(data=http_content, full_outpath_noext=full_outpath_noext, clean_text=clean_text) 234 | 235 | if buffer is not None: 236 | global downloaded_count 237 | downloaded_count += 1 238 | await save_img(buffer, full_outpath) 239 | 240 | async def download_set_dict(opt, matches_dict: dict): 241 | async with aiohttp.ClientSession() as session: 242 | global downloaded_count 243 | current_parquet_file_downloaded_count = 0 244 | tasks = [] 245 | for row in matches_dict: 246 | if downloaded_count < opt.limit: 247 | current_parquet_file_downloaded_count += 1 248 | pre_text=row["TEXT"] 249 | image_url=row["URL"] 250 | 251 | clean_text = cleanup_text(pre_text) 252 | 253 | full_outpath_noext = os.path.join(opt.out_dir, clean_text) 254 | 255 | if (opt.verbose): 256 | print(f"{Fore.LIGHTGREEN_EX}***** Verbose log: ***** {Style.RESET_ALL}") 257 | print(f"{Fore.LIGHTGREEN_EX} url: {image_url}{Style.RESET_ALL}") 258 | print(f"{Fore.LIGHTGREEN_EX} text: {pre_text}{Style.RESET_ALL}") 259 | print(f"{Fore.LIGHTGREEN_EX} captn: {clean_text}{Style.RESET_ALL}") 260 | 261 | if any(glob.glob(full_outpath_noext + ".*")): 262 | print(f"{Fore.YELLOW} already exists: {Fore.LIGHTWHITE_EX}{full_outpath_noext}{Fore.YELLOW}, skipping{Style.RESET_ALL}") 263 | return 264 | 265 | if not opt.test: 266 | tasks.append( 267 | download_image(image_url=image_url, clean_text=clean_text, full_outpath_noext=full_outpath_noext, session=session) 268 | ) 269 | else: 270 | current_parquet_file_downloaded_count += 1 271 | downloaded_count += 1 272 | if len(tasks) > 63: 273 | await asyncio.gather(*tasks) 274 | tasks = [] 275 | else: 276 | print(f"{Fore.YELLOW} Limit reached: {opt.limit}, exiting...{Style.RESET_ALL}") 277 | break 278 | if not opt.test & len(tasks) > 0: 279 | await asyncio.gather(*tasks) 280 | print(f"{Fore.LIGHTBLUE_EX} Downloaded chunk of {current_parquet_file_downloaded_count} images{Style.RESET_ALL}") 281 | 282 | def query_parquet(df: pd.DataFrame, opt): 283 | # TODO: efficiency, expression tree? 284 | matches = df 285 | 286 | matches = matches[(matches.HEIGHT > opt.min_hw) & (matches.WIDTH > opt.min_hw)] 287 | 288 | if 'punsafe' in matches.columns: 289 | matches = matches[(matches.punsafe > unsafe_threshhold)] 290 | 291 | if ('aesthetic' in matches): 292 | matches = matches[(matches.aesthetic > aesthetic_threshhold)] 293 | 294 | if opt.search_text: 295 | for word in opt.search_text.split(","): 296 | matches = matches[matches[opt.column].str.contains(word, case=False)] 297 | 298 | matches = matches[~matches["URL"].str.contains("dreamstime.com", case=False)] # watermarks 299 | matches = matches[~matches["URL"].str.contains("alamy.com", case=False)] # watermarks 300 | matches = matches[~matches["URL"].str.contains("123rf.com", case=False)] # watermarks 301 | matches = matches[~matches["URL"].str.contains("colourbox.com", case=False)] # watermarks 302 | matches = matches[~matches["URL"].str.contains("envato.com", case=False)] # watermarks 303 | matches = matches[~matches["URL"].str.contains("stockfresh.com", case=False)] # watermarks 304 | matches = matches[~matches["URL"].str.contains("depositphotos.com", case=False)] # watermarks 305 | matches = matches[~matches["URL"].str.contains("istockphoto.com", case=False)] # watermarks 306 | 307 | return matches 308 | 309 | async def download_laion_matches(opt): 310 | print(f"{Fore.LIGHTBLUE_EX} Searching for {opt.search_text} in column: {opt.column} in {opt.laion_dir}/*.parquet{Style.RESET_ALL}") 311 | 312 | for idx, file in enumerate(glob.iglob(os.path.join(opt.laion_dir, "*.parquet"))): 313 | if idx < opt.parquet_skip: 314 | print(f"{Fore.YELLOW} Skipping file {idx+1}/{opt.parquet_skip}: {file}{Style.RESET_ALL}") 315 | continue 316 | 317 | global downloaded_count 318 | if downloaded_count < opt.limit: 319 | print(f"{Fore.CYAN} reading file: {file}{Style.RESET_ALL}") 320 | 321 | df = pd.read_parquet(file, engine="auto") 322 | matches = query_parquet(df, opt) 323 | # print(f"{Fore.CYAN} matches in current parquet file:{ Style.RESET_ALL}") 324 | # print(matches) 325 | 326 | match_dict = matches.to_dict('records') # TODO: pandas problems later in script... needs revisiting 327 | 328 | await download_set_dict(opt, match_dict) 329 | else: 330 | print(f"{Fore.YELLOW}limit reached before reading next parquet file. idx: {idx}, filename: {file}{Style.RESET_ALL}") 331 | break 332 | 333 | def isWindows(): 334 | return sys.platform.startswith('win') 335 | 336 | def ensure_path_exists(path: str): 337 | if not os.path.exists(path): 338 | print(f"{Fore.LIGHTBLUE_EX}creating path: {path}{Style.RESET_ALL}") 339 | os.makedirs(path) 340 | 341 | if __name__ == '__main__': 342 | print(f"{Fore.CYAN}Launching...{Style.RESET_ALL}") 343 | inVenv = in_virtualenv() 344 | print(f"is running in venv: {inVenv}") 345 | #assert inVenv, "Error loading venv. Please run 'source everydream-venv/bin/activate', or in windows 'everydream-venv/bin/activate.bat'" 346 | 347 | parser = get_parser() 348 | opt = parser.parse_args() 349 | 350 | print(f"Test only mode: {opt.test}") 351 | 352 | if(opt.search_text is None and opt.force is False): 353 | print(f"{Fore.YELLOW}** No search terms provided, exiting...") 354 | print(f"** Use --force to bypass safety to dump entire DB{Style.RESET_ALL}") 355 | sys.exit(2) 356 | 357 | ensure_path_exists(opt.out_dir) 358 | 359 | if (opt.laion_dir[-1] != "/" or opt.laion_dir[-1] != "\\"): 360 | opt.laion_dir += "/" 361 | 362 | if (isWindows()): 363 | print("{Fore.CYAN}Windows detected, using asyncio.WindowsSelectorEventLoopPolicy{Style.RESET_ALL}") 364 | asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) 365 | else: 366 | print("{Fore.CYAN}Unix detected, using default asyncio event loop policy{Style.RESET_ALL}") 367 | 368 | import time 369 | s = time.perf_counter() 370 | 371 | result = asyncio.run(download_laion_matches(opt)) 372 | 373 | elapsed = time.perf_counter() - s 374 | print(f"{Fore.CYAN} **** Job Complete ****") 375 | print(f" search_text: \"{opt.search_text}\", force: {opt.force}") 376 | print(f" Total downloaded {downloaded_count} images") 377 | print(f"{__file__} executed in {elapsed:0.2f} seconds.{Style.RESET_ALL}{Style.RESET_ALL}") -------------------------------------------------------------------------------- /scripts/extract_video_frames.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from pathlib import Path 3 | import cv2 4 | 5 | def get_parser(**parser_kwargs): 6 | parser = argparse.ArgumentParser(**parser_kwargs) 7 | parser.add_argument( 8 | "--vid_dir", 9 | required=True, 10 | type=str, 11 | nargs="?", 12 | const=True, 13 | help="directory with videos to extract frames", 14 | ) 15 | parser.add_argument( 16 | "--out_dir", 17 | type=str, 18 | nargs="?", 19 | const=True, 20 | help="directory to put extracted images", 21 | ) 22 | parser.add_argument( 23 | "--format", 24 | type=str, 25 | nargs="?", 26 | const=True, 27 | default="png", 28 | choices=["png", "jpg"], 29 | help="image file format of the extracted frames", 30 | ) 31 | parser.add_argument( 32 | "--interval", 33 | type=int, 34 | nargs="?", 35 | const=True, 36 | default=10, 37 | help="number of seconds between frame captures", 38 | ) 39 | return parser 40 | 41 | def get_videos(input_dir): 42 | for f in input_dir.iterdir(): 43 | file_path = Path(f) 44 | if file_path.suffix in [".mp4", ".avi", ".mov", ".mpeg", ".mpg", ".mkv"]: 45 | yield file_path 46 | 47 | def capture_frames(input_dir, output_dir): 48 | print (f'Capturing video frames in {opt.interval} second intervals.\n') 49 | 50 | for video_path in get_videos(input_dir): 51 | print(f'Extracting {video_path}') 52 | cap = cv2.VideoCapture(str(video_path)) 53 | if not cap.isOpened(): 54 | print(f'Could not open video') 55 | continue 56 | 57 | output = output_dir / video_path.stem 58 | output.mkdir(exist_ok=True, parents=True) 59 | 60 | current_frame = 0 61 | count = 0 62 | fps = cap.get(cv2.CAP_PROP_FPS) 63 | while cap.isOpened(): 64 | ret, frame = cap.read() 65 | if ret: 66 | count_str = str(count).zfill(4) 67 | cv2.imwrite(str(output / f'frame_{count_str}.{opt.format}'), frame) 68 | current_frame += fps * opt.interval 69 | cap.set(cv2.CAP_PROP_POS_FRAMES, current_frame) 70 | count += 1 71 | else: 72 | cap.release() 73 | break 74 | 75 | print(f'\nFinished extracting frames to {output_dir}\n') 76 | 77 | if __name__ == "__main__": 78 | parser = get_parser() 79 | opt = parser.parse_args() 80 | 81 | if (not Path(opt.vid_dir).exists): 82 | print("Video directory does not exist.") 83 | exit(1) 84 | 85 | if (opt.out_dir is None): 86 | output = Path(opt.vid_dir) / "output" 87 | print(f"No output directory specified, using default: {output}") 88 | else: 89 | output = Path(opt.out_dir) 90 | capture_frames(Path(opt.vid_dir), output) 91 | -------------------------------------------------------------------------------- /scripts/filename_replace.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import glob 4 | import argparse 5 | 6 | def get_parser(**parser_kwargs): 7 | parser = argparse.ArgumentParser(**parser_kwargs) 8 | parser.add_argument( 9 | "--img_dir", 10 | type=str, 11 | nargs="?", 12 | const=True, 13 | default="input", 14 | help="directory with images to be renamed", 15 | ), 16 | parser.add_argument( 17 | "--find", 18 | type=str, 19 | nargs="?", 20 | const=True, 21 | default=None, 22 | help="what strings to replace, in csv format, default: 'a man,a woman,a person'", 23 | ), 24 | parser.add_argument( 25 | "--replace", 26 | type=str, 27 | nargs="?", 28 | required=False, 29 | const=True, 30 | default=None, 31 | help="string to replace with, ex. 'john doe'", 32 | ), 33 | parser.add_argument( 34 | "--append_only", 35 | type=str, 36 | nargs="?", 37 | required=False, 38 | const=True, 39 | default=None, 40 | help="skips pronoun replace, adds a string at the end of the filename, use for 'by artist name' or 'in the style of somestyle'", 41 | ) 42 | 43 | return parser 44 | 45 | def isWindows(): 46 | return sys.platform.startswith('win') 47 | 48 | def get_replace_list(opt): 49 | if opt.find is None: 50 | return ("a man", "a woman", "a person", \ 51 | "a girl", "a boy", \ 52 | "a young woman", "a young man", \ 53 | "a beautiful woman", "a handsome man", \ 54 | "a beautiful young woman", "a handsome young man", 55 | ) 56 | else: 57 | return opt.find.split(",") 58 | 59 | def get_outfile_name(infile, append): 60 | new_filename = f"{os.path.splitext(infile)[0]} {append}{os.path.splitext(infile)[1]}" 61 | return new_filename 62 | 63 | def rename_files(opt): 64 | find_list = get_replace_list(opt) 65 | 66 | for idx, file in enumerate(glob.iglob(f"{opt.img_dir}/*")): 67 | print(file) 68 | 69 | if os.path.splitext(file)[1] in (".jpg", ".png", ".jpeg", ".gif", ".bmp", ".webp"): 70 | new_filename = file 71 | if opt.append_only is not None: 72 | new_filename = get_outfile_name(file, opt.append_only) 73 | else: 74 | for s in find_list: 75 | if s in file: 76 | new_filename = new_filename.replace(s, opt.replace) 77 | try: 78 | print(f"Renaming {file} to {new_filename}") 79 | if os.path.exists(new_filename): 80 | new_filename = new_filename = get_outfile_name(file, f"_{idx}") 81 | print(f"filename already exists, appended '_n' to {new_filename}") 82 | 83 | try: 84 | os.rename(file, new_filename) 85 | except Exception as e: 86 | print(f"Error renaming file: {file}, skipping, error: {e}") 87 | except Exception as e: 88 | print(f"error opening file: {file}") 89 | print(f"{e}") 90 | raise e 91 | 92 | 93 | if __name__ == "__main__": 94 | parser = get_parser() 95 | opt = parser.parse_args() 96 | 97 | import time 98 | 99 | s = time.perf_counter() 100 | 101 | rename_files(opt) 102 | 103 | elapsed = time.perf_counter() - s 104 | print(f"{__file__} executed in {elapsed:0.2f} seconds.") -------------------------------------------------------------------------------- /scripts/image_caption_gui.py: -------------------------------------------------------------------------------- 1 | # Python GUI tool to manually caption images for machine learning. 2 | # A sidecar file is created for each image with the same name and a .txt extension. 3 | # 4 | # [control/command + o] to open a folder of images. 5 | # [page down] and [page up] to go to next and previous images. Hold shift to skip 10 images. 6 | # [shift + home] and [shift + end] to go to first and last images. 7 | # [shift + delete] to move the current image into a '_deleted' folder. 8 | # [escape] to exit the app. 9 | 10 | import sys 11 | import tkinter as tk 12 | from tkinter import filedialog 13 | from PIL import Image, ImageTk 14 | from pathlib import Path 15 | 16 | IMG_EXT = ["jpg", "jpeg", "png", "webp"] 17 | 18 | class CaptionedImage(): 19 | def __init__(self, image_path): 20 | self.base_path = image_path.parent 21 | self.path = image_path 22 | 23 | def caption_path(self): 24 | return self.base_path / (self.path.stem + '.txt') 25 | 26 | def read_caption(self): 27 | caption_path = self.caption_path() 28 | if caption_path.exists(): 29 | with open(caption_path, 'r', encoding='utf-8', newline='') as f: 30 | return f.read() 31 | return '' 32 | 33 | def write_caption(self, caption): 34 | caption_path = self.caption_path() 35 | with open(str(caption_path), 'w', encoding='utf-8', newline='') as f: 36 | f.write(caption) 37 | 38 | # sort 39 | def __lt__(self, other): 40 | return str(self.path).lower() < str(other.path).lower() 41 | 42 | class ImageView(tk.Frame): 43 | 44 | def __init__(self, root): 45 | tk.Frame.__init__(self, root) 46 | 47 | self.root = root 48 | self.base_path = None 49 | self.images = [] 50 | self.index = 0 51 | 52 | # image 53 | self.image_frame = tk.Frame(self) 54 | self.image_label = tk.Label(self.image_frame) 55 | self.image_label.place(relx=0.5, rely=0.5, anchor=tk.CENTER) 56 | self.image_frame.pack(expand=True, fill=tk.BOTH, side=tk.LEFT) 57 | 58 | # caption field 59 | self.caption_frame = tk.Frame(self) 60 | self.caption_field = tk.Text(self.caption_frame, wrap="word", width=50) 61 | self.caption_field.pack(expand=True, fill=tk.BOTH) 62 | self.caption_frame.pack(fill=tk.Y, side=tk.RIGHT) 63 | 64 | def open_folder(self): 65 | dir = filedialog.askdirectory() 66 | if not dir: 67 | return 68 | self.base_path = Path(dir) 69 | if self.base_path is None: 70 | return 71 | self.images.clear() 72 | for ext in IMG_EXT: 73 | for file in self.base_path.glob(f'*.{ext}'): 74 | self.images.append(CaptionedImage(file)) 75 | self.images.sort() 76 | self.update_ui() 77 | 78 | def store_caption(self): 79 | txt = self.caption_field.get(1.0, tk.END) 80 | txt = txt.replace('\r', '').replace('\n', '').strip() 81 | self.images[self.index].write_caption(txt) 82 | 83 | def set_index(self, index): 84 | self.index = index % len(self.images) 85 | 86 | def go_to_image(self, index): 87 | if len(self.images) == 0: 88 | return 89 | self.store_caption() 90 | self.set_index(index) 91 | self.update_ui() 92 | 93 | def next_image(self): 94 | self.go_to_image(self.index + 1) 95 | 96 | def prev_image(self): 97 | self.go_to_image(self.index - 1) 98 | 99 | # move current image to a "_deleted" folder 100 | def delete_image(self): 101 | if len(self.images) == 0: 102 | return 103 | img = self.images[self.index] 104 | 105 | trash_path = self.base_path / '_deleted' 106 | if not trash_path.exists(): 107 | trash_path.mkdir() 108 | img.path.rename(trash_path / img.path.name) 109 | caption_path = img.caption_path() 110 | if caption_path.exists(): 111 | caption_path.rename(trash_path / caption_path.name) 112 | del self.images[self.index] 113 | self.set_index(self.index) 114 | self.update_ui() 115 | 116 | def update_ui(self): 117 | if (len(self.images)) == 0: 118 | self.filename.set('') 119 | self.caption_field.delete(1.0, tk.END) 120 | self.image_label.configure(image=None) 121 | return 122 | img = self.images[self.index] 123 | # filename 124 | title = self.images[self.index].path.name if len(self.images) > 0 else '' 125 | self.root.title(title + f' ({self.index+1}/{len(self.images)})') 126 | # caption 127 | self.caption_field.delete(1.0, tk.END) 128 | self.caption_field.insert(tk.END, img.read_caption()) 129 | # image 130 | img = Image.open(self.images[self.index].path) 131 | 132 | # scale the image to fit inside the frame 133 | w = self.image_frame.winfo_width() 134 | h = self.image_frame.winfo_height() 135 | if img.width > w or img.height > h: 136 | img.thumbnail((w, h)) 137 | photoImage = ImageTk.PhotoImage(img) 138 | self.image_label.configure(image=photoImage) 139 | self.image_label.image = photoImage 140 | 141 | if __name__=='__main__': 142 | root = tk.Tk() 143 | root.geometry('1200x800') 144 | root.title('Image Captions') 145 | 146 | if sys.platform == 'darwin': 147 | root.bind('', lambda e: view.open_folder()) 148 | else: 149 | root.bind('', lambda e: view.open_folder()) 150 | root.bind('', lambda e: root.destroy()) 151 | root.bind('', lambda e: view.prev_image()) 152 | root.bind('', lambda e: view.next_image()) 153 | root.bind('', lambda e: view.go_to_image(view.index - 10)) 154 | root.bind('', lambda e: view.go_to_image(view.index + 10)) 155 | root.bind('', lambda e: view.go_to_image(0)) 156 | root.bind('', lambda e: view.go_to_image(len(view.images) - 1)) 157 | root.bind('', lambda e: view.delete_image()) 158 | 159 | view = ImageView(root) 160 | view.pack(side=tk.TOP, fill=tk.BOTH, expand=True) 161 | root.mainloop() 162 | --------------------------------------------------------------------------------