pax_global_header 0000666 0000000 0000000 00000000064 14410124605 0014507 g ustar 00root root 0000000 0000000 52 comment=9706ca2168b32a15388a616b4795e8c0a8ff8297
thumbhash-py-0.1.2/ 0000775 0000000 0000000 00000000000 14410124605 0014120 5 ustar 00root root 0000000 0000000 thumbhash-py-0.1.2/.github/ 0000775 0000000 0000000 00000000000 14410124605 0015460 5 ustar 00root root 0000000 0000000 thumbhash-py-0.1.2/.github/workflows/ 0000775 0000000 0000000 00000000000 14410124605 0017515 5 ustar 00root root 0000000 0000000 thumbhash-py-0.1.2/.github/workflows/build-publish.yml 0000664 0000000 0000000 00000001664 14410124605 0023012 0 ustar 00root root 0000000 0000000 name: Build and Publish
on:
push:
tags:
- v*
jobs:
build:
name: Build wheels
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install build dependencies
run: python -m pip install --upgrade hatch
- name: Build
run: python -m hatch build
- uses: actions/upload-artifact@v3
with:
name: artifacts
path: dist/*
if-no-files-found: error
publish:
name: Publish release
needs:
- build
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v3
with:
name: artifacts
path: dist
- name: Push build artifacts to PyPI
uses: pypa/gh-action-pypi-publish@v1.6.4
with:
skip_existing: true
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
- name: Publish Github Release
uses: softprops/action-gh-release@v1
with:
files: dist/*
thumbhash-py-0.1.2/.gitignore 0000664 0000000 0000000 00000006645 14410124605 0016123 0 ustar 00root root 0000000 0000000 # Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
### Python Patch ###
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
poetry.toml
# ruff
.ruff_cache/
# LSP config files
pyrightconfig.json
# End of https://www.toptal.com/developers/gitignore/api/python thumbhash-py-0.1.2/LICENSE 0000664 0000000 0000000 00000002047 14410124605 0015130 0 ustar 00root root 0000000 0000000 MIT License
Copyright (c) 2023 Justin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
thumbhash-py-0.1.2/README.md 0000664 0000000 0000000 00000002035 14410124605 0015377 0 ustar 00root root 0000000 0000000
# thumbhash-py
A Python port of the [thumbhash](https://github.com/evanw/thumbhash) encoder by [Evan Wallace](https://github.com/evanw)
## Installation
Install thumbhash with pip
```sh
pip install thumbhash-py
```
Optionally install with pillow support:
```sh
pip install thumbhash-py[pillow]
```
## Usage
Encode a RGBA array to a ThumbHash
```py
from thumbhash import rgba_to_thumb_hash
rgba = [100, 85, 15, 255, 100, 84, 32, 255,...]
width = 100
height = 75
thumb_hash = rgba_to_thumb_hash(rgba, width, height) # [86, 8, 10, 13, 128, 22, 234, 86, 111, 117, ...]
```
Open an image using pillow, scale down to max dimensions of 100x100 and encode to a ThumbHash
```py
from thumbhash import image_to_thumb_hash
thumb_hash = image_to_thumb_hash('image.jpg') # [86, 8, 10, 13, 128, 22, 234, 86, 111, 117, ...]
```
## Features
As of now this library only handles the conversion of images to hashes, not the reverse.
thumbhash-py-0.1.2/pyproject.toml 0000664 0000000 0000000 00000003145 14410124605 0017037 0 ustar 00root root 0000000 0000000 [build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "thumbhash-py"
description = 'A very compact representation of an image placeholder'
readme = "README.md"
requires-python = ">=3.7"
license = "MIT"
keywords = []
authors = [
{ name = "Justin", email = "justin@forlenza.co" },
]
classifiers = [
"Development Status :: 4 - Beta",
"Programming Language :: Python",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
dependencies = [
]
dynamic = ["version"]
[project.optional-dependencies]
pillow = [
"pillow"
]
[project.urls]
Documentation = "https://github.com/justinforlenza/thumbhash-py#readme"
Issues = "https://github.com/justinforlenza/thumbhash-py/issues"
Source = "https://github.com/justinforlenza/thumbhash-py"
[tool.hatch.version]
path = "thumbhash/__about__.py"
[tool.hatch.envs.default]
dependencies = [
"pytest",
"pytest-cov",
]
[tool.hatch.envs.default.scripts]
cov = "pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=thumbhash --cov=tests {args}"
no-cov = "cov --no-cov {args}"
[[tool.hatch.envs.test.matrix]]
python = ["37", "38", "39", "310", "311"]
[tool.coverage.run]
branch = true
parallel = true
omit = [
"thumbhash/__about__.py",
]
[tool.coverage.report]
exclude_lines = [
"no cov",
"if __name__ == .__main__.:",
"if TYPE_CHECKING:",
]
thumbhash-py-0.1.2/requirements.txt 0000664 0000000 0000000 00000000006 14410124605 0017400 0 ustar 00root root 0000000 0000000 pillow thumbhash-py-0.1.2/thumbhash/ 0000775 0000000 0000000 00000000000 14410124605 0016103 5 ustar 00root root 0000000 0000000 thumbhash-py-0.1.2/thumbhash/__about__.py 0000664 0000000 0000000 00000000025 14410124605 0020360 0 ustar 00root root 0000000 0000000 __version__ = '0.1.2' thumbhash-py-0.1.2/thumbhash/__init__.py 0000664 0000000 0000000 00000012056 14410124605 0020220 0 ustar 00root root 0000000 0000000 import math
from typing import List, Tuple
from pathlib import Path
from itertools import chain
try:
from PIL import Image, ImageOps
has_pil = True
except ImportError:
has_pil = False
def rgba_to_thumb_hash(w: int, h: int, rgba: List[int]) -> List[int]:
'''
Encodes an RGBA image to a ThumbHash
'''
if w > 100 or h > 100:
raise ValueError(f"{w}x{h} doesn't fit in 100x100")
avg_r, avg_g, avg_b, avg_a = 0, 0, 0, 0
for i in range(w * h):
j = i * 4
alpha = rgba[j + 3] / 255
avg_r += alpha / 255 * rgba[j]
avg_g += alpha / 255 * rgba[j + 1]
avg_b += alpha / 255 * rgba[j + 2]
avg_a += alpha
if avg_a:
avg_r /= avg_a
avg_g /= avg_a
avg_b /= avg_a
has_alpha = avg_a < w * h
l_limit = 5 if has_alpha else 7
lx = max(1, round(l_limit * w / max(w, h)))
ly = max(1, round(l_limit * h / max(w, h)))
l, p, q, a = [], [], [], []
for i in range(w * h):
j = i * 4
alpha = rgba[j + 3] / 255
r = avg_r * (1 - alpha) + alpha / 255 * rgba[j]
g = avg_g * (1 - alpha) + alpha / 255 * rgba[j + 1]
b = avg_b * (1 - alpha) + alpha / 255 * rgba[j + 2]
l.append((r + g + b) / 3)
p.append((r + g) / 2 - b)
q.append(r - g)
a.append(alpha)
def encode_channel(channel: list, nx: int, ny: int):
dc = 0
ac = []
scale = 0
fx = [0] * w
for cy in range(ny):
cx = 0
while cx * ny < nx * (ny - cy):
f = 0.0
for x in range(w):
fx[x] = math.cos(math.pi / w * cx * (x + 0.5))
for y in range(h):
fy = math.cos(math.pi / h * cy * (y + 0.5))
for x in range(w):
f += channel[x + y * w] * fx[x] * fy
f /= (w * h)
if cx > 0 or cy > 0:
ac.append(f)
scale = max(scale, abs(f))
else:
dc = f
cx += 1
if scale:
for i in range(len(ac)):
ac[i] = 0.5 + 0.5 / scale * ac[i]
return dc, ac, scale
l_dc, l_ac, l_scale = encode_channel(l, max(3, lx), max(3, ly))
p_dc, p_ac, p_scale = encode_channel(p, 3, 3)
q_dc, q_ac, q_scale = encode_channel(q, 3, 3)
a_dc, a_ac, a_scale = encode_channel(a, 5, 5) if has_alpha else 1.0, [], 1.0
is_landscape = w > h
header24 = round(63 * l_dc) | (round(31.5 + 31.5 * p_dc) << 6) | (round(31.5 + 31.5 * q_dc) << 12) | (round(31 * l_scale) << 18) | (has_alpha << 23)
header16 = (ly if is_landscape else lx) | (round(63 * p_scale) << 3) | (round(63 * q_scale) << 9) | (is_landscape << 15)
thumb_hash = [header24 & 255, (header24 >> 8) & 255, header24 >> 16, header16 & 255, header16 >> 8]
is_odd = False
if has_alpha:
thumb_hash.append(round(15 * a_dc) | (round(15 * a_scale) << 4))
for ac in [l_ac, p_ac, q_ac]:
for f in ac:
u = int(round(15.0 * f))
if is_odd:
thumb_hash[-1] |= u << 4
else:
thumb_hash.append(u)
is_odd = not is_odd
if has_alpha:
for f in a_ac:
u = int(round(15.0 * f))
if is_odd:
thumb_hash[-1] |= u << 4
else:
thumb_hash.append(u)
is_odd = not is_odd
return thumb_hash
def image_to_thumb_hash(fp: str | bytes | Path) -> List[int]:
'''
Opens given image file and encodes to a ThumbHash
'''
if not has_pil:
raise ImportError('Pillow not installed, please re-install with pillow extra')
img = Image.open(fp)
img = img.convert('RGBA')
img.thumbnail((100, 100))
img = ImageOps.exif_transpose(img)
rgba_2d = list(img.getdata())
rgba = list(chain(*rgba_2d))
thumb_hash = rgba_to_thumb_hash(img.width, img.height, rgba)
return thumb_hash
def thumb_hash_to_average_rgba(thumb_hash: List[int]) -> Tuple[int]:
'''
Extracts the average color from a ThumbHash
'''
if len(thumb_hash) < 5:
return None
header = thumb_hash[0] | (thumb_hash[1] << 8) | (thumb_hash[2] << 16)
l = (header & 63) / 63.0
p = ((header >> 6) & 63) / 31.5 - 1.0
q = ((header >> 12) & 63) / 31.5 - 1.0
has_alpha = (header >> 23) != 0
a = (thumb_hash[5] & 15) / 15.0 if has_alpha else 1.0
b = l - 2.0 / 3.0 * p
r = (3.0 * l - b + q) / 2.0
g = r - q
return (
max(0.0, min(1.0, r)),
max(0.0, min(1.0, g)),
max(0.0, min(1.0, b)),
a
)
def thumb_hash_to_approximate_aspect_ratio(thumb_hash: List[int]) -> float:
'''
Extracts approxmiate aspect ratio of a ThumbHash
'''
if len(thumb_hash) < 5:
return None
has_alpha = (thumb_hash[2] & 0x80) != 0
l_max = 5 if has_alpha else 7
l_min = thumb_hash[3] & 7
is_landscape = (thumb_hash[4] & 0x80) != 0
lx = l_max if is_landscape else l_min
ly = l_min if is_landscape else l_max
return lx / ly