├── .editorconfig ├── .github └── ISSUE_TEMPLATE.md ├── .gitignore ├── .mergify.yml ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── .gitignore ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── images │ └── available_units.png ├── index.rst ├── installation.rst ├── make.bat ├── nider.colors.rst ├── nider.mixins.rst ├── nider.rst ├── readme.rst └── usage.rst ├── examples ├── add_watermark_example │ ├── bg.jpg │ ├── result.jpg │ └── script.py ├── draw_on_bg_example │ ├── result.png │ └── script.py ├── draw_on_bg_with_watermark_example │ ├── result.png │ └── script.py ├── draw_on_image_example │ ├── bg.jpg │ ├── result.png │ └── script.py ├── draw_on_texture_example │ ├── result.png │ ├── script.py │ └── texture.png ├── example1 │ ├── bg.jpg │ ├── result.png │ └── script.py ├── example2 │ ├── bg.jpg │ ├── result.png │ └── script.py ├── example3 │ ├── bg.png │ ├── result.png │ └── script.py └── example4 │ ├── result.png │ ├── script.py │ └── texture.png ├── nider ├── __init__.py ├── colors │ ├── __init__.py │ ├── colormap.py │ └── utils.py ├── core.py ├── exceptions.py ├── mixins │ ├── __init__.py │ ├── img_components_mixins.py │ └── text_mixins.py ├── models.py ├── textures │ ├── Sports.png │ ├── asanoha-400px.png │ ├── asfalt.png │ ├── binding_dark.png │ ├── black_paper.png │ ├── black_thread.png │ ├── blackmamba.png │ ├── broken_noise.png │ ├── cartographer.png │ ├── circles-and-roundabouts.png.png │ ├── congruent_outline.png │ ├── congruent_pentagon.png │ ├── cream_dust.png │ ├── crissXcross.png │ ├── crossword.png │ ├── dark_embroidery.png │ ├── dark_geometric.png │ ├── dark_leather.png │ ├── dark_mosaic.png │ ├── dark_wall.png │ ├── dark_wood.png │ ├── debut_dark.png │ ├── denim.png │ ├── diagmonds.png │ ├── dirty_old_shirt.png │ ├── eight_horns.png │ ├── elastoplast.png │ ├── ep_naturalblack.png │ ├── escheresque_ste.png │ ├── extra_clean_paper.png │ ├── foggy_birds.png │ ├── footer_lodyas.png │ ├── fresh_snow.png │ ├── geometry.png │ ├── geometry2.png │ ├── gplaypattern.png │ ├── gray_sand.png │ ├── grey.png │ ├── handmadepaper.png │ ├── ice_age.png │ ├── irongrip.png │ ├── light_wool.png │ ├── lightpaperfibers.png │ ├── navy_blue.png │ ├── old_mathematics.png │ ├── paper_fibers.png │ ├── photography.png │ ├── pink dust.png │ ├── random_grey_variations.png │ ├── redox_01.png │ ├── retina_wood.png │ ├── sakura.png │ ├── sayagata-400px.png │ ├── school.png │ ├── snow.png │ ├── stardust.png │ ├── subtle_white_feathers.png │ ├── swirl_pattern.png │ ├── symphony.png │ ├── tileable_wood_texture.png │ ├── topography.png │ ├── type.png │ ├── use_your_illusion.png │ ├── weather.png │ ├── wood_1.png │ ├── wood_pattern.png │ └── zwartevilt.png ├── tools.py └── utils.py ├── requirements ├── dev.txt ├── prod.txt └── test.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── test_colors.py ├── test_core.py ├── test_mixins.py ├── test_models.py └── test_utils.py ├── tox.ini └── travis_pypi_setup.py /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * nider version: 2 | * Python version: 3 | * Operating System: 4 | 5 | ### Description 6 | 7 | Describe what you were trying to get done. 8 | Tell us what happened, what went wrong, and what you expected to happen. 9 | 10 | ### What I Did 11 | 12 | ``` 13 | Paste the command(s) you ran and the output. 14 | If there was a crash, please include the traceback here. 15 | ``` 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | # pyenv python configuration file 62 | .python-version 63 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | pull_request_rules: 2 | - name: automatic merge for PyUp pull requests 3 | conditions: 4 | - author=pyup-bot 5 | - status-success=Travis CI - Pull Request 6 | actions: 7 | merge: 8 | method: merge 9 | - name: delete head branch after merge 10 | conditions: 11 | - merged 12 | actions: 13 | delete_head_branch: {} 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | deploy: 2 | provider: pypi 3 | password: 4 | secure: eUsXVNsHfyU9jbKasEE6m1v4p8iTc8LmBMXR0kAIcEbwx8IYA7cQIaa4exahTqFAQnMYDhjgfldPnkwawiag2878SyiLJAOK63I7QYfYU+COauXCinKeQPjIFfoDYif5gPh9qLzcDxAkx6oSizkLBDLujlSbE8xDSfOWC5Ank/D4eGfla+KcumtYovPibGtwMN+W3TxAAiREfAuGldOb6i5XwuMqNO3l5aIJVLgG5Ba4xECO/KUw8QBIvr03+x01TJVrJn1nBLnaj7Oyq56BXwBD+QcZMWeP4wUcMaRo4HkrVD8IrVx2V4kithRE5Iqbh6QvC/akbMMSR6A0fTujo4iFWExym3dlUnwEXHR4APXoVwF5NmpOQPH2sWGd5VK41dbQ5WLQpJ78QPVlHL7Xertp6zuuHzAUeaE99dXg8X0JYk1wygdTLsJDfOqVeprtMCKySDizUpSrFi61/Zij7NzNguIh31jbwDPgLtf1fx83mGo9bdhTnVksSi2UEpHgAmlQmltS8I7w69Y95u++ZWz+urRNVWrj9jybFzqTM2RJCfGQN+9M7fhKgn7rgAlJbHvVelI26mq05pi541JPUpKjYZU2+3WplMcmixfRHtvZ8duGpxlVi6xRGxAMF6j8IL6cNQ2z1LQwIZasNVmhguVP7xkq3BPD+YdeGsjPA1g= 5 | user: pythad 6 | distributions: sdist bdist_wheel 7 | on: 8 | python: 3.8 9 | repo: pythad/nider 10 | tags: true 11 | before_install: 12 | - python --version 13 | - python -m pip install --upgrade pip 14 | - pip --version 15 | - pip install -r requirements/dev.txt 16 | install: pip install -U tox-travis 17 | language: python 18 | python: 19 | - 3.8 20 | - 3.7 21 | - 3.6 22 | script: tox 23 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Vladyslav Ovchynnykov 9 | 10 | Contributors 11 | ------------ 12 | 13 | None yet. Why not be the first? 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | ============ 4 | Contributing 5 | ============ 6 | 7 | Contributions are welcome, and they are greatly appreciated! Every 8 | little bit helps, and credit will always be given. 9 | 10 | You can contribute in many ways: 11 | 12 | Types of Contributions 13 | ---------------------- 14 | 15 | Report Bugs 16 | ~~~~~~~~~~~ 17 | 18 | Report bugs at https://github.com/pythad/nider/issues. 19 | 20 | If you are reporting a bug, please include: 21 | 22 | * Your operating system name and version. 23 | * Any details about your local setup that might be helpful in troubleshooting. 24 | * Detailed steps to reproduce the bug. 25 | 26 | Fix Bugs 27 | ~~~~~~~~ 28 | 29 | Look through the GitHub issues for bugs. Anything tagged with "bug" 30 | and "help wanted" is open to whoever wants to implement it. 31 | 32 | Implement Features 33 | ~~~~~~~~~~~~~~~~~~ 34 | 35 | Look through the GitHub issues for features. Anything tagged with "enhancement" 36 | and "help wanted" is open to whoever wants to implement it. 37 | 38 | Write Documentation 39 | ~~~~~~~~~~~~~~~~~~~ 40 | 41 | nider could always use more documentation, whether as part of the 42 | official nider docs, in docstrings, or even on the web in blog posts, 43 | articles, and such. 44 | 45 | Submit Feedback 46 | ~~~~~~~~~~~~~~~ 47 | 48 | The best way to send feedback is to file an issue at https://github.com/pythad/nider/issues. 49 | 50 | If you are proposing a feature: 51 | 52 | * Explain in detail how it would work. 53 | * Keep the scope as narrow as possible, to make it easier to implement. 54 | * Remember that this is a volunteer-driven project, and that contributions 55 | are welcome :) 56 | 57 | Get Started! 58 | ------------ 59 | 60 | Ready to contribute? Here's how to set up `nider` for local development. 61 | 62 | 1. Fork the `nider` repo on GitHub. 63 | 2. Clone your fork locally:: 64 | 65 | $ git clone git@github.com:your_name_here/nider.git 66 | 67 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 68 | 69 | $ mkvirtualenv nider 70 | $ cd nider/ 71 | $ python setup.py develop 72 | 73 | 4. Create a branch for local development:: 74 | 75 | $ git checkout -b name-of-your-bugfix-or-feature 76 | 77 | Now you can make your changes locally. 78 | 79 | 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: 80 | 81 | $ flake8 nider tests 82 | $ python setup.py test or py.test 83 | $ tox 84 | 85 | To get flake8 and tox, just pip install them into your virtualenv. 86 | 87 | 6. Commit your changes and push your branch to GitHub:: 88 | 89 | $ git add . 90 | $ git commit -m "Your detailed description of your changes." 91 | $ git push origin name-of-your-bugfix-or-feature 92 | 93 | 7. Submit a pull request through the GitHub website. 94 | 95 | Pull Request Guidelines 96 | ----------------------- 97 | 98 | Before you submit a pull request, check that it meets these guidelines: 99 | 100 | 1. The pull request should include tests. 101 | 2. If the pull request adds functionality, the docs should be updated. Put 102 | your new functionality into a function with a docstring, and add the 103 | feature to the list in README.rst. 104 | 3. The pull request should work for Python 3.4 and 3.5. Check 105 | https://travis-ci.org/pythad/nider/pull_requests 106 | and make sure that the tests pass for all supported Python versions. 107 | 108 | Tips 109 | ---- 110 | 111 | To run a subset of tests:: 112 | 113 | 114 | $ python -m unittest discover tests 115 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | History 3 | ======= 4 | 5 | 0.1.0 (2017-07-27) 6 | ------------------ 7 | 8 | * First release on PyPI. 9 | 10 | 11 | 0.2.0 (2017-08-12) 12 | ------------------ 13 | 14 | * Added ``PIL.ImageEnhance`` and ``PIL.ImageFilter`` built-in support 15 | * Enabled auto color generation for unit colors 16 | 17 | 18 | 0.3.0 (2017-08-17) 19 | ------------------ 20 | 21 | * Dropped shadow support for units 22 | * Added outline support for units 23 | * Made unit's font config as a separate class 24 | 25 | 26 | 0.4.0 (2017-09-14) 27 | ------------------ 28 | 29 | * Added ability to add watermarks to images 30 | 31 | 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | MIT License 3 | 4 | Copyright (c) 2017, Vladyslav Ovchynnykov 5 | 6 | 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: 7 | 8 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | 10 | 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. 11 | 12 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | 7 | recursive-include tests * 8 | recursive-include requirements * 9 | recursive-exclude * __pycache__ 10 | recursive-exclude * *.py[co] 11 | 12 | recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif 13 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean clean-test clean-pyc clean-build docs help 2 | .DEFAULT_GOAL := help 3 | define BROWSER_PYSCRIPT 4 | import os, webbrowser, sys 5 | try: 6 | from urllib import pathname2url 7 | except: 8 | from urllib.request import pathname2url 9 | 10 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 11 | endef 12 | export BROWSER_PYSCRIPT 13 | 14 | define PRINT_HELP_PYSCRIPT 15 | import re, sys 16 | 17 | for line in sys.stdin: 18 | match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) 19 | if match: 20 | target, help = match.groups() 21 | print("%-20s %s" % (target, help)) 22 | endef 23 | export PRINT_HELP_PYSCRIPT 24 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 25 | 26 | help: 27 | @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) 28 | 29 | clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts 30 | 31 | 32 | clean-build: ## remove build artifacts 33 | rm -fr build/ 34 | rm -fr dist/ 35 | rm -fr .eggs/ 36 | find . -name '*.egg-info' -exec rm -fr {} + 37 | find . -name '*.egg' -exec rm -f {} + 38 | 39 | clean-pyc: ## remove Python file artifacts 40 | find . -name '*.pyc' -exec rm -f {} + 41 | find . -name '*.pyo' -exec rm -f {} + 42 | find . -name '*~' -exec rm -f {} + 43 | find . -name '__pycache__' -exec rm -fr {} + 44 | 45 | clean-test: ## remove test and coverage artifacts 46 | rm -fr .tox/ 47 | rm -f .coverage 48 | rm -fr htmlcov/ 49 | 50 | lint: ## check style with flake8 51 | flake8 nider tests 52 | 53 | test: ## run tests quickly with the default Python 54 | 55 | python -m unittest discover tests 56 | 57 | test-all: ## run tests on every Python version with tox 58 | tox 59 | 60 | coverage: ## check code coverage quickly with the default Python 61 | coverage run -m unittest discover tests 62 | coverage report -m 63 | coverage html 64 | $(BROWSER) htmlcov/index.html 65 | 66 | build_docs: ## run sphinx build on docs/ directory 67 | sphinx-build -b html docs/ docs/_build 68 | 69 | docs: ## generate Sphinx HTML documentation, including API docs 70 | sphinx-apidoc -o docs/ -T nider 71 | $(MAKE) -C docs clean 72 | $(MAKE) -C docs html 73 | $(BROWSER) docs/_build/html/index.html 74 | 75 | docs_force: 76 | sphinx-apidoc -o docs/ -T -f nider 77 | $(MAKE) -C docs clean 78 | $(MAKE) -C docs html 79 | $(BROWSER) docs/_build/html/index.html 80 | 81 | servedocs: docs ## compile the docs watching for changes 82 | watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . 83 | 84 | release: clean ## package and upload a release 85 | python setup.py sdist upload 86 | python setup.py bdist_wheel upload 87 | 88 | dist: clean ## builds source and wheel package 89 | python setup.py sdist 90 | python setup.py bdist_wheel 91 | ls -l dist 92 | 93 | install: clean ## install the package to the active Python's site-packages 94 | python setup.py install 95 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | nider 3 | ===== 4 | 5 | .. image:: https://img.shields.io/travis/pythad/nider.svg 6 | :target: https://travis-ci.org/pythad/nider 7 | :alt: Travis build 8 | 9 | .. image:: https://img.shields.io/pypi/pyversions/nider.svg 10 | :target: https://pypi.python.org/pypi/nider 11 | :alt: Supported python versions 12 | 13 | .. image:: https://img.shields.io/pypi/v/nider.svg 14 | :target: https://pypi.python.org/pypi/nider 15 | :alt: PyPI version 16 | 17 | .. image:: https://readthedocs.org/projects/nider/badge/?version=latest 18 | :target: https://nider.readthedocs.io/en/latest/?badge=latest 19 | :alt: Documentation Status 20 | 21 | .. image:: https://pyup.io/repos/github/pythad/nider/shield.svg 22 | :target: https://pyup.io/repos/github/pythad/nider/ 23 | :alt: Updates 24 | 25 | .. image:: https://img.shields.io/github/license/pythad/nider.svg 26 | :target: https://pypi.python.org/pypi/nider 27 | :alt: License 28 | 29 | Python package for text images generation and watermarking 30 | 31 | 32 | * Free software: MIT license 33 | * Documentation: https://nider.readthedocs.io. 34 | 35 | ``nider`` is an approach to make generation of text images simple yet flexible. Creating of an image is as simple as describing units you want to be rendered to the image and choosing a method that will be used for drawing. 36 | 37 | ************ 38 | Installation 39 | ************ 40 | 41 | .. code-block:: console 42 | 43 | $ pip install nider 44 | 45 | ******* 46 | Example 47 | ******* 48 | 49 | Creating a simple image is as easy as 50 | 51 | .. code-block:: python 52 | 53 | from nider.models import Header 54 | from nider.models import Paragraph 55 | from nider.models import Linkback 56 | from nider.models import Content 57 | from nider.models import Image 58 | 59 | header = Header('Your super interesting title!') 60 | para = Paragraph('Lorem ipsum dolor sit amet.') 61 | linkback = Linkback('foo.com | @username') 62 | content = Content(para, header, linkback, padding=60) 63 | 64 | img = Image(content, fullpath='result.png') 65 | 66 | img.draw_on_bg('#212121') 67 | 68 | *************** 69 | Featured images 70 | *************** 71 | 72 | All of the featured images were drawn using ``nider`` package. Code used to generate them can be found `here `_. 73 | 74 | 75 | Example 1 76 | ========= 77 | .. image:: https://github.com/pythad/nider/raw/master/examples/example1/result.png 78 | :alt: example1 79 | 80 | Example 2 81 | ========= 82 | .. image:: https://github.com/pythad/nider/raw/master/examples/example2/result.png 83 | :alt: example2 84 | 85 | Example 3 86 | ========= 87 | .. image:: https://github.com/pythad/nider/raw/master/examples/example3/result.png 88 | :alt: example3 89 | 90 | Example 4 91 | ========= 92 | .. image:: https://github.com/pythad/nider/raw/master/examples/example4/result.png 93 | :alt: example4 94 | 95 | Watermark example 1 96 | =================== 97 | .. image:: https://github.com/pythad/nider/raw/master/examples/add_watermark_example/result.jpg 98 | :alt: add_watermark_example 99 | 100 | Watermark example 2 101 | =================== 102 | .. image:: https://github.com/pythad/nider/raw/master/examples/draw_on_bg_with_watermark_example/result.png 103 | :alt: draw_on_bg_with_watermark_example 104 | 105 | -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/docs/.gitignore -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/nider.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/nider.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/nider" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/nider" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # nider documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | 19 | # If extensions (or modules to document with autodoc) are in another 20 | # directory, add these directories to sys.path here. If the directory is 21 | # relative to the documentation root, use os.path.abspath to make it 22 | # absolute, like shown here. 23 | #sys.path.insert(0, os.path.abspath('.')) 24 | 25 | # Get the project root dir, which is the parent dir of this 26 | cwd = os.getcwd() 27 | project_root = os.path.dirname(cwd) 28 | 29 | # Insert the project root dir as the first element in the PYTHONPATH. 30 | # This lets us ensure that the source package is imported, and that its 31 | # version is used. 32 | sys.path.insert(0, project_root) 33 | 34 | import nider 35 | 36 | # -- General configuration --------------------------------------------- 37 | 38 | # If your documentation needs a minimal Sphinx version, state it here. 39 | #needs_sphinx = '1.0' 40 | 41 | # Add any Sphinx extension module names here, as strings. They can be 42 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 43 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon'] 44 | 45 | # Add any paths that contain templates here, relative to this directory. 46 | templates_path = ['_templates'] 47 | 48 | # The suffix of source filenames. 49 | source_suffix = '.rst' 50 | 51 | # The encoding of source files. 52 | #source_encoding = 'utf-8-sig' 53 | 54 | # The master toctree document. 55 | master_doc = 'index' 56 | 57 | # General information about the project. 58 | project = u'nider' 59 | copyright = u"2017, Vladyslav Ovchynnykov" 60 | 61 | # The version info for the project you're documenting, acts as replacement 62 | # for |version| and |release|, also used in various other places throughout 63 | # the built documents. 64 | # 65 | # The short X.Y version. 66 | version = nider.__version__ 67 | # The full version, including alpha/beta/rc tags. 68 | release = nider.__version__ 69 | 70 | # The language for content autogenerated by Sphinx. Refer to documentation 71 | # for a list of supported languages. 72 | #language = None 73 | 74 | # There are two options for replacing |today|: either, you set today to 75 | # some non-false value, then it is used: 76 | #today = '' 77 | # Else, today_fmt is used as the format for a strftime call. 78 | #today_fmt = '%B %d, %Y' 79 | 80 | # List of patterns, relative to source directory, that match files and 81 | # directories to ignore when looking for source files. 82 | exclude_patterns = ['_build'] 83 | 84 | # The reST default role (used for this markup: `text`) to use for all 85 | # documents. 86 | #default_role = None 87 | 88 | # If true, '()' will be appended to :func: etc. cross-reference text. 89 | #add_function_parentheses = True 90 | 91 | # If true, the current module name will be prepended to all description 92 | # unit titles (such as .. function::). 93 | #add_module_names = True 94 | 95 | # If true, sectionauthor and moduleauthor directives will be shown in the 96 | # output. They are ignored by default. 97 | #show_authors = False 98 | 99 | # The name of the Pygments (syntax highlighting) style to use. 100 | pygments_style = 'sphinx' 101 | 102 | # A list of ignored prefixes for module index sorting. 103 | #modindex_common_prefix = [] 104 | 105 | # If true, keep warnings as "system message" paragraphs in the built 106 | # documents. 107 | #keep_warnings = False 108 | 109 | 110 | # -- Options for HTML output ------------------------------------------- 111 | 112 | # The theme to use for HTML and HTML Help pages. See the documentation for 113 | # a list of builtin themes. 114 | html_theme = 'default' 115 | 116 | # Theme options are theme-specific and customize the look and feel of a 117 | # theme further. For a list of options available for each theme, see the 118 | # documentation. 119 | #html_theme_options = {} 120 | 121 | # Add any paths that contain custom themes here, relative to this directory. 122 | #html_theme_path = [] 123 | 124 | # The name for this set of Sphinx documents. If None, it defaults to 125 | # " v documentation". 126 | #html_title = None 127 | 128 | # A shorter title for the navigation bar. Default is the same as 129 | # html_title. 130 | #html_short_title = None 131 | 132 | # The name of an image file (relative to this directory) to place at the 133 | # top of the sidebar. 134 | #html_logo = None 135 | 136 | # The name of an image file (within the static path) to use as favicon 137 | # of the docs. This file should be a Windows icon file (.ico) being 138 | # 16x16 or 32x32 pixels large. 139 | #html_favicon = None 140 | 141 | # Add any paths that contain custom static files (such as style sheets) 142 | # here, relative to this directory. They are copied after the builtin 143 | # static files, so a file named "default.css" will overwrite the builtin 144 | # "default.css". 145 | html_static_path = ['_static'] 146 | 147 | # If not '', a 'Last updated on:' timestamp is inserted at every page 148 | # bottom, using the given strftime format. 149 | #html_last_updated_fmt = '%b %d, %Y' 150 | 151 | # If true, SmartyPants will be used to convert quotes and dashes to 152 | # typographically correct entities. 153 | #html_use_smartypants = True 154 | 155 | # Custom sidebar templates, maps document names to template names. 156 | #html_sidebars = {} 157 | 158 | # Additional templates that should be rendered to pages, maps page names 159 | # to template names. 160 | #html_additional_pages = {} 161 | 162 | # If false, no module index is generated. 163 | #html_domain_indices = True 164 | 165 | # If false, no index is generated. 166 | #html_use_index = True 167 | 168 | # If true, the index is split into individual pages for each letter. 169 | #html_split_index = False 170 | 171 | # If true, links to the reST sources are added to the pages. 172 | #html_show_sourcelink = True 173 | 174 | # If true, "Created using Sphinx" is shown in the HTML footer. 175 | # Default is True. 176 | #html_show_sphinx = True 177 | 178 | # If true, "(C) Copyright ..." is shown in the HTML footer. 179 | # Default is True. 180 | #html_show_copyright = True 181 | 182 | # If true, an OpenSearch description file will be output, and all pages 183 | # will contain a tag referring to it. The value of this option 184 | # must be the base URL from which the finished HTML is served. 185 | #html_use_opensearch = '' 186 | 187 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 188 | #html_file_suffix = None 189 | 190 | # Output file base name for HTML help builder. 191 | htmlhelp_basename = 'niderdoc' 192 | 193 | 194 | # -- Options for LaTeX output ------------------------------------------ 195 | 196 | latex_elements = { 197 | # The paper size ('letterpaper' or 'a4paper'). 198 | #'papersize': 'letterpaper', 199 | 200 | # The font size ('10pt', '11pt' or '12pt'). 201 | #'pointsize': '10pt', 202 | 203 | # Additional stuff for the LaTeX preamble. 204 | #'preamble': '', 205 | } 206 | 207 | # Grouping the document tree into LaTeX files. List of tuples 208 | # (source start file, target name, title, author, documentclass 209 | # [howto/manual]). 210 | latex_documents = [ 211 | ('index', 'nider.tex', 212 | u'nider Documentation', 213 | u'Vladyslav Ovchynnykov', 'manual'), 214 | ] 215 | 216 | # The name of an image file (relative to this directory) to place at 217 | # the top of the title page. 218 | #latex_logo = None 219 | 220 | # For "manual" documents, if this is true, then toplevel headings 221 | # are parts, not chapters. 222 | #latex_use_parts = False 223 | 224 | # If true, show page references after internal links. 225 | #latex_show_pagerefs = False 226 | 227 | # If true, show URL addresses after external links. 228 | #latex_show_urls = False 229 | 230 | # Documents to append as an appendix to all manuals. 231 | #latex_appendices = [] 232 | 233 | # If false, no module index is generated. 234 | #latex_domain_indices = True 235 | 236 | 237 | # -- Options for manual page output ------------------------------------ 238 | 239 | # One entry per manual page. List of tuples 240 | # (source start file, name, description, authors, manual section). 241 | man_pages = [ 242 | ('index', 'nider', 243 | u'nider Documentation', 244 | [u'Vladyslav Ovchynnykov'], 1) 245 | ] 246 | 247 | # If true, show URL addresses after external links. 248 | #man_show_urls = False 249 | 250 | 251 | # -- Options for Texinfo output ---------------------------------------- 252 | 253 | # Grouping the document tree into Texinfo files. List of tuples 254 | # (source start file, target name, title, author, 255 | # dir menu entry, description, category) 256 | texinfo_documents = [ 257 | ('index', 'nider', 258 | u'nider Documentation', 259 | u'Vladyslav Ovchynnykov', 260 | 'nider', 261 | 'One line description of project.', 262 | 'Miscellaneous'), 263 | ] 264 | 265 | # Documents to append as an appendix to all manuals. 266 | #texinfo_appendices = [] 267 | 268 | # If false, no module index is generated. 269 | #texinfo_domain_indices = True 270 | 271 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 272 | #texinfo_show_urls = 'footnote' 273 | 274 | # If true, do not generate a @detailmenu in the "Top" node's menu. 275 | #texinfo_no_detailmenu = False 276 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/images/available_units.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/docs/images/available_units.png -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to nider's documentation! 2 | ================================= 3 | 4 | Nider is an approach to make generation of text based images simple yet flexible. 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | 9 | installation 10 | usage 11 | Full API reference 12 | contributing 13 | authors 14 | history 15 | 16 | Indices and tables 17 | ================== 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | * :ref:`search` 22 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | ============ 4 | Installation 5 | ============ 6 | 7 | 8 | Stable release 9 | -------------- 10 | 11 | To install nider, run this command in your terminal: 12 | 13 | .. code-block:: console 14 | 15 | $ pip install nider 16 | 17 | This is the preferred method to install nider, as it will always install the most recent stable release. 18 | 19 | If you don't have `pip`_ installed, this `Python installation guide`_ can guide 20 | you through the process. 21 | 22 | .. _pip: https://pip.pypa.io 23 | .. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ 24 | 25 | 26 | From sources 27 | ------------ 28 | 29 | The sources for nider can be downloaded from the `Github repo`_. 30 | 31 | You can either clone the public repository: 32 | 33 | .. code-block:: console 34 | 35 | $ git clone git://github.com/pythad/nider 36 | 37 | Or download the `tarball`_: 38 | 39 | .. code-block:: console 40 | 41 | $ curl -OL https://github.com/pythad/nider/tarball/master 42 | 43 | Once you have a copy of the source, you can install it with: 44 | 45 | .. code-block:: console 46 | 47 | $ python setup.py install 48 | 49 | 50 | .. _Github repo: https://github.com/pythad/nider 51 | .. _tarball: https://github.com/pythad/nider/tarball/master 52 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\nider.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\nider.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/nider.colors.rst: -------------------------------------------------------------------------------- 1 | nider\.colors package 2 | ===================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | nider\.colors\.colormap module 8 | ------------------------------ 9 | 10 | .. automodule:: nider.colors.colormap 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | nider\.colors\.utils module 16 | --------------------------- 17 | 18 | .. automodule:: nider.colors.utils 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | 24 | Module contents 25 | --------------- 26 | 27 | .. automodule:: nider.colors 28 | :members: 29 | :undoc-members: 30 | :show-inheritance: 31 | -------------------------------------------------------------------------------- /docs/nider.mixins.rst: -------------------------------------------------------------------------------- 1 | nider\.mixins package 2 | ===================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | nider\.mixins\.img\_components\_mixins module 8 | --------------------------------------------- 9 | 10 | .. automodule:: nider.mixins.img_components_mixins 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | nider\.mixins\.text\_mixins module 16 | ---------------------------------- 17 | 18 | .. automodule:: nider.mixins.text_mixins 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | 24 | Module contents 25 | --------------- 26 | 27 | .. automodule:: nider.mixins 28 | :members: 29 | :undoc-members: 30 | :show-inheritance: 31 | -------------------------------------------------------------------------------- /docs/nider.rst: -------------------------------------------------------------------------------- 1 | nider package 2 | ============= 3 | 4 | nider\.core module 5 | ------------------ 6 | 7 | .. automodule:: nider.core 8 | :members: Font, Outline 9 | 10 | nider\.models module 11 | -------------------- 12 | 13 | .. automodule:: nider.models 14 | :members: Header, Paragraph, Linkback, Watermark, Content, Image, FacebookSquarePost, FacebookLandscapePost, TwitterPost, TwitterLargeCard, InstagramSquarePost, InstagramPortraitPost, InstagramLandscapePost 15 | 16 | nider\.exceptions module 17 | ------------------------ 18 | 19 | .. automodule:: nider.exceptions 20 | :members: 21 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Usage 3 | ===== 4 | 5 | This article is a tutorial for ``nider`` package and at the same time it is a full reference of all ``nider`` models and possibilities. 6 | 7 | *********** 8 | Image units 9 | *********** 10 | 11 | There are three main units each ``nider.Image`` can consist of: 12 | 13 | - header 14 | - paragraph 15 | - linkback 16 | 17 | .. image:: images/available_units.png 18 | 19 | Each of the units is represented by a class in ``nider.models``: 20 | 21 | - :class:`nider.models.Header` 22 | - :class:`nider.models.Paragraph` 23 | - :class:`nider.models.Linkback` 24 | 25 | ``nider.models.Header`` 26 | ========================= 27 | 28 | .. autoclass:: nider.models.Header 29 | 30 | Example 31 | ------- 32 | 33 | .. code-block:: python 34 | 35 | from nider.core import Font 36 | from nider.core import Outline 37 | 38 | from nider.models import Header 39 | 40 | 41 | header = Header(text='Your super interesting title!', 42 | font=Font('/home/me/.local/share/fonts/Roboto/Roboto-Bold.ttf', 30), 43 | text_width=40, 44 | align='left', 45 | color='#ededed', 46 | outline=Oultine(2, '#222') 47 | ) 48 | 49 | 50 | ``nider.models.Paragraph`` 51 | ============================ 52 | 53 | This class has the same attribures and behaviour as :class:`nider.models.Header`. 54 | 55 | .. autoclass:: nider.models.Paragraph 56 | 57 | Example 58 | ------- 59 | 60 | .. code-block:: python 61 | 62 | from nider.core import Font 63 | from nider.core import Outline 64 | 65 | from nider.models import Paragraph 66 | 67 | 68 | para = Paragraph(text='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 69 | font=Font('/home/me/.local/share/fonts/Roboto/Roboto-Bold.ttf', 30), 70 | text_width=65, 71 | align='left', 72 | color='#ededed' 73 | outline=Oultine(1, '#000') 74 | ) 75 | 76 | 77 | ``nider.models.Linkback`` 78 | =========================== 79 | 80 | .. autoclass:: nider.models.Linkback 81 | 82 | Example 83 | ------- 84 | 85 | .. code-block:: python 86 | 87 | from nider.core import Font 88 | from nider.core import Outline 89 | 90 | from nider.models import Linkback 91 | 92 | 93 | linkback = Linkback(text='foo.com | @username', 94 | font=Font('/home/me/.local/share/fonts/Roboto/Roboto-Bold.ttf', 30), 95 | color='#ededed', 96 | outline=Oultine(2, '#000') 97 | ) 98 | 99 | ------------ 100 | 101 | .. note:: 102 | 103 | Parameters ``color`` and ``outline.color`` are optional for any unit. They can be generated automatically by ``nider``. ``nider`` analyzes background color of either a texture or of an image and chooses an opposite one to it. So if your image in mainly dark , white text color will be auto generated and set. The same applies to outline color. 104 | 105 | Although it's a nice feature for backgrounds you have no control over, we'd recommend to provide colors explicitly. 106 | 107 | ************* 108 | Image content 109 | ************* 110 | 111 | In order to aggregate all of the units together you need to create an instance of :class:`nider.models.Content` class. 112 | 113 | ``nider.models.Content`` 114 | ========================== 115 | 116 | .. autoclass:: nider.models.Content 117 | 118 | Example 119 | ------- 120 | 121 | .. code-block:: python 122 | 123 | from nider.models import Content 124 | from nider.models import Linkback 125 | from nider.models import Paragraph 126 | 127 | 128 | para = Paragraph(...) 129 | 130 | linkback = Linkback(...) 131 | 132 | content = Content(para, linkback=linkback, padding=60) 133 | 134 | 135 | ********************* 136 | Initializing an image 137 | ********************* 138 | 139 | After the content is prepared it's the right time to initialize an image. In ``nider`` a basic image is represented by ``nider.models.Image``. 140 | 141 | ``nider.models.Image`` 142 | ======================== 143 | 144 | .. autoclass:: nider.models.Image 145 | 146 | Example 147 | ------- 148 | 149 | .. code-block:: python 150 | 151 | from nider.models import Content 152 | from nider.models import Image 153 | 154 | 155 | content = Content(...) 156 | 157 | img = Image(content, 158 | fullpath='example.png', 159 | width=500, 160 | height=500 161 | ) 162 | 163 | Social media images 164 | ------------------- 165 | 166 | ``nider`` comes with some pre-built models that can be used to generate images for some social networks. These are subclasses of ``nider.models.Image`` with changed size. 167 | 168 | Instagram 169 | ^^^^^^^^^ 170 | 171 | - :class:`nider.models.InstagramSquarePost` - 1080x1080 image 172 | - :class:`nider.models.InstagramPortraitPost` - 1080x1350 image 173 | - :class:`nider.models.InstagramLandscapePost` - 1080x566 image 174 | 175 | Facebook 176 | ^^^^^^^^ 177 | 178 | - :class:`nider.models.FacebookSquarePost` - 470x470 image 179 | - :class:`nider.models.FacebookLandscapePost` - 1024x512 image 180 | 181 | Twitter 182 | ^^^^^^^ 183 | 184 | - :class:`nider.models.TwitterPost` - 1024x512 image 185 | - :class:`nider.models.TwitterLargeCard` - 506x506 image 186 | 187 | ============ 188 | 189 | I highly recommend reading this `post `_ if you are curious about what are the right image sizes for social media images. 190 | 191 | ******************** 192 | Drawing on the image 193 | ******************** 194 | 195 | Having an instance of ``nider.models.Image`` we are ready to create a real image. 196 | 197 | ``nider`` comes with 3 options of drawing your image: 198 | 199 | - ``Image.draw_on_texture`` - draws preinitialized image and its attributes on a texture. 200 | 201 | .. note:: 202 | You don't need to create textured images by pasting texture mulpitle times in Photoshop or Gimp. ``nider`` takes care of filling image of any size with textrure you privide. 203 | 204 | - ``Image.draw_on_bg`` - Draws preinitialized image and its attributes on a colored background. nider uses a color you provide to fill the image and then draws the content. 205 | 206 | - ``Image.draw_on_image`` - Draws preinitialized image and its attributes on an image. Content will be drawn directly on the image you provide. 207 | 208 | 209 | ``Image.draw_on_texture`` 210 | ========================= 211 | 212 | .. automethod:: nider.models.Image.draw_on_texture 213 | 214 | Example 215 | ------- 216 | 217 | .. code-block:: python 218 | 219 | from nider.models import Content 220 | from nider.models import Image 221 | 222 | 223 | content = Content(...) 224 | 225 | img = Image(content, 226 | fullpath='example.png', 227 | width=500, 228 | height=500 229 | ) 230 | 231 | img.draw_on_texture('example_texture.png') 232 | 233 | 234 | Check the full example `here `_ . 235 | 236 | ============ 237 | 238 | ``nider`` comes with a `huge bundle of textures `_. As for now you need to copy them to your machine if you want to use any of them. 239 | 240 | ``Image.draw_on_bg`` 241 | ==================== 242 | 243 | .. automethod:: nider.models.Image.draw_on_bg 244 | 245 | Example 246 | ------- 247 | 248 | .. code-block:: python 249 | 250 | from nider.models import Content 251 | from nider.models import Image 252 | 253 | 254 | content = Content(...) 255 | 256 | img = Image(content, 257 | fullpath='example.png', 258 | width=500, 259 | height=500 260 | ) 261 | 262 | img.draw_on_bg('#efefef') 263 | 264 | Check the full example `here `_ . 265 | 266 | ``Image.draw_on_image`` 267 | ======================= 268 | 269 | .. automethod:: nider.models.Image.draw_on_image 270 | 271 | Examples 272 | -------- 273 | 274 | .. code-block:: python 275 | 276 | from nider.models import Content 277 | from nider.models import Image 278 | 279 | 280 | content = Content(...) 281 | 282 | img = Image(content, 283 | fullpath='example.png', 284 | width=500, 285 | height=500 286 | ) 287 | 288 | img.draw_on_image('example_bg.jpg') 289 | 290 | Using filters and enhancements: 291 | 292 | .. code-block:: python 293 | 294 | img.draw_on_image('example_bg.jpg', 295 | image_enhancements=((ImageEnhance.Contrast, 0.75), 296 | (ImageEnhance.Brightness, 0.5)), 297 | image_filters=((ImageFilter.BLUR),), 298 | ) 299 | 300 | Check the full example `here `_ . 301 | 302 | ============ 303 | 304 | That's it. After any of draw methods has been called and successfully completed the new image will be saved to ``Image.fullpath``. 305 | 306 | ***************** 307 | Adding watermarks 308 | ***************** 309 | 310 | ``nider`` comes with built-in support for adding watermarks to your images. 311 | 312 | First of all you need to create an instanse of :class:`nider.models.Watermark` class. 313 | 314 | .. autoclass:: nider.models.Watermark 315 | 316 | 317 | Example 318 | ======= 319 | 320 | .. code-block:: python 321 | 322 | watermark = Watermark(text='COPYRIGHT', 323 | font=Font('/home/me/.local/share/fonts/Roboto/Roboto-Bold.ttf'), 324 | color='#111', 325 | cross=True, 326 | rotate_angle=-45, 327 | opacity=0.35 328 | ) 329 | 330 | ============ 331 | 332 | After this you can either add watermark to you ``Content`` instance and draw watermark on ``nider`` generated images: 333 | 334 | .. code-block:: python 335 | 336 | from nider.models import Content 337 | from nider.models import Image 338 | from nider.models import Watermark 339 | 340 | 341 | watermark = Watermark(...) 342 | 343 | content = Content(..., watermark=watermark) 344 | 345 | img = Image(content, 346 | fullpath='example.png', 347 | width=500, 348 | height=500 349 | ) 350 | 351 | img.draw_on_bg('#efefef') 352 | 353 | or you can add a watermark to an existing image using :func:`nider.tools.add_watermark`: 354 | 355 | .. autofunction:: nider.tools.add_watermark 356 | 357 | Example 358 | ======= 359 | 360 | .. code-block:: python 361 | 362 | from nider.models import Watermark 363 | 364 | from nider.tools import add_watermark 365 | 366 | 367 | watermark = Watermark(...) 368 | add_watermark('path/to/my/img', watermark) 369 | -------------------------------------------------------------------------------- /examples/add_watermark_example/bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/add_watermark_example/bg.jpg -------------------------------------------------------------------------------- /examples/add_watermark_example/result.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/add_watermark_example/result.jpg -------------------------------------------------------------------------------- /examples/add_watermark_example/script.py: -------------------------------------------------------------------------------- 1 | from nider.core import Font 2 | 3 | from nider.models import Watermark 4 | 5 | from nider.tools import add_watermark 6 | 7 | 8 | # TODO: change this fontpath to the fontpath on your machine 9 | roboto_fonts_folder = '/home/ovd/.local/share/fonts/Roboto/' 10 | 11 | watermark = Watermark(text='COPYRIGHT', 12 | font=Font(roboto_fonts_folder + 'Roboto-Medium.ttf', 20), 13 | color='#111', 14 | cross=True 15 | ) 16 | 17 | add_watermark('bg.jpg', watermark, 'result.jpg') 18 | -------------------------------------------------------------------------------- /examples/draw_on_bg_example/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/draw_on_bg_example/result.png -------------------------------------------------------------------------------- /examples/draw_on_bg_example/script.py: -------------------------------------------------------------------------------- 1 | from nider.core import Font 2 | 3 | from nider.models import Paragraph 4 | from nider.models import Content 5 | from nider.models import Image 6 | 7 | 8 | # TODO: change this fontpath to the fontpath on your machine 9 | roboto_font_folder = '/home/ovd/.local/share/fonts/Roboto/' 10 | 11 | para = Paragraph(text='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 12 | font=Font(roboto_font_folder + 'Roboto-Medium.ttf', 20), 13 | text_width=49, 14 | align='center', 15 | color='#121212' 16 | ) 17 | 18 | content = Content(para) 19 | 20 | img = Image(content, 21 | width=500, 22 | height=500, 23 | fullpath='result.png' 24 | ) 25 | 26 | img.draw_on_bg('#efefef') 27 | -------------------------------------------------------------------------------- /examples/draw_on_bg_with_watermark_example/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/draw_on_bg_with_watermark_example/result.png -------------------------------------------------------------------------------- /examples/draw_on_bg_with_watermark_example/script.py: -------------------------------------------------------------------------------- 1 | from nider.core import Font 2 | 3 | from nider.models import Paragraph 4 | from nider.models import Watermark 5 | from nider.models import Content 6 | from nider.models import Image 7 | 8 | 9 | # TODO: change this fontpath to the fontpath on your machine 10 | fonts_folder = '/home/ovd/.local/share/fonts/Roboto/' 11 | 12 | para = Paragraph(text='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 13 | font=Font(fonts_folder + 'Roboto-Medium.ttf', 20), 14 | text_width=49, 15 | align='center', 16 | color='#121212' 17 | ) 18 | 19 | watermark = Watermark(text='COPYRIGHT', 20 | font=Font(fonts_folder + 'Roboto-Medium.ttf'), 21 | color='#111', 22 | cross=True 23 | ) 24 | 25 | content = Content(para, watermark=watermark) 26 | 27 | img = Image(content, 28 | width=500, 29 | height=500, 30 | fullpath='result.png', 31 | ) 32 | 33 | img.draw_on_bg('#efefef') 34 | -------------------------------------------------------------------------------- /examples/draw_on_image_example/bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/draw_on_image_example/bg.jpg -------------------------------------------------------------------------------- /examples/draw_on_image_example/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/draw_on_image_example/result.png -------------------------------------------------------------------------------- /examples/draw_on_image_example/script.py: -------------------------------------------------------------------------------- 1 | from nider.core import Font 2 | from nider.core import Outline 3 | 4 | from nider.models import Header 5 | from nider.models import Paragraph 6 | from nider.models import Linkback 7 | from nider.models import Content 8 | from nider.models import Image 9 | 10 | from PIL import ImageEnhance 11 | from PIL import ImageFilter 12 | 13 | 14 | # TODO: change this fontpath to the fontpath on your machine 15 | roboto_font_folder = '/home/ovd/.local/share/fonts/Roboto/' 16 | 17 | outline = Outline(2, '#121212') 18 | 19 | header = Header(text='Your super interesting title!', 20 | font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 30), 21 | text_width=40, 22 | align='left', 23 | color='#ededed', 24 | outline=outline 25 | ) 26 | 27 | para = Paragraph(text='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 28 | font=Font(roboto_font_folder + 'Roboto-Medium.ttf', 29), 29 | text_width=65, 30 | align='left', 31 | color='#ededed', 32 | outline=outline 33 | ) 34 | 35 | linkback = Linkback(text='foo.com | @username', 36 | font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 24), 37 | color='#ededed', 38 | outline=outline 39 | ) 40 | 41 | content = Content(para, header, linkback) 42 | 43 | img = Image(content, 44 | fullpath='result.png', 45 | width=1080, 46 | height=720 47 | ) 48 | 49 | # TODO: change this image path to the image path on your machine 50 | img.draw_on_image('bg.jpg', 51 | image_enhancements=((ImageEnhance.Contrast, 0.75), 52 | (ImageEnhance.Brightness, 0.5)), 53 | image_filters=((ImageFilter.BLUR),) 54 | ) 55 | -------------------------------------------------------------------------------- /examples/draw_on_texture_example/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/draw_on_texture_example/result.png -------------------------------------------------------------------------------- /examples/draw_on_texture_example/script.py: -------------------------------------------------------------------------------- 1 | from nider.core import Font 2 | from nider.core import Outline 3 | 4 | from nider.models import Header 5 | from nider.models import Paragraph 6 | from nider.models import Linkback 7 | from nider.models import Content 8 | from nider.models import TwitterPost 9 | 10 | 11 | # TODO: change this fontpath to the fontpath on your machine 12 | roboto_font_folder = '/home/ovd/.local/share/fonts/Roboto/' 13 | 14 | outline = Outline(2, '#121212') 15 | 16 | header = Header(text='Your super interesting title!', 17 | font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 30), 18 | text_width=40, 19 | align='left', 20 | color='#ededed' 21 | ) 22 | 23 | para = Paragraph(text='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.', 24 | font=Font(roboto_font_folder + 'Roboto-Medium.ttf', 29), 25 | text_width=65, 26 | align='left', 27 | color='#ededed' 28 | ) 29 | 30 | linkback = Linkback(text='foo.com | @username', 31 | font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 24), 32 | color='#ededed' 33 | ) 34 | 35 | content = Content(para, header, linkback) 36 | 37 | img = TwitterPost(content, 38 | fullpath='result.png' 39 | ) 40 | 41 | # TODO: change this texture path to the texture path on your machine 42 | img.draw_on_texture('texture.png') 43 | -------------------------------------------------------------------------------- /examples/draw_on_texture_example/texture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/draw_on_texture_example/texture.png -------------------------------------------------------------------------------- /examples/example1/bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/example1/bg.jpg -------------------------------------------------------------------------------- /examples/example1/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/example1/result.png -------------------------------------------------------------------------------- /examples/example1/script.py: -------------------------------------------------------------------------------- 1 | from nider.core import Font 2 | from nider.core import Outline 3 | 4 | from nider.models import Content 5 | from nider.models import Linkback 6 | from nider.models import Paragraph 7 | from nider.models import Image 8 | 9 | 10 | # TODO: change this fontpath to the fontpath on your machine 11 | roboto_font_folder = '/home/ovd/.local/share/fonts/Roboto/' 12 | 13 | text_outline = Outline(2, '#121212') 14 | 15 | para = Paragraph(text='“You\'ve gotta dance like there\'s nobody watching, love like you\'ll never be hurt, sing like there\'s nobody listening, and live like it\'s heaven on earth.”', 16 | font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 35), 17 | text_width=30, 18 | align='center', 19 | color='#ededed', 20 | outline=text_outline 21 | ) 22 | 23 | linkback = Linkback(text='― William W. Purkey', 24 | font=Font(roboto_font_folder + 'Roboto-Medium.ttf', 25), 25 | color='#ededed', 26 | outline=text_outline 27 | ) 28 | 29 | content = Content(paragraph=para, linkback=linkback) 30 | 31 | img = Image(content, 32 | fullpath='result.png', 33 | width=500, 34 | height=750 35 | ) 36 | 37 | # TODO: change this image path to the image path on your machine 38 | img.draw_on_image('bg.jpg') 39 | -------------------------------------------------------------------------------- /examples/example2/bg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/example2/bg.jpg -------------------------------------------------------------------------------- /examples/example2/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/example2/result.png -------------------------------------------------------------------------------- /examples/example2/script.py: -------------------------------------------------------------------------------- 1 | from nider.core import Font 2 | from nider.core import Outline 3 | 4 | from nider.models import Content 5 | from nider.models import Header 6 | from nider.models import Image 7 | 8 | 9 | # TODO: change this fontpath to the fontpath on your machine 10 | roboto_font_folder = '/home/ovd/.local/share/fonts/Roboto/' 11 | 12 | text_outline = Outline(1, '#efefef') 13 | 14 | header = Header(text='Google bought a service that allows patients to undergo basic clinical tests at home using smartphones.', 15 | font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 22), 16 | text_width=50, 17 | align='left', 18 | color='#000100', 19 | outline=text_outline 20 | ) 21 | 22 | content = Content(header=header) 23 | 24 | img = Image(content, 25 | fullpath='result.png', 26 | width=600, 27 | height=314 28 | ) 29 | 30 | # TODO: change this image path to the image path on your machine 31 | img.draw_on_image('bg.jpg') 32 | -------------------------------------------------------------------------------- /examples/example3/bg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/example3/bg.png -------------------------------------------------------------------------------- /examples/example3/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/example3/result.png -------------------------------------------------------------------------------- /examples/example3/script.py: -------------------------------------------------------------------------------- 1 | from nider.core import Font 2 | from nider.core import Outline 3 | 4 | from nider.models import Header 5 | from nider.models import Paragraph 6 | from nider.models import Linkback 7 | from nider.models import Content 8 | from nider.models import Image 9 | 10 | from PIL import ImageFilter 11 | 12 | # TODO: change this fontpath to the fontpath on your machine 13 | roboto_font_folder = '/home/ovd/.local/share/fonts/Roboto/' 14 | 15 | text_outline = Outline(2, '#111') 16 | 17 | header = Header(text='The first solar eclipse to cross America in 99 years is coming. To some, it’s an act of God.', 18 | font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 28), 19 | text_width=53, 20 | line_padding=3, 21 | align='left', 22 | color='#ededed', 23 | outline=text_outline, 24 | ) 25 | 26 | para = Paragraph(text='Tens of millions of people are expected to cram into a narrow path, from Oregon to the Carolinas, to see the remarkable event.', 27 | font=Font(roboto_font_folder + 'Roboto-Medium.ttf', 25), 28 | text_width=60, 29 | align='left', 30 | color='#ededed', 31 | outline=text_outline, 32 | ) 33 | 34 | linkback = Linkback(text='@washingtonpost', 35 | font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 17), 36 | color='#ededed', 37 | outline=text_outline, 38 | ) 39 | 40 | content = Content(para, header, linkback) 41 | 42 | img = Image(content, 43 | fullpath='result.png', 44 | width=1080, 45 | height=720 46 | ) 47 | 48 | # TODO: change this image path to the image path on your machine 49 | img.draw_on_image('bg.png', image_filters=((ImageFilter.BLUR),)) 50 | -------------------------------------------------------------------------------- /examples/example4/result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/example4/result.png -------------------------------------------------------------------------------- /examples/example4/script.py: -------------------------------------------------------------------------------- 1 | from nider.core import Font 2 | from nider.core import Outline 3 | 4 | from nider.models import Content 5 | from nider.models import Linkback 6 | from nider.models import Paragraph 7 | from nider.models import Image 8 | 9 | 10 | # TODO: change this fontpath to the fontpath on your machine 11 | roboto_font_folder = '/home/ovd/.local/share/fonts/Roboto/' 12 | 13 | text_outline = Outline(1, '#121212') 14 | 15 | para = Paragraph(text='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.', 16 | font=Font(roboto_font_folder + 'Roboto-Medium.ttf', 25), 17 | text_width=35, 18 | align='center', 19 | color='#efefef', 20 | outline=text_outline 21 | ) 22 | 23 | linkback = Linkback(text='@foobar', 24 | font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 20), 25 | color='#efefef', 26 | outline=text_outline 27 | ) 28 | 29 | content = Content(paragraph=para, linkback=linkback) 30 | 31 | img = Image(content, 32 | fullpath='result.png', 33 | width=500, 34 | height=500 35 | ) 36 | 37 | # TODO: change this texture path to the texture path on your machine 38 | img.draw_on_texture('texture.png') 39 | -------------------------------------------------------------------------------- /examples/example4/texture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/examples/example4/texture.png -------------------------------------------------------------------------------- /nider/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Top-level package for nider.""" 4 | 5 | __author__ = """Vladyslav Ovchynnykov""" 6 | __email__ = 'ovd4mail@gmail.com' 7 | __version__ = '0.5.0' 8 | -------------------------------------------------------------------------------- /nider/colors/__init__.py: -------------------------------------------------------------------------------- 1 | from .colormap import BASIC_COLORS, FLAT_UI_COLORS, COLORS, rgb 2 | from .utils import color_to_rgb, get_img_dominant_color, monochrome_color, generate_opposite_color, blend 3 | -------------------------------------------------------------------------------- /nider/colors/colormap.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple, ChainMap 2 | 3 | 4 | rgb = namedtuple('Color', ['R', 'G', 'B']) 5 | 6 | # RGB : color mappings 7 | BASIC_COLORS_RGB_TO_NAME = { 8 | rgb(255, 255, 255): ['white'], 9 | rgb(0, 0, 0): ['black'], 10 | rgb(255, 0, 0): ['red'], 11 | rgb(0, 255, 0): ['lime'], 12 | rgb(0, 0, 255): ['blue'], 13 | rgb(255, 255, 0): ['yellow'], 14 | rgb(0, 255, 255): ['cyan', 'aqua'], 15 | rgb(255, 0, 255): ['magenta', 'fuchsia'], 16 | rgb(192, 192, 192): ['silver'], 17 | rgb(128, 128, 128): ['gray'], 18 | rgb(128, 0, 0): ['maroon'], 19 | rgb(128, 128, 0): ['olive'], 20 | rgb(0, 128, 0): ['green'], 21 | rgb(128, 0, 128): ['purple'], 22 | rgb(0, 128, 128): ['teal'], 23 | rgb(0, 0, 128): ['navy'], 24 | 25 | } 26 | 27 | FLAT_UI_COLORS_RGB_TO_NAMES = { 28 | rgb(26, 188, 156): ['turquoise'], 29 | rgb(46, 204, 113): ['emerland'], 30 | rgb(52, 152, 219): ['peterriver'], 31 | rgb(155, 89, 182): ['amethyst'], 32 | rgb(52, 73, 94): ['wetasphalt'], 33 | rgb(22, 160, 133): ['greensea'], 34 | rgb(39, 174, 96): ['nephritis'], 35 | rgb(41, 128, 185): ['belizehole'], 36 | rgb(142, 68, 173): ['wisteria'], 37 | rgb(44, 62, 80): ['midnightblue'], 38 | rgb(241, 196, 15): ['sunflower'], 39 | rgb(230, 126, 34): ['carrot'], 40 | rgb(231, 76, 60): ['alizarin'], 41 | rgb(236, 240, 241): ['clouds'], 42 | rgb(149, 165, 166): ['concrete'], 43 | rgb(243, 156, 18): ['orange'], 44 | rgb(211, 84, 0): ['pumpkin'], 45 | rgb(192, 57, 43): ['pomegranate'], 46 | rgb(189, 195, 199): ['silver'], 47 | rgb(127, 140, 141): ['asbestos'] 48 | } 49 | 50 | # color : RGB mappings 51 | BASIC_COLORS = dict( 52 | (name.lower(), rgb) 53 | for rgb, names in BASIC_COLORS_RGB_TO_NAME.items() 54 | for name in names) 55 | 56 | FLAT_UI_COLORS = dict( 57 | (name.lower(), rgb) 58 | for rgb, names in FLAT_UI_COLORS_RGB_TO_NAMES.items() 59 | for name in names) 60 | 61 | # dictionary of all availabe colors 62 | COLORS = dict(ChainMap(BASIC_COLORS, FLAT_UI_COLORS)) 63 | -------------------------------------------------------------------------------- /nider/colors/utils.py: -------------------------------------------------------------------------------- 1 | import functools 2 | 3 | from colorthief import ColorThief 4 | from PIL import ImageColor 5 | 6 | from nider.colors import rgb, COLORS 7 | 8 | 9 | def color_to_rgb(color): 10 | try: 11 | return rgb(*ImageColor.getrgb(color)) 12 | except AttributeError as e: 13 | # assume that color is already an rgb tuple 14 | return rgb(*color) 15 | 16 | 17 | def get_img_dominant_color(img_path): 18 | '''Finds img dominant color 19 | 20 | Using colorthief module finds image dominant color 21 | 22 | Attributes: 23 | img_path (str): path to an image to get a dominant color for 24 | Returns: 25 | Dominant rgb color for provided image 26 | ''' 27 | color_thief = ColorThief(img_path) 28 | return rgb(*color_thief.get_color(quality=1)) 29 | 30 | 31 | def monochrome_color(color, invert=False): 32 | '''Generates a monochrome(black or white) color 33 | 34 | Generates a monochrome version of a color for a provided color 35 | 36 | Attributes: 37 | color (tuple(int, int, int)): Color to generate a monochrome one for 38 | Returns: 39 | Monochrome rgb color that can be either black or white 40 | ''' 41 | color_luminance = 1 - (0.299 * color[0] + 0.587 * 42 | color[1] + 0.114 * color[2]) / 255 43 | if invert: 44 | return COLORS['black'] if color_luminance < 0.5 else COLORS['white'] 45 | return COLORS['black'] if color_luminance >= 0.5 else COLORS['white'] 46 | 47 | 48 | generate_opposite_color = functools.partial(monochrome_color, invert=True) 49 | 50 | 51 | def blend(first, second, coefficient=0.5): 52 | '''Adds two colors 53 | 54 | Adds two colors with use of coefficient to determine which color 55 | has more power 56 | 57 | Attributes: 58 | coefficient (float): a 0 <= number <= 1 number that defines power of the first color 59 | Returns: 60 | rgb color - result of the blending 61 | ''' 62 | first, second = color_to_rgb(first), color_to_rgb(second) 63 | r = int(coefficient * first.R + ((1 - coefficient) * second.R)) 64 | g = int(coefficient * first.G + ((1 - coefficient) * second.G)) 65 | b = int(coefficient * first.B + ((1 - coefficient) * second.B)) 66 | return rgb(r, g, b) 67 | -------------------------------------------------------------------------------- /nider/core.py: -------------------------------------------------------------------------------- 1 | import textwrap 2 | 3 | from nider.colors.utils import color_to_rgb 4 | from nider.mixins import AlignMixin, MultilineTextMixin 5 | from nider.utils import get_font 6 | 7 | 8 | class Font: 9 | '''Base class for text's font 10 | 11 | Args: 12 | path (str): path to the font used in the object. 13 | size (int): size of the font. 14 | 15 | Raises: 16 | nider.exceptions.DefaultFontWarning: if ``path`` is ``None``. 17 | nider.exceptions.FontNotFoundWarning: if ``path`` does not exist. 18 | ''' 19 | is_default = False 20 | 21 | def __init__(self, path=None, size=18): 22 | self.path = path 23 | self.size = size 24 | self._set_font() 25 | 26 | def _set_font(self): 27 | '''Sets object's font''' 28 | self.font = get_font(self.path, self.size) 29 | self.is_default = self.font.is_default 30 | 31 | 32 | class Outline: 33 | '''Base class for text's outline 34 | 35 | Args: 36 | width (int): width of the stroke. 37 | color (str): string that represents outline color. Must be compatible with `PIL.ImageColor `_ `color names `_. 38 | 39 | Warning: 40 | Due to PIL limitations - core library used for drawing, nider doesn't support 'true' outlineі. That is why high width outlines will look rather ugly and we don't recommend usign outlines with width > 3. 41 | ''' 42 | 43 | def __init__(self, width=2, color=None): 44 | self.width = width 45 | self._set_color(color) 46 | 47 | def _set_color(self, color): 48 | '''Sets object's color''' 49 | self.color = color_to_rgb(color) if color else None 50 | 51 | 52 | class Text: 53 | ''' 54 | Args: 55 | text (str): text to use. 56 | font (nider.core.Font): font object that represents text's font. 57 | color (str): string that represents a color. Must be compatible with `PIL.ImageColor `_ `color names `_ 58 | outline (nider.core.Outline): outline object that represents text's outline. 59 | 60 | Raises: 61 | nider.exceptions.DefaultFontWarning: if ``font.path`` is ``None``. 62 | nider.exceptions.FontNotFoundWarning: if ``font.path`` does not exist. 63 | ''' 64 | 65 | def __init__(self, text, font, color, outline): 66 | self._set_text(text) 67 | self.font_object = font 68 | self.font = font.font 69 | self._set_color(color) 70 | self.outline = outline 71 | 72 | def _set_text(self, text): 73 | '''Sets object's text data''' 74 | self.text = text 75 | 76 | def _set_color(self, color): 77 | '''Sets object's color and outline''' 78 | self.color = color_to_rgb(color) if color else None 79 | 80 | 81 | class MultilineText(MultilineTextMixin, Text): 82 | ''' 83 | Args: 84 | text (str): text used for the unit. 85 | font (nider.core.Font): font object that represents text's font. 86 | text_width (int): units's text width - number of characters in a line. 87 | line_padding (int): unit's line padding - padding (in pixels) between the lines. 88 | color (str): string that represents a color. Must be compatible with `PIL.ImageColor `_ `color names `_. 89 | outline (nider.core.Outline): outline object that represents text's outline. 90 | 91 | Raises: 92 | AttributeError: if ``text_width`` < 0. 93 | nider.exceptions.DefaultFontWarning: if ``font.path`` is ``None``. 94 | nider.exceptions.FontNotFoundWarning: if ``font.path`` does not exist.''' 95 | 96 | def __init__(self, text_width, line_padding, *args, **kwargs): 97 | MultilineTextMixin.__init__( 98 | self, text_width=text_width, line_padding=line_padding) 99 | Text.__init__(self, *args, **kwargs) 100 | 101 | 102 | class SingleLineTextUnit(AlignMixin, Text): 103 | ''' 104 | Args: 105 | text (str): text used for the unit. 106 | font (nider.core.Font): font object that represents text's font. 107 | color (str): string that represents a color. Must be compatible with `PIL.ImageColor `_ `color names `_. 108 | outline (nider.core.Outline): outline object that represents text's outline. 109 | align ('left' or 'center' or 'right'): side with respect to which the text will be aligned. 110 | 111 | Raises: 112 | nider.exceptions.InvalidAlignException: if ``align` is not supported by nider. 113 | nider.exceptions.DefaultFontWarning: if ``font.path`` is ``None``. 114 | nider.exceptions.FontNotFoundWarning: if ``font.path`` does not exist. 115 | ''' 116 | 117 | def __init__(self, text, font=None, 118 | color=None, outline=None, 119 | align='right' 120 | ): 121 | if font is None: 122 | font = Font() 123 | AlignMixin.__init__(self, align=align) 124 | Text.__init__( 125 | self, text=text, font=font, 126 | color=color, outline=outline 127 | ) 128 | self._set_height() 129 | 130 | def _set_height(self): 131 | '''Sets unit\'s height''' 132 | _, self.height = self.font.getsize(self.text) 133 | 134 | 135 | class MultilineTextUnit(AlignMixin, MultilineText): 136 | ''' 137 | Args: 138 | text (str): text used for the unit. 139 | font (nider.core.Font): font object that represents text's font. 140 | text_width (int): units's text width - number of characters in a line. 141 | line_padding (int): unit's line padding - padding (in pixels) between the lines. 142 | color (str): string that represents a color. Must be compatible with `PIL.ImageColor `_ `color names `_. 143 | outline (nider.core.Outline): outline object that represents text's outline. 144 | align ('left' or 'center' or 'right'): side with respect to which the text will be aligned. 145 | 146 | Raises: 147 | nider.exceptions.InvalidAlignException: if ``align` is not supported by nider. 148 | AttributeError: if ``text_width`` < 0. 149 | nider.exceptions.DefaultFontWarning: if ``font.path`` is ``None``. 150 | nider.exceptions.FontNotFoundWarning: if ``font.path`` does not exist. 151 | ''' 152 | 153 | def __init__(self, text, 154 | font=None, 155 | text_width=21, line_padding=6, 156 | color=None, outline=None, 157 | align='center'): 158 | if font is None: 159 | font = Font() 160 | AlignMixin.__init__(self, align=align) 161 | MultilineText.__init__(self, text=text, 162 | font=font, 163 | text_width=text_width, line_padding=line_padding, 164 | color=color, outline=outline 165 | ) 166 | self._set_unit() 167 | 168 | def _set_unit(self): 169 | '''Sets a unit used in the image 170 | 171 | Sets textwraped unit's text that will be used in the image and also 172 | attachs header height to the obj instance. 173 | ''' 174 | self.wrapped_lines = textwrap.wrap(self.text, width=self.text_width) 175 | self._set_height() 176 | 177 | def _set_height(self): 178 | '''Sets unit's height used in the image 179 | 180 | Calculates unit's height by adding height of each line and its padding. 181 | ''' 182 | self.height = 0 183 | for line in self.wrapped_lines: 184 | _, h = self.font.getsize(line) 185 | self.height += h 186 | 187 | self.height += (len(self.wrapped_lines) - 1) * self.line_padding 188 | -------------------------------------------------------------------------------- /nider/exceptions.py: -------------------------------------------------------------------------------- 1 | class ImageGeneratorException(Exception): 2 | '''Base class for exceptions raised by nider''' 3 | 4 | 5 | class ImageGeneratorWarning(Warning): 6 | '''Base class for warnings raised by nider''' 7 | 8 | 9 | class InvalidAlignException(ImageGeneratorException): 10 | '''Exception raised when align is not supported by nider''' 11 | 12 | def __init__(self, align_provided, available_aligns=None): 13 | if available_aligns is None: 14 | available_aligns = ['center', 'right', 'left'] 15 | available_aligns_str = ' or '.join(available_aligns) 16 | super().__init__( 17 | "Align has to be set either to {}. You provided '{}'".format(available_aligns_str, align_provided)) 18 | 19 | 20 | class FontNotFoundWarning(ImageGeneratorWarning): 21 | '''Warning raised when font cannot be found''' 22 | 23 | def __init__(self, fontpath_provided): 24 | super().__init__( 25 | "Font {} hasn't been found. Default font has been set instead".format(fontpath_provided)) 26 | 27 | 28 | class FontNotFoundException(ImageGeneratorWarning): 29 | '''Exception raised when font cannot be found''' 30 | 31 | def __init__(self, fontpath_provided): 32 | super().__init__( 33 | "Font {} hasn't been found.".format(fontpath_provided)) 34 | 35 | 36 | class DefaultFontWarning(ImageGeneratorWarning): 37 | '''Warning raised when default font was used''' 38 | 39 | def __init__(self): 40 | super().__init__( 41 | "Font hasn't been provided. Default font has been set instead") 42 | 43 | 44 | class ImageSizeFixedWarning(ImageGeneratorWarning): 45 | '''Warning raised when the size of the image has to be adjusted to the provided content's size because the content takes much space''' 46 | 47 | def __init__(self): 48 | super().__init__( 49 | "Image size has been adjusted to the provided content size because the content took too much space") 50 | 51 | 52 | class AutoGeneratedUnitColorUsedWarning(ImageGeneratorWarning): 53 | '''Warning raised when auto generated unit color was used''' 54 | 55 | def __init__(self, unit, color_used): 56 | super().__init__( 57 | "You didn't provide a color for {}. Auto generated one('{}') has been used".format(unit.__class__.__name__, color_used)) 58 | 59 | 60 | class AutoGeneratedUnitOutlinecolorUsedWarning(ImageGeneratorWarning): 61 | '''Warning raised when auto generated unit's outline color was used''' 62 | 63 | def __init__(self, unit, color_used): 64 | super().__init__( 65 | "You didn't provide an outline color for {}. Auto generated one('{}') has been used".format(unit.__class__.__name__, color_used)) 66 | -------------------------------------------------------------------------------- /nider/mixins/__init__.py: -------------------------------------------------------------------------------- 1 | from .img_components_mixins import AlignMixin 2 | from .text_mixins import MultilineTextMixin 3 | -------------------------------------------------------------------------------- /nider/mixins/img_components_mixins.py: -------------------------------------------------------------------------------- 1 | from nider.exceptions import InvalidAlignException 2 | 3 | 4 | class AlignMixin: 5 | 6 | def __init__(self, align): 7 | self._set_align(align) 8 | 9 | def _set_align(self, align): 10 | '''Sets align for the child object''' 11 | possible_aligns = ['right', 'center', 'left'] 12 | if align not in possible_aligns: 13 | raise InvalidAlignException(align) 14 | self.align = align 15 | -------------------------------------------------------------------------------- /nider/mixins/text_mixins.py: -------------------------------------------------------------------------------- 1 | class MultilineTextMixin: 2 | 3 | def __init__(self, text_width, line_padding): 4 | self._set_text_width(text_width) 5 | self.line_padding = line_padding 6 | 7 | def _set_text_width(self, text_width): 8 | '''Sets text_width used in the child object''' 9 | if text_width > 0: 10 | self.text_width = text_width 11 | else: 12 | raise AttributeError( 13 | '{} text_width has to be an instance of int and > 0'.format( 14 | self.__class__.__name__)) 15 | -------------------------------------------------------------------------------- /nider/models.py: -------------------------------------------------------------------------------- 1 | import math 2 | import os 3 | import warnings 4 | 5 | from PIL import Image as PIL_Image, ImageDraw, ImageEnhance 6 | 7 | from nider.colors import color_to_rgb, get_img_dominant_color, generate_opposite_color, blend 8 | from nider.core import Font, Text, MultilineTextUnit, SingleLineTextUnit 9 | from nider.exceptions import (ImageGeneratorException, ImageSizeFixedWarning, 10 | AutoGeneratedUnitColorUsedWarning, AutoGeneratedUnitOutlinecolorUsedWarning) 11 | from nider.utils import get_random_bgcolor, get_random_texture, is_path_creatable 12 | 13 | 14 | class Header(MultilineTextUnit): 15 | __doc__ = '''Class that represents a header used in images''' + \ 16 | '\n\n' + MultilineTextUnit.__doc__ 17 | 18 | 19 | class Paragraph(MultilineTextUnit): 20 | __doc__ = '''Class that represents a paragraph used in images''' + \ 21 | '\n\n' + MultilineTextUnit.__doc__ 22 | 23 | 24 | class Linkback(SingleLineTextUnit): 25 | '''Class that represents a linkback used in images 26 | 27 | Args: 28 | text (str): text used for the unit. 29 | font (nider.core.Font): font object that represents text's font. 30 | color (str): string that represents a color. Must be compatible with `PIL.ImageColor `_ `color names `_ 31 | outline (nider.core.Outline): outline object that represents text's outline. 32 | align ('left' or 'center' or 'right'): side with respect to which the text will be aligned. 33 | bottom_padding (int): linkback’s bottom padding - padding (in pixels) between the bottom of the image and the linkback itself. 34 | 35 | Raises: 36 | nider.exceptions.InvalidAlignException: if ``align`` is not supported by nider. 37 | nider.exceptions.DefaultFontWarning: if ``font.path`` is ``None``. 38 | nider.exceptions.FontNotFoundWarning: if ``font.path`` does not exist. 39 | ''' 40 | 41 | def __init__(self, text, font=None, 42 | color=None, outline=None, 43 | align='right', bottom_padding=20): 44 | self.bottom_padding = bottom_padding 45 | super().__init__(text=text, font=font, color=color, outline=outline, 46 | align=align) 47 | 48 | def _set_height(self): 49 | '''Sets linkback\'s height''' 50 | super()._set_height() 51 | self.height += self.bottom_padding 52 | 53 | 54 | class Watermark(Text): 55 | '''Class that represents a watermark used in images 56 | 57 | Args: 58 | text (str): text to use. 59 | font (nider.core.Font): font object that represents text's font. 60 | color (str): string that represents a color. Must be compatible with `PIL.ImageColor `_ `color names `_ 61 | outline (nider.core.Outline): outline object that represents text's outline. 62 | cross (bool): boolean flag that indicates whether watermark has to be drawn with a cross. 63 | rotate_angle (int): angle to which watermark's text has to be rotated. 64 | opacity (0 <= float <= 1): opacity level of the watermark (applies to both the text and the cross). 65 | 66 | Raises: 67 | nider.exceptions.ImageGeneratorException: if ``font`` is the default font. 68 | nider.exceptions.DefaultFontWarning: if ``font.path`` is ``None``. 69 | nider.exceptions.FontNotFoundWarning: if ``font.path`` does not exist. 70 | 71 | Note: 72 | Watermark tries to takes all available width of the image so providing ``font.size`` has no affect on the watermark. 73 | ''' 74 | 75 | def __init__(self, text, font, 76 | color=None, outline=None, 77 | cross=True, rotate_angle=None, 78 | opacity=0.25): 79 | if font.is_default: 80 | raise ImageGeneratorException( 81 | 'Watermark cannot be drawn using a default font. Please provide an existing font') 82 | super().__init__(text=text, font=font, color=color, outline=outline) 83 | self.cross = cross 84 | self.rotate_angle = rotate_angle 85 | self.opacity = opacity 86 | 87 | def _adjust_fontsize(self, bg_image): 88 | text_width, text_height = self.font.getsize(self.text) 89 | angle = self.rotate_angle 90 | 91 | # If the width of the image is bigger than the height of the image and we rotate 92 | # our watermark it may go beyond the bounding box of the original image, 93 | # that's why we need to take into consideration the actual width of the rotated 94 | # waterwark inside the original image's bounding box 95 | bg_image_w, bg_image_h = bg_image.size 96 | if angle and (bg_image_w > bg_image_h): 97 | max_wm_w = 2 * \ 98 | abs(bg_image_h / (2 * math.sin(math.radians(angle)))) 99 | else: 100 | max_wm_w = bg_image_w 101 | 102 | while text_width + text_height < max_wm_w: 103 | self.font_object = Font( 104 | self.font_object.path, self.font_object.size + 1) 105 | self.font = self.font_object.font 106 | text_width, text_height = self.font.getsize(self.text) 107 | 108 | 109 | class Content: 110 | '''Class that aggregates different units into a sigle object 111 | 112 | Args: 113 | paragraph (nider.models.Paragraph): paragraph used for in the content. 114 | header (nider.models.Header): header used for in the content. 115 | linkback (nider.models.Linkback): linkback used for in the content. 116 | watermark (nider.models.Watermark): watermark used for in the content. 117 | padding (int): content's padding - padding (in pixels) between the units. 118 | 119 | Raises: 120 | nider.exceptions.ImageGeneratorException: if neither of ``paragraph``, ``header`` or ``linkback`` is provided. 121 | 122 | Note: 123 | ``padding`` is taken into account only if image is to get resized. If size allows content to fit freely, pre-calculated paddings will be used. 124 | 125 | Note: 126 | Content has to consist at least of one unit: header, paragraph or linkback. 127 | ''' 128 | 129 | def __init__(self, paragraph=None, header=None, linkback=None, watermark=None, padding=45): 130 | if not any((paragraph, header, linkback, watermark)): 131 | raise ImageGeneratorException( 132 | 'Content has to consist at least of one unit.') 133 | self.para = paragraph 134 | self.header = header 135 | self.linkback = linkback 136 | self.watermark = watermark 137 | self.padding = padding 138 | self.depends_on_opposite_to_bg_color = not all( 139 | unit.color for unit in [ 140 | self.para, self.header, self.linkback, self.watermark 141 | ] if unit 142 | ) 143 | # Variable to check if the content fits into the img. Default is true, 144 | # but it may changed by in Img._fix_image_size() 145 | self.fits = True 146 | self._set_content_height() 147 | 148 | def _set_content_height(self): 149 | '''Sets content\'s height''' 150 | self.height = 0 151 | if self.para: 152 | self.height += 2 * self.padding + self.para.height 153 | if self.header: 154 | self.height += 1 * self.padding + self.header.height 155 | if self.linkback: 156 | self.height += self.linkback.height 157 | 158 | 159 | class Image: 160 | '''Base class for a text based image 161 | 162 | Args: 163 | content (nider.models.Content): content object that has units to be rendered. 164 | fullpath (str): path where the image has to be saved. 165 | width (int): width of the image to be generated. 166 | height (int): height of the image to be generated. 167 | title (str): title of the image. Serves as metadata for latter rendering in html. May be used as alt text of the image. If no title is provided ``content.header.text`` will be set as the value. 168 | description (str): description of the image. Serves as metadata for latter rendering in html. May be used as description text of the image. If no description is provided ``content.paragraph.text`` will be set as the value. 169 | 170 | Raises: 171 | nider.exceptions.ImageGeneratorException: if the current user doesn't have sufficient permissions to create the file at passed ``fullpath``. 172 | AttributeError: if width <= 0 or height <= 0. 173 | ''' 174 | 175 | def __init__(self, content, fullpath, width=1080, height=1080, title=None, description=None): 176 | self._set_content(content) 177 | self._set_fullpath(fullpath) 178 | self._set_image_size(width, height) 179 | self._set_title(title) 180 | self._set_description(description) 181 | 182 | def draw_on_texture(self, texture_path=None): 183 | '''Draws preinitialized image and its attributes on a texture 184 | 185 | If ``texture_path`` is set to ``None``, random texture from ``nider/textures`` will be taken. 186 | 187 | Args: 188 | texture_path (str): path of the texture to use. 189 | 190 | Raises: 191 | FileNotFoundError: if texture file at path ``texture_path`` cannot be found. 192 | nider.exceptions.ImageSizeFixedWarning: if the image size has to be adjusted to the provided content's size because the content takes too much space. 193 | ''' 194 | if texture_path is None: 195 | texture_path = get_random_texture() 196 | elif not os.path.isfile(texture_path): 197 | raise FileNotFoundError( 198 | 'Can\'t find texture {}. Please, choose an existing texture'.format(texture_path)) 199 | if self.content.depends_on_opposite_to_bg_color: 200 | self.opposite_to_bg_color = generate_opposite_color( 201 | get_img_dominant_color(texture_path) 202 | ) 203 | self._create_image() 204 | self._create_draw_object() 205 | self._fill_image_with_texture(texture_path) 206 | self._draw_content() 207 | self._save() 208 | 209 | def draw_on_bg(self, bgcolor=None): 210 | '''Draws preinitialized image and its attributes on a colored background 211 | 212 | If ``bgcolor`` is set to ``None``, random ``nider.colors.colormap.FLAT_UI_COLORS`` will be taken. 213 | 214 | Args: 215 | bgcolor (str): string that represents a background color. Must be compatible with `PIL.ImageColor `_ `color names `_ 216 | 217 | Raises: 218 | nider.exceptions.ImageSizeFixedWarning: if the image size has to be adjusted to the provided content's size because the content takes too much space. 219 | ''' 220 | self.bgcolor = color_to_rgb( 221 | bgcolor) if bgcolor else get_random_bgcolor() 222 | if self.content.depends_on_opposite_to_bg_color: 223 | self.opposite_to_bg_color = generate_opposite_color(self.bgcolor) 224 | self._create_image() 225 | self._create_draw_object() 226 | self._fill_image_with_color() 227 | self._draw_content() 228 | self._save() 229 | 230 | def draw_on_image(self, image_path, image_enhancements=None, image_filters=None): 231 | '''Draws preinitialized image and its attributes on an image 232 | 233 | Args: 234 | image_path (str): path of the image to draw on. 235 | image_enhancements (itarable): itarable of tuples, each containing a class from ``PIL.ImageEnhance`` that will be applied and factor - a floating point value controlling the enhancement. Check `documentation `_ of ``PIL.ImageEnhance`` for more info about availabe enhancements. 236 | image_filters (itarable): itarable of filters from ``PIL.ImageFilter`` that will be applied. Check `documentation `_ of ``PIL.ImageFilter`` for more info about availabe filters. 237 | 238 | Raises: 239 | FileNotFoundError: if image file at path ``image_path`` cannot be found. 240 | ''' 241 | if not os.path.isfile(image_path): 242 | raise FileNotFoundError( 243 | 'Can\'t find image {}. Please, choose an existing image'.format(image_path)) 244 | self.image = PIL_Image.open(image_path) 245 | if self.content.depends_on_opposite_to_bg_color: 246 | self.opposite_to_bg_color = generate_opposite_color( 247 | get_img_dominant_color(image_path) 248 | ) 249 | if image_filters: 250 | for image_filter in image_filters: 251 | self.image = self.image.filter(image_filter) 252 | if image_enhancements: 253 | for enhancement in image_enhancements: 254 | enhance_method, enhance_factor = enhancement[0], enhancement[1] 255 | enhancer = enhance_method(self.image) 256 | self.image = enhancer.enhance(enhance_factor) 257 | self._create_draw_object() 258 | self.width, self.height = self.image.size 259 | self._draw_content() 260 | self._save() 261 | 262 | def _save(self): 263 | '''Saves the image''' 264 | self.image.save(self.fullpath) 265 | 266 | def _set_content(self, content): 267 | '''Sets content used in the image''' 268 | self.content = content 269 | self.header = content.header 270 | self.para = content.para 271 | self.linkback = content.linkback 272 | self.watermark = content.watermark 273 | 274 | def _set_fullpath(self, fullpath): 275 | '''Sets path where to save the image''' 276 | if is_path_creatable(fullpath): 277 | self.fullpath = fullpath 278 | else: 279 | raise ImageGeneratorException( 280 | "Is seems impossible to create a file in path {}".format(fullpath)) 281 | 282 | def _set_image_size(self, width, height): 283 | '''Sets width and height of the image''' 284 | if width <= 0 or height <= 0: 285 | raise AttributeError( 286 | "Width or height of the image have to be positive integers") 287 | self.width = width 288 | self.height = height 289 | 290 | def _set_title(self, title): 291 | '''Sets title of the image''' 292 | if title: 293 | self.title = title 294 | elif self.content.header: 295 | self.title = self.content.header.text 296 | else: 297 | self.title = '' 298 | 299 | def _set_description(self, description): 300 | '''Sets description of the image''' 301 | if description: 302 | self.description = description 303 | elif self.content.para: 304 | self.description = self.content.para.text 305 | else: 306 | self.description = '' 307 | 308 | def _fix_image_size(self): 309 | '''Fixes image's size''' 310 | 311 | if self.content.height >= self.height: 312 | warnings.warn(ImageSizeFixedWarning()) 313 | self.content.fits = False 314 | self.height = self.content.height 315 | 316 | def _create_image(self): 317 | '''Creates a basic PIL image 318 | 319 | Creates a basic PIL image previously fixing its size 320 | ''' 321 | self._fix_image_size() 322 | self.image = PIL_Image.new("RGBA", (self.width, self.height)) 323 | 324 | def _create_draw_object(self): 325 | '''Creates a basic PIL Draw object''' 326 | self.draw = ImageDraw.Draw(self.image) 327 | 328 | def _fill_image_with_texture(self, texture_path): 329 | '''Fills an image with a texture 330 | 331 | Fills an image with a texture by reapiting it necessary number of times 332 | 333 | Attributes: 334 | texture_path (str): path of the texture to use 335 | ''' 336 | texture = PIL_Image.open(texture_path, 'r') 337 | texture_w, texture_h = texture.size 338 | bg_w, bg_h = self.image.size 339 | times_for_Ox = math.ceil(bg_w / texture_w) 340 | times_for_Oy = math.ceil(bg_h / texture_h) 341 | for y in range(times_for_Oy): 342 | for x in range(times_for_Ox): 343 | offset = (x * texture_w, y * texture_h) 344 | self.image.paste(texture, offset) 345 | 346 | def _fill_image_with_color(self): 347 | '''Fills an image with a color 348 | 349 | Fills an image with a color by creating a colored rectangle of the image 350 | size 351 | ''' 352 | self.draw.rectangle([(0, 0), self.image.size], fill=self.bgcolor) 353 | 354 | def _prepare_content(self): 355 | '''Prepares content for drawing''' 356 | content = self.content 357 | for unit in [content.header, content.para, content.linkback]: 358 | if unit: 359 | if not unit.color: 360 | color_to_use = self.opposite_to_bg_color 361 | # explicitly sets unit's color to disntinc to bg one 362 | unit.color = color_to_use 363 | warnings.warn( 364 | AutoGeneratedUnitColorUsedWarning(unit, color_to_use)) 365 | if unit.outline and not unit.outline.color: 366 | color_to_use = blend(unit.color, '#000', 0.2) 367 | unit.outline.color = color_to_use 368 | warnings.warn( 369 | AutoGeneratedUnitOutlinecolorUsedWarning(unit, color_to_use)) 370 | 371 | def _draw_content(self): 372 | '''Draws each unit of the content on the image''' 373 | self._prepare_content() 374 | if self.header: 375 | self._draw_header() 376 | if self.para: 377 | self._draw_para() 378 | if self.linkback: 379 | self._draw_linkback() 380 | if self.watermark: 381 | self._draw_watermark() 382 | 383 | def _draw_header(self): 384 | '''Draws the header on the image''' 385 | current_h = self.content.padding 386 | self._draw_unit(current_h, self.header) 387 | 388 | def _draw_para(self): 389 | '''Draws the paragraph on the image''' 390 | if self.content.fits: 391 | # Trying to center everything 392 | current_h = math.floor( 393 | (self.height - self.para.height) / 2) 394 | self._draw_unit(current_h, self.para) 395 | else: 396 | if self.header: 397 | header_with_padding_height = 2 * self.content.padding + self.header.height 398 | current_h = header_with_padding_height 399 | else: 400 | current_h = self.content.padding 401 | self._draw_unit(current_h, self.para) 402 | 403 | def _draw_linkback(self): 404 | '''Draws a linkback on the image''' 405 | current_h = self.height - self.linkback.height 406 | self._draw_unit(current_h, self.linkback) 407 | 408 | def _draw_watermark(self): 409 | '''Draws a watermark on the image''' 410 | watermark_image = PIL_Image.new('RGBA', self.image.size, (0, 0, 0, 0)) 411 | self.watermark._adjust_fontsize(self.image) 412 | draw = ImageDraw.Draw(watermark_image, 'RGBA') 413 | w_width, w_height = self.watermark.font.getsize(self.watermark.text) 414 | draw.text(((watermark_image.size[0] - w_width) / 2, 415 | (watermark_image.size[1] - w_height) / 2), 416 | self.watermark.text, font=self.watermark.font, 417 | fill=self.watermark.color) 418 | 419 | if self.watermark.rotate_angle: 420 | watermark_image = watermark_image.rotate( 421 | self.watermark.rotate_angle, PIL_Image.BICUBIC) 422 | 423 | alpha = watermark_image.split()[3] 424 | alpha = ImageEnhance.Brightness(alpha).enhance(self.watermark.opacity) 425 | watermark_image.putalpha(alpha) 426 | 427 | # Because watermark can be rotated we create a separate image for cross 428 | # so that it doesn't get rotated also. + It's impossible to drawn 429 | # on a rotated image 430 | if self.watermark.cross: 431 | watermark_cross_image = PIL_Image.new( 432 | 'RGBA', self.image.size, (0, 0, 0, 0)) 433 | cross_draw = ImageDraw.Draw(watermark_cross_image, 'RGBA') 434 | line_width = 1 + int(sum(self.image.size) / 2 * 0.007) 435 | cross_draw.line( 436 | (0, 0) + watermark_image.size, 437 | fill=self.watermark.color, 438 | width=line_width 439 | ) 440 | cross_draw.line( 441 | (0, watermark_image.size[1], watermark_image.size[0], 0), 442 | fill=self.watermark.color, 443 | width=line_width 444 | ) 445 | watermark_cross_alpha = watermark_cross_image.split()[3] 446 | watermark_cross_alpha = ImageEnhance.Brightness( 447 | watermark_cross_alpha).enhance(self.watermark.opacity) 448 | watermark_cross_image.putalpha(watermark_cross_alpha) 449 | # Adds cross to the watermark 450 | watermark_image = PIL_Image.composite( 451 | watermark_cross_image, watermark_image, watermark_cross_image) 452 | 453 | self.image = PIL_Image.composite( 454 | watermark_image, self.image, watermark_image) 455 | 456 | def _draw_unit(self, start_height, unit): 457 | '''Draws the text and its outline on the image starting at specific height''' 458 | current_h = start_height 459 | try: 460 | lines = unit.wrapped_lines 461 | except AttributeError: 462 | # text is a one-liner. Construct a list out of it for later usage 463 | lines = [unit.text] 464 | line_padding = getattr(unit, 'line_padding', None) 465 | outline = unit.outline 466 | font = unit.font 467 | 468 | for line in lines: 469 | w, h = self.draw.textsize(line, font=unit.font) 470 | if unit.align == "center": 471 | x = (self.width - w) / 2 472 | elif unit.align == "left": 473 | x = self.width * 0.075 474 | elif unit.align == "right": 475 | x = 0.925 * self.width - w 476 | y = current_h 477 | 478 | if outline: 479 | # thin border 480 | self.draw.text((x - outline.width, y), line, font=font, 481 | fill=outline.color) 482 | self.draw.text((x + outline.width, y), line, font=font, 483 | fill=outline.color) 484 | self.draw.text((x, y - outline.width), line, font=font, 485 | fill=outline.color) 486 | self.draw.text((x, y + outline.width), line, font=font, 487 | fill=outline.color) 488 | 489 | # thicker border 490 | self.draw.text((x - outline.width, y - outline.width), line, 491 | font=font, fill=outline.color) 492 | self.draw.text((x + outline.width, y - outline.width), line, 493 | font=font, fill=outline.color) 494 | self.draw.text((x - outline.width, y + outline.width), line, 495 | font=font, fill=outline.color) 496 | self.draw.text((x + outline.width, y + outline.width), line, 497 | font=font, fill=outline.color) 498 | 499 | self.draw.text((x, y), line, unit.color, font=font) 500 | 501 | if line_padding: 502 | current_h += h + line_padding 503 | 504 | 505 | class FacebookSquarePost(Image): 506 | '''Alias of :class:`nider.models.Image` with ``width=470`` and ``height=470``''' 507 | 508 | def __init__(self, *args, **kwargs): 509 | kwargs['width'] = kwargs.get('width', 470) 510 | kwargs['height'] = kwargs.get('height', 470) 511 | super().__init__(*args, **kwargs) 512 | 513 | 514 | class FacebookLandscapePost(Image): 515 | '''Alias of :class:`nider.models.Image` with ``width=1024`` and ``height=512``''' 516 | 517 | def __init__(self, *args, **kwargs): 518 | kwargs['width'] = kwargs.get('width', 1024) 519 | kwargs['height'] = kwargs.get('height', 512) 520 | super().__init__(*args, **kwargs) 521 | 522 | 523 | TwitterPost = FacebookLandscapePost 524 | 525 | 526 | class TwitterLargeCard(Image): 527 | '''Alias of :class:`nider.models.Image` with ``width=506`` and ``height=506``''' 528 | 529 | def __init__(self, *args, **kwargs): 530 | kwargs['width'] = kwargs.get('width', 506) 531 | kwargs['height'] = kwargs.get('height', 506) 532 | super().__init__(*args, **kwargs) 533 | 534 | 535 | class InstagramSquarePost(Image): 536 | '''Alias of :class:`nider.models.Image` with ``width=1080`` and ``height=1080``''' 537 | 538 | def __init__(self, *args, **kwargs): 539 | kwargs['width'] = kwargs.get('width', 1080) 540 | kwargs['height'] = kwargs.get('height', 1080) 541 | super().__init__(*args, **kwargs) 542 | 543 | 544 | class InstagramPortraitPost(Image): 545 | '''Alias of :class:`nider.models.Image` with ``width=1080`` and ``height=1350``''' 546 | 547 | def __init__(self, *args, **kwargs): 548 | kwargs['width'] = kwargs.get('width', 1080) 549 | kwargs['height'] = kwargs.get('height', 1350) 550 | super().__init__(*args, **kwargs) 551 | 552 | 553 | class InstagramLandscapePost(Image): 554 | '''Alias of :class:`nider.models.Image` with ``width=1080`` and ``height=566``''' 555 | 556 | def __init__(self, *args, **kwargs): 557 | kwargs['width'] = kwargs.get('width', 1080) 558 | kwargs['height'] = kwargs.get('height', 566) 559 | super().__init__(*args, **kwargs) 560 | -------------------------------------------------------------------------------- /nider/textures/Sports.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/Sports.png -------------------------------------------------------------------------------- /nider/textures/asanoha-400px.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/asanoha-400px.png -------------------------------------------------------------------------------- /nider/textures/asfalt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/asfalt.png -------------------------------------------------------------------------------- /nider/textures/binding_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/binding_dark.png -------------------------------------------------------------------------------- /nider/textures/black_paper.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/black_paper.png -------------------------------------------------------------------------------- /nider/textures/black_thread.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/black_thread.png -------------------------------------------------------------------------------- /nider/textures/blackmamba.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/blackmamba.png -------------------------------------------------------------------------------- /nider/textures/broken_noise.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/broken_noise.png -------------------------------------------------------------------------------- /nider/textures/cartographer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/cartographer.png -------------------------------------------------------------------------------- /nider/textures/circles-and-roundabouts.png.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/circles-and-roundabouts.png.png -------------------------------------------------------------------------------- /nider/textures/congruent_outline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/congruent_outline.png -------------------------------------------------------------------------------- /nider/textures/congruent_pentagon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/congruent_pentagon.png -------------------------------------------------------------------------------- /nider/textures/cream_dust.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/cream_dust.png -------------------------------------------------------------------------------- /nider/textures/crissXcross.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/crissXcross.png -------------------------------------------------------------------------------- /nider/textures/crossword.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/crossword.png -------------------------------------------------------------------------------- /nider/textures/dark_embroidery.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/dark_embroidery.png -------------------------------------------------------------------------------- /nider/textures/dark_geometric.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/dark_geometric.png -------------------------------------------------------------------------------- /nider/textures/dark_leather.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/dark_leather.png -------------------------------------------------------------------------------- /nider/textures/dark_mosaic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/dark_mosaic.png -------------------------------------------------------------------------------- /nider/textures/dark_wall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/dark_wall.png -------------------------------------------------------------------------------- /nider/textures/dark_wood.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/dark_wood.png -------------------------------------------------------------------------------- /nider/textures/debut_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/debut_dark.png -------------------------------------------------------------------------------- /nider/textures/denim.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/denim.png -------------------------------------------------------------------------------- /nider/textures/diagmonds.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/diagmonds.png -------------------------------------------------------------------------------- /nider/textures/dirty_old_shirt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/dirty_old_shirt.png -------------------------------------------------------------------------------- /nider/textures/eight_horns.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/eight_horns.png -------------------------------------------------------------------------------- /nider/textures/elastoplast.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/elastoplast.png -------------------------------------------------------------------------------- /nider/textures/ep_naturalblack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/ep_naturalblack.png -------------------------------------------------------------------------------- /nider/textures/escheresque_ste.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/escheresque_ste.png -------------------------------------------------------------------------------- /nider/textures/extra_clean_paper.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/extra_clean_paper.png -------------------------------------------------------------------------------- /nider/textures/foggy_birds.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/foggy_birds.png -------------------------------------------------------------------------------- /nider/textures/footer_lodyas.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/footer_lodyas.png -------------------------------------------------------------------------------- /nider/textures/fresh_snow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/fresh_snow.png -------------------------------------------------------------------------------- /nider/textures/geometry.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/geometry.png -------------------------------------------------------------------------------- /nider/textures/geometry2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/geometry2.png -------------------------------------------------------------------------------- /nider/textures/gplaypattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/gplaypattern.png -------------------------------------------------------------------------------- /nider/textures/gray_sand.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/gray_sand.png -------------------------------------------------------------------------------- /nider/textures/grey.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/grey.png -------------------------------------------------------------------------------- /nider/textures/handmadepaper.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/handmadepaper.png -------------------------------------------------------------------------------- /nider/textures/ice_age.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/ice_age.png -------------------------------------------------------------------------------- /nider/textures/irongrip.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/irongrip.png -------------------------------------------------------------------------------- /nider/textures/light_wool.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/light_wool.png -------------------------------------------------------------------------------- /nider/textures/lightpaperfibers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/lightpaperfibers.png -------------------------------------------------------------------------------- /nider/textures/navy_blue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/navy_blue.png -------------------------------------------------------------------------------- /nider/textures/old_mathematics.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/old_mathematics.png -------------------------------------------------------------------------------- /nider/textures/paper_fibers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/paper_fibers.png -------------------------------------------------------------------------------- /nider/textures/photography.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/photography.png -------------------------------------------------------------------------------- /nider/textures/pink dust.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/pink dust.png -------------------------------------------------------------------------------- /nider/textures/random_grey_variations.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/random_grey_variations.png -------------------------------------------------------------------------------- /nider/textures/redox_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/redox_01.png -------------------------------------------------------------------------------- /nider/textures/retina_wood.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/retina_wood.png -------------------------------------------------------------------------------- /nider/textures/sakura.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/sakura.png -------------------------------------------------------------------------------- /nider/textures/sayagata-400px.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/sayagata-400px.png -------------------------------------------------------------------------------- /nider/textures/school.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/school.png -------------------------------------------------------------------------------- /nider/textures/snow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/snow.png -------------------------------------------------------------------------------- /nider/textures/stardust.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/stardust.png -------------------------------------------------------------------------------- /nider/textures/subtle_white_feathers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/subtle_white_feathers.png -------------------------------------------------------------------------------- /nider/textures/swirl_pattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/swirl_pattern.png -------------------------------------------------------------------------------- /nider/textures/symphony.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/symphony.png -------------------------------------------------------------------------------- /nider/textures/tileable_wood_texture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/tileable_wood_texture.png -------------------------------------------------------------------------------- /nider/textures/topography.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/topography.png -------------------------------------------------------------------------------- /nider/textures/type.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/type.png -------------------------------------------------------------------------------- /nider/textures/use_your_illusion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/use_your_illusion.png -------------------------------------------------------------------------------- /nider/textures/weather.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/weather.png -------------------------------------------------------------------------------- /nider/textures/wood_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/wood_1.png -------------------------------------------------------------------------------- /nider/textures/wood_pattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/wood_pattern.png -------------------------------------------------------------------------------- /nider/textures/zwartevilt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythad/nider/be71e09968559c5504c59158aa339136fb891fb4/nider/textures/zwartevilt.png -------------------------------------------------------------------------------- /nider/tools.py: -------------------------------------------------------------------------------- 1 | from nider.models import Image, Content 2 | 3 | 4 | def add_watermark(image_path, watermark, new_path=None, 5 | image_enhancements=None, image_filters=None): 6 | '''Function to add watermarks to images 7 | 8 | Args: 9 | image_path (str): path of the image to which watermark has to be added. 10 | watermark (nider.models.Watermark): watermark object. 11 | new_path (str): path where the image has to be saved. **If set to None (default option), initial image will be overwritten.** 12 | image_enhancements (itarable): itarable of tuples, each containing a class from ``PIL.ImageEnhance`` that will be applied and factor - a floating point value controlling the enhancement. Check `documentation `_ of ``PIL.ImageEnhance`` for more info about availabe enhancements. 13 | image_filters (itarable): itarable of filters from ``PIL.ImageFilter`` that will be applied. Check `documentation `_ of ``PIL.ImageFilter`` for more info about availabe filters. 14 | 15 | Raises: 16 | FileNotFoundError: if image file at path ``image_path`` cannot be found. 17 | nider.exceptions.ImageGeneratorException: if the current user doesn't have sufficient permissions to create the file at passed ``new_path``. 18 | ''' 19 | if new_path is None: 20 | new_path = image_path 21 | content = Content(watermark=watermark) 22 | new_image = Image(content, fullpath=new_path) 23 | new_image.draw_on_image(image_path, 24 | image_enhancements=image_enhancements, 25 | image_filters=image_filters) 26 | -------------------------------------------------------------------------------- /nider/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | import warnings 4 | from contextlib import contextmanager 5 | 6 | from PIL import Image, ImageFont 7 | 8 | from nider.colors import FLAT_UI_COLORS 9 | from nider.exceptions import DefaultFontWarning, FontNotFoundWarning 10 | 11 | 12 | def get_font(fontfullpath, fontsize): 13 | '''Function to create a truetype ``PIL.ImageFont`` that provides fallbacks for invalid arguments 14 | 15 | Args: 16 | fontfullpath (str): path to the desired font. 17 | fontsize (int): size of the font. 18 | 19 | Returns: 20 | PIL.ImageFont: Default PIL ImageFont if ``fontfullpath`` is either unreachable or provided ``fontfullpath`` is ``None``. 21 | 22 | Raises: 23 | nider.exceptions.DefaultFontWarning: if ``fontfullpath`` is ``None``. 24 | nider.exceptions.FontNotFoundWarning: if ``fontfullpath`` does not exist. 25 | ''' 26 | if fontfullpath is None: 27 | warnings.warn(DefaultFontWarning()) 28 | font = ImageFont.load_default() 29 | font.is_default = True 30 | elif not os.path.exists(fontfullpath): 31 | warnings.warn(FontNotFoundWarning(fontfullpath)) 32 | font = ImageFont.load_default() 33 | font.is_default = True 34 | else: 35 | font = ImageFont.truetype(fontfullpath, fontsize) 36 | font.is_default = False 37 | return font 38 | 39 | 40 | def is_path_creatable(pathname): 41 | '''Function to check if the current user has sufficient permissions to create the passed 42 | pathname 43 | 44 | Args: 45 | pathname (str): path to check. 46 | 47 | Returns: 48 | bool: ``True`` if the current user has sufficient permissions to create the passed ``pathname``. ``False`` otherwise. 49 | ''' 50 | # Parent directory of the passed path. If empty, we substitute the current 51 | # working directory (CWD) instead. 52 | dirname = os.path.dirname(pathname) or os.getcwd() 53 | return os.access(dirname, os.W_OK) 54 | 55 | 56 | @contextmanager 57 | def create_test_image(): 58 | '''Context manager to yield a ``PIL.Image``''' 59 | try: 60 | image = Image.new('RGBA', size=(50, 50), color=(155, 0, 0)) 61 | image.save('test.png') 62 | yield 63 | finally: 64 | os.remove('test.png') 65 | 66 | 67 | def get_random_texture(): 68 | '''Returns the path to a random texture from the local ``nider/textures`` folder''' 69 | textures_folder = os.path.dirname( 70 | os.path.realpath(__file__)) + '/textures' 71 | texture = random.choice(os.listdir(textures_folder)) 72 | texture_path = textures_folder + '/' + texture 73 | return texture_path 74 | 75 | 76 | def get_random_bgcolor(): 77 | '''Returns random flat ui color from ``nider.colors.colormap.FLAT_UI_COLORS``''' 78 | return random.choice(list(FLAT_UI_COLORS.values())) 79 | -------------------------------------------------------------------------------- /requirements/dev.txt: -------------------------------------------------------------------------------- 1 | -r prod.txt 2 | 3 | bumpversion==0.6.0 4 | watchdog==0.10.3 5 | flake8==3.8.3 6 | tox==3.19.0 7 | coverage==5.2.1 8 | Sphinx==3.2.0 9 | cryptography==3.0 10 | PyYAML==5.3.1 11 | -------------------------------------------------------------------------------- /requirements/prod.txt: -------------------------------------------------------------------------------- 1 | colorthief==0.2.1 2 | Pillow==7.2.0 3 | -------------------------------------------------------------------------------- /requirements/test.txt: -------------------------------------------------------------------------------- 1 | -r prod.txt 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.5.0 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | search = version='{current_version}' 8 | replace = version='{new_version}' 9 | 10 | [bumpversion:file:nider/__init__.py] 11 | search = __version__ = '{current_version}' 12 | replace = __version__ = '{new_version}' 13 | 14 | [bdist_wheel] 15 | universal = 1 16 | 17 | [flake8] 18 | exclude = docs 19 | 20 | [aliases] 21 | 22 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """The setup script.""" 5 | 6 | 7 | try: # for pip >= 10 8 | from pip._internal.req import parse_requirements 9 | except ImportError: # for pip <= 9.0.3 10 | from pip.req import parse_requirements 11 | 12 | from setuptools import setup, find_packages 13 | 14 | try: # for pip >= 10 15 | from pip._internal.network.session import PipSession 16 | except ImportError: # for pip <= 9.0.3 17 | from pip._internal.download import PipSession 18 | 19 | 20 | with open('README.rst') as readme_file: 21 | readme = readme_file.read() 22 | 23 | with open('HISTORY.rst') as history_file: 24 | history = history_file.read() 25 | 26 | parsed_requirements = parse_requirements( 27 | 'requirements/prod.txt', 28 | session=PipSession() 29 | ) 30 | 31 | parsed_test_requirements = parse_requirements( 32 | 'requirements/test.txt', 33 | session=PipSession() 34 | ) 35 | try: 36 | requirements = [str(ir.req) for ir in parsed_requirements] 37 | test_requirements = [str(tr.req) for tr in parsed_test_requirements] 38 | except AttributeError: 39 | requirements = [str(ir.requirement) for ir in parsed_requirements] 40 | test_requirements = [str(tr.requirement) for tr in parsed_test_requirements] 41 | 42 | setup( 43 | name='nider', 44 | version='0.5.0', 45 | description="Python package to add text to images, textures and different backgrounds", 46 | long_description=readme + '\n\n' + history, 47 | author="Vladyslav Ovchynnykov", 48 | author_email='ovd4mail@gmail.com', 49 | url='https://github.com/pythad/nider', 50 | packages=find_packages(include=['nider*']), 51 | include_package_data=True, 52 | install_requires=requirements, 53 | license="MIT license", 54 | zip_safe=False, 55 | keywords='nider', 56 | classifiers=[ 57 | 'Development Status :: 5 - Production/Stable', 58 | 'Intended Audience :: Developers', 59 | 'License :: OSI Approved :: MIT License', 60 | 'Natural Language :: English', 61 | 'Programming Language :: Python :: 3', 62 | 'Programming Language :: Python :: 3.6', 63 | 'Programming Language :: Python :: 3.7', 64 | 'Programming Language :: Python :: 3.8' 65 | ], 66 | test_suite='tests', 67 | tests_require=test_requirements, 68 | ) 69 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Unit test package for nider.""" 4 | -------------------------------------------------------------------------------- /tests/test_colors.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from nider.colors import monochrome_color, color_to_rgb, COLORS 4 | 5 | 6 | class TestMonochromeColor(unittest.TestCase): 7 | 8 | def test_main_functionality(self): 9 | self.assertEqual(monochrome_color((255, 255, 255)), COLORS['white']) 10 | self.assertEqual(monochrome_color((254, 254, 254)), COLORS['white']) 11 | self.assertEqual(monochrome_color((255, 112, 112)), COLORS['white']) 12 | self.assertEqual(monochrome_color((0, 0, 0)), COLORS['black']) 13 | self.assertEqual(monochrome_color((1, 1, 1)), COLORS['black']) 14 | self.assertEqual(monochrome_color((30, 0, 0)), COLORS['black']) 15 | 16 | 17 | class TestColorToRgb(unittest.TestCase): 18 | 19 | def test_main_functionality(self): 20 | self.assertEqual(color_to_rgb('#000'), (0, 0, 0)) 21 | self.assertEqual(color_to_rgb((0, 0, 0)), (0, 0, 0)) 22 | 23 | 24 | if __name__ == '__main__': 25 | unittest.main() 26 | -------------------------------------------------------------------------------- /tests/test_core.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest import mock 3 | 4 | from nider.core import Font, Outline, Text, MultilineText, SingleLineTextUnit, MultilineTextUnit 5 | 6 | 7 | class TestFont(unittest.TestCase): 8 | 9 | def setUp(self): 10 | self.font_mock = mock.Mock() 11 | 12 | def test_setting_font(self): 13 | self.font_mock.path = 'foo/bar' 14 | self.font_mock.size = 23 15 | Font._set_font(self.font_mock) 16 | self.assertIsNotNone(self.font_mock.font) 17 | 18 | def test_initialization(self): 19 | font = Font() 20 | self.assertIsNotNone(font.font) 21 | 22 | 23 | class TestOutline(unittest.TestCase): 24 | 25 | def setUp(self): 26 | self.outline_mock = mock.Mock() 27 | 28 | def test_setting_color_with_color_provided(self): 29 | Outline._set_color(self.outline_mock, '#000') 30 | self.assertEqual(self.outline_mock.color, (0, 0, 0)) 31 | 32 | def test_setting_color_without_color(self): 33 | Outline._set_color(self.outline_mock, None) 34 | self.assertIsNone(self.outline_mock.color) 35 | 36 | def test_initialization(self): 37 | outline = Outline(2, '#111') 38 | self.assertEqual(outline.width, 2) 39 | self.assertEqual(outline.color, (17, 17, 17)) 40 | 41 | 42 | class TestText(unittest.TestCase): 43 | 44 | def setUp(self): 45 | self.text_mock = mock.Mock() 46 | 47 | # Tests for text handling 48 | 49 | def test_setting_text(self): 50 | Text._set_text(self.text_mock, 'foo') 51 | self.assertEqual(self.text_mock.text, 'foo') 52 | 53 | def test_setting_color_with_color_provided(self): 54 | Text._set_color(self.text_mock, '#000') 55 | self.assertEqual(self.text_mock.color, (0, 0, 0)) 56 | 57 | def test_setting_color_without_color(self): 58 | Text._set_color(self.text_mock, None) 59 | self.assertIsNone(self.text_mock.color) 60 | 61 | def test_initialization(self): 62 | outline = Outline(2, '#111') 63 | text = Text('foo', Font(), '#000', outline) 64 | self.assertEqual(text.text, 'foo') 65 | self.assertIsNotNone(text.font) 66 | self.assertEqual(text.color, (0, 0, 0)) 67 | self.assertEqual(text.outline, outline) 68 | 69 | 70 | class TestMultilineText(unittest.TestCase): 71 | 72 | @mock.patch('nider.mixins.MultilineTextMixin.__init__') 73 | @mock.patch('nider.core.Text.__init__') 74 | def test_proper_inheritance(self, 75 | T_mock, 76 | MTM_mock): 77 | font = Font() 78 | multiline_text = MultilineText(text='foo', font=font, 79 | color='#000', outline=None, 80 | text_width=20, line_padding=5) 81 | T_mock.assert_called_once_with(multiline_text, text='foo', 82 | font=font, 83 | color='#000', outline=None) 84 | MTM_mock.assert_called_once_with(multiline_text, 85 | text_width=20, 86 | line_padding=5) 87 | 88 | 89 | class TestSingleLineTextUnit(unittest.TestCase): 90 | 91 | @mock.patch('nider.core.SingleLineTextUnit._set_height') 92 | @mock.patch('nider.mixins.AlignMixin.__init__') 93 | @mock.patch('nider.core.Text.__init__') 94 | def test_proper_inheritance(self, T_mock, AM_mock, _set_height_mock): 95 | font = Font() 96 | unit = SingleLineTextUnit(text='foo', 97 | font=font, 98 | color='#000', outline=None, align='center') 99 | T_mock.assert_called_once_with(unit, text='foo', 100 | font=font, 101 | color='#000', outline=None 102 | ) 103 | AM_mock.assert_called_once_with(unit, align='center') 104 | 105 | def test_set_height(self): 106 | unit = SingleLineTextUnit('foo', Font()) 107 | # height of the default font 108 | self.assertEqual(unit.height, 11) 109 | 110 | 111 | class TestMultilineTextUnit(unittest.TestCase): 112 | 113 | @mock.patch('nider.core.MultilineTextUnit._set_unit') 114 | @mock.patch('nider.mixins.AlignMixin.__init__') 115 | @mock.patch('nider.core.MultilineText.__init__') 116 | def test_proper_inheritance(self, 117 | MT_mock, 118 | AM_mock, 119 | _set_unit_mock): 120 | font = Font() 121 | unit = MultilineTextUnit(text='foo', font=font, 122 | color='#000', outline=None, 123 | text_width=20, line_padding=5, 124 | align='center') 125 | MT_mock.assert_called_once_with(unit, text='foo', 126 | font=font, 127 | color='#000', 128 | outline=None, 129 | text_width=20, 130 | line_padding=5) 131 | AM_mock.assert_called_once_with(unit, align='center') 132 | 133 | @mock.patch('nider.core.MultilineTextUnit._set_height') 134 | def test_set_unit(self, _set_height_mock): 135 | unit = MultilineTextUnit(text='Lorem imsup dolor si amet', 136 | font=Font(), 137 | text_width=5) 138 | self.assertEqual(unit.wrapped_lines, 139 | ['Lorem', 'imsup', 'dolor', 'si', 'amet']) 140 | 141 | def test_set_height(self): 142 | unit = MultilineTextUnit(text='Lorem imsup dolor si amet', 143 | font=Font(), 144 | text_width=5, 145 | line_padding=6) 146 | self.assertEqual(unit.height, 79) 147 | 148 | 149 | if __name__ == '__main__': 150 | unittest.main() 151 | -------------------------------------------------------------------------------- /tests/test_mixins.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest import mock 3 | 4 | from nider.exceptions import InvalidAlignException 5 | from nider.mixins import MultilineTextMixin, AlignMixin 6 | 7 | 8 | class TestMultilineTextMixinInitializationMethods(unittest.TestCase): 9 | 10 | def setUp(self): 11 | self.mixin_mock = mock.Mock() 12 | 13 | def test_set_text_width_with_valid_config(self): 14 | MultilineTextMixin._set_text_width(self.mixin_mock, 20) 15 | self.assertEqual(self.mixin_mock.text_width, 20) 16 | 17 | def test_set_text_width_with_invalid_config(self): 18 | with self.assertRaises(AttributeError): 19 | MultilineTextMixin._set_text_width(self.mixin_mock, -1) 20 | 21 | 22 | class TestMultilineTextMixin(unittest.TestCase): 23 | 24 | def setUp(self): 25 | self.mixin = MultilineTextMixin(20, 15) 26 | 27 | def test_line_padding(self): 28 | self.assertEqual(self.mixin.line_padding, 15) 29 | 30 | 31 | class TestAlignMixinInitializationMethods(unittest.TestCase): 32 | 33 | def setUp(self): 34 | self.mixin_mock = mock.Mock() 35 | 36 | def test_set_align_with_valid_config(self): 37 | for align in ['right', 'center', 'left']: 38 | with self.subTest(): 39 | AlignMixin._set_align(self.mixin_mock, align) 40 | self.assertEqual(self.mixin_mock.align, align) 41 | 42 | def test_align_with_invalid_config(self): 43 | with self.assertRaises(InvalidAlignException): 44 | AlignMixin._set_align(self.mixin_mock, align='bar') 45 | 46 | 47 | if __name__ == '__main__': 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /tests/test_models.py: -------------------------------------------------------------------------------- 1 | import math 2 | import os 3 | import unittest 4 | from unittest import mock 5 | 6 | from PIL import Image as PIL_Image, ImageDraw, ImageEnhance, ImageFilter 7 | 8 | from nider.core import Font, Outline, MultilineTextUnit 9 | from nider.exceptions import ImageSizeFixedWarning, ImageGeneratorException 10 | from nider.models import (Content, FacebookLandscapePost, FacebookSquarePost, Header, 11 | InstagramLandscapePost, InstagramPortraitPost, InstagramSquarePost, Linkback, Watermark, 12 | Paragraph, TwitterLargeCard, TwitterPost, Image) 13 | from nider.utils import create_test_image, get_random_texture 14 | 15 | 16 | class TestLinkback(unittest.TestCase): 17 | 18 | def setUp(self): 19 | self.linkback = Linkback(text='foo') 20 | 21 | def test_set_height(self): 22 | # height of the default font 23 | self.assertEqual(self.linkback.height, 31) 24 | 25 | 26 | class TestWatermarkBehavior(unittest.TestCase): 27 | 28 | def test_watermark_initialization_with_default_font(self): 29 | with self.assertRaises(ImageGeneratorException): 30 | Watermark(text='foo', font=Font()) 31 | 32 | 33 | class TestContent(unittest.TestCase): 34 | 35 | def test_initialization_without_any_units(self): 36 | with self.assertRaises(ImageGeneratorException): 37 | Content() 38 | 39 | def test_depending_on_opposite_to_bg_color(self): 40 | header = Header(text='foo') 41 | linkback = Linkback(text='bar') 42 | para = Paragraph(text='foo bar') 43 | content = Content(para, header=header, linkback=linkback) 44 | single_unit_content = Content(para) 45 | self.assertTrue(content.depends_on_opposite_to_bg_color) 46 | self.assertTrue(single_unit_content.depends_on_opposite_to_bg_color) 47 | 48 | def test_depending_on_opposite_to_bg_color_with_one_dependency(self): 49 | header = Header(text='foo', color='#000') 50 | linkback = Linkback(text='bar') 51 | para = Paragraph(text='foo bar', color='#000') 52 | content = Content(para, header=header, linkback=linkback) 53 | single_unit_content = Content(para) 54 | self.assertTrue(content.depends_on_opposite_to_bg_color) 55 | self.assertFalse(single_unit_content.depends_on_opposite_to_bg_color) 56 | 57 | def test_depending_on_opposite_to_bg_color_without_dependencies(self): 58 | header = Header(text='foo', color='#000') 59 | linkback = Linkback(text='bar', color='#000') 60 | para = Paragraph(text='foo bar', color='#000') 61 | content = Content(para, header=header, linkback=linkback) 62 | single_unit_content = Content(para) 63 | self.assertFalse(content.depends_on_opposite_to_bg_color) 64 | self.assertFalse(single_unit_content.depends_on_opposite_to_bg_color) 65 | 66 | 67 | class TestContentBehavior(unittest.TestCase): 68 | 69 | def setUp(self): 70 | header = Header(text='foo') 71 | linkback = Linkback(text='bar') 72 | para = Paragraph(text='foo bar') 73 | self.content = Content(para, header=header, linkback=linkback) 74 | 75 | def test_content_height(self): 76 | self.assertIsNotNone(self.content.height) 77 | 78 | 79 | class TestImageInitializationMethods(unittest.TestCase): 80 | 81 | def setUp(self): 82 | self.image_mock = mock.Mock() 83 | 84 | def test_set_content(self): 85 | para = Paragraph(text='foo bar') 86 | content = Content(para) 87 | Image._set_content(self.image_mock, content) 88 | self.assertEqual(self.image_mock.content, content) 89 | 90 | def test_set_fullpath_with_valid_path(self): 91 | fullpath = 'test.png' 92 | Image._set_fullpath(self.image_mock, fullpath) 93 | self.assertEqual(self.image_mock.fullpath, fullpath) 94 | 95 | def test_set_fullpath_with_invalid_path(self): 96 | fullpath = 'non/existent/directory/test.png' 97 | with self.assertRaises(ImageGeneratorException): 98 | Image._set_fullpath(self.image_mock, fullpath) 99 | self.assertNotEqual(self.image_mock.fullpath, fullpath) 100 | 101 | def test_set_image_size(self): 102 | w, h = 500, 500 103 | Image._set_image_size(self.image_mock, w, h) 104 | self.assertEqual(self.image_mock.width, w) 105 | self.assertEqual(self.image_mock.height, h) 106 | 107 | def test_invalid_params_to_set_image_size(self): 108 | invalid_sizes = [(-1, -2), (-1.5, -5.5)] 109 | for invalid_size in invalid_sizes: 110 | with self.subTest(): 111 | with self.assertRaises(AttributeError): 112 | Image._set_image_size(self.image_mock, invalid_size[ 113 | 0], invalid_size[1]) 114 | 115 | def test_set_title_with_title_provided(self): 116 | Image._set_title(self.image_mock, 'foo') 117 | self.assertEqual(self.image_mock.title, 'foo') 118 | 119 | def test_set_title_without_title_provided_but_with_header(self): 120 | header = Header('title') 121 | content = Content(header=header) 122 | Image._set_content(self.image_mock, content) 123 | Image._set_title(self.image_mock, '') 124 | self.assertEqual(self.image_mock.title, 'title') 125 | 126 | def test_set_title_default_behavior(self): 127 | self.image_mock.content.header = None 128 | Image._set_title(self.image_mock, None) 129 | self.assertEqual(self.image_mock.title, '') 130 | 131 | def test_set_description_with_description_provided(self): 132 | Image._set_description(self.image_mock, 'foo') 133 | self.assertEqual(self.image_mock.description, 'foo') 134 | 135 | def test_set_description_without_description_provided_but_with_para(self): 136 | para = Paragraph('description') 137 | content = Content(paragraph=para) 138 | Image._set_content(self.image_mock, content) 139 | Image._set_description(self.image_mock, '') 140 | self.assertEqual(self.image_mock.description, 'description') 141 | 142 | def test_set_description_default_behavior(self): 143 | self.image_mock.content.para = None 144 | Image._set_description(self.image_mock, None) 145 | self.assertEqual(self.image_mock.description, '') 146 | 147 | 148 | class TestImageBaseMethods(unittest.TestCase): 149 | 150 | def setUp(self): 151 | header = Header(text='foo') 152 | linkback = Linkback(text='bar') 153 | para = Paragraph(text='foo bar') 154 | content = Content(para, header=header, linkback=linkback) 155 | fullpath = 'test.png' 156 | self.img = Image(content, fullpath) 157 | 158 | def test_fix_img_size(self): 159 | self.img.content.height = 101 160 | self.img.height = 100 161 | with self.assertWarns(ImageSizeFixedWarning): 162 | self.img._fix_image_size() 163 | self.assertFalse(self.img.content.fits) 164 | self.assertEqual(self.img.height, self.img.content.height) 165 | 166 | def test_no_need_for_fix_img_size(self): 167 | self.img.content.height = 100 168 | self.img.height = 101 169 | self.img._fix_image_size() 170 | self.assertTrue(self.img.content.fits) 171 | self.assertNotEqual(self.img.height, self.img.content.height) 172 | 173 | def test_create_img(self): 174 | self.img._create_image() 175 | self.assertIsInstance(self.img.image, PIL_Image.Image) 176 | 177 | def test_create_draw_object(self): 178 | self.img._create_image() 179 | self.img._create_draw_object() 180 | self.assertIsInstance(self.img.draw, ImageDraw.ImageDraw) 181 | 182 | @mock.patch('nider.models.Image._save') 183 | @mock.patch('nider.models.Image._draw_content') 184 | def test_draw_on_texture(self, 185 | _draw_content_mock, 186 | _save): 187 | self.img.draw_on_texture() 188 | self.assertIsNotNone(self.img.opposite_to_bg_color) 189 | self.assertTrue(_draw_content_mock.called) 190 | 191 | def test_draw_on_texture_with_invalid_texturepath(self): 192 | with self.assertRaises(FileNotFoundError): 193 | self.img.draw_on_texture(texture_path='foo/bar.png') 194 | 195 | @mock.patch('nider.models.Image._save') 196 | @mock.patch('nider.models.Image._draw_content') 197 | def test_draw_on_bg(self, 198 | _draw_content_mock, 199 | _save): 200 | self.img.draw_on_bg() 201 | self.assertIsNotNone(self.img.opposite_to_bg_color) 202 | self.assertTrue(_draw_content_mock.called) 203 | 204 | @mock.patch('nider.models.Image._save') 205 | @mock.patch('nider.models.Image._draw_content') 206 | def test_draw_on_image(self, 207 | _draw_content_mock, 208 | _save): 209 | with create_test_image(): 210 | self.img.draw_on_image( 211 | image_path=os.path.abspath('test.png')) 212 | self.assertIsNotNone(self.img.opposite_to_bg_color) 213 | self.assertTrue(_draw_content_mock.called) 214 | 215 | @mock.patch('PIL.ImageEnhance._Enhance.enhance') 216 | @mock.patch('nider.models.Image._save') 217 | @mock.patch('nider.models.Image._draw_content') 218 | def test_draw_on_image_with_enhancements(self, 219 | _draw_content_mock, 220 | _save, 221 | enhance_mock): 222 | with create_test_image(): 223 | enhance_mock.return_value = PIL_Image.open('test.png') 224 | self.img.draw_on_image( 225 | image_path=os.path.abspath('test.png'), 226 | image_enhancements=((ImageEnhance.Sharpness, 0.5), 227 | (ImageEnhance.Brightness, 0.5))) 228 | self.assertTrue(enhance_mock.called) 229 | self.assertTrue(_draw_content_mock.called) 230 | 231 | @mock.patch('PIL.Image.Image.filter') 232 | @mock.patch('nider.models.Image._save') 233 | @mock.patch('nider.models.Image._draw_content') 234 | def test_draw_on_image_with_filters(self, 235 | _draw_content_mock, 236 | _save, 237 | filter_mock): 238 | filters = (ImageFilter.BLUR, ImageFilter.GaussianBlur(2)) 239 | with create_test_image(): 240 | filter_mock.return_value = PIL_Image.open('test.png') 241 | self.img.draw_on_image( 242 | image_path=os.path.abspath('test.png'), 243 | image_filters=filters) 244 | self.assertTrue(filter_mock.called) 245 | self.assertTrue(_draw_content_mock.called) 246 | 247 | def test_draw_on_image_with_invalid_imagepath(self): 248 | with self.assertRaises(FileNotFoundError): 249 | self.img.draw_on_image('foo/bar.png') 250 | 251 | 252 | class TestImageMethodsThatRequireImageAndDraw(unittest.TestCase): 253 | 254 | def setUp(self): 255 | header = Header(text='foo') 256 | linkback = Linkback(text='bar') 257 | para = Paragraph(text='foo bar') 258 | content = Content(para, header=header, linkback=linkback, padding=45) 259 | self.fullpath = 'test.png' 260 | self.img = Image(content, self.fullpath) 261 | self.img._create_image() 262 | self.img._create_draw_object() 263 | self.img.opposite_to_bg_color = '#000' 264 | 265 | @classmethod 266 | def tearDownClass(self): 267 | fullpath = 'test.png' 268 | os.remove(fullpath) 269 | 270 | @mock.patch('PIL.Image.Image.paste') 271 | def test_fill_img_with_texture(self, mock): 272 | texture = get_random_texture() 273 | self.img._fill_image_with_texture(texture) 274 | self.assertTrue(mock.called) 275 | 276 | @mock.patch('PIL.ImageDraw.ImageDraw.rectangle') 277 | def test_fill_img_with_color(self, mock): 278 | bgcolor = '#000' 279 | self.img.bgcolor = bgcolor 280 | self.img._fill_image_with_color() 281 | mock.assert_called_once_with( 282 | [(0, 0), self.img.image.size], fill=bgcolor) 283 | 284 | @mock.patch('nider.models.Image._draw_unit') 285 | def test_draw_header(self, mock): 286 | self.img._draw_header() 287 | mock.assert_called_once_with(45, 288 | self.img.header) 289 | 290 | @mock.patch('nider.models.Image._draw_unit') 291 | def test_draw_para_with_content_that_fits(self, mock): 292 | self.img._draw_para() 293 | current_h = math.floor( 294 | (self.img.height - self.img.para.height) / 2) 295 | mock.assert_called_once_with(current_h, self.img.para) 296 | 297 | @mock.patch('nider.models.Image._draw_unit') 298 | def test_draw_para_content_with_header_that_does_not_fit(self, mock): 299 | self.img.content.fits = False 300 | self.img._draw_para() 301 | header_with_padding_height = 2 * \ 302 | self.img.content.padding + self.img.header.height 303 | current_h = header_with_padding_height 304 | mock.assert_called_once_with(current_h, self.img.para) 305 | 306 | @mock.patch('nider.models.Image._draw_unit') 307 | def test_draw_para_content_without_header_that_does_not_fit(self, mock): 308 | self.img.content.fits = False 309 | self.img.header = None 310 | self.img._draw_para() 311 | current_h = self.img.content.padding 312 | mock.assert_called_once_with(current_h, self.img.para) 313 | 314 | @mock.patch('PIL.ImageDraw.ImageDraw.text') 315 | def test_draw_linkback(self, mock): 316 | self.img.color = '#000' 317 | aligns = ['center', 'right', 'left'] 318 | for align in aligns: 319 | with self.subTest(): 320 | self.img.linkback.align = align 321 | self.img._draw_linkback() 322 | self.assertTrue(mock.called) 323 | 324 | def test_prepare_content(self): 325 | self.img.content.header.outline = Outline() 326 | self.img.content.para.outline = Outline() 327 | self.img.content.linkback.outline = Outline() 328 | content = self.img.content 329 | self.img._prepare_content() 330 | for unit in [content.header, content.para, content.linkback]: 331 | self.assertIsNotNone(unit.color) 332 | self.assertIsNotNone(unit.outline.color) 333 | 334 | def test_prepare_content_with_None_units(self): 335 | self.img.content.para.outline = Outline() 336 | content = self.img.content 337 | content.header = None 338 | content.linkback = None 339 | self.img._prepare_content() 340 | self.assertIsNotNone(content.para.color) 341 | self.assertIsNotNone(content.para.outline.color) 342 | 343 | @mock.patch('nider.models.Image._draw_linkback') 344 | @mock.patch('nider.models.Image._draw_para') 345 | @mock.patch('nider.models.Image._draw_header') 346 | def test_draw_content(self, _draw_header_mock, 347 | _draw_para_mock, _draw_linkback_mock): 348 | self.img._draw_content() 349 | self.assertTrue(_draw_header_mock.called) 350 | self.assertTrue(_draw_para_mock.called) 351 | self.assertTrue(_draw_linkback_mock.called) 352 | 353 | @mock.patch('PIL.ImageDraw.ImageDraw.text') 354 | def test_draw_unit_with_outline(self, text_mock): 355 | available_outlines = [None, Outline(2, '#111')] 356 | self.img.color = '#000' 357 | start_height = 0 358 | aligns = ['center', 'right', 'left'] 359 | for align in aligns: 360 | for outline in available_outlines: 361 | with self.subTest(): 362 | unit = MultilineTextUnit( 363 | text='foo', outline=outline, 364 | align=align) 365 | self.img._draw_unit(start_height, unit) 366 | self.assertTrue(text_mock.called) 367 | 368 | def test_save(self): 369 | self.img._save() 370 | self.assertTrue(os.path.isfile(self.fullpath)) 371 | 372 | 373 | class TestFacebookSquarePost(unittest.TestCase): 374 | 375 | @mock.patch('nider.models.Image._set_fullpath') 376 | def setUp(self, *mocks): 377 | self.post = FacebookSquarePost(content=mock.Mock(), 378 | fullpath=mock.Mock()) 379 | 380 | def test_size(self): 381 | self.assertEqual(self.post.width, 470) 382 | self.assertEqual(self.post.height, 470) 383 | 384 | 385 | class TestFacebookLandscapePost(unittest.TestCase): 386 | 387 | @mock.patch('nider.models.Image._set_fullpath') 388 | def setUp(self, *mocks): 389 | self.post = FacebookLandscapePost(content=mock.Mock(), 390 | fullpath=mock.Mock()) 391 | 392 | def test_size(self): 393 | self.assertEqual(self.post.width, 1024) 394 | self.assertEqual(self.post.height, 512) 395 | 396 | 397 | class TestTwitterPost(unittest.TestCase): 398 | 399 | @mock.patch('nider.models.Image._set_fullpath') 400 | def setUp(self, *mocks): 401 | self.post = TwitterPost(content=mock.Mock(), 402 | fullpath=mock.Mock()) 403 | 404 | def test_size(self): 405 | self.assertEqual(self.post.width, 1024) 406 | self.assertEqual(self.post.height, 512) 407 | 408 | 409 | class TestTwitterLargeCard(unittest.TestCase): 410 | 411 | @mock.patch('nider.models.Image._set_fullpath') 412 | def setUp(self, *mocks): 413 | self.post = TwitterLargeCard(content=mock.Mock(), 414 | fullpath=mock.Mock()) 415 | 416 | def test_size(self): 417 | self.assertEqual(self.post.width, 506) 418 | self.assertEqual(self.post.height, 506) 419 | 420 | 421 | class TestInstagramSquarePost(unittest.TestCase): 422 | 423 | @mock.patch('nider.models.Image._set_fullpath') 424 | def setUp(self, *mocks): 425 | self.post = InstagramSquarePost(content=mock.Mock(), 426 | fullpath=mock.Mock()) 427 | 428 | def test_size(self): 429 | self.assertEqual(self.post.width, 1080) 430 | self.assertEqual(self.post.height, 1080) 431 | 432 | 433 | class TestInstagramPortraitPost(unittest.TestCase): 434 | 435 | @mock.patch('nider.models.Image._set_fullpath') 436 | def setUp(self, *mocks): 437 | self.post = InstagramPortraitPost(content=mock.Mock(), 438 | fullpath=mock.Mock()) 439 | 440 | def test_size(self): 441 | self.assertEqual(self.post.width, 1080) 442 | self.assertEqual(self.post.height, 1350) 443 | 444 | 445 | class TestInstagramLandscapePost(unittest.TestCase): 446 | 447 | @mock.patch('nider.models.Image._set_fullpath') 448 | def setUp(self, *mocks): 449 | self.post = InstagramLandscapePost(content=mock.Mock(), 450 | fullpath=mock.Mock()) 451 | 452 | def test_size(self): 453 | self.assertEqual(self.post.width, 1080) 454 | self.assertEqual(self.post.height, 566) 455 | 456 | 457 | if __name__ == '__main__': 458 | unittest.main() 459 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | from unittest import mock 4 | 5 | from nider.exceptions import FontNotFoundWarning 6 | from nider.utils import get_font 7 | 8 | 9 | class TestGetFont(unittest.TestCase): 10 | 11 | @mock.patch('PIL.ImageFont.load_default') 12 | def test_with_none_params(self, load_default_mock): 13 | get_font(fontfullpath=None, fontsize=None) 14 | self.assertTrue(load_default_mock.called) 15 | 16 | @mock.patch('PIL.ImageFont.load_default') 17 | def test_with_nonexistent_fontfullpath(self, load_default_mock): 18 | with self.assertWarns(FontNotFoundWarning): 19 | get_font(fontfullpath='foo/bar', fontsize=None) 20 | self.assertTrue(load_default_mock.called) 21 | 22 | @mock.patch('PIL.ImageFont.truetype') 23 | @mock.patch('os.path.exists') 24 | @mock.patch('PIL.ImageFont.load_default') 25 | def test_existent_font(self, load_default_mock, 26 | path_exists_mock, truetype_mock): 27 | path_exists_mock.return_value = True 28 | return_mock = mock.MagicMock() 29 | truetype_mock.return_value = return_mock 30 | font = get_font( 31 | fontfullpath=os.path.abspath('/foo/bar/'), 32 | fontsize=15) 33 | self.assertTrue(font, return_mock) 34 | self.assertFalse(load_default_mock.called) 35 | 36 | 37 | if __name__ == '__main__': 38 | unittest.main() 39 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py36, py37, py38, flake8 3 | 4 | [travis] 5 | python = 6 | 3.8: py38 7 | 3.7: py37 8 | 3.6: py36 9 | 10 | [testenv:flake8] 11 | basepython=python 12 | deps=flake8 13 | commands=flake8 nider/ 14 | 15 | [flake8] 16 | ignore=E501,F401,F841,W504 17 | 18 | [testenv] 19 | setenv = 20 | PYTHONPATH = {toxinidir} 21 | deps = 22 | commands = python setup.py test 23 | 24 | ; If you want to make tox run the tests with the same versions, create a 25 | ; requirements.txt with the pinned versions and uncomment the following lines: 26 | ; deps = 27 | ; -r{toxinidir}/requirements.txt 28 | -------------------------------------------------------------------------------- /travis_pypi_setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """Update encrypted deploy password in Travis config file.""" 4 | 5 | 6 | from __future__ import print_function 7 | import base64 8 | import json 9 | import os 10 | from getpass import getpass 11 | import yaml 12 | from cryptography.hazmat.primitives.serialization import load_pem_public_key 13 | from cryptography.hazmat.backends import default_backend 14 | from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 15 | 16 | 17 | try: 18 | from urllib import urlopen 19 | except ImportError: 20 | from urllib.request import urlopen 21 | 22 | 23 | GITHUB_REPO = 'pythad/nider' 24 | TRAVIS_CONFIG_FILE = os.path.join( 25 | os.path.dirname(os.path.abspath(__file__)), '.travis.yml') 26 | 27 | 28 | def load_key(pubkey): 29 | """Load public RSA key. 30 | 31 | Work around keys with incorrect header/footer format. 32 | 33 | Read more about RSA encryption with cryptography: 34 | https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ 35 | """ 36 | try: 37 | return load_pem_public_key(pubkey.encode(), default_backend()) 38 | except ValueError: 39 | # workaround for https://github.com/travis-ci/travis-api/issues/196 40 | pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') 41 | return load_pem_public_key(pubkey.encode(), default_backend()) 42 | 43 | 44 | def encrypt(pubkey, password): 45 | """Encrypt password using given RSA public key and encode it with base64. 46 | 47 | The encrypted password can only be decrypted by someone with the 48 | private key (in this case, only Travis). 49 | """ 50 | key = load_key(pubkey) 51 | encrypted_password = key.encrypt(password, PKCS1v15()) 52 | return base64.b64encode(encrypted_password) 53 | 54 | 55 | def fetch_public_key(repo): 56 | """Download RSA public key Travis will use for this repo. 57 | 58 | Travis API docs: http://docs.travis-ci.com/api/#repository-keys 59 | """ 60 | keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo) 61 | data = json.loads(urlopen(keyurl).read().decode()) 62 | if 'key' not in data: 63 | errmsg = "Could not find public key for repo: {}.\n".format(repo) 64 | errmsg += "Have you already added your GitHub repo to Travis?" 65 | raise ValueError(errmsg) 66 | return data['key'] 67 | 68 | 69 | def prepend_line(filepath, line): 70 | """Rewrite a file adding a line to its beginning.""" 71 | with open(filepath) as f: 72 | lines = f.readlines() 73 | 74 | lines.insert(0, line) 75 | 76 | with open(filepath, 'w') as f: 77 | f.writelines(lines) 78 | 79 | 80 | def load_yaml_config(filepath): 81 | """Load yaml config file at the given path.""" 82 | with open(filepath) as f: 83 | return yaml.load(f) 84 | 85 | 86 | def save_yaml_config(filepath, config): 87 | """Save yaml config file at the given path.""" 88 | with open(filepath, 'w') as f: 89 | yaml.dump(config, f, default_flow_style=False) 90 | 91 | 92 | def update_travis_deploy_password(encrypted_password): 93 | """Put `encrypted_password` into the deploy section of .travis.yml.""" 94 | config = load_yaml_config(TRAVIS_CONFIG_FILE) 95 | 96 | config['deploy']['password'] = dict(secure=encrypted_password) 97 | 98 | save_yaml_config(TRAVIS_CONFIG_FILE, config) 99 | 100 | line = ('# This file was autogenerated and will overwrite' 101 | ' each time you run travis_pypi_setup.py\n') 102 | prepend_line(TRAVIS_CONFIG_FILE, line) 103 | 104 | 105 | def main(args): 106 | """Add a PyPI password to .travis.yml so that Travis can deploy to PyPI. 107 | 108 | Fetch the Travis public key for the repo, and encrypt the PyPI password 109 | with it before adding, so that only Travis can decrypt and use the PyPI 110 | password. 111 | """ 112 | public_key = fetch_public_key(args.repo) 113 | password = args.password or getpass('PyPI password: ') 114 | update_travis_deploy_password(encrypt(public_key, password.encode())) 115 | print("Wrote encrypted password to .travis.yml -- you're ready to deploy") 116 | 117 | 118 | if '__main__' == __name__: 119 | import argparse 120 | parser = argparse.ArgumentParser(description=__doc__) 121 | parser.add_argument('--repo', default=GITHUB_REPO, 122 | help='GitHub repo (default: %s)' % GITHUB_REPO) 123 | parser.add_argument('--password', 124 | help='PyPI password (will prompt if not provided)') 125 | 126 | args = parser.parse_args() 127 | main(args) 128 | --------------------------------------------------------------------------------