Radu Boncea 2 роки тому
коміт
983354ca0d

+ 251 - 0
.gitignore

@@ -0,0 +1,251 @@
+# Created by https://www.toptal.com/developers/gitignore/api/macos,python,visualstudiocode,vim
+# Edit at https://www.toptal.com/developers/gitignore?templates=macos,python,visualstudiocode,vim
+
+### macOS ###
+# General
+.DS_Store
+.AppleDouble
+.LSOverride
+
+# Icon must end with two \r
+Icon
+
+
+# Thumbnails
+._*
+
+# Files that might appear in the root of a volume
+.DocumentRevisions-V100
+.fseventsd
+.Spotlight-V100
+.TemporaryItems
+.Trashes
+.VolumeIcon.icns
+.com.apple.timemachine.donotpresent
+
+# Directories potentially created on remote AFP share
+.AppleDB
+.AppleDesktop
+Network Trash Folder
+Temporary Items
+.apdisk
+
+### macOS Patch ###
+# iCloud generated files
+*.icloud
+
+### Python ###
+# 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/
+
+### Python Patch ###
+# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
+poetry.toml
+
+# ruff
+.ruff_cache/
+
+# LSP config files
+pyrightconfig.json
+
+### Vim ###
+# Swap
+[._]*.s[a-v][a-z]
+!*.svg  # comment out if you don't need vector files
+[._]*.sw[a-p]
+[._]s[a-rt-v][a-z]
+[._]ss[a-gi-z]
+[._]sw[a-p]
+
+# Session
+Session.vim
+Sessionx.vim
+
+# Temporary
+.netrwhist
+*~
+# Auto-generated tag files
+tags
+# Persistent undo
+[._]*.un~
+
+### VisualStudioCode ###
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+!.vscode/*.code-snippets
+
+# Local History for Visual Studio Code
+.history/
+
+# Built Visual Studio Code Extensions
+*.vsix
+
+### VisualStudioCode Patch ###
+# Ignore all local history of files
+.history
+.ionide
+
+# End of https://www.toptal.com/developers/gitignore/api/macos,python,visualstudiocode,vim
+
+output/*

+ 7 - 0
README.md

@@ -0,0 +1,7 @@
+'''console
+python diffuser.py image_to_image --text "A fantasy landscape, trending on artstation" --source_image=https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg --model="runwayml/stable-diffusion-v1-5" --ftype=f32 --backend=mps
+'''
+
+'''console
+python diffuser.py text_to_image --text "A girl, long hair, working on a laptop at a desk, in front of 2 large monitors, picasso style" --model="runwayml/stable-diffusion-v1-5" --ftype=f32 --backend=mps
+'''

+ 62 - 0
diffusers/diffuser.py

@@ -0,0 +1,62 @@
+import uuid
+import torch
+import fire
+from diffusers import (
+    StableDiffusionPipeline,
+    StableDiffusionImg2ImgPipeline
+    )
+import requests
+from PIL import Image
+from io import BytesIO
+
+
+class Diffuser(object):
+    default_backend = "cuda"
+
+    def text_to_image(self, 
+                      text, 
+                      model = "runwayml/stable-diffusion-v1-5", 
+                      ftype='f16', 
+                      backend=default_backend,
+                      dst_path=None):
+        
+        if dst_path is None:
+            dst_path = "image-{}.png".format(str(uuid.uuid4()))
+        torch_dtype = torch.float16 if ftype == 'f16' else torch.float32
+        pipeline = StableDiffusionPipeline.from_pretrained(model, torch_dtype=torch_dtype)
+        pipeline.to(backend)
+        image = pipeline(text).images[0]
+        image.save(dst_path)
+
+    
+    def image_to_image(self, 
+                       text, 
+                       source_image, 
+                       model = "runwayml/stable-diffusion-v1-5", 
+                       ftype='f16', 
+                       backend=default_backend,
+                       dst_path=None):
+        
+        if dst_path is None:
+            dst_path = "image-{}.png".format(str(uuid.uuid4()))
+        torch_dtype = torch.float16 if ftype == 'f16' else torch.float32
+        pipeline = StableDiffusionImg2ImgPipeline.from_pretrained(model, torch_dtype=torch_dtype)
+        pipeline.to(backend)
+        
+        # if image is a url, download it
+        if source_image.startswith("http"):
+            response = requests.get(source_image)
+            source_image = Image.open(BytesIO(response.content)).convert("RGB")
+            source_image = source_image.resize((768, 512))
+        else:
+            source_image = Image.open(source_image).convert("RGB")
+            source_image = source_image.resize((768, 512))
+        
+        image = pipeline(prompt=text, image=source_image, strength=0.75, guidance_scale=7.5).images[0]
+        image.save(dst_path)
+
+
+
+if __name__ == "__main__":
+    diffuser = Diffuser()
+    fire.Fire(diffuser)

BIN
diffusers/images/kids-drawing-princess.png


BIN
diffusers/output/image-210ea7ac-c35b-4935-86a5-1da3bb073103.png


BIN
diffusers/output/image-36ab2061-8db7-48ef-9681-99d2f5182a16.png


BIN
diffusers/output/image-76779850-71cd-4a28-a01b-8665c10d1eac.png


BIN
diffusers/output/image-ebce52bd-c59e-4084-bc3e-35f0a01471f6.png


BIN
diffusers/output/image.png


BIN
diffusers/output/squirrel.png


+ 32 - 0
requirements.txt

@@ -0,0 +1,32 @@
+accelerate==0.18.0
+certifi==2022.12.7
+charset-normalizer==3.1.0
+diffusers==0.15.1
+filelock==3.12.0
+fire==0.5.0
+huggingface-hub==0.13.4
+idna==3.4
+importlib-metadata==6.6.0
+install==1.3.5
+Jinja2==3.1.2
+MarkupSafe==2.1.2
+mpmath==1.3.0
+networkx==3.1
+numpy==1.24.3
+packaging==23.1
+Pillow==9.5.0
+psutil==5.9.5
+PyYAML==6.0
+regex==2023.3.23
+requests==2.28.2
+six==1.16.0
+sympy==1.11.1
+termcolor==2.3.0
+tokenizers==0.13.3
+torch==2.0.0
+torch-vision==0.1.6.dev0
+tqdm==4.65.0
+transformers==4.28.1
+typing_extensions==4.5.0
+urllib3==1.26.15
+zipp==3.15.0