[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: [Wabri, TheJoin95]\nopen_collective: schrodinger-hat\n"
  },
  {
    "path": ".github/workflows/upload-release.yml",
    "content": "name: 'Upload latest release on PyPi'\n\non:\n  workflow_dispatch:\n  release:\n    types: [published]\n\njobs:\n  upload_latest_release:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - name: Upload latest release on PyPi\n        uses: ./\n        env:\n          TWINE_USERNAME: ${{ secrets.TWINE_USERNAME }}\n          TWINE_PASSWORD: ${{ secrets.TWINE_PASSWORD }}\n\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\nPipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# Vim \n.vim/\n*.sw*\n\n# Miscellaneous\n.DS_Store\ncustom_palette.npz\n\n# Testing images\nimages/*resized*\nimages/*avg*\nimages/*processed*\nimages/*quantize*\n\n# pycharm\n.idea/"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\nAll notable changes to this project will be documented in this file.\n\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Code of Conduct\r\n\r\nAll members, committers and volunteers in this project are required to act according to the following Code of Conduct. We ask you to follow these guidelines which help steer our interactions and strive to keep this as a positive and growing project and help us provide and ensure a safe environment for everyone.\r\n\r\nIf you are being harassed, notice that someone else is being harassed, or have any other concerns, please contact us with a PM. Your reports will be taken seriously and not dismissed or argued with.\r\n\r\n## What we believe in and how we act\r\n\r\n* In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. We welcome people regardless of these or other attributes.\r\n* Our community is based on mutual respect, tolerance, and encouragement.\r\n* We believe that a diverse community where people treat each other with respect is stronger, more vibrant and has more potential contributors and more sources for ideas. We aim for more diversity.\r\n* We are kind, welcoming and courteous to everyone.\r\n* We are respectful of others, their positions, their skills, their commitments and their efforts.\r\n* We are attentive in our communications, whether in person or online, and we are tactful and respectful when approaching differing views and experiences.\r\n* We are aware that language shapes reality. Thus, we use inclusive, gender-neutral language in the documents we provide and when we talk to people. When referring to a group of people, we aim to use gender-neutral terms like \"team\", \"folks\" or \"everyone\".\r\n* We respect that people have differences of opinion and criticize constructively.\r\n\r\nIf you are being harassed, notice that someone else is being harassed, or have any other concerns, please contact us with a PM. Your reports will be taken seriously and not dismissed or argued with.\r\n\r\n## Unacceptable Behavior\r\n\r\n* Do not be mean or rude.\r\n* Do not discriminate against anyone.\r\n* Sexism and racism of any kind (including sexist and racist \"jokes\"), demeaning or insulting behaviour and harassment are seen as direct violations to this Code of Conduct. Harassment includes offensive verbal comments related to age, body size, culture, ethnicity, gender expression, gender identity, level of experience, nationality, personal ability or disability, physical appearance, physical or mental difference, race, religion, set of skills, sexual orientation, socio-economic status, and subculture. Harassment also includes sexual images in public spaces, deliberate intimidation, stalking, following, harassing photography or recording, inappropriate physical contact, and unwelcome sexual attention.\r\n* Respect that some individuals and cultures consider the casual use of profanity offensive and off-putting.\r\n* Derailing, tone arguments and otherwise playing on people's desires to be nice are not welcome, especially in discussions about violations to this Code of Conduct.\r\n* Please avoid unstructured critique.\r\n* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behaviour is not welcome.\r\n* Publishing others' private information, such as a physical or electronic address, without explicit permission\r\n* Other conduct which could reasonably be considered inappropriate in a professional setting\r\n\r\n## Responsibilities\r\n\r\nProject maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.\r\n\r\n## Enforcement\r\n\r\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project core team members or owner with a PM. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.\r\n\r\nProject maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.\r\n\r\n## Consequences for Violations\r\n\r\nIf a participant engages in any behaviour violating this Code of Conduct, the core team members and project owner of this project may take any action they deem appropriate, including warning the offender or expulsion from the project, exclusion from any interaction and loss of all rights in this project.\r\n\r\nProject maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.\r\n\r\nDecisions about consequences of violations of this Code of Conduct are made by this projects core team members and project owner as named above and will not be discussed with the person responsible for the violation.\r\n\r\n## Scope\r\n\r\nThis Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.\r\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to ImageGoNord\r\n\r\nThanks for contributing to this project!\r\n\r\nThis is a set of guidelines for contributing to ImageGoNord. Please take a moment to review this document in order to make the contribution process easy and effective for everyone involved.\r\n\r\nFollowing these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue, assessing changes, and helping you finalize your pull requests.\r\n\r\nAs for everything else in the project, the contributions to ImageGoNord are governed by our [Code of Conduct][code-of-conduct]. By participating, you are expected to uphold this code. Please report unacceptable behavior via [email][email].\r\n\r\n## Getting Started\r\n\r\nImageGoNord is an open source project and we love to receive contributions from the community! There are many ways to contribute, from [writing- and improving documentation and tutorials](#documentations), [reporting bugs](#bug-reports), [submitting enhancement suggestions](#enhancement-suggestions) which can be incorporated into ImageGoNord itself by [submitting a pull request](#pull-requests).\r\n\r\nThe project development workflow and process uses [GitHub Issues][gh-issues]- and [Pull Requests][gh-pr] management to track issues and pull requests.\r\n\r\nBefore you continue with this contribution guideslines we highly recommend to read the awesome GitHub [Open Source Guide](https://opensource.guide) on how to [making open source contributions][gh-osguide-contribute].\r\n\r\n### Bug Reports\r\n\r\nA bug is a *demonstrable problem* that is caused by the code in the repository. This section guides you through submitting a bug report for ImageGoNord. Following these guidelines helps maintainers and the community understand your report, reproduce the behavior and find related reports.\r\n\r\n**Do NOT report security vulnerabilities in public issues!** Please contact the core team members and the project owner in a responsible manner by [email][email] only. We will assess the issue as soon as possible on a best-effort basis and will give you an estimate for when we have a fix and release available for an eventual public disclosure.\r\n\r\n* **Use the [GitHub Issues search][gh-issues]** — check if the issue has already been reported. If it has **and the issue is still open**, add a comment to the existing issue instead of opening a new one. If you find a closed issue that seems like it is the same thing that you are experiencing, open a new issue and include a link to the original issue in the body of your new one.\r\n* **Check if the issue has been fixed** — try to reproduce it using the [latest version][version-latest] and [`develop`][branch-develop] branch in the repository.\r\n* **Isolate the problem** — ideally create a [MCVE](#mcve).\r\n\r\nWhen you are creating a bug report, please provide as much detail and context as possible. Fill out [the required template][template-issue], the information it asks for helps maintainers to reproduce the problem and resolve issues faster.\r\n\r\n* **Use a clear and descriptive title** for the issue to identify the problem.\r\n* **Describe the exact steps which reproduce the problem** in as many details as possible.\r\n* **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem.\r\n* **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets. If you are providing snippets in the issue, use [Markdown code blocks][gh-help-markdown-code-blocks] or [attach files to the issue](https://help.github.com/articles/file-attachments-on-issues-and-pull-requests).\r\n\r\nIf possible please provide more context by answering these questions:\r\n\r\n* **Did the problem start happening recently** e.g. after updating to a new version of Nord or was this always a problem?\r\n  * If the problem started happening recently, **can you reproduce the problem in an older version of Nord?**\r\n  * What is the most recent version in which the problem does not happen?\r\n* **Can you reliably reproduce the issue?** If not, please provide details about how often the problem happens and under which conditions it normally happens.\r\n\r\nPlease include details about your configuration and environment:\r\n\r\n* What is the version of ImageGoNord you are running?\r\n* What is the name and the version of your OS?\r\n  * Have you tried to reproduce it on different OS environments and if yes is the behavior the same for all?\r\n\r\n### Enhancement Suggestions\r\n\r\nThis section guides you through submitting an enhancement suggestion, including completely new features and minor improvements to existing functionality or any new [port project][gh-readme-port-projects]. Following these guidelines helps maintainers and the community understand your suggestion and find related suggestions.\r\n\r\n* **Use the [GitHub Issues search][gh-issues]** — check if this enhancement has already been suggested. If it has **and the issue is still open**, add your additions as comment to the existing issue instead of opening a new one.\r\n* **Determine [which repository the contribution belongs to](#port-projects).**\r\n* **Check if the enhancement has already been implemented** — use the [latest version][version-latest] and [`develop`][branch-develop] branch to ensure that the feature or improvement has not already been added.\r\n* **Provide a reduced show case** — ideally create a [MCVE](#mcve).\r\n\r\nBefore creating enhancement suggestions, please check if your idea fits with the scope and provide as much detail and context as possible using a structured layout like the [the issue template][template-issue].\r\n\r\n* **Use a clear and descriptive title** for the issue to identify the suggestion.\r\n* **Provide a step-by-step description of the suggested enhancement** in as many details as possible and provide use-cases.\r\n* **Provide examples to demonstrate the need of an enhancement**. Include copy/pasteable snippets which you use in those examples, use [Markdown code blocks][gh-help-markdown-code-blocks] or [attach files to the issue][gh-help-attach-files].\r\n* **Describe the current behavior** and **explain which behavior you expected to see instead** and why.\r\n* **Explain why this enhancement would be useful** to most ImageGoNord users.\r\n* **Maybe list some other projects where this enhancement exists.**\r\n\r\n### Pull Requests\r\n\r\nThis section guides you through submitting an pull request. Following these guidelines helps maintainers and the community to better understand your code.\r\n\r\n**Please [suggest an enhancement](#enhancement-suggestions) or [report a bug](#bug-reports) first before embarking on any significant pull request** (e.g. implementing features, refactoring code, fixing a bug), otherwise you risk spending a lot of time working on something that the core team members and project owner might not want to merge into the project.\r\n\r\nWhen you are submitting an pull request, please provide as much detail and context as possible. Fill out [the required template][template-pr] to help maintainers to understand your submitted code.\r\n\r\n* **Use a clear and descriptive title for the pull request**\r\n* **Do not include issue numbers in the pull request title** but fill in the metadata section at the top of the [required pull request template][template-pr] making use of the [GitHub issue keywords][gh-help-issue-keywords] to link to specific [enhancement suggestions](#enhancement-suggestions) or [bug reports](#bug-reports).\r\n* **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the change.\r\n* **Make sure to follow the [JavaScript](#javascript-code-style) and [Git commit message](#git-commit-messages) style guides**.\r\n* **Remain focused in scope and avoid to include unrelated commits**.\r\n* **Features and improvements should always be accompanied with tests and documentation**. If the pull request improves the performance consider to include a benchmark test, optimally including a chart.\r\n* **Lint and test before submitting the pull request**.\r\n* **Make sure to create the pull request from a [topic branch][git-docs-branching-workflows]**.\r\n\r\n**All pull requests must be send against the `develop` branch** - Please read the [branch organization](#branch-organization) section below for details about the branching model.\r\n\r\n## Branch Organization\r\n\r\nMore to come\r\n\r\n## How else can I help?\r\n\r\n### Improve Issues\r\n\r\nSome issues are created with missing information, not reproducible, or plain invalid. You can help to make it easier for maintainer to understand and resolve them faster. since handling issues takes a lot of time that could rather spend on writing code.\r\n\r\n### Give Feedback On Issues and Pull Requests\r\n\r\nWe're always looking for more opinions on discussions in issues and pull request reviews which is a good opportunity to influence the future direction of ImageGoNord.\r\n\r\nThe [question][gh-issues-label-question] issue label is a good place to find ongoing discussions and questions.\r\n\r\n## Styleguides\r\n\r\nMore to come\r\n\r\n## MCVE\r\n\r\nA Minimal, Complete, and Verifiable Example.\r\n\r\nWhen [reporting a bug](#bug-reports), somtimes even when [suggestig a enhancement](#enhancement-suggestions), the issue can be processed faster if you provide code for reproduction. That code should be…\r\n\r\n* …Minimal – Use as little code as possible that still produces the same behavior\r\n* …Complete – Provide all parts needed to reproduce the behavior\r\n* …Verifiable – Test the code you're about to provide to make sure it reproduces the behavior\r\n\r\nA MCVE is a common practice like on [Stack Overflow][stackoverflow-mcve] and sometimes it is also called [SSCCE][sscce], a *Short, Self Contained, Correct (Compilable), Example*.\r\n\r\nThe recommened way for GitHub based projects is to create it as [Gist](https://gist.github.com) or new repository, but of course you can [attach it to issues and pull requests as files](https://help.github.com/articles/file-attachments-on-issues-and-pull-requests), use any free code paste- or file hosting service or paste the code in [Markdown code blocks][gh-help-markdown-code-blocks] into the issue.\r\n\r\n### Minimal\r\n\r\nThe more code there is to go through, the less likely developers can understand your enhancement or find the bug. Streamline your example in one of two ways:\r\n\r\n* **Restart from scratch**. Create new code, adding in only what is needed to demonstrate the behavior and is also useful if you can't post the original code publicly for legal or ethical reasons.\r\n* **Divide and conquer**. When you have a small amount of code, but the source of the bug is entirely unclear, start removing code a bit at a time until the problem disappears – then add the last part back and document this behavior to help developers to trace- and debug faster.\r\n\r\n#### Minimal and readable\r\n\r\nMinimal does not mean terse – don't sacrifice communication to brevity. Use consistent naming and indentation following the [styleguide](#styleguides), and include comments if needed to explain portions of the code.\r\n\r\n### Complete\r\n\r\nMake sure all resources and code necessary to reproduce the behavior is included. The problem might not be in the part you suspect it is, but another part entirely.\r\n\r\n### Verifiable\r\n\r\nTo entirely understand your enhancement or bug report, developers will need to verify that it *exists*:\r\n\r\n* **Follow the contribution guidelines regarding the description and details**. Without information developers won't be able to understand and reproduce the behavior.\r\n* **Eliminate any issues that aren't relevant**. Ensure that there are no compile-time errors.\r\n* **Make sure that the example actually reproduces the problem**. Sometimes the bug gets fixed inadvertently or unconsciously while composing the example or does not occur when running on fresh machine environment.\r\n\r\n## Credits\r\n\r\nThanks for the inspirations and attributions to GitHub's [Open Source Guides](https://opensource.guide) and various contribution guides of large open source projects like [Atom][ref-atom-contributing], [React][ref-react-contributing] and [Ruby on Rails][ref-rubyonrails-contributing].\r\n\r\n[branch-develop]: https://github.com/schroedinger-hat/ImageGoNord-pip/tree/develop\r\n[changelog]: https://github.com/schroedinger-hat/ImageGoNord-pip/blob/develop/CHANGELOG.md\r\n[code-of-conduct]: https://github.com/schroedinger-hat/ImageGoNord-pip/blob/develop/CODE_OF_CONDUCT.md\r\n[email]: mailto:scrordinger.hat.show@gmail.com\r\n[gh-help-attach-files]: https://help.github.com/articles/file-attachments-on-issues-and-pull-requests\r\n[gh-help-issue-keywords]: https://help.github.com/articles/closing-issues-using-keywords\r\n[gh-help-markdown-code-blocks]: https://help.github.com/articles/basic-writing-and-formatting-syntax\r\n[gh-issues]: https://github.com/schroedinger-hat/ImageGoNord-pip/issues\r\n[gh-issues-label-question]: https://github.com/schroedinger-hat/ImageGoNord-pip/labels/question\r\n[gh-pr]: https://github.com/schroedinger-hat/ImageGoNord-pip/pulls\r\n[gh-osguide-contribute]: https://opensource.guide/how-to-contribute\r\n[gh-readme-port-projects]: https://github.com/schroedinger-hat/ImageGoNord-pip#port-projects\r\n[git-docs-branching-workflows]: https://git-scm.com/book/en/v2/Git-Branching-Branching-Workflows\r\n[gitflow]: http://nvie.com/posts/a-successful-git-branching-model\r\n[ref-atom-contributing]: https://github.com/atom/atom/blob/main/CONTRIBUTING.md\r\n[ref-react-contributing]: https://facebook.github.io/react/contributing/how-to-contribute.html\r\n[ref-rubyonrails-contributing]: http://guides.rubyonrails.org/contributing_to_ruby_on_rails.html\r\n[semver]: http://semver.org\r\n[stackoverflow-mcve]: https://stackoverflow.com/help/mcve\r\n[sscce]: http://sscce.org\r\n[template-issue]: https://github.com/schroedinger-hat/ImageGoNord-pip/blob/develop/.github/ISSUE_TEMPLATE.md\r\n[template-pr]: https://github.com/schroedinger-hat/ImageGoNord-pip/blob/develop/.github/PULL_REQUEST_TEMPLATE.md\r\n[version-latest]: https://github.com/schroedinger-hat/ImageGoNord-pip/releases/latest\r\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM python:3.9-slim\n\nWORKDIR /app\nCOPY upload-release.sh .\n\nRUN pip install twine && pip install setuptools\n\nRUN chmod +x upload-release.sh\nENTRYPOINT [ \"/app/upload-release.sh\" ]"
  },
  {
    "path": "ImageGoNord/GoNord.py",
    "content": "\nimport base64\nimport os\nfrom io import BytesIO\n\nfrom math import ceil\n\nimport threading\n\nfrom PIL import Image, ImageFilter, ExifTags\n\nimport numpy as np\nimport ffmpeg\nimport uuid\nimport shutil\nimport requests\n\ntry:\n    import torch\n    import skimage.color as convertor\n    import torchvision.transforms as transforms\nexcept ImportError:\n    # AI feature disabled\n    pass\n\n\ntry:\n    import importlib.resources as pkg_resources\nexcept ImportError:\n    # Try backported to PY<37 `importlib_resources`.\n    import importlib_resources as pkg_resources\n\nfrom .palettes import Nord as nord_palette\nfrom .models import PaletteNet as palette_net\n\nfrom ImageGoNord.utility.quantize import quantize_to_palette\nimport ImageGoNord.utility.palette_loader as pl\nfrom ImageGoNord.utility.ConvertUtility import ConvertUtility\n\ntry:\n    from ImageGoNord.utility.model import FeatureEncoder,RecoloringDecoder\nexcept ImportError:\n    # AI feature disabled\n    pass\n\n\nclass NordPaletteFile:\n    \"\"\"\n    A class used to map the nord color-scheme into files.\n    Each file contains the hex of colors\n\n    ...\n\n    Attributes\n    ----------\n    AURORA : str\n        Aurora color-palette\n    FROST : str\n        Frost color-palette\n    POLAR_NIGHT : str\n        Polar night color-palette\n    SNOW_STORM : str\n        Snow Storm color-palette\n\n    \"\"\"\n\n    AURORA = \"Aurora.txt\"\n    FROST = \"Frost.txt\"\n    POLAR_NIGHT = \"PolarNight.txt\"\n    SNOW_STORM = \"SnowStorm.txt\"\n\n\nclass GoNord(object):\n    \"\"\"\n    A class used for converting image to the nord palette\n    It can be used also for converting image to other palette by loading different palette\n\n    This class need Pillow and apply 3 different palette conversion algorithm:\n        - replace pixel by avg area pixel\n        - replace pixel by pixel\n        - apply a filter by using pillow features\n\n    Attributes\n    ----------\n    PALETTE_LOOKUP_PATH : str\n        path to look for finding the palette files (.txt)\n    USE_GAUSSIAN_BLUR : bool\n        enable or disable the blur (in output)\n    USE_AVG_COLOR : bool\n        enable or disable avg algorithm\n    AVG_BOX_DATA : dict\n        params (width and height) of the avg area to be considered\n    AVAILABLE_PALETTE : list\n        loaded palette list\n    PALETTE_DATA : dict\n        available palette data in hex : rgb format\n\n    Methods\n    -------\n    set_palette_lookup_path(self, path)\n        Set the base_path for the palette folder\n\n    set_default_nord_palette(self)\n        Set available palette as the default palette\n\n    get_palette_data(self)\n        Build the palette data from configuration\n\n    add_color_to_palette(self, hex_color)\n        Add hex color to current palette\n\n    reset_palette(self)\n        Reset the available_palette prop\n\n    add_file_to_palette(self, file)\n        Append a custom file to the available palette\n\n    enable_gaussian_blur(self)\n        Enable blur filter\n\n    disable_gaussian_blur(self)\n        disabled blur filter\n\n    open_image(self, path)\n        Load an image using Pillow utility\n\n    resize_image(self, image, w=0, h=0)\n        Resize an image using Pillow utility\n\n    image_to_base64(self, image, extension)\n        Convert a Pillow image to base64 string\n\n    base64_to_image(self, img_b64)\n        Convert a base64 string to a Pillow image\n\n    load_pixel_image(self, opened_image)\n        Load the pixel map of a given Pillow image\n\n    enable_avg_algorithm(self)\n        Enable avg algorithm\n\n    disable_avg_algorithm(self)\n        Disabled avg algorithm\n\n    set_avg_box_data(self, w=-2, h=3)\n        Set the dimension of the AVG area box to use\n\n    quantize_image(self, image, save_path='')\n        Quantize a Pillow image by applying the available palette\n\n    convert_image(self, image, palettedata, save_path='')\n        Process a Pillow image by replacing pixel or by avg algorithm\n\n    save_image_to_file(self, image, path)\n        Save a Pillow image to file\n    \"\"\"\n\n    DEFAULT_PALETTE_PATH = '../palettes/Nord/'\n\n    if (os.path.exists('../palettes/Nord/') == False):\n        pa = pkg_resources.open_text(nord_palette, NordPaletteFile.AURORA)\n        DEFAULT_PALETTE_PATH = os.path.dirname(nord_palette.__file__) + '/'\n\n    PALETTE_LOOKUP_PATH = DEFAULT_PALETTE_PATH\n    USE_GAUSSIAN_BLUR = False\n    USE_AVG_COLOR = False\n    AVG_BOX_DATA = {\"w\": -2, \"h\": 3}\n    TRANSPARENCY_TOLERANCE = 190\n    MAX_THREADS = 10\n\n    EXIF_IGN = \"ImageGoNord by Schroedinger Hat\"\n    EXIF_IGN_AI = \"ImageGoNord AI by Schroedinger Hat\"\n\n    PALETTE_NET_REPO_FOLDER = 'https://github.com/Schroedinger-Hat/ImageGoNord-pip/raw/main/ImageGoNord/models/PaletteNet/'\n\n    AVAILABLE_PALETTE = []\n    PALETTE_DATA = {}\n\n    def __init__(self):\n        \"\"\"Constructor: init variables & config\"\"\"\n        self.set_default_nord_palette()\n        self.set_avg_box_data()\n\n    def set_palette_lookup_path(self, path):\n        \"\"\"Set the base_path for the palette folder\"\"\"\n        self.PALETTE_LOOKUP_PATH = path\n\n    def set_default_nord_palette(self):\n        \"\"\"Set available palette as the default palette\"\"\"\n        self.AVAILABLE_PALETTE = [\n            NordPaletteFile.POLAR_NIGHT,\n            NordPaletteFile.SNOW_STORM,\n            NordPaletteFile.FROST,\n            NordPaletteFile.AURORA,\n        ]\n\n    def get_palette_data(self):\n        \"\"\"\n        Build the palette data from configuration\n\n        Returns\n        -------\n        dict\n            The palette data: keys are hex color code, values are rgb values\n        \"\"\"\n        for palette_file in self.AVAILABLE_PALETTE:\n            hex_colors = pl.import_palette_from_file(\n                self.PALETTE_LOOKUP_PATH + palette_file)\n            for hex_color in hex_colors:\n                self.PALETTE_DATA[hex_color] = pl.export_tripletes_from_color(\n                    hex_color)\n\n        # Delete empty lines, if they exist.\n        if self.PALETTE_DATA.get('') and len(self.PALETTE_DATA['']) == 0:\n            del self.PALETTE_DATA['']\n\n        return self.PALETTE_DATA\n\n    def add_color_to_palette(self, hex_color):\n        self.PALETTE_DATA[hex_color[1:]] = pl.export_tripletes_from_color(hex_color[1:])\n\n    def reset_palette(self):\n        \"\"\"Reset available palette array\"\"\"\n        self.AVAILABLE_PALETTE = []\n        self.PALETTE_DATA = {}\n\n    def add_file_to_palette(self, file):\n        \"\"\"Method for adding file to the available palette\"\"\"\n        self.AVAILABLE_PALETTE.append(file)\n        self.get_palette_data()\n\n    def set_transparency_tolerance(self, tolerance):\n        \"\"\"Method for changing the alpha tolerance\"\"\"\n        self.TRANSPARENCY_TOLERANCE = int(tolerance)\n\n    def enable_gaussian_blur(self):\n        \"\"\"Enable gaussian blur on the output img\"\"\"\n        self.USE_GAUSSIAN_BLUR = True\n\n    def disable_gaussian_blur(self):\n        \"\"\"Disable gaussian blur on the output img\"\"\"\n        self.USE_GAUSSIAN_BLUR = False\n\n    def open_image(self, path):\n        \"\"\"\n        Load an image using Pillow utility\n\n        Parameters\n        ----------\n        path : str\n            the path and the filename where to save the image\n\n        Returns\n        -------\n        pillow image\n            opened image\n        \"\"\"\n        opened_image = Image.open(path)\n        if (type(opened_image.getpixel((0,0))) == int):\n            opened_image = opened_image.convert('RGB')\n        \n        exif = opened_image.getexif()\n        exif[ExifTags.Base.ProcessingSoftware] = self.EXIF_IGN\n\n        return opened_image\n\n    def resize_image(self, image, size=(0, 0)):\n        \"\"\"\n        Resize an image using Pillow utility\n\n        Parameters\n        ----------\n        image : pillow image\n            The source pillow image\n\n        :param size:\n            (width, height) of returning image, using half image size if not specified\n\n        Returns\n        -------\n        pillow image\n            resized image\n        \"\"\"\n\n        if len(size) == 2 and all(size):\n            return image.resize(size)\n\n        w, h = image.size\n        half_size = (round(w / 2), round(h / 2))\n        return image.resize(half_size)\n\n    def image_to_base64(self, image, extension):\n        \"\"\"\n        Convert a Pillow image to base64 string\n\n        Available extension: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html\n\n        Parameters\n        ----------\n        image : pillow image\n            The source pillow image\n        extension : str\n            The extension of the source image (mandatory)\n\n        Returns\n        -------\n        pillow image\n            processed image\n        \"\"\"\n        im_file = BytesIO()\n        exif = image.getexif()\n        image.save(im_file, format=extension, exif=exif)\n        im_bytes = im_file.getvalue()\n        return base64.b64encode(im_bytes)\n\n    def base64_to_image(self, img_b64):\n        \"\"\"\n        Convert a base64 string to a Pillow image\n\n        Parameters\n        ----------\n        img_b64 : str\n            The base64 string representation of the image\n\n        Returns\n        -------\n        pillow image\n            The converted image from base64\n        \"\"\"\n        im_bytes = base64.b64decode(img_b64)\n        im_file = BytesIO(im_bytes)\n        return self.open_image(im_file)\n\n    def load_pixel_image(self, opened_image):\n        \"\"\"\n        Load the pixel map of a given Pillow image\n\n        Parameters\n        ----------\n        image : pillow image\n            The source pillow image\n\n        Returns\n        -------\n        pillow image\n            pixel map of the opened image\n        \"\"\"\n        return opened_image.load()\n\n    def enable_avg_algorithm(self):\n        \"\"\"\n        Enabled avg algorithm\n\n        \"\"\"\n        self.USE_AVG_COLOR = True\n\n    def disable_avg_algorithm(self):\n        \"\"\"\n        Disabled avg algorithm\n\n        \"\"\"\n        self.USE_AVG_COLOR = False\n\n    def set_avg_box_data(self, w=-2, h=2):\n        \"\"\"\n        Set the dimension of the AVG area box to use\n\n        Parameters\n        ----------\n        w : int\n            Box's width\n        h : int\n            Box's height\n\n        \"\"\"\n        self.AVG_BOX_DATA['w'] = w\n        self.AVG_BOX_DATA['h'] = h\n\n    def quantize_image(self, image, fill_color='2E3440', save_path=''):\n        \"\"\"\n        Quantize a Pillow image by applying the available palette\n\n        Parameters\n        ----------\n        image : pillow image\n            The source pillow image\n        fill_color: str\n            Default fill color as foreground\n        save_path : str, optional\n            the path and the filename where to save the image\n\n        Returns\n        -------\n        pillow image\n            quantized image\n        \"\"\"\n\n        data_colors = pl.create_data_colors(self.get_palette_data())\n        while len(data_colors) < 768:\n            data_colors.extend(pl.export_tripletes_from_color(fill_color))\n\n        palimage = Image.new('P', (1, 1))\n        palimage.putpalette(data_colors)\n        quantize_img = quantize_to_palette(image, palimage)\n        exif = quantize_img.getexif()\n        exif[ExifTags.Base.ProcessingSoftware] = self.EXIF_IGN\n\n        if (save_path != ''):\n            self.save_image_to_file(quantize_img, save_path)\n\n        return quantize_img\n\n    def converted_loop(self, is_rgba, pixels, original_pixels, maxRow, maxCol, minRow=0, minCol=0):\n        color_checked = {}\n        for row in range(minRow, maxRow, 1):\n            for col in range(minCol, maxCol, 1):\n                try:\n                    color_to_check = pixels[row, col]\n                except Exception:\n                    continue\n\n                if (is_rgba):\n                    if (color_to_check[3] < self.TRANSPARENCY_TOLERANCE):\n                        continue\n\n                if self.USE_AVG_COLOR == True:\n                    # todo: improve this feature in performance\n                    color_to_check = ConvertUtility.get_avg_color(\n                        pixels=original_pixels, row=row, col=col, w=self.AVG_BOX_DATA['w'], h=self.AVG_BOX_DATA['h'])\n\n                # saving in memory every checked color to improve performance\n                key_color_checked = ','.join(str(e) for e in list(color_to_check))\n                if (key_color_checked in color_checked):\n                    difference = color_checked[key_color_checked]\n                else:\n                    differences = [[ConvertUtility.color_difference(color_to_check, target_value), target_name]\n                                   for target_name, target_value in self.PALETTE_DATA.items()]\n                    differences.sort()\n                    difference = differences[0][1]\n\n                color_checked[key_color_checked] = difference\n                colors_list = self.PALETTE_DATA[difference]\n                if (is_rgba and len(colors_list) == 3):\n                    colors_list.append(color_to_check[3])\n\n                pixels[row, col] = tuple(colors_list)\n        return pixels\n\n    def load_and_save_models(self):\n        rd_model = requests.get(self.PALETTE_NET_REPO_FOLDER + 'RD.state_dict.pt')\n        fe_model = requests.get(self.PALETTE_NET_REPO_FOLDER + 'FE.state_dict.pt')\n\n        with open(os.path.dirname(palette_net.__file__) + '/FE.state_dict.pt', \"wb\") as f:\n            f.write(fe_model.content)\n        \n        with open(os.path.dirname(palette_net.__file__) + '/RD.state_dict.pt', \"wb\") as f:\n            f.write(rd_model.content)\n\n    def convert_image_by_model(self, image, use_model_cpu=False):\n        \"\"\"\n        Process a Pillow image by using a PyTorch model \"PaletteNet\" for recoloring the image\n\n        Parameters\n        ----------\n        image : pillow image\n            The source pillow image\n        use_model_cpu : bool, optional\n            true if using cpu power\n\n        Returns\n        -------\n        pillow image\n            processed image\n        \"\"\"\n        FE = FeatureEncoder() # torch.Size([64, 3, 3, 3])\n        RD = RecoloringDecoder() # torch.Size([530, 256, 3, 3])\n\n        if (\n            os.path.exists(os.path.dirname(palette_net.__file__) + '/FE.state_dict.pt')\n            and os.path.exists(os.path.dirname(palette_net.__file__) + '/RD.state_dict.pt')\n        ):\n            FE.load_state_dict(torch.load(pkg_resources.open_binary(palette_net, \"FE.state_dict.pt\")))\n            RD.load_state_dict(torch.load(pkg_resources.open_binary(palette_net, \"RD.state_dict.pt\")))\n        else:\n            self.load_and_save_models()\n\n        if use_model_cpu:\n            FE.to(\"cpu\")\n            RD.to(\"cpu\")\n\n        lab_image = ((convertor.rgb2lab(np.array(image))) - [50,0,0] ) / [50,127,127]\n\n        img = torch.Tensor(lab_image).permute(2,0,1)\n\n        h = 16*int(img.shape[1]/16)\n        w = 16*int(img.shape[2]/16)\n\n        T = transforms.Resize((h,w))\n\n        img = T(img)\n        img = img.unsqueeze(0)\n        palette = []\n        for hex, rgb_value in self.PALETTE_DATA.items():\n            a = []\n            for j in [2,4,6]:\n                a.append(int(hex[j-2:j],16))\n            palette.append(a)\n\n        try:\n            pal_np = np.array(palette).reshape(1,6,3)/255\n        except:\n            # this feature is limited to 6 colours\n            # we're taking the first six\n            pal_np = np.array(palette[0:6]).reshape(1,6,3)/255\n\n        pal = torch.Tensor((convertor.rgb2lab(pal_np) - [50,0,0] ) / [50,128,128]).unsqueeze(0)\n\n        image = img\n        palette = pal\n        illu = image[:,0:1,:,:]\n\n        with torch.no_grad():\n            c1,c2,c3,c4 = FE(image)\n            out = RD(c1, c2, c3, c4, palette, illu)\n            final_image = torch.cat([(illu+1)*50, out*128],axis = 1).permute(0,2,3,1)[0]\n            # need to convert float value returning in skimage to 0-255 range values for pillow (computer vision / training lib vs pixel operation lib)\n            return Image.fromarray((convertor.lab2rgb(final_image) * 255).astype(np.uint8))\n\n    def convert_image(self, image, save_path='', use_model=False, use_model_cpu=False, parallel_threading=False):\n        \"\"\"\n        Process a Pillow image by replacing pixel or by avg algorithm\n\n        Parameters\n        ----------\n        image : pillow image\n            The source pillow image\n        save_path : str, optional\n            the path and the filename where to save the image\n        use_model : bool, optional\n            true if using ai model\n        use_model_cpu : bool, optional\n            true if using cpu power\n        parallel_threading : bool, optional\n            true to enable multi-thread conversion loop\n\n        Returns\n        -------\n        pillow image\n            processed image\n        \"\"\"\n        self.get_palette_data()\n        original_image = image.copy()\n        original_pixels = self.load_pixel_image(original_image)\n        original_image.close()\n        pixels = self.load_pixel_image(image)\n        is_rgba = (image.mode == 'RGBA')\n        exif = image.getexif()\n        exif[ExifTags.Base.ProcessingSoftware] = self.EXIF_IGN\n\n        if use_model:\n            if torch != None:\n                image = self.convert_image_by_model(image, use_model_cpu)\n                exif = image.getexif()\n                exif[ExifTags.Base.ProcessingSoftware] = self.EXIF_IGN_AI\n            else:\n                print('Please install the dependencies required for the AI feature: pip install image-go-nord[AI]')\n        else:\n            if not parallel_threading:\n                self.converted_loop(is_rgba, pixels, original_pixels, image.size[0], image.size[1])\n            else:\n                step = ceil(image.size[0] / self.MAX_THREADS)\n                threads = []\n                for row in range(step, image.size[0] + step, step):\n                    args = (is_rgba, pixels, original_pixels, row, image.size[1], row - step, 0)\n                    t = threading.Thread(target=self.converted_loop, args=args)\n                    t.daemon = True\n                    t.start()\n                    threads.append(t)\n\n                for t in threads:\n                    t.join(timeout=30)\n\n        if self.USE_GAUSSIAN_BLUR:\n            image = image.filter(ImageFilter.GaussianBlur(1))\n\n        if (save_path != ''):\n            self.save_image_to_file(image, save_path)\n\n        return image\n\n    def save_image_to_file(self, image, path):\n        \"\"\"\n        Save a Pillow image to file\n\n        Parameters\n        ----------\n        image : pillow image\n            The source pillow image\n        path : str\n            the path and the filename where to save the image\n        \"\"\"\n        exif = image.getexif()\n        image.save(path, exif=exif)\n\n\n\n    def get_video_information(self, video_path):\n        \"\"\"\n        Get basic information about the video file\n\n        Parameters\n        ----------\n        video_path : str\n            Path of input video file\n\n        Returns\n        -------\n        tuple\n            The tuple of width, height, avg_framerate, duration, total_frames\n        \"\"\"\n\n        probe = ffmpeg.probe(video_path)\n        video_stream = next(\n                (stream for stream in probe['streams'] if stream['codec_type'] == 'video'),\n                None)\n\n        width = int(video_stream['width'])\n        height = int(video_stream['height'])\n        avg_frame_rate = video_stream['avg_frame_rate'].split('/')\n        framerate = int(avg_frame_rate[0]) / int(1 if avg_frame_rate[1] == 0 else avg_frame_rate[1])\n        duration = float(probe['format']['duration'])\n        total_frames = int(duration * framerate)\n\n        return width, height, round(framerate, 2), duration, total_frames\n\n    def convert_vid_to_np_arr(self, video_path, width, height, start_time, duration):\n        \"\"\"\n        Convert video to array of numpy elements\n\n        Parameters\n        ----------\n        video_path : str\n            Path of input video file\n        width : int\n            Width of video(numpy array width)\n        height: int\n            Height of video(numpy array depth)\n        start_time : int\n            Time to seek forward in the video\n        duration : int\n            Number of frames to capture\n        fill_color: str\n            Default fill color as foreground\n        save_path : str, optional\n            the path and the filename where to save the image\n\n\n        Returns\n        -------\n        ndarray\n            The numpy array of video frames\n        \"\"\"\n        \n        out, _ = (\n            ffmpeg\n            .input(video_path, ss=str(start_time), t=str(duration))\n            .output('pipe:', format='rawvideo', pix_fmt='rgb24', loglevel='quiet')\n            .run(capture_stdout=True)\n        )\n        # Generate numpy array from stdout\n        video_np_arr = (\n            np\n            .frombuffer(out, np.uint8)\n            .reshape([-1, height, width, 3])\n        )\n        return video_np_arr\n\n    def vidwrite(self, fn, cube, images, framerate, start_frame, total_frames, vcodec='libx264'):\n        \"\"\"\n        Generate video from the numpy array\n\n        Parameters\n        ----------\n        fn : str\n            Filename\n        cube : ndarray\n            color map that is generated\n        images: ndarray / list\n            list of frames\n        framerate : float\n            FPS of the video\n        v_codec : str / optional\n            Video codec of the output\n\n        Returns\n        -------\n        None\n            Convert the numpy array to video and save to disk\n        \"\"\"\n        \n        # If images is a list, convert to ndarray\n        if not isinstance(images, np.ndarray):\n            images = np.asarray(images)\n        height, width = images.shape[1:3]\n        process = (\n            ffmpeg\n                .input('pipe:', format='rawvideo', pix_fmt='rgb24', r=framerate, s='{}x{}'.format(width, height))\n                .output(fn, pix_fmt='yuv420p', vcodec=vcodec, loglevel='quiet', tune='fastdecode', preset='ultrafast')\n                .overwrite_output()\n                .run_async(pipe_stdin=True)\n        )\n        for idx, frame in enumerate(images):\n            process.stdin.write(\n                ConvertUtility.convert_palette(cube, frame)\n                    .astype(np.uint8)\n                    .tobytes()\n            )\n        process.stdin.close()\n        process.wait()\n\n    def concat_video(self, uid, out, save_path):\n        \"\"\"\n        Concatenate two videos\n\n        Parameters\n        ----------\n        uid : str\n            Unique identifier for the session\n        out : str\n            Output video file path\n\n        Returns\n        -------\n        None\n            Concatenate two videos and save to disk\n        \"\"\"\n        \n        main = ffmpeg.input(out)\n        temp = ffmpeg.input(os.path.join(save_path, f'temp_{uid}.mp4'))\n        (\n            ffmpeg\n            .filter([main, temp],'concat')\n            .output(os.path.join(save_path, f'output_{uid}.mp4'), pix_fmt='rgb24', loglevel='quiet', tune='fastdecode', preset='ultrafast')\n            .overwrite_output()\n            .run(capture_stdout=True)\n        )\n        os.remove(out)\n        os.remove(os.path.join(save_path, f'temp_{uid}.mp4'))\n        os.rename(os.path.join(save_path, f'output_{uid}.mp4'), out)\n\n    def apply_original_audio(self, _input, _output):\n        \"\"\"\n        Concatenate two videos\n\n        Parameters\n        ----------\n        _input : str\n            Input video file path\n        _output : str\n            Output video file path\n\n        Returns\n        -------\n        None\n            Apply the original audio to the output video\n        \"\"\"\n        tmp_filename = '/tmp/' + str(uuid.uuid4())\n        shutil.copyfile(_output, tmp_filename)\n        output_video_stream = ffmpeg.input(tmp_filename).video\n        input_audio_stream = ffmpeg.input(_input).audio\n        (ffmpeg\n          .output(output_video_stream, input_audio_stream, _output, loglevel='quiet', tune='fastdecode', preset='ultrafast')\n          .overwrite_output()\n          .run()\n        )\n        os.remove(tmp_filename)\n\n    def convert_video(self, _input, palette_name, _frames_per_batch = 200, save_path = '/tmp'):\n        \"\"\"\n        Concatenate two videos\n\n        Parameters\n        ----------\n        _input : str\n            Input video file path\n        palette_name : str\n            Name of palette to choose\n        _frames_per_batch : int / optional\n            Number of frames to keep in a batch\n            Higher number indicates more memory usage but faster execution due to lesser number of parts \n        save_path : str\n            Location where to save the output video\n\n        Returns\n        -------\n        None\n            Convert input video and save to disk\n        \"\"\"\n        # Generate some random unique identifier that is generated for each session for the temporary files.\n        uid = uuid.uuid4()\n        palette = list(self.PALETTE_DATA.values())\n\n        _output = os.path.join(save_path, _input.split('.')[0] + str(uid) +'_converted.mp4')\n        # run once to generate the color map file\n        try:\n            # for all colors (256*256*256) assign color from palette\n            precalculated = np.load(f'{palette_name}.npz')['color_cube']\n        except:\n            pl.generate_color_map(palette, palette_name)\n            precalculated = np.load(f'{palette_name}.npz')['color_cube']\n\n        # Initialize variables for conversion\n        width, height, framerate, duration, total_frames = self.get_video_information(_input)\n\n        frames_per_batch = _frames_per_batch\n        frame_number = 0\n        timestamp = 0\n        batch_dur = frames_per_batch / framerate\n        batch_dur = batch_dur if duration > batch_dur else duration\n\n        # Process the entire video in batches of `frames_per_batch` frames\n        while frame_number < total_frames:\n            np_arr = self.convert_vid_to_np_arr(_input, width, height, timestamp, batch_dur)\n            if os.path.exists(_output):\n                self.vidwrite(os.path.join(save_path, f'temp_{uid}.mp4'), precalculated, np_arr, framerate, frame_number, total_frames)\n                self.concat_video(uid, _output, save_path)\n            else:\n                self.vidwrite(_output, precalculated, np_arr, framerate, frame_number, total_frames)\n            if (total_frames - frame_number) < frames_per_batch:\n                frames_per_batch = total_frames - frame_number\n            frame_number += frames_per_batch\n            duration -= batch_dur\n            timestamp += batch_dur \n            batch_dur = batch_dur if duration > batch_dur else duration\n\n        self.apply_original_audio(_input, _output)\n\n        return _output\n"
  },
  {
    "path": "ImageGoNord/GoNord_test.py",
    "content": "import pytest\nfrom PIL import Image\n\nfrom ImageGoNord import GoNord\n\n\n@pytest.fixture\ndef image():\n    return Image.open(\"images/test-profile.jpg\")\n\n\n@pytest.fixture\ndef go_nord():\n    return GoNord()\n\n\n@pytest.mark.skip()  # this is the \"old\" interface\ndef test_resize_image_with_w_and_h(image, go_nord: GoNord):\n    resized_image = go_nord.resize_image(image, w=20, h=20)\n    assert resized_image.size == (20, 20)\n\n\ndef test_resize_image_with_size(image, go_nord: GoNord):\n    resized_image = go_nord.resize_image(image, size=(20, 20))\n    assert resized_image.size == (20, 20)\n\n\ndef test_resize_image(image: Image, go_nord: GoNord):\n    resized_image = go_nord.resize_image(image)\n    w, h = image.size\n    assert resized_image.size == (round(w / 2), round(h / 2))\n"
  },
  {
    "path": "ImageGoNord/__init__.py",
    "content": "# gonord version\n__version__ = \"1.2.0\"\n\nfrom ImageGoNord.GoNord import *"
  },
  {
    "path": "ImageGoNord/models/PaletteNet/__init__.py",
    "content": ""
  },
  {
    "path": "ImageGoNord/models/__init__.py",
    "content": ""
  },
  {
    "path": "ImageGoNord/palettes/Nord/Aurora.txt",
    "content": "#BF616A\n#D08770\n#EBCB8B\n#A3BE8C\n#B48EAD"
  },
  {
    "path": "ImageGoNord/palettes/Nord/Frost.txt",
    "content": "#8FBCBB\n#88C0D0\n#81A1C1\n#5E81AC"
  },
  {
    "path": "ImageGoNord/palettes/Nord/PolarNight.txt",
    "content": "#2E3440\n#3B4252\n#434C5E\n#4C566A"
  },
  {
    "path": "ImageGoNord/palettes/Nord/SnowStorm.txt",
    "content": "#D8DEE9\n#E5E9F0\n#ECEFF4"
  },
  {
    "path": "ImageGoNord/palettes/Nord/__init__.py",
    "content": ""
  },
  {
    "path": "ImageGoNord/palettes/__init__.py",
    "content": ""
  },
  {
    "path": "ImageGoNord/utility/ConvertUtility.py",
    "content": "# -*- coding: utf-8 -*-\nimport numpy as np\n\nclass ConvertUtility:\n  \"\"\"\n  An utility class used for converting image to the nord palette\n\n  Methods\n  -------\n  color_difference(color1, color2)\n    Find the color difference between the two given colors\n\n  get_avg_color(pixels, row, col, w, h)\n    Get the avg color of a given area and return it as tuple containing rgb\n  \"\"\"\n\n  def color_difference(color1, color2):\n    \"\"\"\n    Find the color difference between the two given colors\n\n    Parameters\n    ----------\n    color1 : tuple\n        color in rgb\n    color2 : tuple\n        color in rgb\n\n    Returns\n    -------\n    tuple\n      the resultant color\n    \"\"\"\n    return sum([abs(component1-component2) for component1, component2 in zip(color1, color2)])\n\n  def get_avg_color(pixels, row, col, w=-2, h=3):\n    \"\"\"\n    Get the avg color of a given area and return it as tuple containing rgb\n\n    Parameters\n    ----------\n    pixels : dict\n      The pixel map of the source image\n    row : int\n      Row counter where to start\n    col : int\n      Col counter where to start\n    w : int\n      Box's wdith\n    h : int\n      Box's height\n\n    Returns\n    -------\n    tuple\n      the resultant color in rgb format\n    \"\"\"\n    average_sum = []\n    for k in range(w, h):\n      for l in range(w, h):\n        try:\n          average_sum.append(pixels[row+k, col+l])\n        except:\n          pass\n\n    size = len(average_sum)\n    if (size <= 0):\n      size = 1\n\n    r = 0\n    g = 0\n    b = 0\n    a = 255\n    for x in average_sum:\n      r += x[0]\n      g += x[1]\n      b += x[2]\n      if (len(x) > 3):\n        a += x[3]\n\n    avg_color = (int(r/size), int(g/size), int(b/size))\n    if (a != 255):\n      avg_color = avg_color + (int(a/size), )\n\n    return avg_color\n  \n  def convert_palette(color_cube, image):\n    \"\"\"Convert frame color palette\n\n    Parameters\n    ----------\n    color_cube: ndarray\n      Color map of RGB colorspace created from palette colors\n    image: ndarray\n      Current frame\n\n    Returns\n    -------\n    ndarray\n      color converted frame\n    \"\"\"\n\n    shape = image.shape[0:2]\n    indices = image.reshape(-1,3)\n    # Pass image colors and retrieve corresponding palette color\n    new_image = color_cube[indices[:,0],indices[:,1],indices[:,2]]\n\n    return new_image.reshape(shape[0],shape[1],3).astype(np.uint8)\n\n"
  },
  {
    "path": "ImageGoNord/utility/__init__.py",
    "content": ""
  },
  {
    "path": "ImageGoNord/utility/model.py",
    "content": "from functools import partial\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import OrderedDict\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nclass Conv2dAuto(nn.Conv2d):    \n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.padding =  (self.kernel_size[0] // 2, self.kernel_size[1] // 2)  #dynamic add padding based on the kernel_size       \nconv3x3 = partial(Conv2dAuto, kernel_size=3, bias=False)      \n\ndef activation_func(activation):   #Activation function as mentioned in the paper - Leaky Relu\n    return  nn.ModuleDict([\n        ['relu', nn.ReLU(inplace=True)],\n        ['leaky_relu', nn.LeakyReLU(negative_slope=0.01, inplace=True)],\n        ['none', nn.Identity()]\n    ])[activation]\n\n\nclass ResidualBlock(nn.Module):    \n    def __init__(self, in_channels, out_channels, activation='relu'):\n        super().__init__()\n        self.in_channels, self.out_channels,self.activation =  in_channels, out_channels, activation\n        self.blocks = nn.Identity()\n        self.shortcut = nn.Identity()\n        self.activate = activation_func(activation)   \n    \n    def forward(self, x):\n        residual = x\n        if self.should_apply_shortcut: residual = self.shortcut(x)\n        x = self.blocks(x)\n        x += residual\n        x = self.activate(x)\n        return x\n    \n    @property\n    def should_apply_shortcut(self):\n        return self.in_channels != self.out_channels\n\nclass ResNetResidualBlock(ResidualBlock):\n    def __init__(self, in_channels, out_channels, expansion=1, downsampling=2, conv=conv3x3, *args, **kwargs):\n        super().__init__(in_channels, out_channels)\n        self.expansion, self.downsampling, self.conv = expansion, downsampling, conv\n        self.shortcut = nn.Sequential(OrderedDict(\n        {\n            'conv' : nn.Conv2d(self.in_channels, self.expanded_channels, kernel_size=1,\n                      stride=self.downsampling, bias=False, padding=0),\n            'bn' : nn.InstanceNorm2d(self.expanded_channels)\n            \n        })) if self.should_apply_shortcut else None       \n        \n    @property\n    def expanded_channels(self):\n        return self.out_channels * self.expansion\n    \n    @property\n    def should_apply_shortcut(self):\n        return self.in_channels != self.expanded_channels\n\ndef conv_bn(in_channels, out_channels, conv, *args, **kwargs):\n    return nn.Sequential(OrderedDict({'conv': conv(in_channels, out_channels, *args, **kwargs), \n                          'bn': nn.InstanceNorm2d(out_channels) }))\n    \nclass ResNetBasicBlock(ResNetResidualBlock):\n    expansion = 1\n    def __init__(self, in_channels, out_channels, activation=nn.LeakyReLU, *args, **kwargs):\n        super().__init__(in_channels, out_channels, *args, **kwargs)\n        self.blocks = nn.Sequential(\n            conv_bn(self.in_channels, self.out_channels,conv=self.conv, bias=False, stride=self.downsampling),\n            activation(negative_slope=0.02),\n            conv_bn(self.out_channels, self.expanded_channels,conv=self.conv, bias=False),\n        )\n\nclass FeatureEncoder(nn.Module):\n\n    def __init__(self,*args,**kwargs):\n        super(FeatureEncoder,self).__init__()\n        \n        self.conv=nn.Conv2d(in_channels=3,out_channels=64,kernel_size=3,stride=1,padding=1)     #3xHxW \n        self.norm=nn.InstanceNorm2d(64)\n        self.pool=nn.MaxPool2d(kernel_size=2, stride=2, padding=0)  \n\n        self.res1 = ResNetBasicBlock(64, 128) \n        self.res2 = ResNetBasicBlock(128, 256)\n        self.res3 = ResNetBasicBlock(256, 512)\n             \n    def forward(self, x):\n        x = F.relu(self.norm(self.conv(x)))\n        c4 = self.pool(x)\n        c3 = self.res1(c4)\n        c2 = self.res2(c3)\n        c1 = self.res3(c2)\n        return c1,c2,c3,c4\n\ndef de_conv(in_channels, out_channels,kernel_size=3):         #deconvolution \n    return nn.Sequential(\n            nn.ConvTranspose2d(in_channels, out_channels,kernel_size=3,stride=2,output_padding=1, padding=1,bias=True),\n            nn.InstanceNorm2d(out_channels),\n            nn.LeakyReLU(negative_slope=0.02,inplace=True)\n        )\n\nclass RecoloringDecoder(nn.Module):\n\n    def __init__(self):\n        super().__init__() \n        self.dconv_up_4 = de_conv(18 + 512, 256)                                              #pt,c1\n        self.dconv_up_3 = de_conv(256 + 256, 128)                                             #c2,d1\n        self.dconv_up_2 = de_conv(18 + 128 + 128, 64)                                         #pt,c3,d2\n        self.dconv_up_1 = de_conv(18 + 64 + 64, 64)                                           #pt,c4,d3\n        self.conv_last = nn.Conv2d(1 + 64, 2, kernel_size=3,padding=1)                        #Illu,d4\n\n    def forward(self, c1, c2, c3, c4, target_palettes_1d, illu):\n        bz, h, w = c1.shape[0], c1.shape[2], c1.shape[3]                                      #1,24,16\n        tp_reshpaed = target_palettes_1d.reshape(bz,18,1,1)\n        tp_c1 = tp_reshpaed.repeat(1,1,h,w)\n\n        x = torch.cat((c1,tp_c1), 1)  \n        x = self.dconv_up_4(x)\n\n        x = torch.cat([c2, x], dim=1)                                                         #c2,d1(x)\n        x = self.dconv_up_3(x)\n\n        bz, h, w = x.shape[0], x.shape[2], x.shape[3]     \n        tp_c3 = tp_reshpaed.repeat(1,1,h,w)\n        x = torch.cat([tp_c3,c3,x], dim=1)                                                    #Pt,c3,x\n        x = self.dconv_up_2(x)\n\n        bz, h, w = x.shape[0], x.shape[2], x.shape[3]\n        tp_c4 = tp_reshpaed.repeat(1,1,h,w)\n        x = torch.cat([tp_c4,c4,x], dim=1)                                                    #Pt,c4,x\n        x = self.dconv_up_1(x)\n\n        illu = illu.view(illu.size(0), 1, illu.size(2), illu.size(3))  \n        x = torch.cat((x, illu), dim = 1)\n                                                             #illu,x\n        x = self.conv_last(x)\n        x = torch.tanh(x)\n        return x"
  },
  {
    "path": "ImageGoNord/utility/palette_loader.py",
    "content": "\"\"\"This is the example module.\n\nThis module does stuff.\n\"\"\"\nfrom os import listdir\nimport numpy as np\n\n\ndef load_palette_set(path):\n    \"\"\"Create a list of every colors set on the path given.\n\n      <Description>\n\n    Parameters\n    ----------\n    <argument name>: <type>\n      <argument description>\n    <argument>: <type>\n      <argument description>\n\n    Returns\n    -------\n    <type>\n      <description>\n    \"\"\"\n    directories = listdir(path)\n\n    palette_list = [palette_file.replace(\n        \".txt\", '') for palette_file in directories]\n\n    return palette_list\n\n\ndef find_palettes(path):\n    \"\"\"Create a set with every palettes stored in the directory given.\n\n      <Description>\n\n    Parameters\n    ----------\n    <argument name>: <type>\n      <argument description>\n    <argument>: <type>\n      <argument description>\n\n    Returns\n    -------\n    <type>\n      <description>\n    \"\"\"\n    palettes = [palette.lower() for palette in listdir(path)]\n    return palettes\n\n\ndef import_palette_from_file(filename):\n    \"\"\"<Short Description>\n\n      <Description>\n\n    Parameters\n    ----------\n    <argument name>: <type>\n      <argument description>\n    <argument>: <type>\n      <argument description>\n\n    Returns\n    -------\n    <type>\n      <description>\n    \"\"\"\n    opened_file = open(filename, \"r\")\n    palette = [line.replace('#', '').replace('\\n', '')\n               for line in opened_file.readlines()]\n    return palette\n\n\ndef create_data_colors(palette):\n    \"\"\"<Short Description>\n\n      <Description>\n\n    Parameters\n    ----------\n    <argument name>: <type>\n      <argument description>\n    <argument>: <type>\n      <argument description>\n\n    Returns\n    -------\n    <type>\n      <description>\n    \"\"\"\n    data = []\n    for color in palette:\n        data.extend((export_tripletes_from_color(color)))\n    return data\n\n\ndef export_tripletes_from_color(hex_color):\n    \"\"\"<Short Description>\n\n      <Description>\n\n    Parameters\n    ----------\n    <argument name>: <type>\n      <argument description>\n    <argument>: <type>\n      <argument description>\n\n    Returns\n    -------\n    <type>\n      <description>\n    \"\"\"\n    hex_triplets = [hex_color[i:i+2] for i in range(0, len(hex_color), 2)]\n    triplets_integer = [int(hex_triplets[i], 16)\n                        for i in range(len(hex_triplets))]\n    return triplets_integer\n\n\ndef generate_color_map(palette, palette_name):\n  \"\"\" Generate a color map\n\n    Generate a color map of entire RGB color space adapted to the color palette\n    The function maps every color to the closest color in the palette before conversion process\n    This increases speed of color conversion as there is only lookups during eecution time\n\n  Parameters\n  ----------\n  palette: ndarray / list\n    Contains the palette in ndarray form(RGB values split)\n  palette_name: string\n    Name of the color palette\n\n  Returns\n  -------\n  None\n    Generates a .npz file and saves it to disk\n  \"\"\"\n  if not isinstance(palette, np.ndarray):\n    palette = np.asarray(palette)\n  precalculated = np.zeros(shape=[256,256,256,3])\n  for i in range(256):\n    for j in range(256):\n      for k in range(256):\n        index = np.argmin(np.sqrt(np.sum(\n            ((palette)-np.array([i,j,k]))**2,\n            axis=1\n          )))\n        precalculated[i,j,k] = palette[index]\n  np.savez_compressed(palette_name, color_cube = precalculated)    "
  },
  {
    "path": "ImageGoNord/utility/quantize.py",
    "content": "\"\"\"This is the example module.\n\nThis module does stuff.\n\"\"\"\n\nfrom PIL import ImageFilter\n\ndef quantize_to_palette(silf, palette):\n    \"\"\"<Short Description>\n\n      <Description>\n\n    Parameters\n    ----------\n    <argument name>: <type>\n      <argument description>\n    <argument>: <type>\n      <argument description>\n\n    Returns\n    -------\n    <type>\n      <description>\n    \"\"\"\n    silf.load()\n    palette.load()\n\n    if palette.mode != \"P\":\n      raise ValueError(\"bad mode for palette image\")\n    if silf.mode != \"RGB\":\n      try:\n        silf = silf.convert(\"RGB\")\n      except Exception as e:\n        print(e)\n        pass\n    if silf.mode != \"RGB\" and silf.mode != \"L\":\n      raise ValueError(\n          \"only RGB or L mode images can be quantized to a palette\"\n      )\n\n    # color quantize, mode P\n    im = silf.quantize(colors=256, method=0, kmeans=5, palette=palette)\n    # convert again from P mode to RGB\n    im = im.convert('RGB')\n\n    return im\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>."
  },
  {
    "path": "MANIFEST.in",
    "content": "include palettes\ninclude models"
  },
  {
    "path": "Pipfile",
    "content": "[[source]]\nname = \"pypi\"\nurl = \"https://pypi.org/simple\"\nverify_ssl = true\n\n[dev-packages]\npylint = \"*\"\nautopep8 = \"*\"\ntwine = \"*\"\n\n[packages]\npillow = \"*\"\n\n[requires]\npython_version = \"3.8\"\n"
  },
  {
    "path": "README.md",
    "content": "# ImageGoNord - RGB image and video to any kind of palette or theme\n\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/image-go-nord)\n[![PyPI](https://img.shields.io/pypi/v/image-go-nord)](https://pypi.org/project/image-go-nord/)\n[![license](https://img.shields.io/badge/license-MIT-green)](https://github.com/schroedinger-Hat/ImageGoNord-pip/blob/main/LICENSE)\n[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/image-go-nord)\n\nA tool that can convert your rgb images to nordtheme, gruvbox, catpuccin and many more palettes.\nVideo included.\n\nThis repository is a python package.\n\nYou can find a demo on [the website](https://ign.schroedinger-hat.org) for testing out the package.\nThe main repository of this whole project is [ImageGoNord](https://github.com/schroedinger-Hat/ImageGoNord).\n\nIt's including an API layer, in case you'd like to set it up also for your project.\n\n### Documentation\n\nYou can find the [documentation into this repository](https://github.com/schroedinger-Hat/ImageGoNord-pip/tree/main/docs) and also on the website.\nIf you have any questions, please reach us at dev@schroedinger-hat.org\n\n### Inspiration\n\nWe are in love with Nordtheme, that is why we created this repository.\n\nOur goal is to make a shortcut to convert anything into any kind of themes, by starting from the images and going to videos.\n<br>An example could be an awesome wallpaper converted into the Nordtheme palette.\n\nWe checked the commnunity and we did not find anything similar or any project that can accomplish this task. So, here we are.\n\nOf course, we resolved the issue for any kind of palette, theme and it's video supported.\n\n### What you can do with this package\n\nYou can convert any image into the nord palette (or others). Here are some examples:\n\n**Original**\n\n[![Original](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test.jpg)](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test.jpg)\n\n\n**Processed with avg algorithm**\n\n[![Original](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-average.jpg)](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-average.jpg)\n\n\n-----\n\n**Original**\n\n[![Original](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile.jpg)](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile.jpg)\n\n\n**Processed with avg algorithm**\n\n[![Original](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile-average.jpg)](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile-average.jpg)\n\n\n### ImageGoNord with AI - PaletteNet\n\nWe implemented the PaletteNet model with PyTorch based on [this implementation](https://github.com/AakritiKinra/PaletteNet-Implementation).\nInside that repository you could find the paper, in case you'd like to develop and train your model.\n\nThere is a lot of room for improvement as the shape of the input is reduced to only 6 colors.\n\nHere are some results that you could compare with other. On our point of view, AI model it seems working great with wallpaper.\n\n**Original**\n\n[![Original](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile.jpg)](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile.jpg)\n\n**AI processed - Aurora palette from Nordtheme**\n\n[![Converted](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile-ai-aurora.jpg)](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile-ai-aurora.jpg)\n\n-----\n\n**Original**\n\n[![Original](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/sh.png)](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/sh.png)\n\n**AI processed - Nordtheme**\n\n[![Converted](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-sh-ai.png)](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-sh-ai.png)\n\n-----\n\n**Original**\n\n[![Original](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/valley.jpg)](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/valley.jpg)\n\n**AI processed - Nordtheme**\n\n[![Converted](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-valley-ai.jpg)](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-valley-ai.jpg)\n\n-----\n\nYou can also convert videos into the nord palette (or others). Here is an example:\n**Original**\n\nhttps://github.com/05Alston/ImageGoNord-pip/assets/89850018/76d4c4a6-9660-4a02-9f46-e5f3f6d0147a\n\n**Processed with algorithm**\n\nhttps://github.com/05Alston/ImageGoNord-pip/assets/89850018/13822280-c019-49b1-92f7-7c658b33a01d\n\n### Core Technical Concepts\n\nWe are using the PIL because it is the most simple library and it is very useful when you need to manipulate some images.\n\nOur goal is also to make this project open source and maintainable by the community. We would love to.\n\n*We believe in the open source community.*\n\n### Getting Started\n\nGetting it from PIP\n\n```\npip install image-go-nord\n```\n\nThen you can use [some example](https://github.com/schroedinger-Hat/ImageGoNord-pip/tree/main/docs/example) to getting started properly!\n\n### Contributing\n- Follow the contributor guidelines\n- Follow the code style / requirements\n- Format for commit messages\n\n# Authors\n\n[TheJoin95](https://github.com/TheJoin95) & [Wabri](https://github.com/Wabri)\n\n### License\n\n[AGPLv3 license](https://github.com/schroedinger-Hat/ImageGoNord-pip/blob/main/LICENSE)\n"
  },
  {
    "path": "action.yml",
    "content": "name: 'Upload latest release on PyPi'\ndescription: 'Upload your release to PyPi package manager'\nruns:\n  using: 'docker'\n  image: 'Dockerfile'"
  },
  {
    "path": "docs/.gitkeep",
    "content": ""
  },
  {
    "path": "docs/README.md",
    "content": "\n# Documentation\n\nThe documentation is under development (as the package) and it is [available also on the website](https://ign.schroedinger-hat.org/documentation/python).\nYou can find some usage and some example under the example folder.\n\n# Class & Methods\n\n## NordPaletteFile:\n\nA class used to map the nord color-scheme into files.  Each file contains the hex code of the nord palette, divided into:\n  - AURORA.txt: Aurora color-palette\n  - FROST.txt: Frost color-palette\n  - POLAR_NIGHT.txt: Polar night color-palette\n  - SNOW_STORM.txt: Snow Storm color-palette\n\n## GoNord\n\nA class used for converting image to the nord palette. It can be used also for converting image to other palette by loading different palette or hex color.\nThis class needs Pillow and apply 3 different palette conversion algorithm:\n  - replace pixel by avg area pixel (convert method)\n  - replace pixel by pixel (convert method)\n  - apply a filter by using pillow features (quantize method)\n\n\n### GoNord Attributes\n\n**PALETTE_LOOKUP_PATH**: str - path to look for finding the palette files (.txt)\n\n**USE_GAUSSIAN_BLUR**: bool - enable or disable the blur (in output)\n\n**USE_AVG_COLOR**: bool - enable or disable avg algorithm\n\n**AVG_BOX_DATA**: dict - params (width and height) of the avg area to be considered\n\n**AVAILABLE_PALETTE**: list - loaded palette list\n\n**PALETTE_DATA**: dict - available palette data in hex : rgb format\n\n\n\n## Methods\n\n### set_palette_lookup_path\nSet the base_path for the palette folder, if different from the default.\n\n`set_palette_lookup_path(self, path)`\n\n-----\n\n\n### set_default_nord_palette\nSet available palette as the default palette.\n\nThe default palette is the full Nordtheme palette.\n\n`set_default_nord_palette(self)`\n\n-----\n\n\n### get_palette_data\nBuild the palette data from configuration\n\n`get_palette_data(self)`\n\n**Returns**: dict - The palette data: keys are hex color code, values are rgb values\n\n-----\n\n\n### add_color_to_palette\nAdd hex color to current palette\n\n`add_color_to_palette(self, hex_color)`\n\n-----\n\n\n### reset_palette\nReset the available_palette prop\n\n`reset_palette(self)`\n\n-----\n\n\n### add_file_to_palette\nAppend a custom file to the available palette\n\n`add_file_to_palette(self, file)`\n\n-----\n\n\n### enable_gaussian_blur\nEnable blur filter\n  \n`enable_gaussian_blur(self)`\n\n-----\n\n\n### disable_gaussian_blur\ndisabled blur filter\n  \n`disable_gaussian_blur(self)`\n\n-----\n\n\n### open_image\nLoad an image using Pillow utility\n  \n`open_image(self, path)`\n\n**Parameters**:\n  - path: str - the path and the filename where to save the image\n\n**Returns**: pillow Image - the opened image\n\n-----\n\n\n### resize_image\nResize an image using Pillow utility\n  \n`resize_image(self, image, w=0, h=0)`\n\n**Parameters**\n- image: pillow image - The source pillow image\n- w: int - New width\n- h: int - New height\n\n**Returns**: pillow image - the resized image\n\n-----\n\n\n### image_to_base64\nConvert a Pillow image to base64 string\n\nAvailable extension: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html\n\n`image_to_base64(self, image, extension)`\n\n**Parameters**\n- image: pillow image - The source pillow image\n- extension: str - The extension of the source image (mandatory)\n\n**Returns**: pillow image - processed image\n\n-----\n\n### base64_to_image\nConvert a base64 string to a Pillow image\n  \n`base64_to_image(self, img_b64)`\n\n**Parameters**\nimg_b64: str - The base64 string representation of the image\n\n**Returns**: pillow image - The converted image from base64\n\n-----\n\n### load_pixel_image\nLoad the pixel map of a given Pillow image\n  \n`load_pixel_image(self, opened_image)`\n\n**Parameters**\n- image: pillow image - The source pillow image\n\n**Returns**: pillow image - pixel map of the opened image\n\n-----\n\n\n### enable_avg_algorithm\nEnable avg algorithm\n  \n`enable_avg_algorithm(self)`\n\n-----\n\n\n### disable_avg_algorithm\n  Disabled avg algorithm\n  \n`disable_avg_algorithm(self)`\n\n-----\n\n\n### set_avg_box_data\nSet the dimension of the AVG area box to use\n  \n`set_avg_box_data(self, w=-2, h=3)`\n\n**Parameters**\n\n- w: int - Box's width\n- h: int - Box's height\n\n\n-----\n\n\n### quantize_image\nQuantize a Pillow image by applying the available palette\n  \n`quantize_image(self, image, save_path='')`\n\n**Parameters**\n- image: pillow image - The source pillow image\n- fill_color: str - Default fill color as foreground\n- save_path : str, optional - the path and the filename where to save the image\n\n**Returns**: pillow image - quantized image\n\n-----\n\n\n### convert_image\nProcess a Pillow image by replacing pixel or by avg algorithm\n  \n`convert_image(self, image, palettedata, save_path='')`\n\n**Parameters**\n\n- image : pillow image - The source pillow image\n- save_path : str, optional - the path and the filename where to save the image\n\n**Returns**: pillow image - processed image\n\n-----\n\n\n### save_image_to_file\n  Save a Pillow image to file\n  \n`save_image_to_file(self, image, path)`\n\n**Parameters**\n- image: pillow image - The source pillow image\n- path: str - the path and the filename where to save the image\n\n-----\n\n## Example\n\n### Import GoNord from ImageGoNord package\n\nfrom ImageGoNord import NordPaletteFile, GoNord\n\n### Use replace pixel by pixel algorithm\n\n```\ngo_nord = GoNord()\nimage = go_nord.open_image(\"images/test.jpg\")\ngo_nord.convert_image(image, save_path='images/test.processed.jpg')\n```\n\n### Use Avg algorithm, clean default palette and add just the POLAR NIGHT and SNOW STORM colors\n```\ngo_nord.enable_avg_algorithm()\ngo_nord.reset_palette()\ngo_nord.add_file_to_palette(NordPaletteFile.POLAR_NIGHT)\ngo_nord.add_file_to_palette(NordPaletteFile.SNOW_STORM)\n// You can add color also by their hex code\ngo_nord.add_color_to_palette('#FF0000')\n\nimage = go_nord.open_image(\"images/test.jpg\")\ngo_nord.convert_image(image, save_path='images/test.avg.jpg')\n```\n\n### Resize image and use the replace pixel by pixel algorithm with less colors\n```\ngo_nord.disable_avg_algorithm()\ngo_nord.reset_palette()\ngo_nord.add_file_to_palette(NordPaletteFile.POLAR_NIGHT)\ngo_nord.add_file_to_palette(NordPaletteFile.SNOW_STORM)\n\nimage = go_nord.open_image(\"images/test.jpg\")\nresized_img = go_nord.resize_image(image)\ngo_nord.convert_image(resized_img, save_path='images/test.resized.jpg')\n```\n\n### Use quantize method for rfiltering an image with the current palette\n```\nimage = go_nord.open_image(\"images/test.jpg\")\ngo_nord.reset_palette()\ngo_nord.set_default_nord_palette()\nquantize_image = go_nord.quantize_image(image, save_path='images/test.quantize.jpg')\n// To base64\ngo_nord.image_to_base64(quantize_image, 'jpeg')\n```\n"
  },
  {
    "path": "docs/example/index.py",
    "content": "from ImageGoNord import NordPaletteFile, GoNord\n\n# E.g. Replace pixel by pixel\ngo_nord = GoNord()\nimage = go_nord.open_image(\"images/test.jpg\")\ngo_nord.convert_image(image, save_path='images/test.processed.jpg')\n\n# E.g. Avg algorithm and less colors\ngo_nord.enable_avg_algorithm()\ngo_nord.reset_palette()\ngo_nord.add_file_to_palette(NordPaletteFile.POLAR_NIGHT)\ngo_nord.add_file_to_palette(NordPaletteFile.SNOW_STORM)\n\n# You can add color also by their hex code\ngo_nord.add_color_to_palette('#FF0000')\n\nimage = go_nord.open_image(\"images/test.jpg\")\ngo_nord.convert_image(image, save_path='images/test.avg.jpg')\n\n# E.g. Resized img no Avg algorithm and less colors\ngo_nord.disable_avg_algorithm()\ngo_nord.reset_palette()\ngo_nord.add_file_to_palette(NordPaletteFile.POLAR_NIGHT)\ngo_nord.add_file_to_palette(NordPaletteFile.SNOW_STORM)\n\nimage = go_nord.open_image(\"images/test.jpg\")\nresized_img = go_nord.resize_image(image)\ngo_nord.convert_image(resized_img, save_path='images/test.resized.jpg')\n\n# E.g. Quantize\n\nimage = go_nord.open_image(\"images/test.jpg\")\ngo_nord.reset_palette()\ngo_nord.set_default_nord_palette()\nquantize_image = go_nord.quantize_image(image, save_path='images/test.quantize.jpg')\n\n# To base64\ngo_nord.image_to_base64(quantize_image, 'jpeg')\n"
  },
  {
    "path": "index.py",
    "content": "from ImageGoNord import NordPaletteFile, GoNord\n\ngo_nord = GoNord()\n\"\"\"image = go_nord.open_image(\"images/test-profile.jpg\")\ngo_nord.convert_image(image, save_path='images/test.processed.jpg') \"\"\"\n\n# E.g. Avg algorithm and less colors\ngo_nord.enable_avg_algorithm()\n# go_nord.reset_palette()\n# go_nord.set_palette_lookup_path('./mypalette')\n# go_nord.add_file_to_palette(NordPaletteFile.POLAR_NIGHT)\n# go_nord.add_file_to_palette(NordPaletteFile.SNOW_STORM)\n# go_nord.add_color_to_palette('#FF0000')\n# go_nord.set_default_nord_palette()\n\nimage = go_nord.open_image(\"images/valley.jpg\")\n# go_nord.convert_image(image, save_path='images/test-valley-avg.jpg')\n\n# E.g. Resized img no Avg algorithm and less colors\ngo_nord.disable_avg_algorithm()\n# go_nord.reset_palette()\n# go_nord.add_file_to_palette(NordPaletteFile.AURORA)\n# go_nord.add_file_to_palette(NordPaletteFile.FROST)\n\nimage = go_nord.open_image(\"images/valley.jpg\")\ngo_nord.convert_image(image, save_path=\"images/test-valley-ai.jpg\", use_model=True)\nexit()\n# output_path = go_nord.convert_video('videos/SampleVideo_720x480.mp4', 'custom_palette', save_path='videos/SampleVideo_converted.mp4')\n\nimage = go_nord.open_image(\"images/test.jpg\")\nresized_img = go_nord.resize_image(image)\ngo_nord.convert_image(resized_img, save_path='images/test.resized.jpg')\n\n# E.g. Quantize\n\nimage = go_nord.open_image(\"images/test.jpg\")\ngo_nord.reset_palette()\ngo_nord.set_default_nord_palette()\nquantize_image = go_nord.quantize_image(image, save_path='images/test.quantize.jpg')\n\n# To base64\ngo_nord.image_to_base64(quantize_image, 'jpeg')\n"
  },
  {
    "path": "setup.py",
    "content": "import pathlib\nfrom setuptools import setup, find_packages\n\nROOT = pathlib.Path('.')\nREADME = (ROOT / \"README.md\").read_text()\n\nsetup(\n    name=\"image-go-nord\",\n    version=\"1.2.0\",\n    description=\"A tool to convert any RGB image or video to any theme or color palette input by the user\",\n    long_description=README,\n    long_description_content_type=\"text/markdown\",\n    url=\"https://github.com/schroedinger-Hat/ImageGoNord-pip\",\n    download_url = 'https://github.com/schroedinger-Hat/ImageGoNord-pip/releases',\n    keywords = ['nordtheme', 'pillow', 'image', 'conversion', 'rgb', 'color-scheme', 'color-palette', 'linux-rice', 'gruvbox', 'catpuccin'],\n    author=\"Schroedinger Hat\",\n    author_email=\"dev@schroedinger-hat.org\",\n    license=\"AGPL-3.0\",\n    classifiers=[\n        'Development Status :: 5 - Production/Stable',\n        'Intended Audience :: Developers',\n        'Topic :: Software Development :: Build Tools',\n        \"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)\",\n        \"Programming Language :: Python :: 3\",\n        \"Programming Language :: Python :: 3.7\"\n    ],\n    project_urls={\n        \"Homepage\": \"https://ign.schroedinger-hat.org\",\n        \"Source\": \"https://github.com/schroedinger-Hat/ImageGoNord-pip\",\n        \"Bug Reports\": \"https://github.com/schroedinger-Hat/ImageGoNord-pip/issues\",\n    },\n    packages=find_packages(),\n    package_data={'': ['*.txt', 'palettes/*.txt']},\n    include_package_data=True,\n    install_requires=[\"Pillow\", \"ffmpeg-python\", \"numpy\", \"requests\"],\n    extras_require = {\n        'AI':  [\"torch\", \"scikit-image\", \"torchvision\"]\n    },\n    python_requires=\">=3.5\"\n)\n"
  },
  {
    "path": "upload-release.sh",
    "content": "#!/bin/sh -l\n\nif $TWINE_USERNAME == \"\" || $TWINE_PASSWORD == \"\"\nthen\n    echo \"No twine info in the environment variables\"\n    return -1\nfi\n\npython setup.py sdist bdist_wheel\necho \"Build finished\"\n\n# TODO: check if dist & build directory are existing and also with the correct files\n\necho \"Twine init\"\ntwine upload dist/*\necho \"Twine ended\""
  }
]