Repository: Schrodinger-Hat/ImageGoNord-pip
Branch: main
Commit: c9881a0d785d
Files: 36
Total size: 18.5 MB
Directory structure:
gitextract_tdy50p_0/
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ └── upload-release.yml
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── ImageGoNord/
│ ├── GoNord.py
│ ├── GoNord_test.py
│ ├── __init__.py
│ ├── models/
│ │ ├── PaletteNet/
│ │ │ ├── FE.state_dict.pt
│ │ │ ├── RD.state_dict.pt
│ │ │ └── __init__.py
│ │ └── __init__.py
│ ├── palettes/
│ │ ├── Nord/
│ │ │ ├── Aurora.txt
│ │ │ ├── Frost.txt
│ │ │ ├── PolarNight.txt
│ │ │ ├── SnowStorm.txt
│ │ │ └── __init__.py
│ │ └── __init__.py
│ └── utility/
│ ├── ConvertUtility.py
│ ├── __init__.py
│ ├── model.py
│ ├── palette_loader.py
│ └── quantize.py
├── LICENSE
├── MANIFEST.in
├── Pipfile
├── README.md
├── action.yml
├── docs/
│ ├── .gitkeep
│ ├── README.md
│ └── example/
│ └── index.py
├── index.py
├── setup.py
└── upload-release.sh
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
github: [Wabri, TheJoin95]
open_collective: schrodinger-hat
================================================
FILE: .github/workflows/upload-release.yml
================================================
name: 'Upload latest release on PyPi'
on:
workflow_dispatch:
release:
types: [published]
jobs:
upload_latest_release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Upload latest release on PyPi
uses: ./
env:
TWINE_USERNAME: ${{ secrets.TWINE_USERNAME }}
TWINE_PASSWORD: ${{ secrets.TWINE_PASSWORD }}
================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# Vim
.vim/
*.sw*
# Miscellaneous
.DS_Store
custom_palette.npz
# Testing images
images/*resized*
images/*avg*
images/*processed*
images/*quantize*
# pycharm
.idea/
================================================
FILE: CHANGELOG.md
================================================
# Changelog
All notable changes to this project will be documented in this file.
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Code of Conduct
All 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.
If 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.
## What we believe in and how we act
* 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.
* Our community is based on mutual respect, tolerance, and encouragement.
* 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.
* We are kind, welcoming and courteous to everyone.
* We are respectful of others, their positions, their skills, their commitments and their efforts.
* We are attentive in our communications, whether in person or online, and we are tactful and respectful when approaching differing views and experiences.
* 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".
* We respect that people have differences of opinion and criticize constructively.
If 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.
## Unacceptable Behavior
* Do not be mean or rude.
* Do not discriminate against anyone.
* 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.
* Respect that some individuals and cultures consider the casual use of profanity offensive and off-putting.
* 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.
* Please avoid unstructured critique.
* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behaviour is not welcome.
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Responsibilities
Project 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.
## Enforcement
Instances 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.
Project 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.
## Consequences for Violations
If 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.
Project 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.
Decisions 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.
## Scope
This 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.
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to ImageGoNord
Thanks for contributing to this project!
This 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.
Following 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.
As 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].
## Getting Started
ImageGoNord 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).
The project development workflow and process uses [GitHub Issues][gh-issues]- and [Pull Requests][gh-pr] management to track issues and pull requests.
Before 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].
### Bug Reports
A 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.
**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.
* **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.
* **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.
* **Isolate the problem** — ideally create a [MCVE](#mcve).
When 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.
* **Use a clear and descriptive title** for the issue to identify the problem.
* **Describe the exact steps which reproduce the problem** in as many details as possible.
* **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem.
* **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).
If possible please provide more context by answering these questions:
* **Did the problem start happening recently** e.g. after updating to a new version of Nord or was this always a problem?
* If the problem started happening recently, **can you reproduce the problem in an older version of Nord?**
* What is the most recent version in which the problem does not happen?
* **Can you reliably reproduce the issue?** If not, please provide details about how often the problem happens and under which conditions it normally happens.
Please include details about your configuration and environment:
* What is the version of ImageGoNord you are running?
* What is the name and the version of your OS?
* Have you tried to reproduce it on different OS environments and if yes is the behavior the same for all?
### Enhancement Suggestions
This 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.
* **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.
* **Determine [which repository the contribution belongs to](#port-projects).**
* **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.
* **Provide a reduced show case** — ideally create a [MCVE](#mcve).
Before 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].
* **Use a clear and descriptive title** for the issue to identify the suggestion.
* **Provide a step-by-step description of the suggested enhancement** in as many details as possible and provide use-cases.
* **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].
* **Describe the current behavior** and **explain which behavior you expected to see instead** and why.
* **Explain why this enhancement would be useful** to most ImageGoNord users.
* **Maybe list some other projects where this enhancement exists.**
### Pull Requests
This section guides you through submitting an pull request. Following these guidelines helps maintainers and the community to better understand your code.
**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.
When 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.
* **Use a clear and descriptive title for the pull request**
* **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).
* **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the change.
* **Make sure to follow the [JavaScript](#javascript-code-style) and [Git commit message](#git-commit-messages) style guides**.
* **Remain focused in scope and avoid to include unrelated commits**.
* **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.
* **Lint and test before submitting the pull request**.
* **Make sure to create the pull request from a [topic branch][git-docs-branching-workflows]**.
**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.
## Branch Organization
More to come
## How else can I help?
### Improve Issues
Some 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.
### Give Feedback On Issues and Pull Requests
We'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.
The [question][gh-issues-label-question] issue label is a good place to find ongoing discussions and questions.
## Styleguides
More to come
## MCVE
A Minimal, Complete, and Verifiable Example.
When [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…
* …Minimal – Use as little code as possible that still produces the same behavior
* …Complete – Provide all parts needed to reproduce the behavior
* …Verifiable – Test the code you're about to provide to make sure it reproduces the behavior
A 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*.
The 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.
### Minimal
The 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:
* **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.
* **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.
#### Minimal and readable
Minimal 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.
### Complete
Make 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.
### Verifiable
To entirely understand your enhancement or bug report, developers will need to verify that it *exists*:
* **Follow the contribution guidelines regarding the description and details**. Without information developers won't be able to understand and reproduce the behavior.
* **Eliminate any issues that aren't relevant**. Ensure that there are no compile-time errors.
* **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.
## Credits
Thanks 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].
[branch-develop]: https://github.com/schroedinger-hat/ImageGoNord-pip/tree/develop
[changelog]: https://github.com/schroedinger-hat/ImageGoNord-pip/blob/develop/CHANGELOG.md
[code-of-conduct]: https://github.com/schroedinger-hat/ImageGoNord-pip/blob/develop/CODE_OF_CONDUCT.md
[email]: mailto:scrordinger.hat.show@gmail.com
[gh-help-attach-files]: https://help.github.com/articles/file-attachments-on-issues-and-pull-requests
[gh-help-issue-keywords]: https://help.github.com/articles/closing-issues-using-keywords
[gh-help-markdown-code-blocks]: https://help.github.com/articles/basic-writing-and-formatting-syntax
[gh-issues]: https://github.com/schroedinger-hat/ImageGoNord-pip/issues
[gh-issues-label-question]: https://github.com/schroedinger-hat/ImageGoNord-pip/labels/question
[gh-pr]: https://github.com/schroedinger-hat/ImageGoNord-pip/pulls
[gh-osguide-contribute]: https://opensource.guide/how-to-contribute
[gh-readme-port-projects]: https://github.com/schroedinger-hat/ImageGoNord-pip#port-projects
[git-docs-branching-workflows]: https://git-scm.com/book/en/v2/Git-Branching-Branching-Workflows
[gitflow]: http://nvie.com/posts/a-successful-git-branching-model
[ref-atom-contributing]: https://github.com/atom/atom/blob/main/CONTRIBUTING.md
[ref-react-contributing]: https://facebook.github.io/react/contributing/how-to-contribute.html
[ref-rubyonrails-contributing]: http://guides.rubyonrails.org/contributing_to_ruby_on_rails.html
[semver]: http://semver.org
[stackoverflow-mcve]: https://stackoverflow.com/help/mcve
[sscce]: http://sscce.org
[template-issue]: https://github.com/schroedinger-hat/ImageGoNord-pip/blob/develop/.github/ISSUE_TEMPLATE.md
[template-pr]: https://github.com/schroedinger-hat/ImageGoNord-pip/blob/develop/.github/PULL_REQUEST_TEMPLATE.md
[version-latest]: https://github.com/schroedinger-hat/ImageGoNord-pip/releases/latest
================================================
FILE: Dockerfile
================================================
FROM python:3.9-slim
WORKDIR /app
COPY upload-release.sh .
RUN pip install twine && pip install setuptools
RUN chmod +x upload-release.sh
ENTRYPOINT [ "/app/upload-release.sh" ]
================================================
FILE: ImageGoNord/GoNord.py
================================================
import base64
import os
from io import BytesIO
from math import ceil
import threading
from PIL import Image, ImageFilter, ExifTags
import numpy as np
import ffmpeg
import uuid
import shutil
import requests
try:
import torch
import skimage.color as convertor
import torchvision.transforms as transforms
except ImportError:
# AI feature disabled
pass
try:
import importlib.resources as pkg_resources
except ImportError:
# Try backported to PY<37 `importlib_resources`.
import importlib_resources as pkg_resources
from .palettes import Nord as nord_palette
from .models import PaletteNet as palette_net
from ImageGoNord.utility.quantize import quantize_to_palette
import ImageGoNord.utility.palette_loader as pl
from ImageGoNord.utility.ConvertUtility import ConvertUtility
try:
from ImageGoNord.utility.model import FeatureEncoder,RecoloringDecoder
except ImportError:
# AI feature disabled
pass
class NordPaletteFile:
"""
A class used to map the nord color-scheme into files.
Each file contains the hex of colors
...
Attributes
----------
AURORA : str
Aurora color-palette
FROST : str
Frost color-palette
POLAR_NIGHT : str
Polar night color-palette
SNOW_STORM : str
Snow Storm color-palette
"""
AURORA = "Aurora.txt"
FROST = "Frost.txt"
POLAR_NIGHT = "PolarNight.txt"
SNOW_STORM = "SnowStorm.txt"
class GoNord(object):
"""
A class used for converting image to the nord palette
It can be used also for converting image to other palette by loading different palette
This class need Pillow and apply 3 different palette conversion algorithm:
- replace pixel by avg area pixel
- replace pixel by pixel
- apply a filter by using pillow features
Attributes
----------
PALETTE_LOOKUP_PATH : str
path to look for finding the palette files (.txt)
USE_GAUSSIAN_BLUR : bool
enable or disable the blur (in output)
USE_AVG_COLOR : bool
enable or disable avg algorithm
AVG_BOX_DATA : dict
params (width and height) of the avg area to be considered
AVAILABLE_PALETTE : list
loaded palette list
PALETTE_DATA : dict
available palette data in hex : rgb format
Methods
-------
set_palette_lookup_path(self, path)
Set the base_path for the palette folder
set_default_nord_palette(self)
Set available palette as the default palette
get_palette_data(self)
Build the palette data from configuration
add_color_to_palette(self, hex_color)
Add hex color to current palette
reset_palette(self)
Reset the available_palette prop
add_file_to_palette(self, file)
Append a custom file to the available palette
enable_gaussian_blur(self)
Enable blur filter
disable_gaussian_blur(self)
disabled blur filter
open_image(self, path)
Load an image using Pillow utility
resize_image(self, image, w=0, h=0)
Resize an image using Pillow utility
image_to_base64(self, image, extension)
Convert a Pillow image to base64 string
base64_to_image(self, img_b64)
Convert a base64 string to a Pillow image
load_pixel_image(self, opened_image)
Load the pixel map of a given Pillow image
enable_avg_algorithm(self)
Enable avg algorithm
disable_avg_algorithm(self)
Disabled avg algorithm
set_avg_box_data(self, w=-2, h=3)
Set the dimension of the AVG area box to use
quantize_image(self, image, save_path='')
Quantize a Pillow image by applying the available palette
convert_image(self, image, palettedata, save_path='')
Process a Pillow image by replacing pixel or by avg algorithm
save_image_to_file(self, image, path)
Save a Pillow image to file
"""
DEFAULT_PALETTE_PATH = '../palettes/Nord/'
if (os.path.exists('../palettes/Nord/') == False):
pa = pkg_resources.open_text(nord_palette, NordPaletteFile.AURORA)
DEFAULT_PALETTE_PATH = os.path.dirname(nord_palette.__file__) + '/'
PALETTE_LOOKUP_PATH = DEFAULT_PALETTE_PATH
USE_GAUSSIAN_BLUR = False
USE_AVG_COLOR = False
AVG_BOX_DATA = {"w": -2, "h": 3}
TRANSPARENCY_TOLERANCE = 190
MAX_THREADS = 10
EXIF_IGN = "ImageGoNord by Schroedinger Hat"
EXIF_IGN_AI = "ImageGoNord AI by Schroedinger Hat"
PALETTE_NET_REPO_FOLDER = 'https://github.com/Schroedinger-Hat/ImageGoNord-pip/raw/main/ImageGoNord/models/PaletteNet/'
AVAILABLE_PALETTE = []
PALETTE_DATA = {}
def __init__(self):
"""Constructor: init variables & config"""
self.set_default_nord_palette()
self.set_avg_box_data()
def set_palette_lookup_path(self, path):
"""Set the base_path for the palette folder"""
self.PALETTE_LOOKUP_PATH = path
def set_default_nord_palette(self):
"""Set available palette as the default palette"""
self.AVAILABLE_PALETTE = [
NordPaletteFile.POLAR_NIGHT,
NordPaletteFile.SNOW_STORM,
NordPaletteFile.FROST,
NordPaletteFile.AURORA,
]
def get_palette_data(self):
"""
Build the palette data from configuration
Returns
-------
dict
The palette data: keys are hex color code, values are rgb values
"""
for palette_file in self.AVAILABLE_PALETTE:
hex_colors = pl.import_palette_from_file(
self.PALETTE_LOOKUP_PATH + palette_file)
for hex_color in hex_colors:
self.PALETTE_DATA[hex_color] = pl.export_tripletes_from_color(
hex_color)
# Delete empty lines, if they exist.
if self.PALETTE_DATA.get('') and len(self.PALETTE_DATA['']) == 0:
del self.PALETTE_DATA['']
return self.PALETTE_DATA
def add_color_to_palette(self, hex_color):
self.PALETTE_DATA[hex_color[1:]] = pl.export_tripletes_from_color(hex_color[1:])
def reset_palette(self):
"""Reset available palette array"""
self.AVAILABLE_PALETTE = []
self.PALETTE_DATA = {}
def add_file_to_palette(self, file):
"""Method for adding file to the available palette"""
self.AVAILABLE_PALETTE.append(file)
self.get_palette_data()
def set_transparency_tolerance(self, tolerance):
"""Method for changing the alpha tolerance"""
self.TRANSPARENCY_TOLERANCE = int(tolerance)
def enable_gaussian_blur(self):
"""Enable gaussian blur on the output img"""
self.USE_GAUSSIAN_BLUR = True
def disable_gaussian_blur(self):
"""Disable gaussian blur on the output img"""
self.USE_GAUSSIAN_BLUR = False
def open_image(self, path):
"""
Load an image using Pillow utility
Parameters
----------
path : str
the path and the filename where to save the image
Returns
-------
pillow image
opened image
"""
opened_image = Image.open(path)
if (type(opened_image.getpixel((0,0))) == int):
opened_image = opened_image.convert('RGB')
exif = opened_image.getexif()
exif[ExifTags.Base.ProcessingSoftware] = self.EXIF_IGN
return opened_image
def resize_image(self, image, size=(0, 0)):
"""
Resize an image using Pillow utility
Parameters
----------
image : pillow image
The source pillow image
:param size:
(width, height) of returning image, using half image size if not specified
Returns
-------
pillow image
resized image
"""
if len(size) == 2 and all(size):
return image.resize(size)
w, h = image.size
half_size = (round(w / 2), round(h / 2))
return image.resize(half_size)
def image_to_base64(self, image, extension):
"""
Convert a Pillow image to base64 string
Available extension: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
Parameters
----------
image : pillow image
The source pillow image
extension : str
The extension of the source image (mandatory)
Returns
-------
pillow image
processed image
"""
im_file = BytesIO()
exif = image.getexif()
image.save(im_file, format=extension, exif=exif)
im_bytes = im_file.getvalue()
return base64.b64encode(im_bytes)
def base64_to_image(self, img_b64):
"""
Convert a base64 string to a Pillow image
Parameters
----------
img_b64 : str
The base64 string representation of the image
Returns
-------
pillow image
The converted image from base64
"""
im_bytes = base64.b64decode(img_b64)
im_file = BytesIO(im_bytes)
return self.open_image(im_file)
def load_pixel_image(self, opened_image):
"""
Load the pixel map of a given Pillow image
Parameters
----------
image : pillow image
The source pillow image
Returns
-------
pillow image
pixel map of the opened image
"""
return opened_image.load()
def enable_avg_algorithm(self):
"""
Enabled avg algorithm
"""
self.USE_AVG_COLOR = True
def disable_avg_algorithm(self):
"""
Disabled avg algorithm
"""
self.USE_AVG_COLOR = False
def set_avg_box_data(self, w=-2, h=2):
"""
Set the dimension of the AVG area box to use
Parameters
----------
w : int
Box's width
h : int
Box's height
"""
self.AVG_BOX_DATA['w'] = w
self.AVG_BOX_DATA['h'] = h
def quantize_image(self, image, fill_color='2E3440', save_path=''):
"""
Quantize a Pillow image by applying the available palette
Parameters
----------
image : pillow image
The source pillow image
fill_color: str
Default fill color as foreground
save_path : str, optional
the path and the filename where to save the image
Returns
-------
pillow image
quantized image
"""
data_colors = pl.create_data_colors(self.get_palette_data())
while len(data_colors) < 768:
data_colors.extend(pl.export_tripletes_from_color(fill_color))
palimage = Image.new('P', (1, 1))
palimage.putpalette(data_colors)
quantize_img = quantize_to_palette(image, palimage)
exif = quantize_img.getexif()
exif[ExifTags.Base.ProcessingSoftware] = self.EXIF_IGN
if (save_path != ''):
self.save_image_to_file(quantize_img, save_path)
return quantize_img
def converted_loop(self, is_rgba, pixels, original_pixels, maxRow, maxCol, minRow=0, minCol=0):
color_checked = {}
for row in range(minRow, maxRow, 1):
for col in range(minCol, maxCol, 1):
try:
color_to_check = pixels[row, col]
except Exception:
continue
if (is_rgba):
if (color_to_check[3] < self.TRANSPARENCY_TOLERANCE):
continue
if self.USE_AVG_COLOR == True:
# todo: improve this feature in performance
color_to_check = ConvertUtility.get_avg_color(
pixels=original_pixels, row=row, col=col, w=self.AVG_BOX_DATA['w'], h=self.AVG_BOX_DATA['h'])
# saving in memory every checked color to improve performance
key_color_checked = ','.join(str(e) for e in list(color_to_check))
if (key_color_checked in color_checked):
difference = color_checked[key_color_checked]
else:
differences = [[ConvertUtility.color_difference(color_to_check, target_value), target_name]
for target_name, target_value in self.PALETTE_DATA.items()]
differences.sort()
difference = differences[0][1]
color_checked[key_color_checked] = difference
colors_list = self.PALETTE_DATA[difference]
if (is_rgba and len(colors_list) == 3):
colors_list.append(color_to_check[3])
pixels[row, col] = tuple(colors_list)
return pixels
def load_and_save_models(self):
rd_model = requests.get(self.PALETTE_NET_REPO_FOLDER + 'RD.state_dict.pt')
fe_model = requests.get(self.PALETTE_NET_REPO_FOLDER + 'FE.state_dict.pt')
with open(os.path.dirname(palette_net.__file__) + '/FE.state_dict.pt', "wb") as f:
f.write(fe_model.content)
with open(os.path.dirname(palette_net.__file__) + '/RD.state_dict.pt', "wb") as f:
f.write(rd_model.content)
def convert_image_by_model(self, image, use_model_cpu=False):
"""
Process a Pillow image by using a PyTorch model "PaletteNet" for recoloring the image
Parameters
----------
image : pillow image
The source pillow image
use_model_cpu : bool, optional
true if using cpu power
Returns
-------
pillow image
processed image
"""
FE = FeatureEncoder() # torch.Size([64, 3, 3, 3])
RD = RecoloringDecoder() # torch.Size([530, 256, 3, 3])
if (
os.path.exists(os.path.dirname(palette_net.__file__) + '/FE.state_dict.pt')
and os.path.exists(os.path.dirname(palette_net.__file__) + '/RD.state_dict.pt')
):
FE.load_state_dict(torch.load(pkg_resources.open_binary(palette_net, "FE.state_dict.pt")))
RD.load_state_dict(torch.load(pkg_resources.open_binary(palette_net, "RD.state_dict.pt")))
else:
self.load_and_save_models()
if use_model_cpu:
FE.to("cpu")
RD.to("cpu")
lab_image = ((convertor.rgb2lab(np.array(image))) - [50,0,0] ) / [50,127,127]
img = torch.Tensor(lab_image).permute(2,0,1)
h = 16*int(img.shape[1]/16)
w = 16*int(img.shape[2]/16)
T = transforms.Resize((h,w))
img = T(img)
img = img.unsqueeze(0)
palette = []
for hex, rgb_value in self.PALETTE_DATA.items():
a = []
for j in [2,4,6]:
a.append(int(hex[j-2:j],16))
palette.append(a)
try:
pal_np = np.array(palette).reshape(1,6,3)/255
except:
# this feature is limited to 6 colours
# we're taking the first six
pal_np = np.array(palette[0:6]).reshape(1,6,3)/255
pal = torch.Tensor((convertor.rgb2lab(pal_np) - [50,0,0] ) / [50,128,128]).unsqueeze(0)
image = img
palette = pal
illu = image[:,0:1,:,:]
with torch.no_grad():
c1,c2,c3,c4 = FE(image)
out = RD(c1, c2, c3, c4, palette, illu)
final_image = torch.cat([(illu+1)*50, out*128],axis = 1).permute(0,2,3,1)[0]
# need to convert float value returning in skimage to 0-255 range values for pillow (computer vision / training lib vs pixel operation lib)
return Image.fromarray((convertor.lab2rgb(final_image) * 255).astype(np.uint8))
def convert_image(self, image, save_path='', use_model=False, use_model_cpu=False, parallel_threading=False):
"""
Process a Pillow image by replacing pixel or by avg algorithm
Parameters
----------
image : pillow image
The source pillow image
save_path : str, optional
the path and the filename where to save the image
use_model : bool, optional
true if using ai model
use_model_cpu : bool, optional
true if using cpu power
parallel_threading : bool, optional
true to enable multi-thread conversion loop
Returns
-------
pillow image
processed image
"""
self.get_palette_data()
original_image = image.copy()
original_pixels = self.load_pixel_image(original_image)
original_image.close()
pixels = self.load_pixel_image(image)
is_rgba = (image.mode == 'RGBA')
exif = image.getexif()
exif[ExifTags.Base.ProcessingSoftware] = self.EXIF_IGN
if use_model:
if torch != None:
image = self.convert_image_by_model(image, use_model_cpu)
exif = image.getexif()
exif[ExifTags.Base.ProcessingSoftware] = self.EXIF_IGN_AI
else:
print('Please install the dependencies required for the AI feature: pip install image-go-nord[AI]')
else:
if not parallel_threading:
self.converted_loop(is_rgba, pixels, original_pixels, image.size[0], image.size[1])
else:
step = ceil(image.size[0] / self.MAX_THREADS)
threads = []
for row in range(step, image.size[0] + step, step):
args = (is_rgba, pixels, original_pixels, row, image.size[1], row - step, 0)
t = threading.Thread(target=self.converted_loop, args=args)
t.daemon = True
t.start()
threads.append(t)
for t in threads:
t.join(timeout=30)
if self.USE_GAUSSIAN_BLUR:
image = image.filter(ImageFilter.GaussianBlur(1))
if (save_path != ''):
self.save_image_to_file(image, save_path)
return image
def save_image_to_file(self, image, path):
"""
Save a Pillow image to file
Parameters
----------
image : pillow image
The source pillow image
path : str
the path and the filename where to save the image
"""
exif = image.getexif()
image.save(path, exif=exif)
def get_video_information(self, video_path):
"""
Get basic information about the video file
Parameters
----------
video_path : str
Path of input video file
Returns
-------
tuple
The tuple of width, height, avg_framerate, duration, total_frames
"""
probe = ffmpeg.probe(video_path)
video_stream = next(
(stream for stream in probe['streams'] if stream['codec_type'] == 'video'),
None)
width = int(video_stream['width'])
height = int(video_stream['height'])
avg_frame_rate = video_stream['avg_frame_rate'].split('/')
framerate = int(avg_frame_rate[0]) / int(1 if avg_frame_rate[1] == 0 else avg_frame_rate[1])
duration = float(probe['format']['duration'])
total_frames = int(duration * framerate)
return width, height, round(framerate, 2), duration, total_frames
def convert_vid_to_np_arr(self, video_path, width, height, start_time, duration):
"""
Convert video to array of numpy elements
Parameters
----------
video_path : str
Path of input video file
width : int
Width of video(numpy array width)
height: int
Height of video(numpy array depth)
start_time : int
Time to seek forward in the video
duration : int
Number of frames to capture
fill_color: str
Default fill color as foreground
save_path : str, optional
the path and the filename where to save the image
Returns
-------
ndarray
The numpy array of video frames
"""
out, _ = (
ffmpeg
.input(video_path, ss=str(start_time), t=str(duration))
.output('pipe:', format='rawvideo', pix_fmt='rgb24', loglevel='quiet')
.run(capture_stdout=True)
)
# Generate numpy array from stdout
video_np_arr = (
np
.frombuffer(out, np.uint8)
.reshape([-1, height, width, 3])
)
return video_np_arr
def vidwrite(self, fn, cube, images, framerate, start_frame, total_frames, vcodec='libx264'):
"""
Generate video from the numpy array
Parameters
----------
fn : str
Filename
cube : ndarray
color map that is generated
images: ndarray / list
list of frames
framerate : float
FPS of the video
v_codec : str / optional
Video codec of the output
Returns
-------
None
Convert the numpy array to video and save to disk
"""
# If images is a list, convert to ndarray
if not isinstance(images, np.ndarray):
images = np.asarray(images)
height, width = images.shape[1:3]
process = (
ffmpeg
.input('pipe:', format='rawvideo', pix_fmt='rgb24', r=framerate, s='{}x{}'.format(width, height))
.output(fn, pix_fmt='yuv420p', vcodec=vcodec, loglevel='quiet', tune='fastdecode', preset='ultrafast')
.overwrite_output()
.run_async(pipe_stdin=True)
)
for idx, frame in enumerate(images):
process.stdin.write(
ConvertUtility.convert_palette(cube, frame)
.astype(np.uint8)
.tobytes()
)
process.stdin.close()
process.wait()
def concat_video(self, uid, out, save_path):
"""
Concatenate two videos
Parameters
----------
uid : str
Unique identifier for the session
out : str
Output video file path
Returns
-------
None
Concatenate two videos and save to disk
"""
main = ffmpeg.input(out)
temp = ffmpeg.input(os.path.join(save_path, f'temp_{uid}.mp4'))
(
ffmpeg
.filter([main, temp],'concat')
.output(os.path.join(save_path, f'output_{uid}.mp4'), pix_fmt='rgb24', loglevel='quiet', tune='fastdecode', preset='ultrafast')
.overwrite_output()
.run(capture_stdout=True)
)
os.remove(out)
os.remove(os.path.join(save_path, f'temp_{uid}.mp4'))
os.rename(os.path.join(save_path, f'output_{uid}.mp4'), out)
def apply_original_audio(self, _input, _output):
"""
Concatenate two videos
Parameters
----------
_input : str
Input video file path
_output : str
Output video file path
Returns
-------
None
Apply the original audio to the output video
"""
tmp_filename = '/tmp/' + str(uuid.uuid4())
shutil.copyfile(_output, tmp_filename)
output_video_stream = ffmpeg.input(tmp_filename).video
input_audio_stream = ffmpeg.input(_input).audio
(ffmpeg
.output(output_video_stream, input_audio_stream, _output, loglevel='quiet', tune='fastdecode', preset='ultrafast')
.overwrite_output()
.run()
)
os.remove(tmp_filename)
def convert_video(self, _input, palette_name, _frames_per_batch = 200, save_path = '/tmp'):
"""
Concatenate two videos
Parameters
----------
_input : str
Input video file path
palette_name : str
Name of palette to choose
_frames_per_batch : int / optional
Number of frames to keep in a batch
Higher number indicates more memory usage but faster execution due to lesser number of parts
save_path : str
Location where to save the output video
Returns
-------
None
Convert input video and save to disk
"""
# Generate some random unique identifier that is generated for each session for the temporary files.
uid = uuid.uuid4()
palette = list(self.PALETTE_DATA.values())
_output = os.path.join(save_path, _input.split('.')[0] + str(uid) +'_converted.mp4')
# run once to generate the color map file
try:
# for all colors (256*256*256) assign color from palette
precalculated = np.load(f'{palette_name}.npz')['color_cube']
except:
pl.generate_color_map(palette, palette_name)
precalculated = np.load(f'{palette_name}.npz')['color_cube']
# Initialize variables for conversion
width, height, framerate, duration, total_frames = self.get_video_information(_input)
frames_per_batch = _frames_per_batch
frame_number = 0
timestamp = 0
batch_dur = frames_per_batch / framerate
batch_dur = batch_dur if duration > batch_dur else duration
# Process the entire video in batches of `frames_per_batch` frames
while frame_number < total_frames:
np_arr = self.convert_vid_to_np_arr(_input, width, height, timestamp, batch_dur)
if os.path.exists(_output):
self.vidwrite(os.path.join(save_path, f'temp_{uid}.mp4'), precalculated, np_arr, framerate, frame_number, total_frames)
self.concat_video(uid, _output, save_path)
else:
self.vidwrite(_output, precalculated, np_arr, framerate, frame_number, total_frames)
if (total_frames - frame_number) < frames_per_batch:
frames_per_batch = total_frames - frame_number
frame_number += frames_per_batch
duration -= batch_dur
timestamp += batch_dur
batch_dur = batch_dur if duration > batch_dur else duration
self.apply_original_audio(_input, _output)
return _output
================================================
FILE: ImageGoNord/GoNord_test.py
================================================
import pytest
from PIL import Image
from ImageGoNord import GoNord
@pytest.fixture
def image():
return Image.open("images/test-profile.jpg")
@pytest.fixture
def go_nord():
return GoNord()
@pytest.mark.skip() # this is the "old" interface
def test_resize_image_with_w_and_h(image, go_nord: GoNord):
resized_image = go_nord.resize_image(image, w=20, h=20)
assert resized_image.size == (20, 20)
def test_resize_image_with_size(image, go_nord: GoNord):
resized_image = go_nord.resize_image(image, size=(20, 20))
assert resized_image.size == (20, 20)
def test_resize_image(image: Image, go_nord: GoNord):
resized_image = go_nord.resize_image(image)
w, h = image.size
assert resized_image.size == (round(w / 2), round(h / 2))
================================================
FILE: ImageGoNord/__init__.py
================================================
# gonord version
__version__ = "1.2.0"
from ImageGoNord.GoNord import *
================================================
FILE: ImageGoNord/models/PaletteNet/FE.state_dict.pt
================================================
[File too large to display: 18.4 MB]
================================================
FILE: ImageGoNord/models/PaletteNet/__init__.py
================================================
================================================
FILE: ImageGoNord/models/__init__.py
================================================
================================================
FILE: ImageGoNord/palettes/Nord/Aurora.txt
================================================
#BF616A
#D08770
#EBCB8B
#A3BE8C
#B48EAD
================================================
FILE: ImageGoNord/palettes/Nord/Frost.txt
================================================
#8FBCBB
#88C0D0
#81A1C1
#5E81AC
================================================
FILE: ImageGoNord/palettes/Nord/PolarNight.txt
================================================
#2E3440
#3B4252
#434C5E
#4C566A
================================================
FILE: ImageGoNord/palettes/Nord/SnowStorm.txt
================================================
#D8DEE9
#E5E9F0
#ECEFF4
================================================
FILE: ImageGoNord/palettes/Nord/__init__.py
================================================
================================================
FILE: ImageGoNord/palettes/__init__.py
================================================
================================================
FILE: ImageGoNord/utility/ConvertUtility.py
================================================
# -*- coding: utf-8 -*-
import numpy as np
class ConvertUtility:
"""
An utility class used for converting image to the nord palette
Methods
-------
color_difference(color1, color2)
Find the color difference between the two given colors
get_avg_color(pixels, row, col, w, h)
Get the avg color of a given area and return it as tuple containing rgb
"""
def color_difference(color1, color2):
"""
Find the color difference between the two given colors
Parameters
----------
color1 : tuple
color in rgb
color2 : tuple
color in rgb
Returns
-------
tuple
the resultant color
"""
return sum([abs(component1-component2) for component1, component2 in zip(color1, color2)])
def get_avg_color(pixels, row, col, w=-2, h=3):
"""
Get the avg color of a given area and return it as tuple containing rgb
Parameters
----------
pixels : dict
The pixel map of the source image
row : int
Row counter where to start
col : int
Col counter where to start
w : int
Box's wdith
h : int
Box's height
Returns
-------
tuple
the resultant color in rgb format
"""
average_sum = []
for k in range(w, h):
for l in range(w, h):
try:
average_sum.append(pixels[row+k, col+l])
except:
pass
size = len(average_sum)
if (size <= 0):
size = 1
r = 0
g = 0
b = 0
a = 255
for x in average_sum:
r += x[0]
g += x[1]
b += x[2]
if (len(x) > 3):
a += x[3]
avg_color = (int(r/size), int(g/size), int(b/size))
if (a != 255):
avg_color = avg_color + (int(a/size), )
return avg_color
def convert_palette(color_cube, image):
"""Convert frame color palette
Parameters
----------
color_cube: ndarray
Color map of RGB colorspace created from palette colors
image: ndarray
Current frame
Returns
-------
ndarray
color converted frame
"""
shape = image.shape[0:2]
indices = image.reshape(-1,3)
# Pass image colors and retrieve corresponding palette color
new_image = color_cube[indices[:,0],indices[:,1],indices[:,2]]
return new_image.reshape(shape[0],shape[1],3).astype(np.uint8)
================================================
FILE: ImageGoNord/utility/__init__.py
================================================
================================================
FILE: ImageGoNord/utility/model.py
================================================
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
device = "cuda" if torch.cuda.is_available() else "cpu"
class Conv2dAuto(nn.Conv2d):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.padding = (self.kernel_size[0] // 2, self.kernel_size[1] // 2) #dynamic add padding based on the kernel_size
conv3x3 = partial(Conv2dAuto, kernel_size=3, bias=False)
def activation_func(activation): #Activation function as mentioned in the paper - Leaky Relu
return nn.ModuleDict([
['relu', nn.ReLU(inplace=True)],
['leaky_relu', nn.LeakyReLU(negative_slope=0.01, inplace=True)],
['none', nn.Identity()]
])[activation]
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, activation='relu'):
super().__init__()
self.in_channels, self.out_channels,self.activation = in_channels, out_channels, activation
self.blocks = nn.Identity()
self.shortcut = nn.Identity()
self.activate = activation_func(activation)
def forward(self, x):
residual = x
if self.should_apply_shortcut: residual = self.shortcut(x)
x = self.blocks(x)
x += residual
x = self.activate(x)
return x
@property
def should_apply_shortcut(self):
return self.in_channels != self.out_channels
class ResNetResidualBlock(ResidualBlock):
def __init__(self, in_channels, out_channels, expansion=1, downsampling=2, conv=conv3x3, *args, **kwargs):
super().__init__(in_channels, out_channels)
self.expansion, self.downsampling, self.conv = expansion, downsampling, conv
self.shortcut = nn.Sequential(OrderedDict(
{
'conv' : nn.Conv2d(self.in_channels, self.expanded_channels, kernel_size=1,
stride=self.downsampling, bias=False, padding=0),
'bn' : nn.InstanceNorm2d(self.expanded_channels)
})) if self.should_apply_shortcut else None
@property
def expanded_channels(self):
return self.out_channels * self.expansion
@property
def should_apply_shortcut(self):
return self.in_channels != self.expanded_channels
def conv_bn(in_channels, out_channels, conv, *args, **kwargs):
return nn.Sequential(OrderedDict({'conv': conv(in_channels, out_channels, *args, **kwargs),
'bn': nn.InstanceNorm2d(out_channels) }))
class ResNetBasicBlock(ResNetResidualBlock):
expansion = 1
def __init__(self, in_channels, out_channels, activation=nn.LeakyReLU, *args, **kwargs):
super().__init__(in_channels, out_channels, *args, **kwargs)
self.blocks = nn.Sequential(
conv_bn(self.in_channels, self.out_channels,conv=self.conv, bias=False, stride=self.downsampling),
activation(negative_slope=0.02),
conv_bn(self.out_channels, self.expanded_channels,conv=self.conv, bias=False),
)
class FeatureEncoder(nn.Module):
def __init__(self,*args,**kwargs):
super(FeatureEncoder,self).__init__()
self.conv=nn.Conv2d(in_channels=3,out_channels=64,kernel_size=3,stride=1,padding=1) #3xHxW
self.norm=nn.InstanceNorm2d(64)
self.pool=nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
self.res1 = ResNetBasicBlock(64, 128)
self.res2 = ResNetBasicBlock(128, 256)
self.res3 = ResNetBasicBlock(256, 512)
def forward(self, x):
x = F.relu(self.norm(self.conv(x)))
c4 = self.pool(x)
c3 = self.res1(c4)
c2 = self.res2(c3)
c1 = self.res3(c2)
return c1,c2,c3,c4
def de_conv(in_channels, out_channels,kernel_size=3): #deconvolution
return nn.Sequential(
nn.ConvTranspose2d(in_channels, out_channels,kernel_size=3,stride=2,output_padding=1, padding=1,bias=True),
nn.InstanceNorm2d(out_channels),
nn.LeakyReLU(negative_slope=0.02,inplace=True)
)
class RecoloringDecoder(nn.Module):
def __init__(self):
super().__init__()
self.dconv_up_4 = de_conv(18 + 512, 256) #pt,c1
self.dconv_up_3 = de_conv(256 + 256, 128) #c2,d1
self.dconv_up_2 = de_conv(18 + 128 + 128, 64) #pt,c3,d2
self.dconv_up_1 = de_conv(18 + 64 + 64, 64) #pt,c4,d3
self.conv_last = nn.Conv2d(1 + 64, 2, kernel_size=3,padding=1) #Illu,d4
def forward(self, c1, c2, c3, c4, target_palettes_1d, illu):
bz, h, w = c1.shape[0], c1.shape[2], c1.shape[3] #1,24,16
tp_reshpaed = target_palettes_1d.reshape(bz,18,1,1)
tp_c1 = tp_reshpaed.repeat(1,1,h,w)
x = torch.cat((c1,tp_c1), 1)
x = self.dconv_up_4(x)
x = torch.cat([c2, x], dim=1) #c2,d1(x)
x = self.dconv_up_3(x)
bz, h, w = x.shape[0], x.shape[2], x.shape[3]
tp_c3 = tp_reshpaed.repeat(1,1,h,w)
x = torch.cat([tp_c3,c3,x], dim=1) #Pt,c3,x
x = self.dconv_up_2(x)
bz, h, w = x.shape[0], x.shape[2], x.shape[3]
tp_c4 = tp_reshpaed.repeat(1,1,h,w)
x = torch.cat([tp_c4,c4,x], dim=1) #Pt,c4,x
x = self.dconv_up_1(x)
illu = illu.view(illu.size(0), 1, illu.size(2), illu.size(3))
x = torch.cat((x, illu), dim = 1)
#illu,x
x = self.conv_last(x)
x = torch.tanh(x)
return x
================================================
FILE: ImageGoNord/utility/palette_loader.py
================================================
"""This is the example module.
This module does stuff.
"""
from os import listdir
import numpy as np
def load_palette_set(path):
"""Create a list of every colors set on the path given.
<Description>
Parameters
----------
<argument name>: <type>
<argument description>
<argument>: <type>
<argument description>
Returns
-------
<type>
<description>
"""
directories = listdir(path)
palette_list = [palette_file.replace(
".txt", '') for palette_file in directories]
return palette_list
def find_palettes(path):
"""Create a set with every palettes stored in the directory given.
<Description>
Parameters
----------
<argument name>: <type>
<argument description>
<argument>: <type>
<argument description>
Returns
-------
<type>
<description>
"""
palettes = [palette.lower() for palette in listdir(path)]
return palettes
def import_palette_from_file(filename):
"""<Short Description>
<Description>
Parameters
----------
<argument name>: <type>
<argument description>
<argument>: <type>
<argument description>
Returns
-------
<type>
<description>
"""
opened_file = open(filename, "r")
palette = [line.replace('#', '').replace('\n', '')
for line in opened_file.readlines()]
return palette
def create_data_colors(palette):
"""<Short Description>
<Description>
Parameters
----------
<argument name>: <type>
<argument description>
<argument>: <type>
<argument description>
Returns
-------
<type>
<description>
"""
data = []
for color in palette:
data.extend((export_tripletes_from_color(color)))
return data
def export_tripletes_from_color(hex_color):
"""<Short Description>
<Description>
Parameters
----------
<argument name>: <type>
<argument description>
<argument>: <type>
<argument description>
Returns
-------
<type>
<description>
"""
hex_triplets = [hex_color[i:i+2] for i in range(0, len(hex_color), 2)]
triplets_integer = [int(hex_triplets[i], 16)
for i in range(len(hex_triplets))]
return triplets_integer
def generate_color_map(palette, palette_name):
""" Generate a color map
Generate a color map of entire RGB color space adapted to the color palette
The function maps every color to the closest color in the palette before conversion process
This increases speed of color conversion as there is only lookups during eecution time
Parameters
----------
palette: ndarray / list
Contains the palette in ndarray form(RGB values split)
palette_name: string
Name of the color palette
Returns
-------
None
Generates a .npz file and saves it to disk
"""
if not isinstance(palette, np.ndarray):
palette = np.asarray(palette)
precalculated = np.zeros(shape=[256,256,256,3])
for i in range(256):
for j in range(256):
for k in range(256):
index = np.argmin(np.sqrt(np.sum(
((palette)-np.array([i,j,k]))**2,
axis=1
)))
precalculated[i,j,k] = palette[index]
np.savez_compressed(palette_name, color_cube = precalculated)
================================================
FILE: ImageGoNord/utility/quantize.py
================================================
"""This is the example module.
This module does stuff.
"""
from PIL import ImageFilter
def quantize_to_palette(silf, palette):
"""<Short Description>
<Description>
Parameters
----------
<argument name>: <type>
<argument description>
<argument>: <type>
<argument description>
Returns
-------
<type>
<description>
"""
silf.load()
palette.load()
if palette.mode != "P":
raise ValueError("bad mode for palette image")
if silf.mode != "RGB":
try:
silf = silf.convert("RGB")
except Exception as e:
print(e)
pass
if silf.mode != "RGB" and silf.mode != "L":
raise ValueError(
"only RGB or L mode images can be quantized to a palette"
)
# color quantize, mode P
im = silf.quantize(colors=256, method=0, kmeans=5, palette=palette)
# convert again from P mode to RGB
im = im.convert('RGB')
return im
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
================================================
FILE: MANIFEST.in
================================================
include palettes
include models
================================================
FILE: Pipfile
================================================
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
pylint = "*"
autopep8 = "*"
twine = "*"
[packages]
pillow = "*"
[requires]
python_version = "3.8"
================================================
FILE: README.md
================================================
# ImageGoNord - RGB image and video to any kind of palette or theme

[](https://pypi.org/project/image-go-nord/)
[](https://github.com/schroedinger-Hat/ImageGoNord-pip/blob/main/LICENSE)
[](https://spectrum.chat/image-go-nord)
A tool that can convert your rgb images to nordtheme, gruvbox, catpuccin and many more palettes.
Video included.
This repository is a python package.
You can find a demo on [the website](https://ign.schroedinger-hat.org) for testing out the package.
The main repository of this whole project is [ImageGoNord](https://github.com/schroedinger-Hat/ImageGoNord).
It's including an API layer, in case you'd like to set it up also for your project.
### Documentation
You can find the [documentation into this repository](https://github.com/schroedinger-Hat/ImageGoNord-pip/tree/main/docs) and also on the website.
If you have any questions, please reach us at dev@schroedinger-hat.org
### Inspiration
We are in love with Nordtheme, that is why we created this repository.
Our goal is to make a shortcut to convert anything into any kind of themes, by starting from the images and going to videos.
<br>An example could be an awesome wallpaper converted into the Nordtheme palette.
We checked the commnunity and we did not find anything similar or any project that can accomplish this task. So, here we are.
Of course, we resolved the issue for any kind of palette, theme and it's video supported.
### What you can do with this package
You can convert any image into the nord palette (or others). Here are some examples:
**Original**
[](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test.jpg)
**Processed with avg algorithm**
[](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-average.jpg)
-----
**Original**
[](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile.jpg)
**Processed with avg algorithm**
[](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile-average.jpg)
### ImageGoNord with AI - PaletteNet
We implemented the PaletteNet model with PyTorch based on [this implementation](https://github.com/AakritiKinra/PaletteNet-Implementation).
Inside that repository you could find the paper, in case you'd like to develop and train your model.
There is a lot of room for improvement as the shape of the input is reduced to only 6 colors.
Here are some results that you could compare with other. On our point of view, AI model it seems working great with wallpaper.
**Original**
[](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile.jpg)
**AI processed - Aurora palette from Nordtheme**
[](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-profile-ai-aurora.jpg)
-----
**Original**
[](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/sh.png)
**AI processed - Nordtheme**
[](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-sh-ai.png)
-----
**Original**
[](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/valley.jpg)
**AI processed - Nordtheme**
[](https://raw.githubusercontent.com/schroedinger-Hat/ImageGoNord-pip/main/images/test-valley-ai.jpg)
-----
You can also convert videos into the nord palette (or others). Here is an example:
**Original**
https://github.com/05Alston/ImageGoNord-pip/assets/89850018/76d4c4a6-9660-4a02-9f46-e5f3f6d0147a
**Processed with algorithm**
https://github.com/05Alston/ImageGoNord-pip/assets/89850018/13822280-c019-49b1-92f7-7c658b33a01d
### Core Technical Concepts
We are using the PIL because it is the most simple library and it is very useful when you need to manipulate some images.
Our goal is also to make this project open source and maintainable by the community. We would love to.
*We believe in the open source community.*
### Getting Started
Getting it from PIP
```
pip install image-go-nord
```
Then you can use [some example](https://github.com/schroedinger-Hat/ImageGoNord-pip/tree/main/docs/example) to getting started properly!
### Contributing
- Follow the contributor guidelines
- Follow the code style / requirements
- Format for commit messages
# Authors
[TheJoin95](https://github.com/TheJoin95) & [Wabri](https://github.com/Wabri)
### License
[AGPLv3 license](https://github.com/schroedinger-Hat/ImageGoNord-pip/blob/main/LICENSE)
================================================
FILE: action.yml
================================================
name: 'Upload latest release on PyPi'
description: 'Upload your release to PyPi package manager'
runs:
using: 'docker'
image: 'Dockerfile'
================================================
FILE: docs/.gitkeep
================================================
================================================
FILE: docs/README.md
================================================
# Documentation
The documentation is under development (as the package) and it is [available also on the website](https://ign.schroedinger-hat.org/documentation/python).
You can find some usage and some example under the example folder.
# Class & Methods
## NordPaletteFile:
A class used to map the nord color-scheme into files. Each file contains the hex code of the nord palette, divided into:
- AURORA.txt: Aurora color-palette
- FROST.txt: Frost color-palette
- POLAR_NIGHT.txt: Polar night color-palette
- SNOW_STORM.txt: Snow Storm color-palette
## GoNord
A 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.
This class needs Pillow and apply 3 different palette conversion algorithm:
- replace pixel by avg area pixel (convert method)
- replace pixel by pixel (convert method)
- apply a filter by using pillow features (quantize method)
### GoNord Attributes
**PALETTE_LOOKUP_PATH**: str - path to look for finding the palette files (.txt)
**USE_GAUSSIAN_BLUR**: bool - enable or disable the blur (in output)
**USE_AVG_COLOR**: bool - enable or disable avg algorithm
**AVG_BOX_DATA**: dict - params (width and height) of the avg area to be considered
**AVAILABLE_PALETTE**: list - loaded palette list
**PALETTE_DATA**: dict - available palette data in hex : rgb format
## Methods
### set_palette_lookup_path
Set the base_path for the palette folder, if different from the default.
`set_palette_lookup_path(self, path)`
-----
### set_default_nord_palette
Set available palette as the default palette.
The default palette is the full Nordtheme palette.
`set_default_nord_palette(self)`
-----
### get_palette_data
Build the palette data from configuration
`get_palette_data(self)`
**Returns**: dict - The palette data: keys are hex color code, values are rgb values
-----
### add_color_to_palette
Add hex color to current palette
`add_color_to_palette(self, hex_color)`
-----
### reset_palette
Reset the available_palette prop
`reset_palette(self)`
-----
### add_file_to_palette
Append a custom file to the available palette
`add_file_to_palette(self, file)`
-----
### enable_gaussian_blur
Enable blur filter
`enable_gaussian_blur(self)`
-----
### disable_gaussian_blur
disabled blur filter
`disable_gaussian_blur(self)`
-----
### open_image
Load an image using Pillow utility
`open_image(self, path)`
**Parameters**:
- path: str - the path and the filename where to save the image
**Returns**: pillow Image - the opened image
-----
### resize_image
Resize an image using Pillow utility
`resize_image(self, image, w=0, h=0)`
**Parameters**
- image: pillow image - The source pillow image
- w: int - New width
- h: int - New height
**Returns**: pillow image - the resized image
-----
### image_to_base64
Convert a Pillow image to base64 string
Available extension: https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
`image_to_base64(self, image, extension)`
**Parameters**
- image: pillow image - The source pillow image
- extension: str - The extension of the source image (mandatory)
**Returns**: pillow image - processed image
-----
### base64_to_image
Convert a base64 string to a Pillow image
`base64_to_image(self, img_b64)`
**Parameters**
img_b64: str - The base64 string representation of the image
**Returns**: pillow image - The converted image from base64
-----
### load_pixel_image
Load the pixel map of a given Pillow image
`load_pixel_image(self, opened_image)`
**Parameters**
- image: pillow image - The source pillow image
**Returns**: pillow image - pixel map of the opened image
-----
### enable_avg_algorithm
Enable avg algorithm
`enable_avg_algorithm(self)`
-----
### disable_avg_algorithm
Disabled avg algorithm
`disable_avg_algorithm(self)`
-----
### set_avg_box_data
Set the dimension of the AVG area box to use
`set_avg_box_data(self, w=-2, h=3)`
**Parameters**
- w: int - Box's width
- h: int - Box's height
-----
### quantize_image
Quantize a Pillow image by applying the available palette
`quantize_image(self, image, save_path='')`
**Parameters**
- image: pillow image - The source pillow image
- fill_color: str - Default fill color as foreground
- save_path : str, optional - the path and the filename where to save the image
**Returns**: pillow image - quantized image
-----
### convert_image
Process a Pillow image by replacing pixel or by avg algorithm
`convert_image(self, image, palettedata, save_path='')`
**Parameters**
- image : pillow image - The source pillow image
- save_path : str, optional - the path and the filename where to save the image
**Returns**: pillow image - processed image
-----
### save_image_to_file
Save a Pillow image to file
`save_image_to_file(self, image, path)`
**Parameters**
- image: pillow image - The source pillow image
- path: str - the path and the filename where to save the image
-----
## Example
### Import GoNord from ImageGoNord package
from ImageGoNord import NordPaletteFile, GoNord
### Use replace pixel by pixel algorithm
```
go_nord = GoNord()
image = go_nord.open_image("images/test.jpg")
go_nord.convert_image(image, save_path='images/test.processed.jpg')
```
### Use Avg algorithm, clean default palette and add just the POLAR NIGHT and SNOW STORM colors
```
go_nord.enable_avg_algorithm()
go_nord.reset_palette()
go_nord.add_file_to_palette(NordPaletteFile.POLAR_NIGHT)
go_nord.add_file_to_palette(NordPaletteFile.SNOW_STORM)
// You can add color also by their hex code
go_nord.add_color_to_palette('#FF0000')
image = go_nord.open_image("images/test.jpg")
go_nord.convert_image(image, save_path='images/test.avg.jpg')
```
### Resize image and use the replace pixel by pixel algorithm with less colors
```
go_nord.disable_avg_algorithm()
go_nord.reset_palette()
go_nord.add_file_to_palette(NordPaletteFile.POLAR_NIGHT)
go_nord.add_file_to_palette(NordPaletteFile.SNOW_STORM)
image = go_nord.open_image("images/test.jpg")
resized_img = go_nord.resize_image(image)
go_nord.convert_image(resized_img, save_path='images/test.resized.jpg')
```
### Use quantize method for rfiltering an image with the current palette
```
image = go_nord.open_image("images/test.jpg")
go_nord.reset_palette()
go_nord.set_default_nord_palette()
quantize_image = go_nord.quantize_image(image, save_path='images/test.quantize.jpg')
// To base64
go_nord.image_to_base64(quantize_image, 'jpeg')
```
================================================
FILE: docs/example/index.py
================================================
from ImageGoNord import NordPaletteFile, GoNord
# E.g. Replace pixel by pixel
go_nord = GoNord()
image = go_nord.open_image("images/test.jpg")
go_nord.convert_image(image, save_path='images/test.processed.jpg')
# E.g. Avg algorithm and less colors
go_nord.enable_avg_algorithm()
go_nord.reset_palette()
go_nord.add_file_to_palette(NordPaletteFile.POLAR_NIGHT)
go_nord.add_file_to_palette(NordPaletteFile.SNOW_STORM)
# You can add color also by their hex code
go_nord.add_color_to_palette('#FF0000')
image = go_nord.open_image("images/test.jpg")
go_nord.convert_image(image, save_path='images/test.avg.jpg')
# E.g. Resized img no Avg algorithm and less colors
go_nord.disable_avg_algorithm()
go_nord.reset_palette()
go_nord.add_file_to_palette(NordPaletteFile.POLAR_NIGHT)
go_nord.add_file_to_palette(NordPaletteFile.SNOW_STORM)
image = go_nord.open_image("images/test.jpg")
resized_img = go_nord.resize_image(image)
go_nord.convert_image(resized_img, save_path='images/test.resized.jpg')
# E.g. Quantize
image = go_nord.open_image("images/test.jpg")
go_nord.reset_palette()
go_nord.set_default_nord_palette()
quantize_image = go_nord.quantize_image(image, save_path='images/test.quantize.jpg')
# To base64
go_nord.image_to_base64(quantize_image, 'jpeg')
================================================
FILE: index.py
================================================
from ImageGoNord import NordPaletteFile, GoNord
go_nord = GoNord()
"""image = go_nord.open_image("images/test-profile.jpg")
go_nord.convert_image(image, save_path='images/test.processed.jpg') """
# E.g. Avg algorithm and less colors
go_nord.enable_avg_algorithm()
# go_nord.reset_palette()
# go_nord.set_palette_lookup_path('./mypalette')
# go_nord.add_file_to_palette(NordPaletteFile.POLAR_NIGHT)
# go_nord.add_file_to_palette(NordPaletteFile.SNOW_STORM)
# go_nord.add_color_to_palette('#FF0000')
# go_nord.set_default_nord_palette()
image = go_nord.open_image("images/valley.jpg")
# go_nord.convert_image(image, save_path='images/test-valley-avg.jpg')
# E.g. Resized img no Avg algorithm and less colors
go_nord.disable_avg_algorithm()
# go_nord.reset_palette()
# go_nord.add_file_to_palette(NordPaletteFile.AURORA)
# go_nord.add_file_to_palette(NordPaletteFile.FROST)
image = go_nord.open_image("images/valley.jpg")
go_nord.convert_image(image, save_path="images/test-valley-ai.jpg", use_model=True)
exit()
# output_path = go_nord.convert_video('videos/SampleVideo_720x480.mp4', 'custom_palette', save_path='videos/SampleVideo_converted.mp4')
image = go_nord.open_image("images/test.jpg")
resized_img = go_nord.resize_image(image)
go_nord.convert_image(resized_img, save_path='images/test.resized.jpg')
# E.g. Quantize
image = go_nord.open_image("images/test.jpg")
go_nord.reset_palette()
go_nord.set_default_nord_palette()
quantize_image = go_nord.quantize_image(image, save_path='images/test.quantize.jpg')
# To base64
go_nord.image_to_base64(quantize_image, 'jpeg')
================================================
FILE: setup.py
================================================
import pathlib
from setuptools import setup, find_packages
ROOT = pathlib.Path('.')
README = (ROOT / "README.md").read_text()
setup(
name="image-go-nord",
version="1.2.0",
description="A tool to convert any RGB image or video to any theme or color palette input by the user",
long_description=README,
long_description_content_type="text/markdown",
url="https://github.com/schroedinger-Hat/ImageGoNord-pip",
download_url = 'https://github.com/schroedinger-Hat/ImageGoNord-pip/releases',
keywords = ['nordtheme', 'pillow', 'image', 'conversion', 'rgb', 'color-scheme', 'color-palette', 'linux-rice', 'gruvbox', 'catpuccin'],
author="Schroedinger Hat",
author_email="dev@schroedinger-hat.org",
license="AGPL-3.0",
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7"
],
project_urls={
"Homepage": "https://ign.schroedinger-hat.org",
"Source": "https://github.com/schroedinger-Hat/ImageGoNord-pip",
"Bug Reports": "https://github.com/schroedinger-Hat/ImageGoNord-pip/issues",
},
packages=find_packages(),
package_data={'': ['*.txt', 'palettes/*.txt']},
include_package_data=True,
install_requires=["Pillow", "ffmpeg-python", "numpy", "requests"],
extras_require = {
'AI': ["torch", "scikit-image", "torchvision"]
},
python_requires=">=3.5"
)
================================================
FILE: upload-release.sh
================================================
#!/bin/sh -l
if $TWINE_USERNAME == "" || $TWINE_PASSWORD == ""
then
echo "No twine info in the environment variables"
return -1
fi
python setup.py sdist bdist_wheel
echo "Build finished"
# TODO: check if dist & build directory are existing and also with the correct files
echo "Twine init"
twine upload dist/*
echo "Twine ended"
gitextract_tdy50p_0/ ├── .github/ │ ├── FUNDING.yml │ └── workflows/ │ └── upload-release.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── ImageGoNord/ │ ├── GoNord.py │ ├── GoNord_test.py │ ├── __init__.py │ ├── models/ │ │ ├── PaletteNet/ │ │ │ ├── FE.state_dict.pt │ │ │ ├── RD.state_dict.pt │ │ │ └── __init__.py │ │ └── __init__.py │ ├── palettes/ │ │ ├── Nord/ │ │ │ ├── Aurora.txt │ │ │ ├── Frost.txt │ │ │ ├── PolarNight.txt │ │ │ ├── SnowStorm.txt │ │ │ └── __init__.py │ │ └── __init__.py │ └── utility/ │ ├── ConvertUtility.py │ ├── __init__.py │ ├── model.py │ ├── palette_loader.py │ └── quantize.py ├── LICENSE ├── MANIFEST.in ├── Pipfile ├── README.md ├── action.yml ├── docs/ │ ├── .gitkeep │ ├── README.md │ └── example/ │ └── index.py ├── index.py ├── setup.py └── upload-release.sh
SYMBOL INDEX (69 symbols across 6 files)
FILE: ImageGoNord/GoNord.py
class NordPaletteFile (line 47) | class NordPaletteFile:
class GoNord (line 73) | class GoNord(object):
method __init__ (line 179) | def __init__(self):
method set_palette_lookup_path (line 184) | def set_palette_lookup_path(self, path):
method set_default_nord_palette (line 188) | def set_default_nord_palette(self):
method get_palette_data (line 197) | def get_palette_data(self):
method add_color_to_palette (line 219) | def add_color_to_palette(self, hex_color):
method reset_palette (line 222) | def reset_palette(self):
method add_file_to_palette (line 227) | def add_file_to_palette(self, file):
method set_transparency_tolerance (line 232) | def set_transparency_tolerance(self, tolerance):
method enable_gaussian_blur (line 236) | def enable_gaussian_blur(self):
method disable_gaussian_blur (line 240) | def disable_gaussian_blur(self):
method open_image (line 244) | def open_image(self, path):
method resize_image (line 267) | def resize_image(self, image, size=(0, 0)):
method image_to_base64 (line 292) | def image_to_base64(self, image, extension):
method base64_to_image (line 316) | def base64_to_image(self, img_b64):
method load_pixel_image (line 334) | def load_pixel_image(self, opened_image):
method enable_avg_algorithm (line 350) | def enable_avg_algorithm(self):
method disable_avg_algorithm (line 357) | def disable_avg_algorithm(self):
method set_avg_box_data (line 364) | def set_avg_box_data(self, w=-2, h=2):
method quantize_image (line 379) | def quantize_image(self, image, fill_color='2E3440', save_path=''):
method converted_loop (line 413) | def converted_loop(self, is_rgba, pixels, original_pixels, maxRow, max...
method load_and_save_models (line 449) | def load_and_save_models(self):
method convert_image_by_model (line 459) | def convert_image_by_model(self, image, use_model_cpu=False):
method convert_image (line 529) | def convert_image(self, image, save_path='', use_model=False, use_mode...
method save_image_to_file (line 591) | def save_image_to_file(self, image, path):
method get_video_information (line 607) | def get_video_information(self, video_path):
method convert_vid_to_np_arr (line 636) | def convert_vid_to_np_arr(self, video_path, width, height, start_time,...
method vidwrite (line 678) | def vidwrite(self, fn, cube, images, framerate, start_frame, total_fra...
method concat_video (line 721) | def concat_video(self, uid, out, save_path):
method apply_original_audio (line 751) | def apply_original_audio(self, _input, _output):
method convert_video (line 778) | def convert_video(self, _input, palette_name, _frames_per_batch = 200,...
FILE: ImageGoNord/GoNord_test.py
function image (line 8) | def image():
function go_nord (line 13) | def go_nord():
function test_resize_image_with_w_and_h (line 18) | def test_resize_image_with_w_and_h(image, go_nord: GoNord):
function test_resize_image_with_size (line 23) | def test_resize_image_with_size(image, go_nord: GoNord):
function test_resize_image (line 28) | def test_resize_image(image: Image, go_nord: GoNord):
FILE: ImageGoNord/utility/ConvertUtility.py
class ConvertUtility (line 4) | class ConvertUtility:
method color_difference (line 17) | def color_difference(color1, color2):
method get_avg_color (line 35) | def get_avg_color(pixels, row, col, w=-2, h=3):
method convert_palette (line 86) | def convert_palette(color_cube, image):
FILE: ImageGoNord/utility/model.py
class Conv2dAuto (line 9) | class Conv2dAuto(nn.Conv2d):
method __init__ (line 10) | def __init__(self, *args, **kwargs):
function activation_func (line 15) | def activation_func(activation): #Activation function as mentioned in ...
class ResidualBlock (line 23) | class ResidualBlock(nn.Module):
method __init__ (line 24) | def __init__(self, in_channels, out_channels, activation='relu'):
method forward (line 31) | def forward(self, x):
method should_apply_shortcut (line 40) | def should_apply_shortcut(self):
class ResNetResidualBlock (line 43) | class ResNetResidualBlock(ResidualBlock):
method __init__ (line 44) | def __init__(self, in_channels, out_channels, expansion=1, downsamplin...
method expanded_channels (line 56) | def expanded_channels(self):
method should_apply_shortcut (line 60) | def should_apply_shortcut(self):
function conv_bn (line 63) | def conv_bn(in_channels, out_channels, conv, *args, **kwargs):
class ResNetBasicBlock (line 67) | class ResNetBasicBlock(ResNetResidualBlock):
method __init__ (line 69) | def __init__(self, in_channels, out_channels, activation=nn.LeakyReLU,...
class FeatureEncoder (line 77) | class FeatureEncoder(nn.Module):
method __init__ (line 79) | def __init__(self,*args,**kwargs):
method forward (line 90) | def forward(self, x):
function de_conv (line 98) | def de_conv(in_channels, out_channels,kernel_size=3): #deconvolu...
class RecoloringDecoder (line 105) | class RecoloringDecoder(nn.Module):
method __init__ (line 107) | def __init__(self):
method forward (line 115) | def forward(self, c1, c2, c3, c4, target_palettes_1d, illu):
FILE: ImageGoNord/utility/palette_loader.py
function load_palette_set (line 9) | def load_palette_set(path):
function find_palettes (line 34) | def find_palettes(path):
function import_palette_from_file (line 55) | def import_palette_from_file(filename):
function create_data_colors (line 78) | def create_data_colors(palette):
function export_tripletes_from_color (line 101) | def export_tripletes_from_color(hex_color):
function generate_color_map (line 124) | def generate_color_map(palette, palette_name):
FILE: ImageGoNord/utility/quantize.py
function quantize_to_palette (line 8) | def quantize_to_palette(silf, palette):
Condensed preview — 36 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (121K chars).
[
{
"path": ".github/FUNDING.yml",
"chars": 107,
"preview": "# These are supported funding model platforms\n\ngithub: [Wabri, TheJoin95]\nopen_collective: schrodinger-hat\n"
},
{
"path": ".github/workflows/upload-release.yml",
"chars": 389,
"preview": "name: 'Upload latest release on PyPi'\n\non:\n workflow_dispatch:\n release:\n types: [published]\n\njobs:\n upload_latest"
},
{
"path": ".gitignore",
"chars": 2202,
"preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
},
{
"path": "CHANGELOG.md",
"chars": 82,
"preview": "# Changelog\nAll notable changes to this project will be documented in this file.\n\n"
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 5876,
"preview": "# Code of Conduct\r\n\r\nAll members, committers and volunteers in this project are required to act according to the followi"
},
{
"path": "CONTRIBUTING.md",
"chars": 14158,
"preview": "# Contributing to ImageGoNord\r\n\r\nThanks for contributing to this project!\r\n\r\nThis is a set of guidelines for contributin"
},
{
"path": "Dockerfile",
"chars": 180,
"preview": "FROM python:3.9-slim\n\nWORKDIR /app\nCOPY upload-release.sh .\n\nRUN pip install twine && pip install setuptools\n\nRUN chmod "
},
{
"path": "ImageGoNord/GoNord.py",
"chars": 26546,
"preview": "\nimport base64\nimport os\nfrom io import BytesIO\n\nfrom math import ceil\n\nimport threading\n\nfrom PIL import Image, ImageFi"
},
{
"path": "ImageGoNord/GoNord_test.py",
"chars": 768,
"preview": "import pytest\nfrom PIL import Image\n\nfrom ImageGoNord import GoNord\n\n\n@pytest.fixture\ndef image():\n return Image.open"
},
{
"path": "ImageGoNord/__init__.py",
"chars": 72,
"preview": "# gonord version\n__version__ = \"1.2.0\"\n\nfrom ImageGoNord.GoNord import *"
},
{
"path": "ImageGoNord/models/PaletteNet/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "ImageGoNord/models/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "ImageGoNord/palettes/Nord/Aurora.txt",
"chars": 39,
"preview": "#BF616A\n#D08770\n#EBCB8B\n#A3BE8C\n#B48EAD"
},
{
"path": "ImageGoNord/palettes/Nord/Frost.txt",
"chars": 31,
"preview": "#8FBCBB\n#88C0D0\n#81A1C1\n#5E81AC"
},
{
"path": "ImageGoNord/palettes/Nord/PolarNight.txt",
"chars": 31,
"preview": "#2E3440\n#3B4252\n#434C5E\n#4C566A"
},
{
"path": "ImageGoNord/palettes/Nord/SnowStorm.txt",
"chars": 23,
"preview": "#D8DEE9\n#E5E9F0\n#ECEFF4"
},
{
"path": "ImageGoNord/palettes/Nord/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "ImageGoNord/palettes/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "ImageGoNord/utility/ConvertUtility.py",
"chars": 2330,
"preview": "# -*- coding: utf-8 -*-\nimport numpy as np\n\nclass ConvertUtility:\n \"\"\"\n An utility class used for converting image to "
},
{
"path": "ImageGoNord/utility/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "ImageGoNord/utility/model.py",
"chars": 5947,
"preview": "from functools import partial\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import"
},
{
"path": "ImageGoNord/utility/palette_loader.py",
"chars": 3368,
"preview": "\"\"\"This is the example module.\n\nThis module does stuff.\n\"\"\"\nfrom os import listdir\nimport numpy as np\n\n\ndef load_palette"
},
{
"path": "ImageGoNord/utility/quantize.py",
"chars": 962,
"preview": "\"\"\"This is the example module.\n\nThis module does stuff.\n\"\"\"\n\nfrom PIL import ImageFilter\n\ndef quantize_to_palette(silf, "
},
{
"path": "LICENSE",
"chars": 34522,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "MANIFEST.in",
"chars": 31,
"preview": "include palettes\ninclude models"
},
{
"path": "Pipfile",
"chars": 191,
"preview": "[[source]]\nname = \"pypi\"\nurl = \"https://pypi.org/simple\"\nverify_ssl = true\n\n[dev-packages]\npylint = \"*\"\nautopep8 = \"*\"\nt"
},
{
"path": "README.md",
"chars": 5839,
"preview": "# ImageGoNord - RGB image and video to any kind of palette or theme\n\n and it is [available also on the website](http"
},
{
"path": "docs/example/index.py",
"chars": 1263,
"preview": "from ImageGoNord import NordPaletteFile, GoNord\n\n# E.g. Replace pixel by pixel\ngo_nord = GoNord()\nimage = go_nord.open_i"
},
{
"path": "index.py",
"chars": 1581,
"preview": "from ImageGoNord import NordPaletteFile, GoNord\n\ngo_nord = GoNord()\n\"\"\"image = go_nord.open_image(\"images/test-profile.j"
},
{
"path": "setup.py",
"chars": 1665,
"preview": "import pathlib\nfrom setuptools import setup, find_packages\n\nROOT = pathlib.Path('.')\nREADME = (ROOT / \"README.md\").read_"
},
{
"path": "upload-release.sh",
"chars": 340,
"preview": "#!/bin/sh -l\n\nif $TWINE_USERNAME == \"\" || $TWINE_PASSWORD == \"\"\nthen\n echo \"No twine info in the environment variable"
}
]
// ... and 2 more files (download for full content)
About this extraction
This page contains the full source code of the Schrodinger-Hat/ImageGoNord-pip GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 36 files (18.5 MB), approximately 27.0k tokens, and a symbol index with 69 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.