diff --git a/Kandinsky-3/.gitignore b/Kandinsky-3/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..68bc17f9ff2104a9d7b6777058bb4c343ca72609 --- /dev/null +++ b/Kandinsky-3/.gitignore @@ -0,0 +1,160 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/Kandinsky-3/LICENSE b/Kandinsky-3/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/Kandinsky-3/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Kandinsky-3/README.md b/Kandinsky-3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a5e400ae20492f325579a2b9b8d654912e9880f1 --- /dev/null +++ b/Kandinsky-3/README.md @@ -0,0 +1,230 @@ +# Kandinsky-3: Text-to-image diffusion model + +![](assets/title.jpg) + +[Kandinsky 3.0 Post](https://habr.com/ru/companies/sberbank/articles/775590/) | [Kandinsky 3.1 Post](https://habr.com/ru/companies/sberbank/articles/805337/) | [Project Page](https://ai-forever.github.io/Kandinsky-3) | [Generate](https://fusionbrain.ai) | [Telegram-bot](https://t.me/kandinsky21_bot) | [Technical Report](https://arxiv.org/pdf/2312.03511.pdf) | [HuggingFace](https://huggingface.co/kandinsky-community/kandinsky-3) | + +# Kandinsky 3.1: + +## Description: + +We present Kandinsky 3.1, the follow-up to the Kandinsky 3.0 model, a large-scale text-to-image generation model based on latent diffusion, continuing the series of text-to-image Kandinsky models and reflecting our progress to achieve higher quality and realism of image generation, which we have enhanced and enriched with a variety of useful features and modes to give users more opportunities to fully utilise the power of our new model. + +## Kandinsky Flash (Kandinsky 3.0 Refiner) + +
+ +
+ + +Diffusion models have problems with fast image generation. To address this problem, we trained a Kandinksy Flash model based on the [Adversarial Diffusion Distillation](https://arxiv.org/abs/2311.17042) approach with some modifications: we trained the model on latents, which reduced the memory overhead and removed distillation loss as it did not affect the training. Also, we applied Kandinsky Flash model to images generated from Kandinsky 3.0 to improve visual quality of generated images. + +### Architecture + +For training Kandinsky Flash we used the following architecture of discriminator. It is the half of Kandinsky 3.0 U-Net encoder with additional head predictions. + + + +### How to use: +Check our jupyter notebooks with examples in `./examples` folder + +```python +from kandinsky3 import get_T2I_Flash_pipeline + +device_map = torch.device('cuda:0') +dtype_map = { + 'unet': torch.float32, + 'text_encoder': torch.float16, + 'movq': torch.float32, +} + +t2i_pipe = get_T2I_Flash_pipeline( + device_map, dtype_map +) + +res = t2i_pipe("A cute corgi lives in a house made out of sushi.") +``` +### Kandinsky Inpainting + +Also, we released a newer version of inpainting model, which we additionally trained the model on the object detection dataset. This allowed to get more stable generation of objects. The new weights are available at [ai-forever/Kandinsky3.1](https://huggingface.co/ai-forever/Kandinsky3.1). Check the usage [example](https://github.com/ai-forever/Kandinsky-3?tab=readme-ov-file#2-inpainting). + + +## Prompt beautification + +
+ +
+ + +Prompt plays crucial role in text-to-image generation. So, in Kandinsky 3.1 we decided to use language model for making prompt better. We used Intel's [neural-chat-7b-v3-1](https://huggingface.co/Intel/neural-chat-7b-v3-1) with the following system prompt as the LLM: + +``` +### System: You are a prompt engineer. Your mission is to expand prompts written by user. You should provide the best prompt for text to image generation in English. +### User: +{prompt} +### Assistant: +{answer of the model} +``` + +## KandiSuperRes + +
+ +
+ +To learn more about KandiSuperRes, please checkout: https://github.com/ai-forever/KandiSuperRes/ + +## Kandinsky IP-Adapter & Kandinsky ControlNet + +
+ +
+ +To allow using image as condition in Kandinsky model, we trained IP-Adapter and HED-based ControlNet model. For more details please check out: https://github.com/ai-forever/kandinsky3-diffusers + +# Kandinsky 3.0: + +## Description: + +Kandinsky 3.0 is an open-source text-to-image diffusion model built upon the Kandinsky2-x model family. In comparison to its predecessors, Kandinsky 3.0 incorporates more data and specifically related to Russian culture, which allows to generate pictures related to Russin culture. Furthermore, enhancements have been made to the text understanding and visual quality of the model, achieved by increasing the size of the text encoder and Diffusion U-Net models, respectively. + +For more information: details of training, example of generations check out our [post](). The english version will be released in a couple of days. + +## Architecture details: + + +![](assets/kandinsky.jpg) + + +Architecture consists of three parts: + ++ Text encoder Flan-UL2 (encoder part) - 8.6B ++ Latent Diffusion U-Net - 3B ++ MoVQ encoder/decoder - 267M + + +## Models + +We release our two models: + ++ [Base](): Base text-to-image diffusion model. This model was trained over 2M steps on 400 A100 ++ [Inpainting](): Inpainting version of the model. The model was initialized from final checkpoint of base model and trained 250k steps on 300 A100. + +## Installing + +To install repo first one need to create conda environment: + +``` +conda create -n kandinsky -y python=3.8; +source activate kandinsky; +pip install torch==1.10.1+cu111 torchvision==0.11.2+cu111 torchaudio==0.10.1 -f https://download.pytorch.org/whl/cu113/torch_stable.html; +pip install -r requirements.txt; +``` +The exact dependencies is got using `pip freeze` and can be found in `exact_requirements.txt` + +## How to use: + +Check our jupyter notebooks with examples in `./examples` folder + +### 1. text2image + +```python +import sys +sys.path.append('..') + +import torch +from kandinsky3 import get_T2I_pipeline + +device_map = torch.device('cuda:0') +dtype_map = { + 'unet': torch.float32, + 'text_encoder': torch.float16, + 'movq': torch.float32, +} + +t2i_pipe = get_T2I_pipeline( + device_map, dtype_map, +) +res = t2i_pipe("A cute corgi lives in a house made out of sushi.") + +res[0] +``` + +### 2. inpainting + +```python +from kandinsky3 import get_inpainting_pipeline + +device_map = torch.device('cuda:0') +dtype_map = { + 'unet': torch.float16, + 'text_encoder': torch.float16, + 'movq': torch.float32, +} + +pipe = get_inpainting_pipeline( + device_map, dtype_map, +) + +image = ... # PIL Image +mask = ... # Numpy array (HxW). Set 1 where image should be masked +image = inp_pipe( "A cute corgi lives in a house made out of sushi.", image, mask) +``` + +## Examples of generations + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
"A beautiful landscape outdoors scene in the crochet knitting art style, drawing in style by Alfons Mucha""gorgeous phoenix, cosmic, darkness, epic, cinematic, moonlight, stars, high - definition, texture,Oscar-Claude Monet""a yellow house at the edge of the danish fjord, in the style of eiko ojala, ingrid baars, ad posters, mountainous vistas, george ault, realistic details, dark white and dark gray, 4k""dragon fruit head, upper body, realistic, illustration by Joshua Hoffine Norman Rockwell, scary, creepy, biohacking, futurism, Zaha Hadid style"
"Amazing playful nice cute strawberry character, dynamic poze, surreal fantazy garden background, gorgeous masterpice, award winning photo, soft natural lighting, 3d, Blender, Octane render, tilt - shift, deep field, colorful, I can't believe how beautiful this is, colorful, cute and sweet baby - loved photo""beautiful fairy-tale desert, in the sky a wave of sand merges with the milky way, stars, cosmism, digital art, 8k""Car, mustang, movie, person, poster, car cover, person, in the style of alessandro gottardo, gold and cyan, gerald harvey jones, reflections, highly detailed illustrations, industrial urban scenes"""cloud in blue sky, a red lip, collage art, shuji terayama, dreamy objects, surreal, criterion collection, showa era, intricate details, mirror"
+ +
+ +## Authors + ++ Vladimir Arkhipkin: [Github](https://github.com/oriBetelgeuse) ++ Anastasia Maltseva [Github](https://github.com/NastyaMittseva) ++ Andrei Filatov [Github](https://github.com/anvilarth), ++ Igor Pavlov: [Github](https://github.com/boomb0om) ++ Julia Agafonova ++ Arseniy Shakhmatov: [Github](https://github.com/cene555), [Blog](https://t.me/gradientdip) ++ Andrey Kuznetsov: [Github](https://github.com/kuznetsoffandrey), [Blog](https://t.me/complete_ai) ++ Denis Dimitrov: [Github](https://github.com/denndimitrov), [Blog](https://t.me/dendi_math_ai) + +## Citation +``` +@misc{arkhipkin2023kandinsky, + title={Kandinsky 3.0 Technical Report}, + author={Vladimir Arkhipkin and Andrei Filatov and Viacheslav Vasilev and Anastasia Maltseva and Said Azizov and Igor Pavlov and Julia Agafonova and Andrey Kuznetsov and Denis Dimitrov}, + year={2023}, + eprint={2312.03511}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` + diff --git a/Kandinsky-3/exact_requirements.txt b/Kandinsky-3/exact_requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..184e9ee9a0944e897dc4aa0cb3775fa884d324ec --- /dev/null +++ b/Kandinsky-3/exact_requirements.txt @@ -0,0 +1,372 @@ +absl-py==1.0.0 +accelerate==0.20.3 +adal==1.2.7 +addict==2.4.0 +aioboto3==11.0.1 +aiobotocore==2.4.2 +aiofiles==23.2.1 +aiohttp==3.8.1 +aiohttp-cors==0.7.0 +aioitertools==0.11.0 +aioredis==1.3.1 +aiosignal==1.2.0 +albumentations==1.3.1 +alembic==1.4.1 +alt-profanity-check==1.0.1 +altair==5.0.1 +antlr4-python3-runtime==4.9.3 +anyio==3.5.0 +apex==0.1 +appdirs==1.4.4 +argon2-cffi==21.3.0 +argon2-cffi-bindings==21.2.0 +asgiref==3.4.1 +astunparse==1.6.3 +async-timeout==4.0.2 +asyncpool==1.0 +asynctest==0.13.0 +attrs==21.4.0 +audioread==2.1.9 +autopage==0.4.0 +avro==1.11.0 +awscli==1.22.38 +azure-common==1.1.27 +azure-storage-blob==2.1.0 +azure-storage-common==2.1.0 +Babel==2.9.1 +backcall==0.2.0 +basicsr==1.4.2 +beautifulsoup4 @ file:///home/conda/feedstock_root/build_artifacts/beautifulsoup4_1631087867185/work +bezier==2021.2.12 +bitarray==2.8.3 +bitmath==1.3.3.1 +bleach==4.1.0 +blessings==1.7 +blis==0.7.11 +bokeh==2.4.2 +boto3==1.24.59 +botocore==1.27.59 +braceexpand==0.1.7 +brotlipy @ file:///home/conda/feedstock_root/build_artifacts/brotlipy_1636012184244/work +cached-property==1.5.2 +cachetools==4.2.4 +catalogue==2.0.10 +certifi==2021.10.8 +cffi==1.15.0 +chardet @ file:///home/conda/feedstock_root/build_artifacts/chardet_1635814832679/work +charset-normalizer==2.0.10 +click==8.0.3 +cliff==3.10.0 +clip @ git+https://github.com/openai/CLIP.git@a1d071733d7111c9c014f024669f959182114e33 +cloudevents==1.2.0 +cloudpathlib==0.16.0 +cloudpickle==2.0.0 +cmaes==0.8.2 +cmake==3.27.7 +cmd2==2.3.3 +colorama==0.4.3 +colorful==0.5.4 +colorlog==6.6.0 +conda==4.11.0 +conda-build==3.21.7 +conda-package-handling @ file:///home/conda/feedstock_root/build_artifacts/conda-package-handling_1636021712360/work +confection==0.1.3 +configparser==5.2.0 +cryptography @ file:///tmp/build/80754af9/cryptography_1639414570729/work +cycler==0.11.0 +cymem==2.0.8 +Cython==0.29.26 +dask==2022.1.0 +databricks-cli==0.16.2 +datasets==2.13.2 +DAWG-Python==0.7.2 +debugpy==1.5.1 +decorator==5.1.1 +deep-translator==1.11.4 +defusedxml==0.7.1 +Deprecated==1.2.13 +deprecation==2.1.0 +diffusers==0.21.4 +dill==0.3.6 +distributed==2022.1.0 +docker==5.0.3 +docker-pycreds==0.4.0 +docopt==0.6.2 +docutils==0.15.2 +einops==0.6.1 +entrypoints==0.3 +fairscale==0.4.6 +fairseq==0.12.2 +fastapi==0.72.0 +fastBPE==0.1.0 +fasttext==0.9.2 +fasttext-langdetect==1.0.5 +ffmpy==0.3.1 +filelock @ file:///home/conda/feedstock_root/build_artifacts/filelock_1641470428964/work +Flask==2.0.2 +fonttools==4.28.5 +fpie==0.2.4 +frozenlist==1.3.0 +fsspec==2023.1.0 +ftfy==6.1.1 +future==0.18.2 +gitdb==4.0.9 +GitPython==3.1.26 +glob2==0.7 +google-api-core==2.4.0 +google-auth==1.35.0 +google-auth-oauthlib==0.4.6 +google-cloud-core==2.2.2 +google-cloud-language==2.3.1 +google-cloud-storage==2.0.0 +google-crc32c==1.3.0 +google-resumable-media==2.1.0 +googleapis-common-protos==1.54.0 +gorilla==0.4.0 +gpustat==0.6.0 +GPUtil==1.4.0 +gradio==3.34.0 +gradio_client==0.2.6 +grpcio==1.43.0 +grpcio-status==1.43.0 +gunicorn==20.1.0 +h11==0.14.0 +h5py==3.6.0 +HeapDict==1.0.1 +hiredis==2.0.0 +horovod==0.28.1 +httpcore==0.17.3 +httpx==0.24.1 +huggingface-hub==0.16.4 +hydra-core==1.3.2 +idna==3.3 +image-reward @ file:///home/jovyan/afilatov/Diffusion/imagen/notebooks/image_assessment/ImageReward +imageio==2.31.2 +importlib-metadata==4.10.1 +importlib-resources==5.4.0 +inflect==5.3.0 +intervaltree==3.1.0 +ipykernel==6.7.0 +ipymarkup==0.9.0 +ipyplot==1.1.1 +ipython==7.31.1 +ipython-genutils==0.2.0 +ipywidgets==7.6.5 +itsdangerous==2.0.1 +jedi==0.18.1 +Jinja2 @ file:///home/conda/feedstock_root/build_artifacts/jinja2_1636510082894/work +jmespath==0.10.0 +joblib==1.1.0 +json5==0.9.6 +jsonschema==4.4.0 +jupyter-archive==3.2.1 +jupyter-client==7.1.2 +jupyter-core==4.9.1 +jupyter-server==1.13.4 +jupyter-server-proxy==1.3.2 +jupyter-tensorboard @ file:///tmp/mlspace/packages/jupyter_tensorboard-0.2.2a0-py2.py3-none-any.whl +jupyterlab==3.3.0a2 +jupyterlab-nvdashboard==0.6.0 +jupyterlab-pygments==0.1.2 +jupyterlab-server==2.10.3 +jupyterlab-tensorboard @ git+https://github.com/rhangelxs/jupyterlab_tensorboard.git@8dc7b1d5f24ece0e76e61b4dbbf36c58b84cbddd +jupyterlab-widgets==1.0.2 +kfserving==0.6.1 +kiwisolver==1.3.2 +kubernetes==21.7.0 +langcodes==3.3.0 +langid==1.1.6 +libarchive-c @ file:///home/conda/feedstock_root/build_artifacts/python-libarchive-c_1643045751069/work +libmambapy @ file:///home/conda/feedstock_root/build_artifacts/mamba-split_1643117251182/work/libmambapy +librosa==0.8.1 +linkify-it-py==2.0.2 +llvmlite==0.38.0 +lmdb==1.4.1 +locket==0.2.1 +Mako==1.1.6 +mamba @ file:///home/conda/feedstock_root/build_artifacts/mamba-split_1643117251182/work/mamba +Markdown==3.3.6 +markdown-it-py==2.2.0 +MarkupSafe @ file:///home/conda/feedstock_root/build_artifacts/markupsafe_1635833550185/work +matplotlib==3.5.1 +matplotlib-inline==0.1.3 +mdit-py-plugins==0.3.3 +mdurl==0.1.2 +minio==6.0.2 +mistune==0.8.4 +mlflow @ file:///tmp/mlspace/packages/mlflow-1.7.2-py3-none-any.whl +mmcv-full==1.4.3 +modin==0.12.1 +mpi4py==3.1.3 +msgpack==1.0.3 +multidict==5.2.0 +multiprocess==0.70.14 +murmurhash==1.0.10 +natasha==1.6.0 +navec==0.10.0 +nbclassic==0.3.5 +nbclient==0.5.10 +nbconvert==6.4.1 +nbformat==5.1.3 +nest-asyncio==1.5.4 +networkx==2.6.3 +nltk==3.6.7 +notebook @ file:///tmp/mlspace/packages/notebook-6.1.4-py3-none-any.whl +npm==0.1.1 +numba==0.55.0 +numpy==1.21.5 +nvidia-ml-py3==7.352.0 +oauthlib==3.1.1 +omegaconf==2.3.0 +opencensus==0.8.0 +opencensus-context==0.1.2 +opencv-python==4.5.5.62 +opencv-python-headless==4.8.1.78 +optional-django==0.1.0 +optuna==2.10.0 +orjson==3.9.7 +packaging==21.3 +pandas==1.3.5 +pandocfilters==1.5.0 +parso==0.8.3 +partd==1.2.0 +pbr==5.8.0 +pexpect==4.8.0 +pickleshare==0.7.5 +Pillow==9.0.0 +pkginfo @ file:///home/conda/feedstock_root/build_artifacts/pkginfo_1638813452194/work +pooch==1.5.2 +portalocker==2.3.2 +preshed==3.0.9 +prettytable==3.0.0 +prometheus-client==0.13.0 +prometheus-flask-exporter==0.18.7 +prompt-toolkit==3.0.26 +proto-plus==1.19.8 +protobuf==3.19.3 +psutil @ file:///home/conda/feedstock_root/build_artifacts/psutil_1640887121529/work +ptyprocess==0.7.0 +py-spy==0.3.11 +pyarrow==12.0.1 +pyasn1==0.4.8 +pyasn1-modules==0.2.8 +pybind11==2.11.1 +pycosat @ file:///home/conda/feedstock_root/build_artifacts/pycosat_1636020357254/work +pycparser==2.21 +pydantic==1.9.0 +pyDeprecate==0.3.2 +pydub==0.25.1 +pyee==8.2.2 +Pygments==2.16.1 +PyJWT==2.3.0 +pymorphy2==0.9.1 +pymorphy2-dicts-ru==2.4.417127.4579844 +pynvml==11.4.1 +pyOpenSSL @ file:///home/conda/feedstock_root/build_artifacts/pyopenssl_1633192417276/work +pyparsing==3.0.7 +pyperclip==1.8.2 +pyppeteer==0.2.6 +pyrsistent==0.18.1 +PySocks @ file:///home/conda/feedstock_root/build_artifacts/pysocks_1635862409558/work +python-dateutil==2.8.2 +python-editor==1.0.4 +python-multipart==0.0.6 +python-speech-features==0.6 +pytorch-lightning==1.7.5 +pytz @ file:///home/conda/feedstock_root/build_artifacts/pytz_1633452062248/work +PyWavelets==1.3.0 +PyYAML @ file:///home/conda/feedstock_root/build_artifacts/pyyaml_1636139801027/work +pyzmq==22.3.0 +qudida==0.0.4 +querystring-parser==1.2.4 +ray==1.6.0 +razdel==0.5.0 +redis==4.1.1 +regex==2022.1.18 +requests==2.27.1 +requests-oauthlib==1.3.0 +resampy==0.2.2 +rich==13.6.0 +rsa==4.8 +ruamel-yaml-conda @ file:///home/conda/feedstock_root/build_artifacts/ruamel_yaml_1636009153751/work +s3fs==2023.1.0 +s3transfer==0.6.2 +sacrebleu==2.0.0 +sacremoses==0.0.53 +safetensors==0.4.0 +scikit-image==0.19.3 +scikit-learn==1.0.1 +scipy==1.7.3 +semantic-version==2.10.0 +Send2Trash==1.8.0 +sentence-transformers==2.2.2 +sentencepiece==0.1.96 +sentry-sdk==1.34.0 +setproctitle==1.3.3 +shortuuid==1.0.11 +simpervisor==0.4 +simplejson==3.17.6 +six==1.16.0 +slovnet==0.6.0 +smart-open==6.4.0 +smmap==5.0.0 +sniffio==1.2.0 +sortedcontainers==2.4.0 +SoundFile==0.10.3.post1 +soupsieve @ file:///home/conda/feedstock_root/build_artifacts/soupsieve_1638550740809/work +sox==1.4.1 +spacy==3.7.2 +spacy-legacy==3.0.12 +spacy-loggers==1.0.5 +SQLAlchemy==1.3.13 +sqlparse==0.4.2 +srsly==2.4.8 +starlette==0.17.1 +stevedore==3.5.0 +table-logger==0.3.6 +tabulate==0.8.9 +taichi==1.6.0 +tblib==1.7.0 +tensorboard==2.11.2 +tensorboard-data-server==0.6.1 +tensorboard-plugin-wit==1.8.1 +termcolor==2.3.0 +terminado==0.13.1 +testpath==0.5.0 +thinc==8.2.1 +threadpoolctl==3.0.0 +tifffile==2021.11.2 +timm==0.9.7 +tokenizers==0.13.3 +toolz==0.11.2 +torch==1.10.1+cu111 +torchaudio==0.10.1+rocm4.1 +torchmetrics==0.11.4 +torchvision==0.11.2+cu111 +tornado==6.1 +tqdm @ file:///home/conda/feedstock_root/build_artifacts/tqdm_1632160078689/work +traitlets==5.1.1 +transformers==4.30.2 +typer==0.4.0 +typing_extensions==4.0.1 +uc-micro-py==1.0.2 +urllib3==1.26.18 +uvicorn==0.17.0 +wandb==0.16.0 +wasabi==1.1.2 +wcwidth==0.2.5 +weasel==0.3.4 +webdataset==0.2.74 +webencodings==0.5.1 +websocket-client==1.2.3 +websockets==11.0.3 +Werkzeug==2.0.2 +widgetsnbextension==3.5.2 +wrapt==1.13.3 +xgboost==1.5.2 +xxhash==3.4.1 +yapf==0.32.0 +yargy==0.16.0 +yarl==1.7.2 +zict==2.0.0 +zipp==3.7.0 diff --git a/Kandinsky-3/kandinsky3/__init__.py b/Kandinsky-3/kandinsky3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a73829095963c216a301d75bbf9cb3840a197612 --- /dev/null +++ b/Kandinsky-3/kandinsky3/__init__.py @@ -0,0 +1,267 @@ +import os +from typing import Optional, Union + +import torch +from huggingface_hub import hf_hub_download, snapshot_download + +from kandinsky3.model.unet import UNet +from kandinsky3.movq import MoVQ +from kandinsky3.condition_encoders import T5TextConditionEncoder +from kandinsky3.condition_processors import T5TextConditionProcessor +from kandinsky3.model.diffusion import BaseDiffusion, get_named_beta_schedule + +from .t2i_pipeline import Kandinsky3T2IPipeline +from .inpainting_pipeline import Kandinsky3InpaintingPipeline + + +def get_T2I_unet( + device: Union[str, torch.device], + weights_path: Optional[str] = None, + dtype: Union[str, torch.dtype] = torch.float32, +) -> (UNet, Optional[torch.Tensor], Optional[dict]): + unet = UNet( + model_channels=384, + num_channels=4, + init_channels=192, + time_embed_dim=1536, + context_dim=4096, + groups=32, + head_dim=64, + expansion_ratio=4, + compression_ratio=2, + dim_mult=(1, 2, 4, 8), + num_blocks=(3, 3, 3, 3), + add_cross_attention=(False, True, True, True), + add_self_attention=(False, True, True, True), + ) + + null_embedding = None + if weights_path: + state_dict = torch.load(weights_path, map_location=torch.device('cpu')) + null_embedding = state_dict['null_embedding'] + unet.load_state_dict(state_dict['unet']) + + unet.to(device=device, dtype=dtype).eval() + return unet, null_embedding + + +def get_T5encoder( + device: Union[str, torch.device], + weights_path: str, + projection_name: str, + dtype: Union[str, torch.dtype] = torch.float32, + low_cpu_mem_usage: bool = True, + load_in_8bit: bool = False, + load_in_4bit: bool = False, +) -> (T5TextConditionProcessor, T5TextConditionEncoder): + tokens_length = 128 + context_dim = 4096 + processor = T5TextConditionProcessor(tokens_length, weights_path) + condition_encoder = T5TextConditionEncoder( + weights_path, context_dim, low_cpu_mem_usage=low_cpu_mem_usage, device=device, + dtype=dtype, load_in_8bit=load_in_8bit, load_in_4bit=load_in_4bit + ) + + if weights_path: + projections_weights_path = os.path.join(weights_path, projection_name) + state_dict = torch.load(projections_weights_path, map_location=torch.device('cpu')) + condition_encoder.projection.load_state_dict(state_dict) + + condition_encoder.projection.to(device=device, dtype=dtype).eval() + return processor, condition_encoder + + +def get_movq( + device: Union[str, torch.device], + weights_path: Optional[str] = None, + dtype: Union[str, torch.dtype] = torch.float32, +) -> MoVQ: + generator_config = { + 'double_z': False, + 'z_channels': 4, + 'resolution': 256, + 'in_channels': 3, + 'out_ch': 3, + 'ch': 256, + 'ch_mult': [1, 2, 2, 4], + 'num_res_blocks': 2, + 'attn_resolutions': [32], + 'dropout': 0.0 + } + movq = MoVQ(generator_config) + + if weights_path: + state_dict = torch.load(weights_path, map_location=torch.device('cpu')) + movq.load_state_dict(state_dict) + + movq.to(device=device, dtype=dtype).eval() + return movq + + +def get_inpainting_unet( + device: Union[str, torch.device], + weights_path: Optional[str] = None, + dtype: Union[str, torch.dtype] = torch.float32, +) -> (UNet, Optional[torch.Tensor], Optional[dict]): + unet = UNet( + model_channels=384, + num_channels=9, + init_channels=192, + time_embed_dim=1536, + context_dim=4096, + groups=32, + head_dim=64, + expansion_ratio=4, + compression_ratio=2, + dim_mult=(1, 2, 4, 8), + num_blocks=(3, 3, 3, 3), + add_cross_attention=(False, True, True, True), + add_self_attention=(False, True, True, True), + ) + + null_embedding = None + if weights_path: + state_dict = torch.load(weights_path, map_location=torch.device('cpu')) + null_embedding = state_dict['null_embedding'] + unet.load_state_dict(state_dict['unet']) + + unet.to(device=device, dtype=dtype).eval() + return unet, null_embedding + + +def get_T2I_pipeline( + device_map: Union[str, torch.device, dict], + dtype_map: Union[str, torch.dtype, dict] = torch.float32, + low_cpu_mem_usage: bool = True, + load_in_8bit: bool = False, + load_in_4bit: bool = False, + cache_dir: str = '/tmp/kandinsky3/', + unet_path: str = None, + text_encoder_path: str = None, + movq_path: str = None, +) -> Kandinsky3T2IPipeline: + # assert ((unet_path is not None) or (text_encoder_path is not None) or (movq_path is not None)) + if not isinstance(device_map, dict): + device_map = { + 'unet': device_map, 'text_encoder': device_map, 'movq': device_map + } + if not isinstance(dtype_map, dict): + dtype_map = { + 'unet': dtype_map, 'text_encoder': dtype_map, 'movq': dtype_map + } + + if unet_path is None: + unet_path = hf_hub_download( + repo_id="ai-forever/Kandinsky3.1", filename='weights/kandinsky3.pt', cache_dir=cache_dir + ) + if text_encoder_path is None: + text_encoder_path = snapshot_download( + repo_id="ai-forever/Kandinsky3.1", allow_patterns="weights/flan_ul2_encoder/*", cache_dir=cache_dir + ) + text_encoder_path = os.path.join(text_encoder_path, 'weights/flan_ul2_encoder') + if movq_path is None: + movq_path = hf_hub_download( + repo_id="ai-forever/Kandinsky3.1", filename='weights/movq.pt', cache_dir=cache_dir + ) + + unet, null_embedding = get_T2I_unet(device_map['unet'], unet_path, dtype=dtype_map['unet']) + processor, condition_encoder = get_T5encoder( + device_map['text_encoder'], text_encoder_path, 'projection.pt', dtype=dtype_map['text_encoder'], + low_cpu_mem_usage=low_cpu_mem_usage, load_in_8bit=load_in_8bit, load_in_4bit=load_in_4bit + ) + movq = get_movq(device_map['movq'], movq_path, dtype=dtype_map['movq']) + return Kandinsky3T2IPipeline( + device_map, dtype_map, unet, null_embedding, processor, condition_encoder, movq, False + ) + + +def get_T2I_Flash_pipeline( + device_map: Union[str, torch.device, dict], + dtype_map: Union[str, torch.dtype, dict] = torch.float32, + low_cpu_mem_usage: bool = True, + load_in_8bit: bool = False, + load_in_4bit: bool = False, + cache_dir: str = '/tmp/kandinsky3/', + unet_path: str = None, + text_encoder_path: str = None, + movq_path: str = None, +) -> Kandinsky3T2IPipeline: + # assert ((unet_path is not None) or (text_encoder_path is not None) or (movq_path is not None)) + if not isinstance(device_map, dict): + device_map = { + 'unet': device_map, 'text_encoder': device_map, 'movq': device_map + } + if not isinstance(dtype_map, dict): + dtype_map = { + 'unet': dtype_map, 'text_encoder': dtype_map, 'movq': dtype_map + } + + if unet_path is None: + unet_path = hf_hub_download( + repo_id="ai-forever/Kandinsky3.1", filename='weights/kandinsky3_flash.pt', cache_dir=cache_dir + ) + if text_encoder_path is None: + text_encoder_path = snapshot_download( + repo_id="ai-forever/Kandinsky3.1", allow_patterns="weights/flan_ul2_encoder/*", cache_dir=cache_dir + ) + text_encoder_path = os.path.join(text_encoder_path, 'weights/flan_ul2_encoder') + if movq_path is None: + movq_path = hf_hub_download( + repo_id="ai-forever/Kandinsky3.1", filename='weights/movq.pt', cache_dir=cache_dir + ) + + unet, null_embedding = get_T2I_unet(device_map['unet'], unet_path, dtype=dtype_map['unet']) + processor, condition_encoder = get_T5encoder( + device_map['text_encoder'], text_encoder_path, 'projection_flash.pt', dtype=dtype_map['text_encoder'], + low_cpu_mem_usage=low_cpu_mem_usage, load_in_8bit=load_in_8bit, load_in_4bit=load_in_4bit + ) + movq = get_movq(device_map['movq'], movq_path, dtype=dtype_map['movq']) + return Kandinsky3T2IPipeline( + device_map, dtype_map, unet, null_embedding, processor, condition_encoder, movq, True + ) + + +def get_inpainting_pipeline( + device_map: Union[str, torch.device, dict], + dtype_map: Union[str, torch.dtype, dict] = torch.float32, + low_cpu_mem_usage: bool = True, + load_in_8bit: bool = False, + load_in_4bit: bool = False, + cache_dir: str = '/tmp/kandinsky3/', + unet_path: str = None, + text_encoder_path: str = None, + movq_path: str = None, +) -> Kandinsky3InpaintingPipeline: + # assert ((unet_path is not None) or (text_encoder_path is not None) or (movq_path is not None)) + if not isinstance(device_map, dict): + device_map = { + 'unet': device_map, 'text_encoder': device_map, 'movq': device_map + } + if not isinstance(dtype_map, dict): + dtype_map = { + 'unet': dtype_map, 'text_encoder': dtype_map, 'movq': dtype_map + } + + if unet_path is None: + unet_path = hf_hub_download( + repo_id="ai-forever/Kandinsky3.1", filename='weights/kandinsky3_inpainting.pt', cache_dir=cache_dir + ) + if text_encoder_path is None: + text_encoder_path = snapshot_download( + repo_id="ai-forever/Kandinsky3.1", allow_patterns="weights/flan_ul2_encoder/*", cache_dir=cache_dir + ) + text_encoder_path = os.path.join(text_encoder_path, 'weights/flan_ul2_encoder') + if movq_path is None: + movq_path = hf_hub_download( + repo_id="ai-forever/Kandinsky3.1", filename='weights/movq.pt', cache_dir=cache_dir + ) + + unet, null_embedding = get_inpainting_unet(device_map['unet'], unet_path, dtype=dtype_map['unet']) + processor, condition_encoder = get_T5encoder( + device_map['text_encoder'], text_encoder_path, 'projection_inpainting.pt', dtype=dtype_map['text_encoder'], + low_cpu_mem_usage=low_cpu_mem_usage, load_in_8bit=load_in_8bit, load_in_4bit=load_in_4bit + ) + movq = get_movq(device_map['movq'], movq_path, dtype=dtype_map['movq']) + return Kandinsky3InpaintingPipeline( + device_map, dtype_map, unet, null_embedding, processor, condition_encoder, movq + ) diff --git a/Kandinsky-3/kandinsky3/condition_encoders.py b/Kandinsky-3/kandinsky3/condition_encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..cd5edc51713943ea2e874b8b1f019e50a6697850 --- /dev/null +++ b/Kandinsky-3/kandinsky3/condition_encoders.py @@ -0,0 +1,40 @@ +import torch +from torch import nn +from transformers import T5EncoderModel +from typing import Optional, Union + + +class T5TextConditionEncoder(nn.Module): + + def __init__( + self, model_path, context_dim, + low_cpu_mem_usage: bool = True, device: Optional[str] = None, + dtype: Union[str, torch.dtype] = torch.float32, load_in_4bit: bool = False, load_in_8bit: bool = False + ): + super().__init__() + self.encoder = T5EncoderModel.from_pretrained( + model_path, low_cpu_mem_usage=low_cpu_mem_usage, device_map=device, + torch_dtype=dtype, load_in_8bit=load_in_8bit, load_in_4bit=load_in_4bit, + ).encoder + self.projection = nn.Sequential( + nn.Linear(self.encoder.config.d_model, context_dim, bias=False), + nn.LayerNorm(context_dim) + ) + + def forward(self, model_input): + embeddings = self.encoder(**model_input).last_hidden_state + context = self.projection(embeddings) + if 'attention_mask' in model_input: + context_mask = model_input['attention_mask'] + context[context_mask == 0] = torch.zeros_like(context[context_mask == 0]) + max_seq_length = context_mask.sum(-1).max() + 1 + context = context[:, :max_seq_length] + context_mask = context_mask[:, :max_seq_length] + else: + context_mask = torch.ones(*embeddings.shape[:-1], dtype=torch.long, device=embeddings.device) + return context, context_mask + + +def get_condition_encoder(conf): + return T5TextConditionEncoder(**conf) + diff --git a/Kandinsky-3/kandinsky3/condition_processors.py b/Kandinsky-3/kandinsky3/condition_processors.py new file mode 100644 index 0000000000000000000000000000000000000000..69eafee143e3fbc40cf0678949db8407356157ec --- /dev/null +++ b/Kandinsky-3/kandinsky3/condition_processors.py @@ -0,0 +1,34 @@ +import torch +from transformers import T5Tokenizer + + +class T5TextConditionProcessor: + + def __init__(self, tokens_length, processor_path): + self.tokens_length = tokens_length + self.processor = T5Tokenizer.from_pretrained(processor_path) + + def encode(self, text=None, negative_text=None): + encoded = self.processor(text, max_length=self.tokens_length, truncation=True) + pad_length = self.tokens_length - len(encoded['input_ids']) + input_ids = encoded['input_ids'] + [self.processor.pad_token_id] * pad_length + attention_mask = encoded['attention_mask'] + [0] * pad_length + condition_model_input = { + 'input_ids': torch.tensor(input_ids, dtype=torch.long), + 'attention_mask': torch.tensor(attention_mask, dtype=torch.long) + } + + if negative_text is not None: + negative_encoded = self.processor(negative_text, max_length=self.tokens_length, truncation=True) + negative_input_ids = negative_encoded['input_ids'][:len(encoded['input_ids'])] + negative_input_ids[-1] = self.processor.eos_token_id + negative_pad_length = self.tokens_length - len(negative_input_ids) + negative_input_ids = negative_input_ids + [self.processor.pad_token_id] * negative_pad_length + negative_attention_mask = encoded['attention_mask'] + [0] * pad_length + negative_condition_model_input = { + 'input_ids': torch.tensor(negative_input_ids, dtype=torch.long), + 'attention_mask': torch.tensor(negative_attention_mask, dtype=torch.long) + } + else: + negative_condition_model_input = None + return condition_model_input, negative_condition_model_input diff --git a/Kandinsky-3/kandinsky3/inpainting_pipeline.py b/Kandinsky-3/kandinsky3/inpainting_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..4a3a65ab27676199464446a29255fe616d620650 --- /dev/null +++ b/Kandinsky-3/kandinsky3/inpainting_pipeline.py @@ -0,0 +1,168 @@ +from typing import Union, List +import PIL +import numpy as np + +import torch +import torchvision.transforms as T +from einops import repeat + +from kandinsky3.model.unet import UNet +from kandinsky3.movq import MoVQ +from kandinsky3.condition_encoders import T5TextConditionEncoder +from kandinsky3.condition_processors import T5TextConditionProcessor +from kandinsky3.model.diffusion import BaseDiffusion, get_named_beta_schedule +from kandinsky3.utils import resize_image_for_diffusion, resize_mask_for_diffusion + + +class Kandinsky3InpaintingPipeline: + + def __init__( + self, + device_map: Union[str, torch.device, dict], + dtype_map: Union[str, torch.dtype, dict], + unet: UNet, + null_embedding: torch.Tensor, + t5_processor: T5TextConditionProcessor, + t5_encoder: T5TextConditionEncoder, + movq: MoVQ, + ): + self.device_map = device_map + self.dtype_map = dtype_map + self.to_pil = T.ToPILImage() + self.to_tensor = T.ToTensor() + + self.unet = unet + self.null_embedding = null_embedding + self.t5_processor = t5_processor + self.t5_encoder = t5_encoder + self.movq = movq + + def shared_step(self, batch: dict) -> dict: + image = batch['image'] + condition_model_input = batch['text'] + negative_condition_model_input = batch['negative_text'] + + bs = image.shape[0] + + masked_latent = None + mask = batch['mask'] + + if 'masked_image' in batch: + masked_latent = batch['masked_image'] + elif self.unet.in_layer.in_channels == 9: + masked_latent = image.masked_fill((1 - mask).bool(), 0) + else: + raise ValueError() + + with torch.cuda.amp.autocast(dtype=self.dtype_map['movq']): + masked_latent = self.movq.encode(masked_latent) + mask = torch.nn.functional.interpolate(mask, size=(masked_latent.shape[2], masked_latent.shape[3])) + + with torch.cuda.amp.autocast(dtype=self.dtype_map['text_encoder']): + context, context_mask = self.t5_encoder(condition_model_input) + + if negative_condition_model_input is not None: + negative_context, negative_context_mask = self.t5_encoder(negative_condition_model_input) + else: + negative_context, negative_context_mask = None, None + + return { + 'context': context, + 'context_mask': context_mask, + 'negative_context': negative_context, + 'negative_context_mask': negative_context_mask, + 'image': image, + 'masked_latent': masked_latent, + 'mask': mask + } + + def prepare_batch( + self, + text: str, + negative_text: str, + image: PIL.Image.Image, + mask: np.ndarray, + ) -> dict: + condition_model_input, negative_condition_model_input = self.t5_processor.encode( + text=text, negative_text=negative_text + ) + batch = { + 'image': self.to_tensor(resize_image_for_diffusion(image.convert("RGB"))) * 2 - 1, + 'mask': 1 - self.to_tensor(resize_mask_for_diffusion(mask)), + 'text': condition_model_input, + 'negative_text': negative_condition_model_input + } + batch['mask'] = batch['mask'].type(self.dtype_map['movq']) + + batch['image'] = batch['image'].unsqueeze(0).to(self.device_map['movq']) + batch['text']['input_ids'] = batch['text']['input_ids'].unsqueeze(0).to(self.device_map['text_encoder']) + batch['text']['attention_mask'] = batch['text']['attention_mask'].unsqueeze(0).to( + self.device_map['text_encoder']) + batch['mask'] = batch['mask'].unsqueeze(0).to(self.device_map['movq']) + + if negative_condition_model_input is not None: + batch['negative_text']['input_ids'] = batch['negative_text']['input_ids'].to( + self.device_map['text_encoder']) + batch['negative_text']['attention_mask'] = batch['negative_text']['attention_mask'].to( + self.device_map['text_encoder']) + + return batch + + def __call__( + self, + text: str, + image: PIL.Image.Image, + mask: np.ndarray, + negative_text: str = None, + images_num: int = 1, + bs: int = 1, + steps: int = 50, + guidance_weight_text: float = 4, + eta=1.0 + ) -> List[PIL.Image.Image]: + + with torch.no_grad(): + batch = self.prepare_batch(text, negative_text, image, mask) + processed = self.shared_step(batch) + betas = get_named_beta_schedule('cosine', 1000) + base_diffusion = BaseDiffusion(betas, percentile=0.95) + times = list(range(999, 0, -1000 // steps)) + + pil_images = [] + k, m = images_num // bs, images_num % bs + for minibatch in [bs] * k + [m]: + if minibatch == 0: + continue + + bs_context = repeat(processed['context'], '1 n d -> b n d', b=minibatch) + bs_context_mask = repeat(processed['context_mask'], '1 n -> b n', b=minibatch) + + if processed['negative_context'] is not None: + bs_negative_context = repeat(processed['negative_context'], '1 n d -> b n d', b=minibatch) + bs_negative_context_mask = repeat(processed['negative_context_mask'], '1 n -> b n', b=minibatch) + else: + bs_negative_context, bs_negative_context_mask = None, None + + mask = processed['mask'].repeat_interleave(minibatch, dim=0) + masked_latent = processed['masked_latent'].repeat_interleave(minibatch, dim=0) + + minibatch = masked_latent.shape[0] + + with torch.cuda.amp.autocast(dtype=self.dtype_map['unet']): + with torch.no_grad(): + images = base_diffusion.p_sample_loop( + self.unet, (minibatch, 4, masked_latent.shape[2], masked_latent.shape[3]), times, + self.device_map['unet'], + bs_context, bs_context_mask, self.null_embedding, guidance_weight_text, eta, + negative_context=bs_negative_context, negative_context_mask=bs_negative_context_mask, + mask=mask, masked_latent=masked_latent, gan=False + ) + + with torch.cuda.amp.autocast(dtype=self.dtype_map['movq']): + images = torch.cat([self.movq.decode(image) for image in images.chunk(2)]) + images = torch.clip((images + 1.) / 2., 0., 1.).cpu() + + for images_chunk in images.chunk(1): + pil_images += [self.to_pil(image) for image in images_chunk] + + return pil_images diff --git a/Kandinsky-3/kandinsky3/model/__init__.py b/Kandinsky-3/kandinsky3/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kandinsky-3/kandinsky3/model/diffusion.py b/Kandinsky-3/kandinsky3/model/diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..0d4fa0a4c316aad11e0fb7db0e006b953384e1b4 --- /dev/null +++ b/Kandinsky-3/kandinsky3/model/diffusion.py @@ -0,0 +1,200 @@ +import math + +import torch +from einops import rearrange +from tqdm import tqdm + +from .utils import get_tensor_items + + +def get_named_beta_schedule(schedule_name, timesteps): + if schedule_name == "linear": + scale = 1000 / timesteps + beta_start = scale * 0.0001 + beta_end = scale * 0.02 + return torch.linspace( + beta_start, beta_end, timesteps, dtype=torch.float32 + ) + elif schedule_name == "cosine": + alpha_bar = lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2 + betas = [] + for i in range(timesteps): + t1 = i / timesteps + t2 = (i + 1) / timesteps + betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), 0.999)) + return torch.tensor(betas, dtype=torch.float32) + + +class BaseDiffusion: + + def __init__(self, betas, percentile=None, gen_noise=torch.randn_like): + self.betas = betas + self.num_timesteps = betas.shape[0] + + alphas = 1. - betas + self.alphas_cumprod = torch.cumprod(alphas, dim=0) + self.alphas_cumprod_prev = torch.cat([torch.ones(1, dtype=betas.dtype), self.alphas_cumprod[:-1]]) + + # calculate q(x_t | x_{t-1}) + self.sqrt_alphas_cumprod = torch.sqrt(self.alphas_cumprod) + self.sqrt_one_minus_alphas_cumprod = torch.sqrt(1. - self.alphas_cumprod) + + # calculate q(x_{t-1} | x_t, x_0) + self.posterior_mean_coef_1 = torch.sqrt(self.alphas_cumprod_prev) * betas / (1. - self.alphas_cumprod) + self.posterior_mean_coef_2 = torch.sqrt(alphas) * (1. - self.alphas_cumprod_prev) / (1. - self.alphas_cumprod) + self.posterior_variance = betas * (1. - self.alphas_cumprod_prev) / (1. - self.alphas_cumprod) + self.posterior_log_variance = torch.log( + torch.cat([self.posterior_variance[1].unsqueeze(0), self.posterior_variance[1:]]) + ) + + self.percentile = percentile + self.time_scale = 1000 // self.num_timesteps + self.gen_noise = gen_noise + self.jump_length = 3 + + def process_x_start(self, x_start): + bs, ndims = x_start.shape[0], len(x_start.shape[1:]) + if self.percentile is not None: + quantile = torch.quantile( + rearrange(x_start, 'b ... -> b (...)').abs(), + self.percentile, + dim=-1 + ) + quantile = torch.clip(quantile, min=1.) + quantile = quantile.reshape(bs, *((1,) * ndims)) + return torch.clip(x_start, -quantile, quantile) / quantile + else: + return torch.clip(x_start, -1., 1.) + + def get_x_start(self, x, t, noise): + sqrt_one_minus_alphas_cumprod = get_tensor_items(self.sqrt_one_minus_alphas_cumprod, t, noise.shape) + sqrt_alphas_cumprod = get_tensor_items(self.sqrt_alphas_cumprod, t, noise.shape) + pred_x_start = (x - sqrt_one_minus_alphas_cumprod * noise) / sqrt_alphas_cumprod + return pred_x_start + + def get_noise(self, x, t, x_start): + sqrt_one_minus_alphas_cumprod = get_tensor_items(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) + sqrt_alphas_cumprod = get_tensor_items(self.sqrt_alphas_cumprod, t, x_start.shape) + pred_noise = (x - sqrt_alphas_cumprod * x_start) / sqrt_one_minus_alphas_cumprod + return pred_noise + + def q_sample(self, x_start, t, noise=None): + if noise is None: + noise = self.gen_noise(x_start) + sqrt_alphas_cumprod = get_tensor_items(self.sqrt_alphas_cumprod, t, x_start.shape) + sqrt_one_minus_alphas_cumprod = get_tensor_items(self.sqrt_one_minus_alphas_cumprod, t, noise.shape) + x_t = sqrt_alphas_cumprod * x_start + sqrt_one_minus_alphas_cumprod * noise + return x_t + + def q_posterior_mean_variance(self, x_start, x_t, t): + posterior_mean_coef_1 = get_tensor_items(self.posterior_mean_coef_1, t, x_start.shape) + posterior_mean_coef_2 = get_tensor_items(self.posterior_mean_coef_2, t, x_t.shape) + posterior_mean = posterior_mean_coef_1 * x_start + posterior_mean_coef_2 * x_t + + posterior_variance = get_tensor_items(self.posterior_variance, t, x_start.shape) + posterior_log_variance = get_tensor_items(self.posterior_log_variance, t, x_start.shape) + return posterior_mean, posterior_variance, posterior_log_variance + + def q_posterior_variance(self, t, prev_t, shape, eta=1., ): + alphas_cumprod = get_tensor_items(self.alphas_cumprod, t, shape) + prev_alphas_cumprod = get_tensor_items(self.alphas_cumprod, prev_t, shape) + + posterior_variance = torch.sqrt( + eta * (1. - alphas_cumprod / prev_alphas_cumprod) * (1. - prev_alphas_cumprod) / (1. - alphas_cumprod) + ) + return posterior_variance + + def text_guidance( + self, model, x, t, context, context_mask, null_embedding, guidance_weight_text, + uncondition_context=None, uncondition_context_mask=None, mask=None, masked_latent=None + ): + large_x = x.repeat(2, 1, 1, 1) + large_t = t.repeat(2).to(x.dtype) + + if uncondition_context is None: + uncondition_context = torch.zeros_like(context) + uncondition_context_mask = torch.zeros_like(context_mask) + uncondition_context[:, 0] = null_embedding + uncondition_context_mask[:, 0] = 1 + large_context = torch.cat([context, uncondition_context]) + large_context_mask = torch.cat([context_mask, uncondition_context_mask]) + + if mask is not None: + mask = mask.repeat(2, 1, 1, 1) + if masked_latent is not None: + masked_latent = masked_latent.repeat(2, 1, 1, 1) + + if model.in_layer.in_channels == 9: + large_x = torch.cat([large_x, mask, masked_latent], dim=1) + + pred_large_noise = model(large_x, large_t * self.time_scale, large_context, large_context_mask.bool()) + pred_noise, uncond_pred_noise = torch.chunk(pred_large_noise, 2) + pred_noise = (guidance_weight_text + 1.) * pred_noise - guidance_weight_text * uncond_pred_noise + return pred_noise + + def p_mean_variance( + self, model, x, t, prev_t, context, context_mask, null_embedding, guidance_weight_text, eta=1., + negative_context=None, negative_context_mask=None, mask=None, masked_latent=None + ): + + pred_noise = self.text_guidance( + model, x, t, context, context_mask, null_embedding, guidance_weight_text, + negative_context, negative_context_mask, mask, masked_latent + ) + + pred_x_start = self.get_x_start(x, t, pred_noise) + pred_x_start = self.process_x_start(pred_x_start) + pred_noise = self.get_noise(x, t, pred_x_start) + pred_var = self.q_posterior_variance(t, prev_t, x.shape, eta) + + prev_alphas_cumprod = get_tensor_items(self.alphas_cumprod, prev_t, x.shape) + pred_mean = torch.sqrt(prev_alphas_cumprod) * pred_x_start + pred_mean += torch.sqrt(1. - prev_alphas_cumprod - pred_var ** 2) * pred_noise + return pred_mean, pred_var + + @torch.no_grad() + def p_sample( + self, model, x, t, prev_t, context, context_mask, null_embedding, guidance_weight_text, eta=1., + negative_context=None, negative_context_mask=None, mask=None, masked_latent=None + ): + bs = x.shape[0] + ndims = len(x.shape[1:]) + pred_mean, pred_var = self.p_mean_variance( + model, x, t, prev_t, context, context_mask, null_embedding, guidance_weight_text, eta, + negative_context=negative_context, negative_context_mask=negative_context_mask, + mask=mask, masked_latent=masked_latent + ) + noise = torch.randn_like(x) + mask = (prev_t != 0).reshape(bs, *((1,) * ndims)) + sample = pred_mean + mask * pred_var * noise + return sample + + @torch.no_grad() + def p_sample_loop( + self, model, shape, times, device, context, context_mask, null_embedding, guidance_weight_text, eta=1., + negative_context=None, negative_context_mask=None, mask=None, masked_latent=None, gan=False, + ): + img = torch.randn(*shape, device=device) + times = times + [0, ] + times = list(zip(times[:-1], times[1:])) + + for time, prev_time in tqdm(times): + time = torch.tensor([time] * shape[0], device=device) + if gan: + x_t = self.q_sample(img, time) + pred_noise = model(x_t, time.type(x_t.dtype), context, context_mask.bool()) + img = self.get_x_start(x_t, time, pred_noise) + else: + prev_time = torch.tensor([prev_time] * shape[0], device=device) + img = self.p_sample( + model, img, time, prev_time, context, context_mask, null_embedding, guidance_weight_text, eta, + negative_context=negative_context, negative_context_mask=negative_context_mask, + mask=mask, masked_latent=masked_latent + ) + return img + + +def get_diffusion(conf): + betas = get_named_beta_schedule(**conf.schedule_params) + base_diffusion = BaseDiffusion(betas, **conf.diffusion_params) + return base_diffusion diff --git a/Kandinsky-3/kandinsky3/model/nn.py b/Kandinsky-3/kandinsky3/model/nn.py new file mode 100644 index 0000000000000000000000000000000000000000..dfbeef55b914376dafc5084528769a5ed938daab --- /dev/null +++ b/Kandinsky-3/kandinsky3/model/nn.py @@ -0,0 +1,84 @@ +import math + +import torch +from torch import nn, einsum +from einops import rearrange, repeat + +from .utils import exist + + +class Identity(nn.Module): + def __init__(self, *args, **kwargs): + super().__init__() + + @staticmethod + def forward(x, *args, **kwargs): + return x + + +class SinusoidalPosEmb(nn.Module): + + def __init__(self, dim): + super().__init__() + self.dim = dim + + def forward(self, x): + half_dim = self.dim // 2 + emb = math.log(10000) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, device=x.device, dtype=x.dtype) * -emb) + emb = rearrange(x, 'i -> i 1') * rearrange(emb, 'j -> 1 j') + return torch.cat((emb.sin(), emb.cos()), dim=-1) + + +class ConditionalGroupNorm(nn.Module): + + def __init__(self, groups, normalized_shape, context_dim): + super().__init__() + self.norm = nn.GroupNorm(groups, normalized_shape, affine=False) + self.context_mlp = nn.Sequential( + nn.SiLU(), + nn.Linear(context_dim, 2 * normalized_shape) + ) + self.context_mlp[1].weight.data.zero_() + self.context_mlp[1].bias.data.zero_() + + def forward(self, x, context): + context = self.context_mlp(context) + ndims = ' 1' * len(x.shape[2:]) + context = rearrange(context, f'b c -> b c{ndims}') + + scale, shift = context.chunk(2, dim=1) + x = self.norm(x) * (scale + 1.) + shift + return x + + +class Attention(nn.Module): + + def __init__(self, in_channels, out_channels, context_dim, head_dim=64): + super().__init__() + assert out_channels % head_dim == 0 + self.num_heads = out_channels // head_dim + self.scale = head_dim ** -0.5 + + self.to_query = nn.Linear(in_channels, out_channels, bias=False) + self.to_key = nn.Linear(context_dim, out_channels, bias=False) + self.to_value = nn.Linear(context_dim, out_channels, bias=False) + + self.output_layer = nn.Linear(out_channels, out_channels, bias=False) + + def forward(self, x, context, context_mask=None): + query = rearrange(self.to_query(x), 'b n (h d) -> b h n d', h=self.num_heads) + key = rearrange(self.to_key(context), 'b n (h d) -> b h n d', h=self.num_heads) + value = rearrange(self.to_value(context), 'b n (h d) -> b h n d', h=self.num_heads) + + attention_matrix = einsum('b h i d, b h j d -> b h i j', query, key) * self.scale + if exist(context_mask): + max_neg_value = -torch.finfo(attention_matrix.dtype).max + context_mask = rearrange(context_mask, 'b j -> b 1 1 j') + attention_matrix = attention_matrix.masked_fill(~context_mask, max_neg_value) + attention_matrix = attention_matrix.softmax(dim=-1) + + out = einsum('b h i j, b h j d -> b h i d', attention_matrix, value) + out = rearrange(out, 'b h n d -> b n (h d)') + out = self.output_layer(out) + return out diff --git a/Kandinsky-3/kandinsky3/model/unet.py b/Kandinsky-3/kandinsky3/model/unet.py new file mode 100644 index 0000000000000000000000000000000000000000..b0475f1050b6b02e2a351acf290547d89452f0f3 --- /dev/null +++ b/Kandinsky-3/kandinsky3/model/unet.py @@ -0,0 +1,516 @@ +import torch +from torch import nn, einsum +from einops import rearrange + +from .nn import Identity, Attention, SinusoidalPosEmb, ConditionalGroupNorm +from .utils import exist, set_default_item, set_default_layer +import torch.nn.functional as F + + +class Block(nn.Module): + + def __init__(self, in_channels, out_channels, time_embed_dim, kernel_size=3, norm_groups=32, up_resolution=None): + super().__init__() + self.group_norm = ConditionalGroupNorm(norm_groups, in_channels, time_embed_dim) + self.activation = nn.SiLU() + self.up_sample = set_default_layer( + exist(up_resolution) and up_resolution, + nn.ConvTranspose2d, (in_channels, in_channels), {'kernel_size': 2, 'stride': 2} + ) + padding = set_default_item(kernel_size == 1, 0, 1) + self.projection = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding) + self.down_sample = set_default_layer( + exist(up_resolution) and not up_resolution, + nn.Conv2d, (out_channels, out_channels), {'kernel_size': 2, 'stride': 2} + ) + + def forward(self, x, time_embed): + x = self.group_norm(x, time_embed) + x = self.activation(x) + x = self.up_sample(x) + x = self.projection(x) + x = self.down_sample(x) + return x + + +class ResNetBlock(nn.Module): + + def __init__( + self, in_channels, out_channels, time_embed_dim, norm_groups=32, compression_ratio=2, up_resolutions=4*[None] + ): + super().__init__() + kernel_sizes = [1, 3, 3, 1] + hidden_channel = max(in_channels, out_channels) // compression_ratio + hidden_channels = [(in_channels, hidden_channel)] + [(hidden_channel, hidden_channel)] * 2 + [(hidden_channel, out_channels)] + self.resnet_blocks = nn.ModuleList([ + Block(in_channel, out_channel, time_embed_dim, kernel_size, norm_groups, up_resolution) + for (in_channel, out_channel), kernel_size, up_resolution in zip(hidden_channels, kernel_sizes, up_resolutions) + ]) + + self.shortcut_up_sample = set_default_layer( + True in up_resolutions, + nn.ConvTranspose2d, (in_channels, in_channels), {'kernel_size': 2, 'stride': 2} + ) + self.shortcut_projection = set_default_layer( + in_channels != out_channels, + nn.Conv2d, (in_channels, out_channels), {'kernel_size': 1} + ) + self.shortcut_down_sample = set_default_layer( + False in up_resolutions, + nn.Conv2d, (out_channels, out_channels), {'kernel_size': 2, 'stride': 2} + ) + + def forward(self, x, time_embed): + out = x + for resnet_block in self.resnet_blocks: + out = resnet_block(out, time_embed) + + x = self.shortcut_up_sample(x) + x = self.shortcut_projection(x) + x = self.shortcut_down_sample(x) + x = x + out + return x + + +class AttentionPolling(nn.Module): + + def __init__(self, num_channels, context_dim, head_dim=64): + super().__init__() + self.attention = Attention(context_dim, num_channels, context_dim, head_dim) + + def forward(self, x, context, context_mask=None): + context = self.attention(context.mean(dim=1, keepdim=True), context, context_mask) + return x + context.squeeze(1) + + +class AttentionBlock(nn.Module): + + def __init__(self, num_channels, time_embed_dim, context_dim=None, norm_groups=32, head_dim=64, expansion_ratio=4): + super().__init__() + self.in_norm = ConditionalGroupNorm(norm_groups, num_channels, time_embed_dim) + self.attention = Attention(num_channels, num_channels, context_dim or num_channels, head_dim) + + hidden_channels = expansion_ratio * num_channels + self.out_norm = ConditionalGroupNorm(norm_groups, num_channels, time_embed_dim) + self.feed_forward = nn.Sequential( + nn.Conv2d(num_channels, hidden_channels, kernel_size=1, bias=False), + nn.SiLU(), + nn.Conv2d(hidden_channels, num_channels, kernel_size=1, bias=False), + ) + + def forward(self, x, time_embed, context=None, context_mask=None): + height, width = x.shape[-2:] + out = self.in_norm(x, time_embed) + out = rearrange(out, 'b c h w -> b (h w) c', h=height, w=width) + context = set_default_item(exist(context), context, out) + out = self.attention(out, context, context_mask) + out = rearrange(out, 'b (h w) c -> b c h w', h=height, w=width) + x = x + out + + out = self.out_norm(x, time_embed) + out = self.feed_forward(out) + x = x + out + return x + + +class DownSampleBlock(nn.Module): + + def __init__( + self, in_channels, out_channels, time_embed_dim, context_dim=None, + num_blocks=3, groups=32, head_dim=64, expansion_ratio=4, compression_ratio=2, + down_sample=True, self_attention=True + ): + super().__init__() + self.self_attention_block = set_default_layer( + self_attention, + AttentionBlock, + (in_channels, time_embed_dim, None, groups, head_dim, expansion_ratio), + layer_2=Identity + ) + + up_resolutions = [[None] * 4] * (num_blocks - 1) + [[None, None, set_default_item(down_sample, False), None]] + hidden_channels = [(in_channels, out_channels)] + [(out_channels, out_channels)] * (num_blocks - 1) + self.resnet_attn_blocks = nn.ModuleList([ + nn.ModuleList([ + ResNetBlock(in_channel, out_channel, time_embed_dim, groups, compression_ratio), + set_default_layer( + exist(context_dim), + AttentionBlock, + (out_channel, time_embed_dim, context_dim, groups, head_dim, expansion_ratio), + layer_2=Identity + ), + ResNetBlock(out_channel, out_channel, time_embed_dim, groups, compression_ratio, up_resolution), + ]) for (in_channel, out_channel), up_resolution in zip(hidden_channels, up_resolutions) + ]) + + def forward(self, x, time_embed, context=None, context_mask=None, control_net_residual=None): + x = self.self_attention_block(x, time_embed) + for in_resnet_block, attention, out_resnet_block in self.resnet_attn_blocks: + x = in_resnet_block(x, time_embed) + x = attention(x, time_embed, context, context_mask) + x = out_resnet_block(x, time_embed) + return x + + +class UpSampleBlock(nn.Module): + + def __init__( + self, in_channels, cat_dim, out_channels, time_embed_dim, context_dim=None, + num_blocks=3, groups=32, head_dim=64, expansion_ratio=4, compression_ratio=2, + up_sample=True, self_attention=True + ): + super().__init__() + up_resolutions = [[None, set_default_item(up_sample, True), None, None]] + [[None] * 4] * (num_blocks - 1) + hidden_channels = [(in_channels + cat_dim, in_channels)] + [(in_channels, in_channels)] * (num_blocks - 2) + [(in_channels, out_channels)] + self.resnet_attn_blocks = nn.ModuleList([ + nn.ModuleList([ + ResNetBlock(in_channel, in_channel, time_embed_dim, groups, compression_ratio, up_resolution), + set_default_layer( + exist(context_dim), + AttentionBlock, + (in_channel, time_embed_dim, context_dim, groups, head_dim, expansion_ratio), + layer_2=Identity + ), + ResNetBlock(in_channel, out_channel, time_embed_dim, groups, compression_ratio), + ]) for (in_channel, out_channel), up_resolution in zip(hidden_channels, up_resolutions) + ]) + + self.self_attention_block = set_default_layer( + self_attention, + AttentionBlock, + (out_channels, time_embed_dim, None, groups, head_dim, expansion_ratio), + layer_2=Identity + ) + + def forward(self, x, time_embed, context=None, context_mask=None): + for in_resnet_block, attention, out_resnet_block in self.resnet_attn_blocks: + x = in_resnet_block(x, time_embed) + x = attention(x, time_embed, context, context_mask) + x = out_resnet_block(x, time_embed) + x = self.self_attention_block(x, time_embed) + return x + +class ControlNetModel(nn.Module): + def __init__(self, + model_channels, + init_channels=None, + num_channels=3, + out_channels=4, + time_embed_dim=None, + context_dim=None, + groups=32, + head_dim=64, + expansion_ratio=4, + compression_ratio=2, + dim_mult=(1, 2, 4, 8), + num_blocks=(3, 3, 3, 3), + add_cross_attention=(False, True, True, True), + add_self_attention=(False, True, True, True) + ): + super().__init__() + init_channels = init_channels or model_channels + self.to_time_embed = nn.Sequential( + SinusoidalPosEmb(init_channels), + nn.Linear(init_channels, time_embed_dim), + nn.SiLU(), + nn.Linear(time_embed_dim, time_embed_dim) + ) + self.feature_pooling = AttentionPolling(time_embed_dim, context_dim, head_dim) + + self.in_layer = nn.Conv2d(num_channels, init_channels, kernel_size=3, padding=1) + + hidden_dims = [init_channels, *map(lambda mult: model_channels * mult, dim_mult)] + in_out_dims = list(zip(hidden_dims[:-1], hidden_dims[1:])) + text_dims = [set_default_item(is_exist, context_dim) for is_exist in add_cross_attention] + layer_params = [num_blocks, text_dims, add_self_attention] + rev_layer_params = map(reversed, layer_params) + + cat_dims = [] + self.num_levels = len(in_out_dims) + self.down_samples = nn.ModuleList([]) + for level, ((in_dim, out_dim), res_block_num, text_dim, self_attention) in enumerate(zip(in_out_dims, *layer_params)): + down_sample = level != (self.num_levels - 1) + cat_dims.append(set_default_item(level != (self.num_levels - 1), out_dim, 0)) + self.down_samples.append( + DownSampleBlock( + in_dim, out_dim, time_embed_dim, text_dim, res_block_num, groups, head_dim, expansion_ratio, + compression_ratio, down_sample, self_attention + ) + ) + + def forward(self, x, time, context=None, context_mask=None): + time_embed = self.to_time_embed(time) + if exist(context): + time_embed = self.feature_pooling(time_embed, context, context_mask) + + hidden_states = [] + x = self.in_layer(x) + for level, down_sample in enumerate(self.down_samples): + x = down_sample(x, time_embed, context, context_mask) + if level != self.num_levels - 1: + hidden_states.append(x) + return hidden_states + +class UNet(nn.Module): + + def __init__(self, + model_channels, + init_channels=None, + num_channels=3, + out_channels=4, + time_embed_dim=None, + context_dim=None, + groups=32, + head_dim=64, + expansion_ratio=4, + compression_ratio=2, + dim_mult=(1, 2, 4, 8), + num_blocks=(3, 3, 3, 3), + add_cross_attention=(False, True, True, True), + add_self_attention=(False, True, True, True), + *args, + **kwargs, + ): + super().__init__() + init_channels = init_channels or model_channels + self.to_time_embed = nn.Sequential( + SinusoidalPosEmb(init_channels), + nn.Linear(init_channels, time_embed_dim), + nn.SiLU(), + nn.Linear(time_embed_dim, time_embed_dim) + ) + self.feature_pooling = AttentionPolling(time_embed_dim, context_dim, head_dim) + + self.in_layer = nn.Conv2d(num_channels, init_channels, kernel_size=3, padding=1) + + hidden_dims = [init_channels, *map(lambda mult: model_channels * mult, dim_mult)] + in_out_dims = list(zip(hidden_dims[:-1], hidden_dims[1:])) + text_dims = [set_default_item(is_exist, context_dim) for is_exist in add_cross_attention] + layer_params = [num_blocks, text_dims, add_self_attention] + rev_layer_params = map(reversed, layer_params) + + cat_dims = [] + self.num_levels = len(in_out_dims) + self.down_samples = nn.ModuleList([]) + for level, ((in_dim, out_dim), res_block_num, text_dim, self_attention) in enumerate(zip(in_out_dims, *layer_params)): + down_sample = level != (self.num_levels - 1) + cat_dims.append(set_default_item(level != (self.num_levels - 1), out_dim, 0)) + self.down_samples.append( + DownSampleBlock( + in_dim, out_dim, time_embed_dim, text_dim, res_block_num, groups, head_dim, expansion_ratio, + compression_ratio, down_sample, self_attention + ) + ) + + self.up_samples = nn.ModuleList([]) + for level, ((out_dim, in_dim), res_block_num, text_dim, self_attention) in enumerate(zip(reversed(in_out_dims), *rev_layer_params)): + up_sample = level != 0 + self.up_samples.append( + UpSampleBlock( + in_dim, cat_dims.pop(), out_dim, time_embed_dim, text_dim, res_block_num, groups, head_dim, + expansion_ratio, compression_ratio, up_sample, self_attention + ) + ) + + self.out_layer = nn.Sequential( + nn.GroupNorm(groups, init_channels), + nn.SiLU(), + nn.Conv2d(init_channels, out_channels, kernel_size=3, padding=1) + ) + + self.control_net = None + + def forward(self, x, time, context=None, context_mask=None, control_net_residual=None): + time_embed = self.to_time_embed(time) + if exist(context): + time_embed = self.feature_pooling(time_embed, context, context_mask) + + hidden_states = [] + x = self.in_layer(x) + for level, down_sample in enumerate(self.down_samples): + x = down_sample(x, time_embed, context, context_mask, control_net_residual) + if level != self.num_levels - 1: + hidden_states.append(x) + for level, up_sample in enumerate(self.up_samples): + if level != 0: + x = torch.cat([x, hidden_states.pop()], dim=1) + x = up_sample(x, time_embed, context, context_mask) + x = self.out_layer(x) + return x + + +class ControlNetModel(nn.Module): + def __init__(self, + model_channels, + init_channels=None, + num_channels=3, + out_channels=4, + time_embed_dim=None, + context_dim=None, + groups=32, + head_dim=64, + expansion_ratio=4, + compression_ratio=2, + dim_mult=(1, 2, 4, 8), + num_blocks=(3, 3, 3, 3), + add_cross_attention=(False, True, True, True), + add_self_attention=(False, True, True, True), + *args, + **kwargs, + ): + super().__init__() + init_channels = init_channels or model_channels + self.to_time_embed = nn.Sequential( + SinusoidalPosEmb(init_channels), + nn.Linear(init_channels, time_embed_dim), + nn.SiLU(), + nn.Linear(time_embed_dim, time_embed_dim) + ) + self.feature_pooling = AttentionPolling(time_embed_dim, context_dim, head_dim) + + self.in_layer = nn.Conv2d(num_channels, init_channels, kernel_size=3, padding=1) + + hidden_dims = [init_channels, *map(lambda mult: model_channels * mult, dim_mult)] + in_out_dims = list(zip(hidden_dims[:-1], hidden_dims[1:])) + text_dims = [set_default_item(is_exist, context_dim) for is_exist in add_cross_attention] + layer_params = [num_blocks, text_dims, add_self_attention] + rev_layer_params = map(reversed, layer_params) + + cat_dims = [] + self.num_levels = len(in_out_dims) + self.down_samples = nn.ModuleList([]) + for level, ((in_dim, out_dim), res_block_num, text_dim, self_attention) in enumerate(zip(in_out_dims, *layer_params)): + down_sample = level != (self.num_levels - 1) + cat_dims.append(set_default_item(level != (self.num_levels - 1), out_dim, 0)) + self.down_samples.append( + DownSampleBlock( + in_dim, out_dim, time_embed_dim, text_dim, res_block_num, groups, head_dim, expansion_ratio, + compression_ratio, down_sample, self_attention + ) + ) + + def forward(self, x, time, context=None, context_mask=None): + time_embed = self.to_time_embed(time) + if exist(context): + time_embed = self.feature_pooling(time_embed, context, context_mask) + + hidden_states = [] + x = self.in_layer(x) + for level, down_sample in enumerate(self.down_samples): + x = down_sample(x, time_embed, context, context_mask) + if level != self.num_levels - 1: + hidden_states.append(x) + return hidden_states + +class ControlUNet(nn.Module): + + def __init__(self, + model_channels, + init_channels=None, + num_channels=3, + out_channels=4, + time_embed_dim=None, + context_dim=None, + groups=32, + head_dim=64, + expansion_ratio=4, + compression_ratio=2, + dim_mult=(1, 2, 4, 8), + num_blocks=(3, 3, 3, 3), + add_cross_attention=(False, True, True, True), + add_self_attention=(False, True, True, True), + control_net_channels=5, + *args, + **kwargs, + ): + super().__init__() + init_channels = init_channels or model_channels + self.to_time_embed = nn.Sequential( + SinusoidalPosEmb(init_channels), + nn.Linear(init_channels, time_embed_dim), + nn.SiLU(), + nn.Linear(time_embed_dim, time_embed_dim) + ) + self.feature_pooling = AttentionPolling(time_embed_dim, context_dim, head_dim) + + self.in_layer = nn.Conv2d(num_channels, init_channels, kernel_size=3, padding=1) + + hidden_dims = [init_channels, *map(lambda mult: model_channels * mult, dim_mult)] + in_out_dims = list(zip(hidden_dims[:-1], hidden_dims[1:])) + text_dims = [set_default_item(is_exist, context_dim) for is_exist in add_cross_attention] + layer_params = [num_blocks, text_dims, add_self_attention] + rev_layer_params = map(reversed, layer_params) + + cat_dims = [] + self.num_levels = len(in_out_dims) + self.down_samples = nn.ModuleList([]) + for level, ((in_dim, out_dim), res_block_num, text_dim, self_attention) in enumerate(zip(in_out_dims, *layer_params)): + down_sample = level != (self.num_levels - 1) + cat_dims.append(set_default_item(level != (self.num_levels - 1), out_dim, 0)) + self.down_samples.append( + DownSampleBlock( + in_dim, out_dim, time_embed_dim, text_dim, res_block_num, groups, head_dim, expansion_ratio, + compression_ratio, down_sample, self_attention + ) + ) + + self.up_samples = nn.ModuleList([]) + for level, ((out_dim, in_dim), res_block_num, text_dim, self_attention) in enumerate(zip(reversed(in_out_dims), *rev_layer_params)): + up_sample = level != 0 + self.up_samples.append( + UpSampleBlock( + in_dim, cat_dims.pop(), out_dim, time_embed_dim, text_dim, res_block_num, groups, head_dim, + expansion_ratio, compression_ratio, up_sample, self_attention + ) + ) + + self.out_layer = nn.Sequential( + nn.GroupNorm(groups, init_channels), + nn.SiLU(), + nn.Conv2d(init_channels, out_channels, kernel_size=3, padding=1) + ) + + self.control_net = ControlNetModel(model_channels, + init_channels, + control_net_channels, + out_channels, + time_embed_dim, + context_dim, + groups, + head_dim, + expansion_ratio, + compression_ratio, + dim_mult, + num_blocks, + add_cross_attention, + add_self_attention) + + def forward(self, x, time, context=None, context_mask=None, control_net_data=None): + time_embed = self.to_time_embed(time) + if exist(context): + time_embed = self.feature_pooling(time_embed, context, context_mask) + + control_net_hiddens = self.control_net(control_net_data, time, context, context_mask) + hidden_states = [] + x = self.in_layer(x) + for level, down_sample in enumerate(self.down_samples): + x = down_sample(x, time_embed, context, context_mask) + if level != self.num_levels - 1: + x += control_net_hiddens.pop(0) + hidden_states.append(x) + for level, up_sample in enumerate(self.up_samples): + if level != 0: + x = torch.cat([x, hidden_states.pop()], dim=1) + x = up_sample(x, time_embed, context, context_mask) + x = self.out_layer(x) + return x + + +def get_control_unet(conf): + unet = ControlUNet(**conf) + return unet + + +def get_unet(conf): + unet = UNet(**conf) + return unet diff --git a/Kandinsky-3/kandinsky3/model/utils.py b/Kandinsky-3/kandinsky3/model/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8e5ae5da0c687164507803325f414d052b66efe9 --- /dev/null +++ b/Kandinsky-3/kandinsky3/model/utils.py @@ -0,0 +1,62 @@ +from torch.nn import Identity +from einops import rearrange + + +def exist(item): + return item is not None + + +def set_default_item(condition, item_1, item_2=None): + if condition: + return item_1 + else: + return item_2 + + +def set_default_layer(condition, layer_1, args_1=[], kwargs_1={}, layer_2=Identity, args_2=[], kwargs_2={}): + if condition: + return layer_1(*args_1, **kwargs_1) + else: + return layer_2(*args_2, **kwargs_2) + + +def get_tensor_items(x, pos, broadcast_shape): + device = pos.device + bs = pos.shape[0] + ndims = len(broadcast_shape[1:]) + x = x.cpu()[pos.cpu()] + return x.reshape(bs, *((1,) * ndims)).to(device) + + +def local_patching(x, height, width, group_size): + if group_size > 0: + x = rearrange( + x, 'b c (h g1) (w g2) -> b (h w) (g1 g2) c', + h=height//group_size, w=width//group_size, g1=group_size, g2=group_size + ) + else: + x = rearrange(x, 'b c h w -> b (h w) c', h=height, w=width) + return x + + +def local_merge(x, height, width, group_size): + if group_size > 0: + x = rearrange( + x, 'b (h w) (g1 g2) c -> b c (h g1) (w g2)', + h=height//group_size, w=width//group_size, g1=group_size, g2=group_size + ) + else: + x = rearrange(x, 'b (h w) c -> b c h w', h=height, w=width) + return x + + +def global_patching(x, height, width, group_size): + x = local_patching(x, height, width, height//group_size) + x = x.transpose(-2, -3) + return x + + +def global_merge(x, height, width, group_size): + x = x.transpose(-2, -3) + x = local_merge(x, height, width, height//group_size) + return x diff --git a/Kandinsky-3/kandinsky3/movq.py b/Kandinsky-3/kandinsky3/movq.py new file mode 100644 index 0000000000000000000000000000000000000000..6a84ffe4f6d462b951172859b1bb85942374de74 --- /dev/null +++ b/Kandinsky-3/kandinsky3/movq.py @@ -0,0 +1,431 @@ +import math +import torch +import torch.nn as nn +import numpy as np +import torch.nn.functional as F + +from .utils import freeze + + +def nonlinearity(x): + return x*torch.sigmoid(x) + + +class SpatialNorm(nn.Module): + def __init__( + self, f_channels, zq_channels=None, norm_layer=nn.GroupNorm, freeze_norm_layer=False, add_conv=False, **norm_layer_params + ): + super().__init__() + self.norm_layer = norm_layer(num_channels=f_channels, **norm_layer_params) + if zq_channels is not None: + if freeze_norm_layer: + for p in self.norm_layer.parameters: + p.requires_grad = False + self.add_conv = add_conv + if self.add_conv: + self.conv = nn.Conv2d(zq_channels, zq_channels, kernel_size=3, stride=1, padding=1) + self.conv_y = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0) + self.conv_b = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0) + def forward(self, f, zq=None): + norm_f = self.norm_layer(f) + if zq is not None: + f_size = f.shape[-2:] + zq = torch.nn.functional.interpolate(zq, size=f_size, mode="nearest") + if self.add_conv: + zq = self.conv(zq) + norm_f = norm_f * self.conv_y(zq) + self.conv_b(zq) + return norm_f + + +def Normalize(in_channels, zq_ch=None, add_conv=None): + return SpatialNorm( + in_channels, zq_ch, norm_layer=nn.GroupNorm, + freeze_norm_layer=False, add_conv=add_conv, num_groups=32, eps=1e-6, affine=True + ) + + +class Upsample(nn.Module): + def __init__(self, in_channels, with_conv): + super().__init__() + self.with_conv = with_conv + if self.with_conv: + self.conv = torch.nn.Conv2d(in_channels, + in_channels, + kernel_size=3, + stride=1, + padding=1) + + def forward(self, x): + x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest") + if self.with_conv: + x = self.conv(x) + return x + + +class Downsample(nn.Module): + def __init__(self, in_channels, with_conv): + super().__init__() + self.with_conv = with_conv + if self.with_conv: + self.conv = torch.nn.Conv2d(in_channels, + in_channels, + kernel_size=3, + stride=2, + padding=0) + + def forward(self, x): + if self.with_conv: + pad = (0,1,0,1) + x = torch.nn.functional.pad(x, pad, mode="constant", value=0) + x = self.conv(x) + else: + x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2) + return x + + +class ResnetBlock(nn.Module): + def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False, + dropout, temb_channels=512, zq_ch=None, add_conv=False): + super().__init__() + self.in_channels = in_channels + out_channels = in_channels if out_channels is None else out_channels + self.out_channels = out_channels + self.use_conv_shortcut = conv_shortcut + + self.norm1 = Normalize(in_channels, zq_ch, add_conv=add_conv) + self.conv1 = torch.nn.Conv2d(in_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1) + if temb_channels > 0: + self.temb_proj = torch.nn.Linear(temb_channels, + out_channels) + self.norm2 = Normalize(out_channels, zq_ch, add_conv=add_conv) + self.dropout = torch.nn.Dropout(dropout) + self.conv2 = torch.nn.Conv2d(out_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1) + if self.in_channels != self.out_channels: + if self.use_conv_shortcut: + self.conv_shortcut = torch.nn.Conv2d(in_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1) + else: + self.nin_shortcut = torch.nn.Conv2d(in_channels, + out_channels, + kernel_size=1, + stride=1, + padding=0) + + def forward(self, x, temb, zq=None): + h = x + h = self.norm1(h, zq) + h = nonlinearity(h) + h = self.conv1(h) + + if temb is not None: + h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None] + + h = self.norm2(h, zq) + h = nonlinearity(h) + h = self.dropout(h) + h = self.conv2(h) + + if self.in_channels != self.out_channels: + if self.use_conv_shortcut: + x = self.conv_shortcut(x) + else: + x = self.nin_shortcut(x) + + return x+h + + +class AttnBlock(nn.Module): + def __init__(self, in_channels, zq_ch=None, add_conv=False): + super().__init__() + self.in_channels = in_channels + + self.norm = Normalize(in_channels, zq_ch, add_conv=add_conv) + self.q = torch.nn.Conv2d(in_channels, + in_channels, + kernel_size=1, + stride=1, + padding=0) + self.k = torch.nn.Conv2d(in_channels, + in_channels, + kernel_size=1, + stride=1, + padding=0) + self.v = torch.nn.Conv2d(in_channels, + in_channels, + kernel_size=1, + stride=1, + padding=0) + self.proj_out = torch.nn.Conv2d(in_channels, + in_channels, + kernel_size=1, + stride=1, + padding=0) + + + def forward(self, x, zq=None): + h_ = x + h_ = self.norm(h_, zq) + q = self.q(h_) + k = self.k(h_) + v = self.v(h_) + + # compute attention + b,c,h,w = q.shape + q = q.reshape(b,c,h*w) + q = q.permute(0,2,1) # b,hw,c + k = k.reshape(b,c,h*w) # b,c,hw + w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] + w_ = w_ * (int(c)**(-0.5)) + w_ = torch.nn.functional.softmax(w_, dim=2) + + # attend to values + v = v.reshape(b,c,h*w) + w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q) + h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] + h_ = h_.reshape(b,c,h,w) + + h_ = self.proj_out(h_) + + return x+h_ + + +class Encoder(nn.Module): + def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, + attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, + resolution, z_channels, double_z=True, **ignore_kwargs): + super().__init__() + self.ch = ch + self.temb_ch = 0 + self.num_resolutions = len(ch_mult) + self.num_res_blocks = num_res_blocks + self.resolution = resolution + self.in_channels = in_channels + + # downsampling + self.conv_in = torch.nn.Conv2d(in_channels, + self.ch, + kernel_size=3, + stride=1, + padding=1) + + curr_res = resolution + in_ch_mult = (1,)+tuple(ch_mult) + self.down = nn.ModuleList() + for i_level in range(self.num_resolutions): + block = nn.ModuleList() + attn = nn.ModuleList() + block_in = ch*in_ch_mult[i_level] + block_out = ch*ch_mult[i_level] + for i_block in range(self.num_res_blocks): + block.append(ResnetBlock(in_channels=block_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout)) + block_in = block_out + if curr_res in attn_resolutions: + attn.append(AttnBlock(block_in)) + down = nn.Module() + down.block = block + down.attn = attn + if i_level != self.num_resolutions-1: + down.downsample = Downsample(block_in, resamp_with_conv) + curr_res = curr_res // 2 + self.down.append(down) + + # middle + self.mid = nn.Module() + self.mid.block_1 = ResnetBlock(in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout) + self.mid.attn_1 = AttnBlock(block_in) + self.mid.block_2 = ResnetBlock(in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout) + + # end + self.norm_out = Normalize(block_in) + self.conv_out = torch.nn.Conv2d(block_in, + 2*z_channels if double_z else z_channels, + kernel_size=3, + stride=1, + padding=1) + + + def forward(self, x): + temb = None + + # downsampling + hs = [self.conv_in(x)] + for i_level in range(self.num_resolutions): + for i_block in range(self.num_res_blocks): + h = self.down[i_level].block[i_block](hs[-1], temb) + if len(self.down[i_level].attn) > 0: + h = self.down[i_level].attn[i_block](h) + hs.append(h) + if i_level != self.num_resolutions-1: + hs.append(self.down[i_level].downsample(hs[-1])) + + # middle + h = hs[-1] + h = self.mid.block_1(h, temb) + h = self.mid.attn_1(h) + h = self.mid.block_2(h, temb) + + # end + h = self.norm_out(h) + h = nonlinearity(h) + h = self.conv_out(h) + return h + + +class Decoder(nn.Module): + def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks, + attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels, + resolution, z_channels, give_pre_end=False, zq_ch=None, add_conv=False, **ignorekwargs): + super().__init__() + self.ch = ch + self.temb_ch = 0 + self.num_resolutions = len(ch_mult) + self.num_res_blocks = num_res_blocks + self.resolution = resolution + self.in_channels = in_channels + self.give_pre_end = give_pre_end + + # compute in_ch_mult, block_in and curr_res at lowest res + in_ch_mult = (1,)+tuple(ch_mult) + block_in = ch*ch_mult[self.num_resolutions-1] + curr_res = resolution // 2**(self.num_resolutions-1) + self.z_shape = (1,z_channels,curr_res,curr_res) + + # z to block_in + self.conv_in = torch.nn.Conv2d(z_channels, + block_in, + kernel_size=3, + stride=1, + padding=1) + + # middle + self.mid = nn.Module() + self.mid.block_1 = ResnetBlock(in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + zq_ch=zq_ch, + add_conv=add_conv) + self.mid.attn_1 = AttnBlock(block_in, zq_ch, add_conv=add_conv) + self.mid.block_2 = ResnetBlock(in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + zq_ch=zq_ch, + add_conv=add_conv) + + # upsampling + self.up = nn.ModuleList() + for i_level in reversed(range(self.num_resolutions)): + block = nn.ModuleList() + attn = nn.ModuleList() + block_out = ch*ch_mult[i_level] + for i_block in range(self.num_res_blocks+1): + block.append(ResnetBlock(in_channels=block_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + zq_ch=zq_ch, + add_conv=add_conv)) + block_in = block_out + if curr_res in attn_resolutions: + attn.append(AttnBlock(block_in, zq_ch, add_conv=add_conv)) + up = nn.Module() + up.block = block + up.attn = attn + if i_level != 0: + up.upsample = Upsample(block_in, resamp_with_conv) + curr_res = curr_res * 2 + self.up.insert(0, up) # prepend to get consistent order + + # end + self.norm_out = Normalize(block_in, zq_ch, add_conv=add_conv) + self.conv_out = torch.nn.Conv2d(block_in, + out_ch, + kernel_size=3, + stride=1, + padding=1) + + def forward(self, z, zq): + #assert z.shape[1:] == self.z_shape[1:] + self.last_z_shape = z.shape + + # timestep embedding + temb = None + + # z to block_in + h = self.conv_in(z) + + # middle + h = self.mid.block_1(h, temb, zq) + h = self.mid.attn_1(h, zq) + h = self.mid.block_2(h, temb, zq) + + # upsampling + for i_level in reversed(range(self.num_resolutions)): + for i_block in range(self.num_res_blocks+1): + h = self.up[i_level].block[i_block](h, temb, zq) + if len(self.up[i_level].attn) > 0: + h = self.up[i_level].attn[i_block](h, zq) + if i_level != 0: + h = self.up[i_level].upsample(h) + + # end + if self.give_pre_end: + return h + + h = self.norm_out(h, zq) + h = nonlinearity(h) + h = self.conv_out(h) + return h + + +class MoVQ(nn.Module): + + def __init__(self, generator_params): + super().__init__() + z_channels = generator_params["z_channels"] + self.encoder = Encoder(**generator_params) + self.quant_conv = torch.nn.Conv2d(z_channels, z_channels, 1) + self.post_quant_conv = torch.nn.Conv2d(z_channels, z_channels, 1) + self.decoder = Decoder(zq_ch=z_channels, **generator_params) + + @torch.no_grad() + def encode(self, x): + h = self.encoder(x) + h = self.quant_conv(h) + return h + + @torch.no_grad() + def decode(self, quant): + decoder_input = self.post_quant_conv(quant) + decoded = self.decoder(decoder_input, quant) + return decoded + + +def get_vae(conf): + movq = MoVQ(conf.params) + if conf.checkpoint is not None: + movq_state_dict = torch.load(conf.checkpoint) + movq.load_state_dict(movq_state_dict) + movq = freeze(movq) + return movq diff --git a/Kandinsky-3/kandinsky3/setup.py b/Kandinsky-3/kandinsky3/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..673596b270c63ef387695e8d0180eba8dff00253 --- /dev/null +++ b/Kandinsky-3/kandinsky3/setup.py @@ -0,0 +1,38 @@ +from setuptools import setup + +setup( + name="kandinsky3", + packages=[ + "kandinsky3", + "kandinsky3/model" + ], + install_requires=[ + "timm", + "torch==1.10.1+cu111", + "torchvision==0.11.2+cu111", + "torchaudio==0.10.1", + "pytorch_lightning==1.7.5", + "transformers", + "accelerate", + "diffusers", + "setuptools==59.5.0", + "omegaconf", + "datasets", + "einops", + "webdataset", + "fsspec", + "s3fs", + "hydra-core", + "scikit-image", + "matplotlib", + "wandb", + "albumentations", + "bezier", + "scipy", + "Pillow", + "tqdm", + "huggingface_hub" + + ], + author="", +) \ No newline at end of file diff --git a/Kandinsky-3/kandinsky3/t2i_pipeline.py b/Kandinsky-3/kandinsky3/t2i_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..95e411ec6b963ac572d67e6b7ee56a134d6e29bf --- /dev/null +++ b/Kandinsky-3/kandinsky3/t2i_pipeline.py @@ -0,0 +1,106 @@ +from typing import Union, List +import PIL + +import torch +import torchvision.transforms as T +from einops import repeat + +from kandinsky3.model.unet import UNet +from kandinsky3.movq import MoVQ +from kandinsky3.condition_encoders import T5TextConditionEncoder +from kandinsky3.condition_processors import T5TextConditionProcessor +from kandinsky3.model.diffusion import BaseDiffusion, get_named_beta_schedule + + +class Kandinsky3T2IPipeline: + + def __init__( + self, + device_map: Union[str, torch.device, dict], + dtype_map: Union[str, torch.dtype, dict], + unet: UNet, + null_embedding: torch.Tensor, + t5_processor: T5TextConditionProcessor, + t5_encoder: T5TextConditionEncoder, + movq: MoVQ, + gan: bool, + ): + self.device_map = device_map + self.dtype_map = dtype_map + self.to_pil = T.ToPILImage() + + self.unet = unet + self.null_embedding = null_embedding + self.t5_processor = t5_processor + self.t5_encoder = t5_encoder + self.movq = movq + + self.gan = gan + + def __call__( + self, + text: str, + negative_text: str = None, + images_num: int = 1, + bs: int = 1, + width: int = 1024, + height: int = 1024, + guidance_scale: float = 3.0, + steps: int = 50, + eta: float = 1.0 + ) -> List[PIL.Image.Image]: + + betas = get_named_beta_schedule('cosine', 1000) + base_diffusion = BaseDiffusion(betas, 0.99) + times = list(range(999, 0, -1000 // steps)) + if self.gan: + times = list(range(979, 0, -250)) + + condition_model_input, negative_condition_model_input = self.t5_processor.encode(text, negative_text) + for input_type in condition_model_input: + condition_model_input[input_type] = condition_model_input[input_type][None].to( + self.device_map['text_encoder'] + ) + + if negative_condition_model_input is not None: + for input_type in negative_condition_model_input: + negative_condition_model_input[input_type] = negative_condition_model_input[input_type][None].to( + self.device_map['text_encoder'] + ) + + pil_images = [] + with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=self.dtype_map['text_encoder']): + context, context_mask = self.t5_encoder(condition_model_input) + if negative_condition_model_input is not None: + negative_context, negative_context_mask = self.t5_encoder(negative_condition_model_input) + else: + negative_context, negative_context_mask = None, None + + k, m = images_num // bs, images_num % bs + for minibatch in [bs] * k + [m]: + if minibatch == 0: + continue + bs_context = repeat(context, '1 n d -> b n d', b=minibatch) + bs_context_mask = repeat(context_mask, '1 n -> b n', b=minibatch) + if negative_context is not None: + bs_negative_context = repeat(negative_context, '1 n d -> b n d', b=minibatch) + bs_negative_context_mask = repeat(negative_context_mask, '1 n -> b n', b=minibatch) + else: + bs_negative_context, bs_negative_context_mask = None, None + + with torch.cuda.amp.autocast(dtype=self.dtype_map['unet']): + images = base_diffusion.p_sample_loop( + self.unet, (minibatch, 4, height // 8, width // 8), times, self.device_map['unet'], + bs_context, bs_context_mask, self.null_embedding, guidance_scale, eta, + negative_context=bs_negative_context, negative_context_mask=bs_negative_context_mask, + gan=self.gan + ) + + with torch.cuda.amp.autocast(dtype=self.dtype_map['movq']): + images = torch.cat([self.movq.decode(image) for image in images.chunk(2)]) + images = torch.clip((images + 1.) / 2., 0., 1.) + for images_chunk in images.chunk(1): + pil_images += [self.to_pil(image) for image in images_chunk] + + return pil_images diff --git a/Kandinsky-3/kandinsky3/utils.py b/Kandinsky-3/kandinsky3/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..403845a232a3d7c1a6b50ee6e6efa75c04638765 --- /dev/null +++ b/Kandinsky-3/kandinsky3/utils.py @@ -0,0 +1,71 @@ +from omegaconf import OmegaConf +import numpy as np +from scipy import ndimage +import torch.nn as nn +from skimage.transform import resize + + +def load_conf(config_path): + conf = OmegaConf.load(config_path) + conf.data.tokens_length = conf.common.tokens_length + conf.data.processor_names = conf.model.encoders.model_names + conf.data.dataset.seed = conf.common.seed + conf.data.dataset.image_size = conf.common.image_size + + conf.trainer.trainer_params.max_steps = conf.common.train_steps + conf.scheduler.params.total_steps = conf.common.train_steps + conf.logger.tensorboard.name = conf.common.experiment_name + + conf.model.encoders.context_dim = conf.model.unet_params.context_dim + return conf + + +def freeze(model): + for p in model.parameters(): + p.requires_grad = False + return model + +def unfreeze(model): + for p in model.parameters(): + p.requires_grad = True + return model + +def zero_module(module): + for p in module.parameters(): + nn.init.zeros_(p) + return module + +def resize_mask_for_diffusion(mask): + reduce_factor = max(1, (mask.size / 1024**2)**0.5) + resized_mask = resize( + mask, + ( + (round(mask.shape[0] / reduce_factor) // 64) * 64, + (round(mask.shape[1] / reduce_factor) // 64) * 64 + ), + preserve_range=True, + anti_aliasing=False + ) + + return resized_mask + +def resize_image_for_diffusion(image): + reduce_factor = max(1, (image.size[0] * image.size[1] / 1024**2)**0.5) + image = image.resize(( + (round(image.size[0] / reduce_factor) // 64) * 64, (round(image.size[1] / reduce_factor) // 64) * 64 + )) + + return image + +def prepare_mask(mask): + ker = np.array([[1, 1, 1, 1, 1], + [1, 5, 5, 5, 1], + [1, 5, 44, 5, 1], + [1, 5, 5, 5, 1], + [1, 1, 1, 1, 1]]) / 100 + out = ndimage.convolve(mask, ker) + out = ndimage.convolve(out, ker) + out = ndimage.convolve(out, ker) + + mask = (out > 0).astype(int) + return mask \ No newline at end of file diff --git a/Kandinsky-3/requirements.txt b/Kandinsky-3/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d26edc34a8e88daaca0455cb473d85b1d4c5916d --- /dev/null +++ b/Kandinsky-3/requirements.txt @@ -0,0 +1,23 @@ +timm + +pytorch_lightning==1.7.5 +transformers +accelerate +diffusers +setuptools==59.5.0 +omegaconf +datasets +einops +webdataset +fsspec +s3fs +hydra-core +scikit-image +matplotlib +wandb +albumentations +bezier +scipy +Pillow +tqdm +huggingface_hub \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..242b8a48db3cfb510ed8d42b835a864722159a22 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Said Azizov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 9125b440049d933dd2595a3182a551e6af72681a..4432b85b23580b684f46d95282896840bbcf2a59 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,137 @@ + +# README + +## Overview + +This project generates a PowerPoint presentation based on user-provided descriptions. It leverages language models to generate text content and an image generation API to create images for the slides. The architecture is modular, allowing for easy extension and customization of the text and image generation components. + +## How to Use + +### Prerequisites + +- Python 3.10 or higher +- Required Python packages (listed in `requirements.txt`) + +### Setup + +1. **Clone the repository**: + + ```bash + git clone --recurse-submodules https://github.com/ai-forever/presentations.git + cd presentations + ``` + +2. **Install dependencies**: + + ```bash + pip install -r requirements.txt + ``` + +3. **Create a .env file** in the root directory with GigaChat credentials: + +Here is the [documentation](https://developers.sber.ru/portal/products/gigachat-api) on how to get access token. + + ```plaintext + AUTH_TOKEN=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + COOKIE=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + ``` + + +4. **Run the FastAPI server** for the image generation API: + + ```bash + python src/kandinsky.py + ``` + +### Running the Script + +To generate a presentation, use the following command: + +```bash +python main.py -d "Description of the presentation" -l 'en' +``` + +This will generate a presentation based on the provided description and save it in the `logs` directory with a timestamp. + +## Examples + +```bash +python main.py -d "Сгенерируй презентацию про планеты солнечной системы" -l 'ru' +``` + +```bash +python main.py -d "Generate presentation about planets of Solar system" -l 'en' +``` + +This command will create a presentation on the topic "Planets of the Solar System" using the configured text and image generation functions. + +## Architecture + +### Main Components + +1. **main.py**: The entry point of the application. It parses command-line arguments, initializes required components, and orchestrates the presentation generation process. + +2. **Font Class (src/font.py)**: Manages fonts used in the presentation. It can select a random font with basic and bold styles and provide paths to various font styles (basic, bold, italic, and italic bold). + +3. **Presentation Generation Functions (src/constructor.py)**: Functions that generate different types of slides in the presentation. They handle the layout, font settings, and placement of text and images. + +4. **Text Generation (src/gigachat.py)**: Contains the `giga_generate` function, which generates text based on a given prompt. + +5. **Image Generation (src/kandinsky.py)**: Includes the `api_k31_generate` function, which generates images based on a prompt using an external API. Additionally, it provides a FastAPI server for the image generation API. + +6. **Prompt Configuration (src/prompt_configs.py)**: Defines the structure of prompts used for generating titles, text, images, and backgrounds for slides. + +### How It Works + +1. **Initialization**: + - `main.py` parses command-line arguments to get the presentation description. + - It initializes the `Font` class with the directory containing font files and sets a random font. + +2. **Prompt Configuration**: + - The `ru_gigachat_config` defines the structure and content of prompts used for generating slide components (titles, text, images, backgrounds). + +3. **Text and Image Generation**: + - The `giga_generate` function generates text based on the provided description. + - The `api_k31_generate` function generates images based on prompts using the FastAPI server. + +4. **Slide Generation**: + - The `generate_presentation` function orchestrates the creation of slides by calling appropriate functions to generate text and images, and then formats them into slides. + +## Extending the Project + +### Adding New Font Styles + +To add new font styles, place the font files in the `fonts` directory and update the `Font` class if necessary to recognize the new styles. + +### Changing Text Generation + +To use a different text generation function, replace the `giga_generate` function from `src/gigachat.py` or add a new function and update the call in `main.py`. + +### Changing Image Generation + +To use a different image generation API, modify the `api_k31_generate` function in `src/kandinsky.py` or add a new function and update the call in `main.py`. + +## Acknowledgements + +This project leverages the `python-pptx` library for PowerPoint generation, PIL for image processing, and other Python libraries for various functionalities. The text and image generation models are based on external APIs and language models. + --- -title: Slides Generaror -emoji: 🏆 -colorFrom: gray -colorTo: pink -sdk: gradio -sdk_version: 4.44.0 -app_file: app.py -pinned: false -license: mit ---- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +Feel free to reach out with any questions or suggestions! + +## Authors + ++ Said Azizov: [Github](https://github.com/stazizov), [Blog](https://t.me/said_azizau) + +## Citation + +``` +@misc{arkhipkin2023kandinsky, + title={Kandinsky 3.0 Technical Report}, + author={Vladimir Arkhipkin and Andrei Filatov and Viacheslav Vasilev and Anastasia Maltseva and Said Azizov and Igor Pavlov and Julia Agafonova and Andrey Kuznetsov and Denis Dimitrov}, + year={2023}, + eprint={2312.03511}, + archivePrefix={arXiv}, + primaryClass={cs.CV} +} +``` diff --git a/app.py b/app.py index 04cc31aa8d0e06aeaac3b59bb361ed71d831e43f..a7937cf603189179622788c949df26b930e4eefd 100644 --- a/app.py +++ b/app.py @@ -1,7 +1,95 @@ import gradio as gr +import time +from src.constructor import generate_presentation +from src.prompt_configs import en_gigachat_config, ru_gigachat_config +from src.gigachat import giga_generate +from src.kandinsky import api_k31_generate +from src.font import Font -def greet(name): - return "Hello " + name + "!!" +logs_dir = "logs" +fonts_dir = "fonts" -demo = gr.Interface(fn=greet, inputs="text", outputs="text") -demo.launch() +def create_presentation(description: str, language: str): + # Select the appropriate prompt configuration based on the selected language + if language == "English": + prompt_config = en_gigachat_config + elif language == "Русский": + prompt_config = ru_gigachat_config + else: + # set default to prevent interruptions in unexpected scenario + prompt_config = en_gigachat_config + + font = Font(fonts_dir) + font.set_random_font() + + output_dir = f'{logs_dir}/{int(time.time())}' + + generate_presentation( + llm_generate=giga_generate, + generate_image=api_k31_generate, + prompt_config=prompt_config, + description=description, + font=font, + output_dir=output_dir, + ) + + filename = f'{output_dir}/presentation.pptx' + + return filename + +# Updated examples to include language selection +examples = [ + ["Generate a presentation on economics, 7 slides", "English"], + ["Сгенерируйте презентацию по экономике, 7 слайдов", "Русский"], + ["Create a presentation on climate change, 6 slides", "English"], + ["Создайте презентацию об изменении климата, 6 слайдов", "Русский"], + ["Create a presentation on artificial intelligence, 8 slides", "English"], + ["Создайте презентацию об искусственном интеллекте, 8 слайдов", "Русский"], + ["Design a presentation on space exploration, 10 slides", "English"], + ["Разработайте презентацию о космических исследованиях, 10 слайдов", "Русский"], + ["Prepare a presentation on the future of renewable energy, 7 slides", "English"], + ["Подготовьте презентацию о будущем возобновляемой энергетики, 7 слайдов", "Русский"], + ["Develop a presentation on the history of art movements, 9 slides", "English"], + ["Разработайте презентацию о истории художественных движений, 9 слайдов", "Русский"], + ["Generate a presentation on the impact of social media, 6 slides", "English"], + ["Сгенерируйте презентацию о влиянии социальных сетей, 6 слайдов", "Русский"], + ["Create a presentation on sustainable urban planning, 8 slides", "English"], + ["Создайте презентацию о устойчивом градостроительстве, 8 слайдов", "Русский"], + ["Разработайте презентацию о новшествах в области медицинских технологий, 7 слайдов", "Русский"], + ["Design a presentation on innovations in healthcare technology, 7 slides", "English"], + ["Подготовьте презентацию о глобальных экономических тенденциях, 5 слайдов", "Русский"], + ["Prepare a presentation on global economic trends, 5 slides", "English"], + ["Разработайте презентацию о психологии потребительского поведения, 6 слайдов", "Русский"], + ["Develop a presentation on the psychology of consumer behavior, 6 slides", "English"], + ["Сгенерируйте презентацию о преимуществах осознанности и медитации, 7 слайдов", "Русский"], + ["Generate a presentation on the benefits of mindfulness and meditation, 7 slides", "English"], + ["Создайте презентацию о достижениях в области автономных транспортных средств, 8 слайдов", "Русский"], + ["Create a presentation on advancements in autonomous vehicles, 8 slides", "English"], + ["Разработайте презентацию о влиянии изменений климатической политики, 5 слайдов", "Русский"], + ["Design a presentation on the impact of climate policy changes, 5 slides", "English"], +] + +iface = gr.Interface( + fn=create_presentation, + inputs=[ + gr.Textbox( + label="Presentation Description", + placeholder="Enter the description for the presentation..." + ), + gr.Dropdown( + label="Language", + choices=["English", "Russian"], + value="English" + ) + ], + outputs=gr.File( + label="Download Presentation" + ), + title="Presentation Generator", + description="Generate a presentation based on the provided description and selected language. Click the button to download the presentation.", + css="footer {visibility: hidden}", + allow_flagging="never", + examples=examples +) + +iface.launch() \ No newline at end of file diff --git a/fonts/Arial.ttf b/fonts/Arial.ttf new file mode 100644 index 0000000000000000000000000000000000000000..003c6fd45c118f2e8ddb2fb841d640dd20999ab4 Binary files /dev/null and b/fonts/Arial.ttf differ diff --git a/fonts/ArialBd.ttf b/fonts/ArialBd.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b7e58f53c110eb3881afce6d402178b1e3ef157f Binary files /dev/null and b/fonts/ArialBd.ttf differ diff --git a/fonts/ArialBdIt.ttf b/fonts/ArialBdIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..00968d29b6efa0c1068fce29ce3ae87ae0f595dc Binary files /dev/null and b/fonts/ArialBdIt.ttf differ diff --git a/fonts/ArialIt.ttf b/fonts/ArialIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..5b05d353598de439996a111aebd310450b4005c4 Binary files /dev/null and b/fonts/ArialIt.ttf differ diff --git a/fonts/ComicSansMS.ttf b/fonts/ComicSansMS.ttf new file mode 100644 index 0000000000000000000000000000000000000000..a72bba400b48ab0bd281d3a4b0c5f6db3e2fab24 Binary files /dev/null and b/fonts/ComicSansMS.ttf differ diff --git a/fonts/ComicSansMSBd.ttf b/fonts/ComicSansMSBd.ttf new file mode 100644 index 0000000000000000000000000000000000000000..75be50486c13f64bf240ec7c03f01f4870afc89f Binary files /dev/null and b/fonts/ComicSansMSBd.ttf differ diff --git a/fonts/CourierNew.ttf b/fonts/CourierNew.ttf new file mode 100644 index 0000000000000000000000000000000000000000..170a6cce18c132b8e8cb7fac8f7a5500dd6b7562 Binary files /dev/null and b/fonts/CourierNew.ttf differ diff --git a/fonts/Georgia.ttf b/fonts/Georgia.ttf new file mode 100644 index 0000000000000000000000000000000000000000..787d11e936659578dc759bf7bf047585844d045e Binary files /dev/null and b/fonts/Georgia.ttf differ diff --git a/fonts/GeorgiaBd.ttf b/fonts/GeorgiaBd.ttf new file mode 100644 index 0000000000000000000000000000000000000000..e121d7e1cbc8cec443a7f548ea3256704745f74d Binary files /dev/null and b/fonts/GeorgiaBd.ttf differ diff --git a/fonts/GeorgiaBdIt.ttf b/fonts/GeorgiaBdIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..1ab2c5530ac5178d93d9f9a56136e46e2e0ba7d1 Binary files /dev/null and b/fonts/GeorgiaBdIt.ttf differ diff --git a/fonts/GeorgiaIt.ttf b/fonts/GeorgiaIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b5c4209e8ff9b859d2f884b06425decb1661932c Binary files /dev/null and b/fonts/GeorgiaIt.ttf differ diff --git a/fonts/Helvetica.ttf b/fonts/Helvetica.ttf new file mode 100644 index 0000000000000000000000000000000000000000..a40c0a7d882a4253a341e7b43cfe7d6f406cdbd0 Binary files /dev/null and b/fonts/Helvetica.ttf differ diff --git a/fonts/HelveticaBd.ttf b/fonts/HelveticaBd.ttf new file mode 100644 index 0000000000000000000000000000000000000000..2a10797604c88ffcecba11c29b89dcba20446b9d Binary files /dev/null and b/fonts/HelveticaBd.ttf differ diff --git a/fonts/HelveticaNeue.ttf b/fonts/HelveticaNeue.ttf new file mode 100644 index 0000000000000000000000000000000000000000..95a77d2b13f73cfea6b11ca84f5acbbaf8008208 Binary files /dev/null and b/fonts/HelveticaNeue.ttf differ diff --git a/fonts/HelveticaNeueBd.ttf b/fonts/HelveticaNeueBd.ttf new file mode 100644 index 0000000000000000000000000000000000000000..5a41fd90d29336f2223f85c821e7593de8348991 Binary files /dev/null and b/fonts/HelveticaNeueBd.ttf differ diff --git a/fonts/LucidaSansUnicode.ttf b/fonts/LucidaSansUnicode.ttf new file mode 100644 index 0000000000000000000000000000000000000000..52638abe36cca270e231cd4861882d5bb73e43b0 Binary files /dev/null and b/fonts/LucidaSansUnicode.ttf differ diff --git a/fonts/README b/fonts/README new file mode 100644 index 0000000000000000000000000000000000000000..bc230018c887404bf9c4b1c6219a2fa10e42d141 --- /dev/null +++ b/fonts/README @@ -0,0 +1,28 @@ +copr-some-nice-fonts +==================== + +This is a Fedora/CentOS repo for easy installing of some nice fonts. This +includes the following fonts: + +- Arial +- Comic Sans MS +- Courier New +- Georgia +- Helvetica Neue +- Helvetica +- Lucida Sans Unicode +- Tahoma +- Times New Roman +- Trebuchet MS +- Verdana + +Using it +-------- + +sudo dnf copr enable adrienverge/some-nice-fonts +sudo dnf install some-nice-fonts + +Building it +----------- + +cp *.ttf ~/rpmbuild/SOURCES && rpmbuild -ba some-nice-fonts.spec diff --git a/fonts/Tahoma.ttf b/fonts/Tahoma.ttf new file mode 100644 index 0000000000000000000000000000000000000000..e8a5ced2739c4ec92a2b084823047dd1b859d061 Binary files /dev/null and b/fonts/Tahoma.ttf differ diff --git a/fonts/TahomaBd.ttf b/fonts/TahomaBd.ttf new file mode 100644 index 0000000000000000000000000000000000000000..bb2a23d9261d8e5e79f1c8c8208b1c76e2658945 Binary files /dev/null and b/fonts/TahomaBd.ttf differ diff --git a/fonts/TimesNewRoman.ttf b/fonts/TimesNewRoman.ttf new file mode 100644 index 0000000000000000000000000000000000000000..50e8dfd1230bdba92000d37ac5adf36b9356a9a5 Binary files /dev/null and b/fonts/TimesNewRoman.ttf differ diff --git a/fonts/TimesNewRomanBd.ttf b/fonts/TimesNewRomanBd.ttf new file mode 100644 index 0000000000000000000000000000000000000000..d4fb9c52b881315199b33aee2a09c488c7640d3b Binary files /dev/null and b/fonts/TimesNewRomanBd.ttf differ diff --git a/fonts/TimesNewRomanBdIt.ttf b/fonts/TimesNewRomanBdIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ba7ba5f8d412ef6cc826197a43a426c600f2baf8 Binary files /dev/null and b/fonts/TimesNewRomanBdIt.ttf differ diff --git a/fonts/TimesNewRomanIt.ttf b/fonts/TimesNewRomanIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..28798d3c6231092583abac946da39b73633bee56 Binary files /dev/null and b/fonts/TimesNewRomanIt.ttf differ diff --git a/fonts/TrebuchetMS.ttf b/fonts/TrebuchetMS.ttf new file mode 100644 index 0000000000000000000000000000000000000000..d122bd31d8712ee70d53c1ff6eb3651a21d1d38f Binary files /dev/null and b/fonts/TrebuchetMS.ttf differ diff --git a/fonts/TrebuchetMSBd.ttf b/fonts/TrebuchetMSBd.ttf new file mode 100644 index 0000000000000000000000000000000000000000..867f56d7766e4099af5c8a426f4021ac059acbe5 Binary files /dev/null and b/fonts/TrebuchetMSBd.ttf differ diff --git a/fonts/TrebuchetMSBdIt.ttf b/fonts/TrebuchetMSBdIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..1ead735bab6f8208a9a1ca156a4aff95168b65c4 Binary files /dev/null and b/fonts/TrebuchetMSBdIt.ttf differ diff --git a/fonts/TrebuchetMSIt.ttf b/fonts/TrebuchetMSIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ab2659ec8e74e8c8b8a71fbfd0cd5cb70b9d98b6 Binary files /dev/null and b/fonts/TrebuchetMSIt.ttf differ diff --git a/fonts/Verdana.ttf b/fonts/Verdana.ttf new file mode 100644 index 0000000000000000000000000000000000000000..637a2093392a914584cc459899c8710b9d9d4d24 Binary files /dev/null and b/fonts/Verdana.ttf differ diff --git a/fonts/VerdanaBd.ttf b/fonts/VerdanaBd.ttf new file mode 100644 index 0000000000000000000000000000000000000000..e4391be2f2fa222893810f2820bfcd850235c911 Binary files /dev/null and b/fonts/VerdanaBd.ttf differ diff --git a/fonts/VerdanaBdIt.ttf b/fonts/VerdanaBdIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..476256a6b8315f9aeb737c8936cfc3815b98ac1f Binary files /dev/null and b/fonts/VerdanaBdIt.ttf differ diff --git a/fonts/VerdanaIt.ttf b/fonts/VerdanaIt.ttf new file mode 100644 index 0000000000000000000000000000000000000000..8542da3ae87932a0b1e04db0050f5315d2a4b4b2 Binary files /dev/null and b/fonts/VerdanaIt.ttf differ diff --git a/fonts/some-nice-fonts.spec b/fonts/some-nice-fonts.spec new file mode 100644 index 0000000000000000000000000000000000000000..a0d78f7a8b4a7722c339cb4d2e9a3a11f4395946 --- /dev/null +++ b/fonts/some-nice-fonts.spec @@ -0,0 +1,105 @@ +# Copyright 2017 Adrien Vergé + +Name: some-nice-fonts +Version: 2.0.0 +Release: 1%{?dist} +Summary: Some nice fonts including Arial, Courier New, Helvetica, etc. +License: Proprietary +URL: https://github.com/adrienverge/copr-some-nice-fonts +Source0: Arial.ttf +Source1: ArialBd.ttf +Source2: ArialIt.ttf +Source3: ArialBdIt.ttf +Source4: ComicSansMS.ttf +Source5: ComicSansMSBd.ttf +Source6: CourierNew.ttf +Source7: Georgia.ttf +Source8: GeorgiaBd.ttf +Source9: GeorgiaIt.ttf +Source10: GeorgiaBdIt.ttf +Source11: Helvetica.ttf +Source12: HelveticaBd.ttf +Source13: HelveticaNeue.ttf +Source14: HelveticaNeueBd.ttf +Source15: LucidaSansUnicode.ttf +Source16: Tahoma.ttf +Source17: TahomaBd.ttf +Source18: TimesNewRoman.ttf +Source19: TimesNewRomanBd.ttf +Source20: TimesNewRomanIt.ttf +Source21: TimesNewRomanBdIt.ttf +Source22: TrebuchetMS.ttf +Source23: TrebuchetMSBd.ttf +Source24: TrebuchetMSIt.ttf +Source25: TrebuchetMSBdIt.ttf +Source26: Verdana.ttf +Source27: VerdanaBd.ttf +Source28: VerdanaIt.ttf +Source29: VerdanaBdIt.ttf + +BuildArch: noarch +BuildRequires: fontpackages-devel + +%description +This package provides the following fonts: +- Arial +- Comic Sans MS +- Courier New +- Georgia +- Helvetica Neue +- Helvetica +- Lucida Sans Unicode +- Tahoma +- Times New Roman +- Trebuchet MS +- Verdana + + +%_font_pkg -n some-nice-fonts *.ttf + + +%prep +%setup -q -c -T -n some-nice-fonts-%{version} + + +%install +rm -rf %{buildroot} +install -m 0755 -d %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE0} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE1} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE2} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE3} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE4} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE5} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE6} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE7} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE8} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE9} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE10} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE11} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE12} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE13} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE14} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE15} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE16} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE17} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE18} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE19} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE20} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE21} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE22} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE23} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE24} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE25} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE26} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE27} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE28} %{buildroot}%{_fontdir} +install -m 0644 -p %{SOURCE29} %{buildroot}%{_fontdir} + + +%changelog +* Mon Nov 20 2017 Adrien Vergé +- Add bold and italic versions when available + +* Fri Jun 23 2017 Adrien Vergé +- Initial package spec diff --git a/main.py b/main.py new file mode 100644 index 0000000000000000000000000000000000000000..603bc5a6b5dc308db3c7f78062fbf4efbeeec8cf --- /dev/null +++ b/main.py @@ -0,0 +1,56 @@ +import time +import argparse +from src.constructor import generate_presentation +from src.prompt_configs import en_gigachat_config, ru_gigachat_config +from src.gigachat import giga_generate +from src.kandinsky import api_k31_generate +from src.font import Font + +def main(): + parser = argparse.ArgumentParser( + description='Generate a presentation.' + ) + parser.add_argument( + '-d', '--description', + type=str, + required=True, + help='Description of the presentation' + ) + parser.add_argument( + '-l', '--language', + type=str, + choices=['en', 'ru'], + default='en', + help='Language for the presentation. Choices are: English, Russian. Default is English.' + ) + args = parser.parse_args() + + # Select the appropriate prompt configuration based on the language argument + if args.language == 'en': + prompt_config = en_gigachat_config + elif args.language == 'ru': + prompt_config = ru_gigachat_config + else: + # set default to prevent interruptions in unexpected scenario + print("only 'en' and 'ru' configs are available, settings default 'en'") + prompt_config = en_gigachat_config + + fonts_dir = "./fonts" + logs_dir = "./logs" + + font = Font(fonts_dir) + font.set_random_font() + + output_dir = f'{logs_dir}/{int(time.time())}' + + generate_presentation( + llm_generate=giga_generate, + generate_image=api_k31_generate, + prompt_config=prompt_config, + description=args.description, + font=font, + output_dir=output_dir, + ) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..42f2be9a0600463c3dd85407e915a47f58dd2974 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,23 @@ +googletrans==4.0.0-rc1 +httpx +fastapi +gradio +huggingface_hub +numpy +Pillow +pydantic +python-dotenv +python_pptx +Requests +scipy +setuptools +scikit-image +torch +torchvision +tqdm +uvicorn + +einops +accelerate +sentencepiece +-r Kandinsky-3/requirements.txt \ No newline at end of file diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/constructor.py b/src/constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..48f0bef34d6f6039d570c13cb127d53b5d5820c8 --- /dev/null +++ b/src/constructor.py @@ -0,0 +1,145 @@ +from pptx import Presentation +from pptx.util import Inches +from pptx.oxml.xmlchemy import OxmlElement +from pptx.dml.color import RGBColor +from pptx.enum.text import PP_ALIGN, MSO_ANCHOR, MSO_AUTO_SIZE + +import random +import os +from PIL import Image +from typing import List, Callable + +from .llm_utils import llm_generate_titles, llm_generate_text, llm_generate_image_prompt, llm_generate_background_prompt +from .prompt_configs import PromptConfig +from .slides import generate_slide +from .font import Font + +import tqdm + + +def generate_presentation( + llm_generate: Callable[[str], str], + generate_image: Callable[[str, int, int], Image.Image], + prompt_config: PromptConfig, + description: str, + font:Font, + output_dir: str, +) -> Presentation: + """ + Generate a PowerPoint presentation based on a description using language and image models. + + Args: + llm_generate (Callable[[str], str]): Function to generate text using a language model. + generate_image (Callable[[str, int, int], Image.Image]): Function to generate images. + prompt_config (PromptConfig): Configuration for prompts. + description (str): Description of the presentation. + output_dir (str): Directory to save generated images and presentation. + font (Font): Font object to manage font styles and paths. + Returns: + Presentation: The generated PowerPoint presentation. + """ + os.makedirs(os.path.join(output_dir, 'backgrounds'), exist_ok=True) + os.makedirs(os.path.join(output_dir, 'pictures'), exist_ok=True) + presentation = Presentation() + presentation.slide_height = Inches(9) + presentation.slide_width = Inches(16) + + pbar = tqdm.tqdm(total=4, desc="Presentation goes brrr...") + + pbar.set_description("Generating titles for presentation") + titles = llm_generate_titles(llm_generate, description, prompt_config) + pbar.update(1) + + pbar.set_description("Generating text for slides") + texts = [None] + llm_generate_text( + llm_generate, + description, + titles[1:], + prompt_config + ) + pbar.update(1) + + # postfix added to keywords describing presentation + background_style = random.choice(prompt_config.background_styles) + + picture_paths = [] + background_paths = [] + pbar.set_description("Generating images for slides") + for t_index, (title, text) in enumerate(zip(titles, texts)): + # Decide randomly presence of image on current slide + if random.choices( + [True, False], + # side-image/plain-text with background image + weights=[4, 1], + k=1)[0] and text: + image_width, image_height = random.choice( + [(768, 1344), (1024, 1024)] + ) + caption_prompt = llm_generate_image_prompt( + llm_generate, + description, + title, + prompt_config + ) + picture = generate_image( + prompt=caption_prompt, + width=image_width, + height=image_height + ) + picture_path = os.path.join( + output_dir, + 'pictures', + f'{t_index:06}.png' + ) + picture.save(picture_path) + else: + picture_path = None + picture_paths.append(picture_path) + + if picture_path is None: + background_width, background_height = 1344, 768 + background_prompt = llm_generate_background_prompt( + llm_generate, + description, + title, + prompt_config, + background_style + ) + background = generate_image( + prompt=background_prompt, + width=background_width, + height=background_height + ) + background_path = os.path.join( + output_dir, + 'backgrounds', + f'{t_index:06}.png' + ) + background.save(background_path) + else: + background_path = None + background_paths.append(background_path) + pbar.update(1) + + pbar.set_description("Packing presentation") + + for index in range(len(titles)): + title = titles[index] + text = texts[index] + picture_path = picture_paths[index] + background_path = background_paths[index] + + generate_slide( + presentation=presentation, + title=title, + text=text, + picture_path=picture_path, + background_path=background_path, + font=font, + ) + pbar.update(1) + + pbar.set_description("Done") + output_path = os.path.join(output_dir, 'presentation.pptx') + presentation.save(output_path) + return presentation \ No newline at end of file diff --git a/src/font.py b/src/font.py new file mode 100644 index 0000000000000000000000000000000000000000..4b843557df4850f6e49b45f8e100daaeebcdfc49 --- /dev/null +++ b/src/font.py @@ -0,0 +1,123 @@ +import os +import random +from typing import Optional + +class Font: + def __init__(self, fonts_dir: str, max_size: int = 66): + """ + Initialize the Font class with a directory containing font files. + + Args: + fonts_dir (str): Path to the directory containing font files. + max_size (int): Maximum font size to use for fitting text. + """ + self.fonts_dir = fonts_dir + self.font_name = None # Default font + self.set_random_font() + self.max_size = max_size + + def set_font(self, font_name: str = "Tahoma") -> None: + """ + Set the font name to be used. + + Args: + font_name (str): Name of the font to set (default is "Tahoma"). + """ + if self._find_font(font_name): + self.font_name = font_name + else: + raise ValueError(f"Font '{font_name}' not found in '{self.fonts_dir}'.") + + def set_random_font(self) -> None: + """ + Set a random font from the fonts directory. The chosen font must have both + basic and bold styles available. + """ + available_fonts = self._find_available_fonts() + if not available_fonts: + raise ValueError("No fonts with both basic and bold styles found.") + + self.font_name = random.choice(available_fonts) + + @property + def basic(self) -> Optional[str]: + """ + Get the path of the basic font style based on the current font name. + + Returns: + Optional[str]: The full path to the basic font style or None if not found. + """ + return self._find_font(f'{self.font_name}') + + @property + def bold(self) -> Optional[str]: + """ + Get the path of the bold font style based on the current font name. + + Returns: + Optional[str]: The full path to the bold font style or None if not found. + """ + return self._find_font(f'{self.font_name}Bd') + + @property + def italic(self) -> Optional[str]: + """ + Get the path of the italic font style based on the current font name. + + Returns: + Optional[str]: The full path to the italic font style or None if not found. + """ + return self._find_font(f'{self.font_name}It') + + @property + def italic_bold(self) -> Optional[str]: + """ + Get the path of the italic bold font style based on the current font name. + + Returns: + Optional[str]: The full path to the italic bold + font style or None if not found. + """ + return self._find_font(f'{self.font_name}BdIt') + + def _find_font(self, font_name: str) -> Optional[str]: + """ + Find a font file in the fonts directory by font name. + + Args: + font_name (str): The font name to find. + + Returns: + Optional[str]: The full path to the font file if found, None otherwise. + """ + if not font_name.endswith(".ttf"): + font_name = f'{font_name}.ttf' + + for filename in os.listdir(self.fonts_dir): + if font_name == filename: + file_path = os.path.join(self.fonts_dir, filename) + return file_path + return None + + def _find_available_fonts(self) -> list: + """ + Find all available fonts in the fonts directory + that have both basic and bold styles. + + Returns: + list: A list of font names (without file extension) + that have both basic and bold styles. + """ + fonts = set() + for filename in os.listdir(self.fonts_dir): + if filename.endswith(".ttf"): + font_name = filename[:-4] # Remove the .ttf extension + if font_name.endswith("Bd"): + basic_font = font_name[:-2] + if os.path.exists(os.path.join(self.fonts_dir, f"{basic_font}.ttf")): + fonts.add(basic_font) + else: + bold_font = f"{font_name}Bd" + if os.path.exists(os.path.join(self.fonts_dir, f"{bold_font}.ttf")): + fonts.add(font_name) + return list(fonts) \ No newline at end of file diff --git a/src/gigachat.py b/src/gigachat.py new file mode 100644 index 0000000000000000000000000000000000000000..a030051631030acbd64462876ab59c5c2f1092c1 --- /dev/null +++ b/src/gigachat.py @@ -0,0 +1,143 @@ +import requests +import base64 +import uuid +import json +import time +from typing import Dict, Optional, Any +from dotenv import load_dotenv +import os + +# Load environment variables from .env file +load_dotenv() + +AUTH_TOKEN = os.getenv("AUTH_TOKEN") +COOKIE = os.getenv("COOKIE") + +# print(f"AUTH_TOKEN: {AUTH_TOKEN}") +# print(f"COOKIE: {COOKIE}") + +def get_auth_token(timeout: float = 2) -> Dict[str, Any]: + """ + Get authentication token. + + Args: + timeout (float): Timeout duration in seconds. + + Returns: + Dict[str, Any]: Dictionary containing the access token and its expiration time. + """ + url = "https://beta.saluteai.sberdevices.ru/v1/token" + payload = 'scope=GIGACHAT_API_CORP' + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Accept': 'application/json', + 'RqUID': str(uuid.uuid4()), + 'Cookie': COOKIE, + 'Authorization': f'Basic {AUTH_TOKEN}' + } + response = requests.post(url, headers=headers, data=payload, timeout=timeout) + response_dict = response.json() + return { + 'access_token': response_dict['tok'], + 'expires_at': response_dict['exp'] + } + +def check_auth_token(token_data: Dict[str, Any]) -> bool: + """ + Check if the authentication token is valid. + + Args: + token_data (Dict[str, Any]): Dictionary containing token data. + + Returns: + bool: True if the token is valid, False otherwise. + """ + return token_data['expires_at'] - time.time() > 5 + +token_data: Optional[Dict[str, Any]] = None + +def get_response( + prompt: str, + model: str, + timeout: int = 120, + n: int = 1, + fuse_key_word: Optional[str] = None, + use_giga_censor: bool = False, + max_tokens: int = 512, +) -> requests.Response: + """ + Send a text generation request to the API. + + Args: + prompt (str): The input prompt. + model (str): The model to be used for generation. + timeout (int): Timeout duration in seconds. + n (int): Number of responses. + fuse_key_word (Optional[str]): Additional keyword to include in the prompt. + use_giga_censor (bool): Whether to use profanity filtering. + max_tokens (int): Maximum number of tokens in the response. + + Returns: + requests.Response: API response. + """ + global token_data + + url = "https://beta.saluteai.sberdevices.ru/v1/chat/completions" + payload = json.dumps({ + "model": model, + "messages": [ + { + "role": "user", + "content": ' '.join([fuse_key_word, prompt]) if fuse_key_word else prompt + } + ], + "temperature": 0.87, + "top_p": 0.47, + "n": n, + "stream": False, + "max_tokens": max_tokens, + "repetition_penalty": 1.07, + "profanity_check": use_giga_censor + }) + + if token_data is None or not check_auth_token(token_data): + token_data = get_auth_token() + + headers = { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'Authorization': f'Bearer {token_data["access_token"]}' + } + response = requests.post(url, headers=headers, data=payload, timeout=timeout) + return response + +def giga_generate( + prompt: str, + model_version: str = "GigaChat-Pro", + max_tokens: int = 2048 +) -> str: + """ + Generate text using the GigaChat model. + + Args: + prompt (str): The input prompt. + model_version (str): The version of the model to use. + max_tokens (int): Maximum number of tokens in the response. + + Returns: + str: Generated text. + """ + response = get_response( + prompt, + model_version, + use_giga_censor=False, + max_tokens=max_tokens, + ) + response_dict = response.json() + + if response_dict['choices'][0]['finish_reason'] == 'blacklist': + print('GigaCensor triggered!') + return 'Censored Text' + else: + response_str = response_dict['choices'][0]['message']['content'] + return response_str \ No newline at end of file diff --git a/src/kandinsky.py b/src/kandinsky.py new file mode 100644 index 0000000000000000000000000000000000000000..914ac78725ace4152b1352cc0fce93434de6bb40 --- /dev/null +++ b/src/kandinsky.py @@ -0,0 +1,90 @@ +import sys +sys.path.append('Kandinsky-3') + +import torch +from kandinsky3 import get_T2I_pipeline +from fastapi import FastAPI, HTTPException +from pydantic import BaseModel +from typing import Optional +import base64 +from io import BytesIO +from PIL import Image +import uvicorn + +import time +from fastapi import FastAPI, HTTPException +from pydantic import BaseModel +import base64 +import requests + +device_map = torch.device('cuda:0') +dtype_map = { + 'unet': torch.float32, + 'text_encoder': torch.float16, + 'movq': torch.float32, +} + +# Initialize the FastAPI app +app = FastAPI() + +# Define the request model +class GenerateImageRequest(BaseModel): + prompt: str + width: Optional[int] = 1024 + height: Optional[int] = 1024 + +# Define the response model +class GenerateImageResponse(BaseModel): + image_base64: str + +# Define the endpoint +@app.post("/k31/", response_model=GenerateImageResponse) +async def generate_image(request: GenerateImageRequest): + try: + # Generate the image using the pipeline + pil_image = t2i_pipe(request.prompt, width=request.width, height=request.height, steps=50)[0] + + # Resize the image if necessary + if pil_image.size != (request.width, request.height): + pil_image = pil_image.resize((request.width, request.height)) + + # Convert the PIL image to base64 + buffered = BytesIO() + pil_image.save(buffered, format="PNG") + image_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8') + + # Return the response + return GenerateImageResponse(image_base64=image_base64) + + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + +def api_k31_generate(prompt, width=1024, height=1024, url = "http://0.0.0.0:8188/k31/"): + # Define the text message and image parameters + data = { + "prompt": prompt, + "width": width, + "height": height + } + + # Send the POST request + response = requests.post(url, json=data) + + # Check if the request was successful + if response.status_code == 200: + # Extract the base64 encoded image from the response + image_base64 = response.json()["image_base64"] + + # You can further process the image here, for example, decode it from base64 + decoded_image = Image.open(BytesIO(base64.b64decode(image_base64))) + + return decoded_image + else: + print("Error:", response.text) + +# Run the FastAPI app +if __name__ == "__main__": + t2i_pipe = get_T2I_pipeline( + device_map, dtype_map, + ) + uvicorn.run(app, host="0.0.0.0", port=8188) diff --git a/src/llm_utils.py b/src/llm_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b4244b621b0a43bd7f8551dd7796903c5b124a6b --- /dev/null +++ b/src/llm_utils.py @@ -0,0 +1,122 @@ +from typing import List, Callable +from googletrans import Translator +import random + +from src.prompt_configs import PromptConfig, prefix + +translator = Translator() + +def get_translation(text: str, dest: str = 'en') -> str: + return translator.translate(text, dest=dest).text + +def llm_generate_titles( + llm_generate: Callable[[str], str], + description: str, + prompt_config: PromptConfig, +) -> List[str]: + """ + Generate presentation slide titles using a language model. + + Args: + llm_generate (Callable[[str], str]): Function to generate text using a language model. + description (str): Description of the presentation. + prompt_config (PromptConfig): Configuration for prompts. + + Returns: + List[str]: List of generated slide titles. + """ + prompt = prompt_config.title_prompt.format( + description=description + ) + titles_str = llm_generate(prompt) + titles = [] + for title in titles_str.split("\n"): + sep_index = title.index('. ') + 2 + title = title.strip()[sep_index:] + title = title.replace('.', '') + title = title.replace('\n', '') + if prefix in title.lower(): + title = title[ + title.lower().index(prefix)+len(prefix): + ] + titles.append(title) + return titles + +def llm_generate_text( + llm_generate: Callable[[str], str], + description: str, + titles: List[str], + prompt_config: PromptConfig +) -> List[str]: + """ + Generate text for each slide title using a language model. + + Args: + llm_generate (Callable[[str], str]): Function to generate text using a language model. + description (str): Description of the presentation. + titles (List[str]): List of slide titles. + prompt_config (PromptConfig): Configuration for prompts. + + Returns: + List[str]: List of generated texts for each slide. + """ + texts = [] + for title in titles: + query = prompt_config.text_prompt.format(description=description, title=title) + text = llm_generate(query) + if prefix in text.lower(): + text = text[text.lower().index(prefix)+len(prefix):] + text = text.replace('\n', '') + texts.append(text) + return texts + +def llm_generate_image_prompt( + llm_generate: Callable[[str], str], + description: str, + title: str, + prompt_config: PromptConfig +) -> str: + """ + Generate an image prompt for a slide using a language model and translate it. + + Args: + llm_generate (Callable[[str], str]): Function to generate text using a language model. + description (str): Description of the presentation. + title (str): Slide title. + prompt_config (PromptConfig): Configuration for prompts. + + Returns: + str: Translated image prompt. + """ + query = prompt_config.image_prompt.format(description=description, title=title) + prompt = llm_generate(query) + if prefix in prompt: + prompt = prompt[prompt.lower().index(prompt)+len(prompt):] + prompt = prompt.replace('\n', '') + return get_translation(prompt) + +def llm_generate_background_prompt( + llm_generate: Callable[[str], str], + description: str, + title: str, + prompt_config: PromptConfig, + background_style: str = '' +) -> str: + """ + Generate a background prompt for a slide using a language model and translate it. + + Args: + llm_generate (Callable[[str], str]): Function to generate text using a language model. + description (str): Description of the presentation. + title (str): Slide title. + prompt_config (PromptConfig): Configuration for prompts. + + Returns: + str: Translated background prompt. + """ + query = prompt_config.background_prompt.format(description=description, title=title) + + keywords = llm_generate(query) + background_prompt = f'{keywords}, {background_style}' + + return get_translation(background_prompt) \ No newline at end of file diff --git a/src/prompt_configs/__init__.py b/src/prompt_configs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..33f62d10d726cc8a24def3ef866ed17132d4b953 --- /dev/null +++ b/src/prompt_configs/__init__.py @@ -0,0 +1,3 @@ +from .prompt_config import PromptConfig, prefix +from .ru_gigachat_config import ru_gigachat_config +from .en_gigachat_config import en_gigachat_config \ No newline at end of file diff --git a/src/prompt_configs/en_gigachat_config.py b/src/prompt_configs/en_gigachat_config.py new file mode 100644 index 0000000000000000000000000000000000000000..1bb19a5a5eef8a0e25a7c450284f0c87f6672f31 --- /dev/null +++ b/src/prompt_configs/en_gigachat_config.py @@ -0,0 +1,144 @@ +from .prompt_config import PromptConfig, prefix + +en_gigachat_config = PromptConfig( + title_prompt = ( + 'You are given a presentation description: "{description}". ' + 'Based on this description and examples, generate slide titles for the presentation. ' + 'The title should be brief, no more than 4 words. ' + 'Answer in English only. ' + 'Present the response as a numbered list. ' + 'Examples:\n ' + 'Query: Description of a presentation about marketing strategy for a new product.\n' + '1. Introduction\n ' + '2. Marketing Goals\n ' + '3. Market Analysis\n ' + '4. Budget\n ' + '5. Conclusion\n ' + 'Query: Presentation about company achievements over the past year.\n' + '1. Welcome\n ' + '2. General Achievements\n ' + '3. Financial Results\n ' + '4. Successful Projects\n ' + '5. Team Development\n ' + '6. Social Initiatives\n ' + '7. Future Plans\n ' + '8. Acknowledgments\n ' + '9. Q&A\n ' + 'Query: Presentation about new technologies in manufacturing.\n' + '1. Introduction\n ' + '2. Current Technologies\n ' + '3. New Developments\n ' + '4. Implementation Examples\n ' + '5. Future Trends\n ' + '6. Conclusion\n ' + '7. Discussion\n ' + 'Response:\n' + ), + text_prompt = ( + 'You are given a presentation description: "{description}". ' + 'Write one sentence no more than 20 words for a slide with the title "{title}". ' + 'Answer in English only. ' + f'Write only the final text, starting with "{prefix} ". ' + 'Examples:\n' + f'{prefix} The 20% sales increase is attributed to the implementation of the new marketing strategy.\n' + f'{prefix} Innovative technologies have improved manufacturing efficiency by 30%.\n' + f'{prefix} New customer engagement approaches have increased satisfaction levels by 15%.\n' + f'{prefix} This year, the company launched three new products that became market leaders.\n' + 'Response:\n' + ), + image_prompt = ( + 'You are given a presentation description: "{description}". ' + 'Generate a detailed description of an aesthetic image for a slide with the title: "{title}". ' + 'The description should be long and highly detailed, covering all aspects of the visual elements. ' + 'Exclude numerical values, text, graphs, company names, and similar content. ' + 'Avoid using text on the image. ' + 'Answer in English only. ' + 'Make it visually pleasing and contextually appropriate. ' + 'Start with the word "Description: ". ' + 'Examples:\n' + f'{prefix} A spacious conference room with a modern design, glass walls letting in plenty of natural light, a long wooden table in the center with laptops and documents, business people in formal attire sitting around, and a cityscape visible through the windows.\n' + f'{prefix} A forest trail surrounded by tall trees with green leaves, fallen leaves on the ground, sunlight filtering through the foliage creating a play of light and shadow, animal tracks visible on the path, and the distant sound of a river.\n' + f'{prefix} A busy street in the city center, with high modern buildings featuring glass facades on both sides, many pedestrians walking, some rushing and others strolling, cars and buses moving along the street, and a clear sky with a few clouds.\n' + f'{prefix} A cozy café with wooden tables and soft chairs, paintings of nature on the walls, large windows letting in plenty of light, patrons sitting at tables, some working on laptops and others chatting over coffee, and a counter with desserts and beverages.\n' + 'Response:\n' + ), + background_prompt = ( + 'Based on the presentation description: "{description}" ' + 'and the current slide title: "{title}". ' + 'Use in-context learning to generate 4 key words related to the content of the slide. ' + 'Write the key words separated by commas. ' + 'Examples:\n' + 'Input: Presentation about the latest trends in digital marketing.\n' + 'Title: Emerging Technologies\n' + f'{prefix} innovation, digital, trends, technology\n\n' + 'Input: Presentation on strategies for improving customer service.\n' + 'Title: Enhancing Engagement\n' + f'{prefix} customer, engagement, strategies, improvement\n\n' + 'Input: Presentation on the impact of climate change on agriculture.\n' + 'Title: Environmental Challenges\n' + f'{prefix} climate, agriculture, impact, sustainability\n\n' + 'Input: Presentation on the benefits of remote work for productivity.\n' + 'Title: Work Efficiency\n' + f'{prefix} remote, productivity, benefits, efficiency\n' + 'Response:\n' + ), + # List of strings!!! + background_styles = [ + ( + 'Gradient. WITHOUT TEXT, Vectors style, ' + 'Gradient dip, More game with colors, Smooth transition. ' + ), + ( + 'Abstract. Clean lines, Modern feel, ' + 'Minimalistic, Soft colors, Elegant look. ' + ), + ( + 'Nature-inspired. Soft green tones, ' + 'Earthy feel, Natural textures, Organic look. ' + ), + ( + 'Technology. Futuristic design, Blue tones, ' + 'Circuit patterns, Sleek lines, High-tech feel. ' + ), + ( + 'Corporate. Professional look, Subtle gradients, ' + 'Clean and polished, Neutral colors, Business-oriented. ' + ), + ( + 'Retro. Bold colors, Geometric shapes, ' + 'Vintage feel, Nostalgic design, Playful patterns. ' + ), + ( + 'Minimalist. White space, Simple shapes, ' + 'Clean and clear, Monochrome tones, Modern elegance. ' + ), + ( + 'Art Deco. Rich textures, Metallic accents, ' + 'Geometric patterns, Glamorous style, 1920s influence. ' + ), + ( + 'Urban. Graffiti art, Vibrant colors, ' + 'Street style, Dynamic patterns, Energetic vibe. ' + ), + ( + 'Watercolor. Soft brush strokes, Blended hues, ' + 'Artistic feel, Fluid shapes, Subtle transitions. ' + ), + ( + 'Dark Mode. Deep black tones, Subtle contrasts, ' + 'Sophisticated look, Modern design, High contrast elements. ' + ), + ( + 'Elegant. Rich colors, Decorative patterns, ' + 'Luxurious textures, Classic style, Refined details. ' + ), + ( + 'Nature-inspired. Earthy colors, Leaf patterns, ' + 'Wood textures, Tranquil feel, Organic shapes. ' + ), + ( + 'Dynamic. Bold contrasts, Energetic lines, ' + 'Motion feel, Vibrant colors, Modern design. ' + ) + ] +) \ No newline at end of file diff --git a/src/prompt_configs/prompt_config.py b/src/prompt_configs/prompt_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ac41c086f8e2a7abcafb029d6dbb94d993503942 --- /dev/null +++ b/src/prompt_configs/prompt_config.py @@ -0,0 +1,18 @@ +from typing import List + +prefix = "prompt: " + +class PromptConfig: + def __init__( + self, + title_prompt: str, + text_prompt: str, + image_prompt: str, + background_prompt: str, + background_styles: List[str], + ): + self.title_prompt = title_prompt + self.text_prompt = text_prompt + self.image_prompt = image_prompt + self.background_prompt = background_prompt + self.background_styles = background_styles \ No newline at end of file diff --git a/src/prompt_configs/ru_gigachat_config.py b/src/prompt_configs/ru_gigachat_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2629d719712f2a045625a25d075c81f17cc56f62 --- /dev/null +++ b/src/prompt_configs/ru_gigachat_config.py @@ -0,0 +1,133 @@ +from .prompt_config import PromptConfig, prefix + +ru_gigachat_config = PromptConfig( + title_prompt = ( + 'тебе дано описание презентации: "{description}". ' + 'На основе данного описания и примеров, сгенерируй заголовки слайдов презентации. ' + 'Заголовок должен быть коротким, не более 4 слов. ' + 'Представь ответ в виде пронумерованного списка. ' + 'Примеры:\n ' + 'Запрос: Описание презентации о стратегии маркетинга для нового продукта.\n' + '1. Введение\n ' + '2. Цели маркетинга\n ' + '3. Анализ рынка\n ' + '4. Бюджет\n ' + '5. Заключение\n ' + 'Запрос: Презентация о достижениях компании за прошлый год.\n' + '1. Приветствие\n ' + '2. Общие достижения\n ' + '3. Финансовые результаты\n ' + '4. Успешные проекты\n ' + '5. Развитие команды\n ' + '6. Социальные инициативы\n ' + '7. Планы на будущее\n ' + '8. Благодарности\n ' + '9. Вопросы и ответы\n ' + 'Запрос: Презентация о новых технологиях в производстве.\n' + '1. Введение в тему\n ' + '2. Текущие технологии\n ' + '3. Новые разработки\n ' + '4. Примеры внедрения\n ' + '5. Будущие тенденции\n ' + '6. Заключение\n ' + '7. Дискуссия\n ' + 'Ответ:\n' + ), + text_prompt = ( + 'тебе дано описание презентации: "{description}". ' + 'Напиши одно предложение не более 20 слов для слайда с заголовком "{title}". ' + f'Напиши только итоговый текст, начинай с "{prefix} ". ' + 'Примеры:\n' + f'{prefix} Увеличение продаж на 20% связано с внедрением новой маркетинговой стратегии.\n' + f'{prefix} Инновационные технологии помогли повысить эффективность производства на 30%.\n' + f'{prefix} Новые подходы к работе с клиентами увеличили уровень удовлетворенности на 15%.\n' + f'{prefix} В этом году компания запустила три новых продукта, которые стали лидерами на рынке.\n' + 'Ответ:\n' + ), + image_prompt = ( + 'тебе дано описание презентации: "{description}". ' + 'Придумай детализированное описание эстетичной картинки для слайда с заголовком: "{title}". ' + 'Описание должно быть длинным и супер детализированным, включающим все аспекты визуальной составляющей. ' + 'Исключи цифровые значения, текст, графики, названия компаний и тому подобное. ' + 'Избегай использования текста на изображении. ' + 'Сделай его визуально приятным и подходящим контексту. ' + 'Начни со слова "описание: ". ' + 'Примеры:\n' + f'{prefix} Просторный зал заседаний с современным дизайном, стеклянные стены пропускают много естественного света, в центре длинный деревянный стол с ноутбуками и документами, вокруг сидят деловые люди в официальной одежде, на заднем плане видна городская панорама через окна.\n' + f'{prefix} Лесная тропа, окруженная высокими деревьями с зелеными листьями, на земле опавшая листва, солнечные лучи пробиваются сквозь листву, создавая игру света и теней, на тропе видны следы животных, вдали слышен шум реки.\n' + f'{prefix} Оживленная улица в центре города, по обе стороны высокие современные здания со стеклянными фасадами, на улице много прохожих, некоторые спешат, другие медленно прогуливаются, между ними едут автомобили и автобусы, небо ясное с редкими облаками.\n' + f'{prefix} Уютное кафе с деревянными столами и мягкими креслами, на стенах висят картины с изображением природы, большие окна пропускают много света, за столами сидят посетители, некоторые работают за ноутбуками, другие беседуют за чашкой кофе, на стойке видны десерты и напитки.\n' + 'Ответ:\n' + ), + background_prompt = ( + 'На основании описания презентации: {description} ' + 'и заголовка текущего слайда: "{title}". ' + 'Используй in-context learning для генерации 4 ключевых слов. ' + 'Напиши их через запятую. ' + 'Примеры:\n' + 'инновации, рост, технологии, успех\n' + 'экология, устойчивость, природа, будущее\n' + 'развитие, обучение, достижения, цели\n' + 'ответственность, сообщество, проекты, партнерство\n' + 'Ответ:\n' + ), + # List of strings!!! + background_styles = [ + ( + 'Gradient. WITHOUT TEXT, Vectors style, ' + 'Gradient dip, More game with colors, Smooth transition. ' + ), + ( + 'Abstract. Clean lines, Modern feel, ' + 'Minimalistic, Soft colors, Elegant look. ' + ), + ( + 'Nature-inspired. Soft green tones, ' + 'Earthy feel, Natural textures, Organic look. ' + ), + ( + 'Technology. Futuristic design, Blue tones, ' + 'Circuit patterns, Sleek lines, High-tech feel. ' + ), + ( + 'Corporate. Professional look, Subtle gradients, ' + 'Clean and polished, Neutral colors, Business-oriented. ' + ), + ( + 'Retro. Bold colors, Geometric shapes, ' + 'Vintage feel, Nostalgic design, Playful patterns. ' + ), + ( + 'Minimalist. White space, Simple shapes, ' + 'Clean and clear, Monochrome tones, Modern elegance. ' + ), + ( + 'Art Deco. Rich textures, Metallic accents, ' + 'Geometric patterns, Glamorous style, 1920s influence. ' + ), + ( + 'Urban. Graffiti art, Vibrant colors, ' + 'Street style, Dynamic patterns, Energetic vibe. ' + ), + ( + 'Watercolor. Soft brush strokes, Blended hues, ' + 'Artistic feel, Fluid shapes, Subtle transitions. ' + ), + ( + 'Dark Mode. Deep black tones, Subtle contrasts, ' + 'Sophisticated look, Modern design, High contrast elements. ' + ), + ( + 'Elegant. Rich colors, Decorative patterns, ' + 'Luxurious textures, Classic style, Refined details. ' + ), + ( + 'Nature-inspired. Earthy colors, Leaf patterns, ' + 'Wood textures, Tranquil feel, Organic shapes. ' + ), + ( + 'Dynamic. Bold contrasts, Energetic lines, ' + 'Motion feel, Vibrant colors, Modern design. ' + ) + ] +) \ No newline at end of file diff --git a/src/slides/__init__.py b/src/slides/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6f40a9425fc3e512f7fb977e04624ff740757300 --- /dev/null +++ b/src/slides/__init__.py @@ -0,0 +1,4 @@ +from .image_slide import generate_image_slide +from .plain_text_slide import generate_plain_text_slide +from .title_slide import generate_title_slide +from .generate_slide import generate_slide \ No newline at end of file diff --git a/src/slides/generate_slide.py b/src/slides/generate_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbd5acbbfdbc7caed2c09e5ad8f6adba9d5dee5 --- /dev/null +++ b/src/slides/generate_slide.py @@ -0,0 +1,67 @@ +from pptx import Presentation +from pptx.util import Inches +from pptx.oxml.xmlchemy import OxmlElement +from pptx.dml.color import RGBColor +from pptx.enum.text import PP_ALIGN, MSO_ANCHOR, MSO_AUTO_SIZE + +from typing import List, Callable, Optional +from PIL import Image +import random +import tqdm +import os + + +from .image_slide import generate_image_slide +from .plain_text_slide import generate_plain_text_slide +from .title_slide import generate_title_slide + +from src.font import Font + +def generate_slide( + presentation: Presentation, + title: str, + text: Optional[str] = None, + background_path: Optional[str] = None, + picture_path: Optional[str] = None, + font: Font = None, + text_font_coeff:float=0.6, +) -> None: + """ + Generate a slide in the presentation based on the provided content. + + Args: + presentation (Presentation): The presentation object. + title (str): The title of the slide. + text (Optional[str]): The text content for the slide (default is None). + picture_path (Optional[str]): The path to the picture for the slide (default is None). + background_path (Optional[str]): The path to the background image for the slide (default is None). + font (Font): Font object to manage font styles and paths. + text_font_coeff (float): Coefficient to adjust the font size + of the text relative to the title (default is 0.6). + """ + + if title and text is None and picture_path is None and background_path: + generate_title_slide( + presentation=presentation, + title=title, + font=font, + background_path=background_path, + ) + elif title and text and background_path and picture_path is None: + generate_plain_text_slide( + presentation=presentation, + title=title, + text=text, + background_path=background_path, + font=font, + text_font_coeff=text_font_coeff, + ) + elif title and text and picture_path and background_path is None: + generate_image_slide( + presentation=presentation, + title=title, + text=text, + picture_path=picture_path, + font=font, + text_font_coeff=text_font_coeff, + ) \ No newline at end of file diff --git a/src/slides/image_slide.py b/src/slides/image_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd7a98679211f7fadc300cb6ede5587a2e31fac --- /dev/null +++ b/src/slides/image_slide.py @@ -0,0 +1,289 @@ +from pptx import Presentation +from pptx.util import Inches +from pptx.oxml.xmlchemy import OxmlElement +from pptx.dml.color import RGBColor +from pptx.enum.text import PP_ALIGN, MSO_ANCHOR, MSO_AUTO_SIZE + +from typing import List, Callable, Optional +from PIL import Image +import random +import tqdm +import os + +from src.font import Font +from .slide_utils import add_paragraph + +def generate_text_title_image_right( + presentation: Presentation, + title: str, + text: str, + picture_path: str, + font:Font, + text_font_coeff:float=0.6, +) -> None: + """ + Add a slide with title, text on the left, and picture on the right. + + Args: + presentation (Presentation): PowerPoint presentation object + title (str): Title for the slide + text (str): Text content for the left side of the slide + picture_path (str): Path to the picture to be inserted on the right side + font (Font): Font object to manage font styles and paths. + text_font_coeff (float): Coefficient to adjust the font size of the text relative to the title (default is 0.6). + Returns: + None + """ + + slide_layout = presentation.slide_layouts[6] + slide = presentation.slides.add_slide(slide_layout) + + slide_height = 9 + slide_width = 16 + margin = min(slide_height, slide_width) / 18 + + # image params + # original image size + x_pixels, y_pixels = Image.open(picture_path).size + assert x_pixels == y_pixels or x_pixels < y_pixels, \ + 'only vertical and square images can be used' + # we need image height to be equal to slide height + image_height = slide_height + # x_pixels / y_pixels = image_width / image_height + image_width = x_pixels / y_pixels * image_height + image_left = slide_width - image_width + image_top = 0 + + slide.shapes.add_picture( + picture_path, + left=Inches(image_left), + top=Inches(image_top), + width=Inches(image_width), + height=Inches(image_height), + ) + + # title params + title_left = margin + title_top = margin + title_width = slide_width - image_width - 2*margin + title_height = slide_height / 6 + + title_box = slide.shapes.add_textbox( + left=Inches(title_left), + top=Inches(title_top), + width=Inches(title_width), + height=Inches(title_height), + ) + title_frame = title_box.text_frame + title_frame.clear() + + title_frame.vertical_anchor = MSO_ANCHOR.MIDDLE + title_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE + title_frame.word_wrap = False + + # title_paragraph = title_frame.add_paragraph() + title_paragraph = add_paragraph(title_frame) + title_paragraph.alignment = PP_ALIGN.CENTER + title_paragraph.text = title + + for max_size in range(font.max_size)[::-5]: + try: + title_frame.fit_text( + font_file=font.bold, + max_size=max_size, + bold=True, + ) + break + except: + pass + + # text params + title_left = margin + text_top = title_height + margin*2 + text_width = slide_width - image_width - 2*margin + text_height = slide_height - title_height - 3*margin + + text_box = slide.shapes.add_textbox( + left=Inches(title_left), + top=Inches(text_top), + width=Inches(text_width), + height=Inches(text_height), + ) + text_frame = text_box.text_frame + text_frame.clear() + + text_frame.vertical_anchor = MSO_ANCHOR.MIDDLE + text_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE + text_frame.word_wrap = False + + # text_paragraph = text_frame.add_paragraph() + text_paragraph = add_paragraph(text_frame) + text_paragraph.text = text + text_paragraph.alignment = PP_ALIGN.CENTER + + for max_size in range(int(max_size*text_font_coeff))[::-5]: + try: + text_frame.fit_text(font_file=font.basic, max_size=max_size) + break + except: + pass + + +def generate_text_title_image_left( + presentation: Presentation, + title: str, + text: str, + picture_path: str, + font:Font, + text_font_coeff:float=0.6, +) -> None: + """ + Add a slide with title, text on the left, and picture on the right. + + Args: + presentation (Presentation): PowerPoint presentation object + title (str): Title for the slide + text (str): Text content for the left side of the slide + picture_path (str): Path to the picture to be inserted on the right side + font (Font): Font object to manage font styles and paths. + text_font_coeff (float): Coefficient to adjust the font + size of the text relative to the title (default is 0.6). + + Returns: + None + """ + + slide_layout = presentation.slide_layouts[6] + slide = presentation.slides.add_slide(slide_layout) + + slide_height = 9 + slide_width = 16 + margin = min(slide_height, slide_width) / 18 + + # image params + # original image size + x_pixels, y_pixels = Image.open(picture_path).size + assert x_pixels == y_pixels or x_pixels < y_pixels, \ + 'only vertical and square images can be used' + # we need image height to be equal to slide height + image_height = slide_height + # x_pixels / y_pixels = image_width / image_height + image_width = x_pixels / y_pixels * image_height + image_left = 0 + image_top = 0 + + slide.shapes.add_picture( + picture_path, + left=Inches(image_left), + top=Inches(image_top), + width=Inches(image_width), + height=Inches(image_height), + ) + + # title params + title_left = image_width + margin + title_top = margin + title_width = slide_width - image_width - 2 * margin + title_height = slide_height / 6 + + title_box = slide.shapes.add_textbox( + left=Inches(title_left), + top=Inches(title_top), + width=Inches(title_width), + height=Inches(title_height), + ) + title_frame = title_box.text_frame + title_frame.clear() + + title_frame.vertical_anchor = MSO_ANCHOR.MIDDLE + title_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE + title_frame.word_wrap = False + + # title_paragraph = title_frame.add_paragraph() + title_paragraph = add_paragraph(title_frame) + title_paragraph.text = title + title_paragraph.alignment = PP_ALIGN.CENTER + + for max_size in range(font.max_size)[::-5]: + try: + title_frame.fit_text( + font_file=font.bold, + max_size=max_size, + bold=True, + ) + break + except: + pass + + # text params + text_left = title_left + text_top = title_height + margin * 2 + text_width = slide_width - image_width - 2 * margin + text_height = slide_height - title_height - 3 * margin + + text_box = slide.shapes.add_textbox( + left=Inches(text_left), + top=Inches(text_top), + width=Inches(text_width), + height=Inches(text_height), + ) + text_frame = text_box.text_frame + text_frame.vertical_anchor = MSO_ANCHOR.MIDDLE + text_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE + text_frame.word_wrap = False + + # text_paragraph = text_frame.add_paragraph() + text_paragraph = add_paragraph(text_frame) + text_paragraph.text = text + text_paragraph.alignment = PP_ALIGN.CENTER + + for max_size in range(int(max_size*text_font_coeff))[::-5]: + try: + text_frame.fit_text( + font_file=font.basic, + max_size=max_size + ) + break + except: + pass + + +def generate_image_slide( + presentation: Presentation, + title: str, + text: str, + picture_path: str, + font: Font, + text_font_coeff: float = 0.6, +) -> None: + """ + Generate a slide with a title, text, and an image, choosing the layout randomly. + + This function creates a slide in a PowerPoint presentation that includes a title, + text, and an image. The layout is chosen randomly between two options: + image on the right or image on the left. + + Args: + presentation (Presentation): PowerPoint presentation object. + title (str): Title for the slide. + text (str): Text content for the slide. + picture_path (str): Path to the picture to be inserted in the slide. + font (Font): Font object to manage font styles and paths. + text_font_coeff (float, optional): Coefficient to adjust the font size of the text + relative to the title (default is 0.65). + + Returns: + None + """ + gen_func = random.choice([ + generate_text_title_image_right, + generate_text_title_image_left, + ]) + gen_func( + presentation=presentation, + title=title, + text=text, + picture_path=picture_path, + font=font, + text_font_coeff=text_font_coeff, + ) \ No newline at end of file diff --git a/src/slides/plain_text_slide.py b/src/slides/plain_text_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..fe098ceda102700c479be0d8849b39c1e0d08a06 --- /dev/null +++ b/src/slides/plain_text_slide.py @@ -0,0 +1,135 @@ +from pptx import Presentation +from pptx.util import Inches +from pptx.oxml.xmlchemy import OxmlElement +from pptx.dml.color import RGBColor +from pptx.enum.text import PP_ALIGN, MSO_ANCHOR, MSO_AUTO_SIZE + +from typing import List, Callable, Optional +from PIL import Image +import random +import tqdm +import os + + + +from src.font import Font +from .slide_utils import set_shape_transparency, add_paragraph + +def generate_plain_text_slide( + presentation: Presentation, + title: str, + text: str, + font:Font, + background_path: str = None, + text_font_coeff:float=0.6, +) -> None: + """ + Add a slide with title, text placeholders on the blurred background image. + + Args: + presentation (Presentation): PowerPoint presentation object + title (str): Title for the slide + text (str): Text content for the slide + background_path (str): Path to the background image for the slide + font (Font): Font object to manage font styles and paths. + text_font_coeff (float): Coefficient to adjust the font size of the text relative to the title (default is 0.6). + Returns: + None + """ + + slide_layout = presentation.slide_layouts[6] + slide = presentation.slides.add_slide(slide_layout) + + slide_height = 9 + slide_width = 16 + margin = min(slide_height, slide_width) / 18 + + # Background image + if background_path: + pic = slide.shapes.add_picture( + background_path, 0, 0, + width=presentation.slide_width, + height=presentation.slide_height + ) + # This moves it to the background + slide.shapes._spTree.remove(pic._element) + slide.shapes._spTree.insert(2, pic._element) + + # Title placeholder + title_left = margin + title_top = margin + title_width = slide_width - 2 * margin + title_height = slide_height / 6 + + title_box = slide.shapes.add_textbox( + left=Inches(title_left), + top=Inches(title_top), + width=Inches(title_width), + height=Inches(title_height), + ) + title_frame = title_box.text_frame + title_frame.clear() + + title_frame.word_wrap = False + title_frame.vertical_anchor = MSO_ANCHOR.MIDDLE + title_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE + + title_paragraph = add_paragraph(title_frame) + title_paragraph.alignment = PP_ALIGN.CENTER + title_paragraph.text = title + + for max_size in range(font.max_size)[::-5]: + try: + title_frame.fit_text( + font_file=font.bold, + max_size=max_size, + bold=True, + ) + break + except: + pass + + # settings white color and transparency to title shape + title_fill = title_box.fill + title_fill.solid() + title_fill.fore_color.rgb = RGBColor(255, 255, 255) + set_shape_transparency(title_box, 0.5) + + # Text placeholder + text_left = Inches(margin) + text_top = Inches(title_height + margin * 2) + text_width = Inches(slide_width - 2 * margin) + text_height = Inches(slide_height - title_height - 3 * margin) + text_box = slide.shapes.add_textbox( + left=text_left, + top=text_top, + width=text_width, + height=text_height + ) + text_frame = text_box.text_frame + text_frame.clear() + + text_frame.word_wrap = False + text_frame.vertical_anchor = MSO_ANCHOR.MIDDLE + text_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE + + text_paragraph = add_paragraph(text_frame) + text_paragraph.text = text + text_paragraph.alignment = PP_ALIGN.CENTER + + for max_size in range(int(max_size*text_font_coeff))[::-5]: + try: + text_frame.fit_text( + font_file=font.basic, + max_size=max_size + ) + break + except: + pass + + # Setting text box fill to white with 80% transparency + text_fill = text_box.fill + text_fill.solid() + text_fill.fore_color.rgb = RGBColor(255, 255, 255) + set_shape_transparency(text_box, 0.5) + \ No newline at end of file diff --git a/src/slides/slide_utils.py b/src/slides/slide_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..32d248e7e09ba84007db4d75c365999176acc843 --- /dev/null +++ b/src/slides/slide_utils.py @@ -0,0 +1,31 @@ +from pptx import Presentation +from pptx.util import Inches +from pptx.oxml.xmlchemy import OxmlElement +from pptx.dml.color import RGBColor +from pptx.enum.text import PP_ALIGN, MSO_ANCHOR, MSO_AUTO_SIZE + +import random +import os +from PIL import Image +from typing import List, Callable + +import tqdm + +def add_paragraph(text_frame): + try: + title_paragraph = text_frame.paragraphs[0] + except: + title_paragraph = text_frame.add_paragraph() + return title_paragraph + +def SubElement(parent, tagname, **kwargs): + element = OxmlElement(tagname) + element.attrib.update(kwargs) + parent.append(element) + return element + +def set_shape_transparency(shape, alpha): + """ Set the transparency (alpha) of a shape""" + ts = shape.fill._xPr.solidFill + sF = ts.get_or_change_to_srgbClr() + SubElement(sF, 'a:alpha', val=str(int(alpha*100000))) \ No newline at end of file diff --git a/src/slides/title_slide.py b/src/slides/title_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..54657b251c8b9c218ba7877133d416e55b4850c0 --- /dev/null +++ b/src/slides/title_slide.py @@ -0,0 +1,94 @@ +from pptx import Presentation +from pptx.util import Inches +from pptx.oxml.xmlchemy import OxmlElement +from pptx.dml.color import RGBColor +from pptx.enum.text import PP_ALIGN, MSO_ANCHOR, MSO_AUTO_SIZE + +import random +import os +from PIL import Image +from typing import List, Callable + +import tqdm + +from .slide_utils import set_shape_transparency, add_paragraph + +from src.font import Font + + +def generate_title_slide( + presentation: Presentation, + title: str, + font:Font, + background_path: str = None, +) -> None: + """ + Add a slide with title, text placeholders on the blurred background image. + + Args: + presentation (Presentation): PowerPoint presentation object + title (str): Title for the slide + text (str): Text content for the slide + background_path (str): Path to the background image for the slide + font (Font): Font object to manage font styles and paths. + Returns: + None + """ + + slide_layout = presentation.slide_layouts[6] + slide = presentation.slides.add_slide(slide_layout) + + slide_height = 9 + slide_width = 16 + margin = min(slide_height, slide_width) / 18 + + # Background image + if background_path: + pic = slide.shapes.add_picture( + background_path, 0, 0, + width=presentation.slide_width, + height=presentation.slide_height + ) + # This moves it to the background + slide.shapes._spTree.remove(pic._element) + slide.shapes._spTree.insert(2, pic._element) + + # Title placeholder + title_left = margin + title_top = margin + title_width = slide_width - 2 * margin + title_height = slide_height - 2 * margin + + title_box = slide.shapes.add_textbox( + left=Inches(title_left), + top=Inches(title_top), + width=Inches(title_width), + height=Inches(title_height), + ) + title_frame = title_box.text_frame + title_frame.clear() + + title_frame.vertical_anchor = MSO_ANCHOR.MIDDLE + title_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE + title_frame.word_wrap = False + + title_paragraph = add_paragraph(title_frame) + title_paragraph.alignment = PP_ALIGN.CENTER + title_paragraph.text = title + + for max_size in range(font.max_size)[::-5]: + try: + title_frame.fit_text( + font_file=font.bold, + max_size=max_size, + bold=True, + ) + break + except TypeError: + pass + + # settings white color and transparency to title shape + title_fill = title_box.fill + title_fill.solid() + title_fill.fore_color.rgb = RGBColor(255, 255, 255) + set_shape_transparency(title_box, 0.5) \ No newline at end of file