pax_global_header00006660000000000000000000000064147044762230014523gustar00rootroot0000000000000052 comment=b28d107b16ce578139f10590e79f32e6fad604d7 py-zopfli-0.2.3.post1/000077500000000000000000000000001470447622300145235ustar00rootroot00000000000000py-zopfli-0.2.3.post1/.github/000077500000000000000000000000001470447622300160635ustar00rootroot00000000000000py-zopfli-0.2.3.post1/.github/workflows/000077500000000000000000000000001470447622300201205ustar00rootroot00000000000000py-zopfli-0.2.3.post1/.github/workflows/ci.yml000066400000000000000000000104401470447622300212350ustar00rootroot00000000000000name: Build + Deploy on: push: branches: [master] tags: ["v*.*.*"] pull_request: branches: [master] release: types: - published env: CIBW_TEST_EXTRAS: test CIBW_TEST_COMMAND: pytest {package}/tests -v jobs: build_sdist: name: Build Source Distribution runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.x" - name: Install dependencies run: pip install --upgrade setuptools twine - name: Build sdist run: python setup.py sdist - name: Check metadata run: twine check dist/*.tar.gz - uses: actions/upload-artifact@v4 with: path: dist/*.tar.gz name: sdist build_wheels: name: ${{ matrix.type }} ${{ matrix.arch }} on ${{ matrix.os }} runs-on: ${{ matrix.os }} defaults: run: shell: bash strategy: fail-fast: false matrix: # macos-13 runners are still x86_64, macos-14 (latest) are arm64; we want to build # the x86_64 wheel on/for x86_64 macs os: [macos-13, windows-latest] arch: [auto64] build: ["*"] include: # the manylinux1 docker images only contain python3.8 and 3.9 - os: ubuntu-latest type: manylinux1 arch: auto build: "cp{38,39}-*" CIBW_MANYLINUX_X86_64_IMAGE: manylinux1 CIBW_MANYLINUX_I686_IMAGE: manylinux1 # the manylinux2010 image also contains python 3.10 and pypy3.8 - os: ubuntu-latest arch: auto type: manylinux2010 build: "pp{38}-* cp310-*" CIBW_MANYLINUX_X86_64_IMAGE: manylinux2010 CIBW_MANYLINUX_I686_IMAGE: manylinux2010 # the manylinux2014 image also contains python 3.11, 3.12, 3.13 and pypy3.9 and 3.10 - os: ubuntu-latest arch: auto type: manylinux2014 build: "pp39-* pp310-* cp311-* cp312-* cp313-*" CIBW_MANYLINUX_X86_64_IMAGE: manylinux2014 CIBW_MANYLINUX_I686_IMAGE: manylinux2014 - os: macos-latest arch: universal2 build: "*" - os: windows-latest arch: auto32 build: "*" steps: - uses: actions/checkout@v4 with: submodules: recursive - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.x" - name: Install dependencies run: pip install cibuildwheel - name: Build Wheels run: python -m cibuildwheel --output-dir wheelhouse . env: CIBW_BUILD: ${{ matrix.build }} CIBW_MANYLINUX_I686_IMAGE: ${{ matrix.CIBW_MANYLINUX_I686_IMAGE }} CIBW_MANYLINUX_X86_64_IMAGE: ${{ matrix.CIBW_MANYLINUX_X86_64_IMAGE }} CIBW_ARCHS: ${{ matrix.arch }} - uses: actions/upload-artifact@v4 with: path: wheelhouse/*.whl name: wheels-${{ matrix.os }}-${{ matrix.arch }}-${{ matrix.type }} build_arch_wheels: name: py${{ matrix.python }} on ${{ matrix.arch }} runs-on: ubuntu-latest strategy: matrix: # aarch64 uses qemu so it's slow, build each py version in parallel jobs python: [38, 39, 310, 311, 312, 313] arch: [aarch64] steps: - uses: actions/checkout@v4 with: submodules: true - uses: docker/setup-qemu-action@v1.2.0 with: platforms: all - name: Install dependencies run: pip install cibuildwheel - name: Build Wheels run: python -m cibuildwheel --output-dir wheelhouse . env: CIBW_BUILD: cp${{ matrix.python }}-* CIBW_ARCHS: ${{ matrix.arch }} - uses: actions/upload-artifact@v4 with: path: wheelhouse/*.whl name: wheels-${{ matrix.arch }}-${{ matrix.python }} deploy: name: Upload if release needs: [build_wheels, build_arch_wheels, build_sdist] runs-on: ubuntu-latest if: github.event_name == 'release' && github.event.action == 'published' steps: - uses: actions/download-artifact@v4 with: path: dist merge-multiple: true - uses: pypa/gh-action-pypi-publish@v1.4.2 with: user: __token__ password: ${{ secrets.PYPI_PASSWORD }} py-zopfli-0.2.3.post1/.gitignore000066400000000000000000000001651470447622300165150ustar00rootroot00000000000000*# #*# build *egg* dist *.py[cd] *~ *.so .tox/ # autogenerated from git tag by setuptools_scm src/zopfli/_version.py py-zopfli-0.2.3.post1/.gitmodules000066400000000000000000000001141470447622300166740ustar00rootroot00000000000000[submodule "zopfli"] path = zopfli url = https://github.com/google/zopfli py-zopfli-0.2.3.post1/COPYING000066400000000000000000000261151470447622300155630ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. py-zopfli-0.2.3.post1/MANIFEST.in000066400000000000000000000005051470447622300162610ustar00rootroot00000000000000include COPYING include tox.ini include zopfli/README include zopfli/Makefile include zopfli/COPYING include zopfli/CONTRIBUTORS include zopfli/CONTRIBUTING.md recursive-include zopfli/src/zopfli *.h recursive-include zopfli/src/zopflipng *.h recursive-include zopfli/src/zopflipng/lodepng *.h recursive-include tests *.py py-zopfli-0.2.3.post1/README.rst000066400000000000000000000042471470447622300162210ustar00rootroot00000000000000|Build Status| PYZOPFLI ======== cPython bindings for `zopfli `__. It requires Python 3.8 or greater. USAGE ===== pyzopfli is a straight forward wrapper around zopfli's ZlibCompress method. :: from zopfli.zlib import compress from zlib import decompress s = 'Hello World' print decompress(compress(s)) pyzopfli also wraps GzipCompress, but the API point does not try to mimic the gzip module. :: from zopfli.gzip import compress from StringIO import StringIO from gzip import GzipFile print GzipFile(fileobj=StringIO(compress("Hello World!"))).read() Both zopfli.zlib.compress and zopfli.gzip.compress support the following keyword arguments. All values should be integers; boolean parmaters are treated as expected, 0 and >0 as false and true. - *verbose* dumps zopfli debugging data to stderr - *numiterations* Maximum amount of times to rerun forward and backward pass to optimize LZ77 compression cost. Good values: 10, 15 for small files, 5 for files over several MB in size or it will be too slow. - *blocksplitting* If true, splits the data in multiple deflate blocks with optimal choice for the block boundaries. Block splitting gives better compression. Default: true (1). - *blocksplittinglast* If true, chooses the optimal block split points only after doing the iterative LZ77 compression. If false, chooses the block split points first, then does iterative LZ77 on each individual block. Depending on the file, either first or last gives the best compression. Default: false (0). - *blocksplittingmax* Maximum amount of blocks to split into (0 for unlimited, but this can give extreme results that hurt compression on some files). Default value: 15. TODO ==== - Stop reading the entire file into memory and support streaming - Monkey patch zlib and gzip so code with an overly tight binding can be easily modified to use zopfli. .. |Build Status| image:: https://github.com/fonttools/py-zopfli/actions/workflows/ci.yml/badge.svg?branch=master :target: https://github.com/fonttools/py-zopfli/actions/workflows/ci.yml py-zopfli-0.2.3.post1/pyproject.toml000066400000000000000000000004471470447622300174440ustar00rootroot00000000000000[build-system] requires = [ # pin setuptools on pypy to workaround this bug: https://github.com/pypa/distutils/issues/283 "setuptools<72.2.0; platform_python_implementation == 'PyPy'", "setuptools; platform_python_implementation != 'PyPy'", ] build-backend = "setuptools.build_meta" py-zopfli-0.2.3.post1/setup.cfg000066400000000000000000000000431470447622300163410ustar00rootroot00000000000000[metadata] license_files = COPYING py-zopfli-0.2.3.post1/setup.py000077500000000000000000000057311470447622300162460ustar00rootroot00000000000000#!/usr/bin/env python """ pyzopfli ====== Python bindings to zopfli """ from setuptools import setup, Extension from setuptools.command.build_ext import build_ext from io import open import os class custom_build_ext(build_ext): """Pass platform-specific compiler/linker flags""" def build_extensions(self): compiler_type = self.compiler.compiler_type if compiler_type in "unix": for ext in self.extensions: # on some Unix-like systems, such as Linux, the libc math # library is not linked by default: # https://github.com/cython/cython/issues/1585 ext.extra_link_args.append("-lm") build_ext.build_extensions(self) with open("README.rst", "r", encoding="utf-8") as readme: long_description = readme.read() prefer_system_zopfli = bool(os.environ.get('USE_SYSTEM_ZOPFLI')) if prefer_system_zopfli: zopfli_ext_kwargs = { 'sources': [ 'src/zopflimodule.c', ], 'libraries': ['zopfli', 'zopflipng'], 'define_macros': [('SYSTEM_ZOPFLI', '1')], } else: zopfli_ext_kwargs = { 'sources': [ 'zopfli/src/zopfli/blocksplitter.c', 'zopfli/src/zopfli/cache.c', 'zopfli/src/zopfli/deflate.c', 'zopfli/src/zopfli/gzip_container.c', 'zopfli/src/zopfli/squeeze.c', 'zopfli/src/zopfli/hash.c', 'zopfli/src/zopfli/katajainen.c', 'zopfli/src/zopfli/lz77.c', 'zopfli/src/zopfli/tree.c', 'zopfli/src/zopfli/util.c', 'zopfli/src/zopfli/zlib_container.c', 'zopfli/src/zopfli/zopfli_lib.c', 'zopfli/src/zopflipng/lodepng/lodepng.cpp', 'zopfli/src/zopflipng/lodepng/lodepng_util.cpp', 'zopfli/src/zopflipng/zopflipng_lib.cc', 'src/zopflimodule.c', ], } setup( name='zopfli', use_scm_version={"write_to": "src/zopfli/_version.py"}, author='Adam DePrince', author_email='deprince@googlealumni.com', maintainer='Cosimo Lupo', maintainer_email='cosimo@anthrotype.com', description='Zopfli module for python', long_description=long_description, ext_modules=[ Extension('zopfli.zopfli', **zopfli_ext_kwargs) ], package_dir={"": "src"}, packages=["zopfli"], zip_safe=True, license='ASL', include_package_data=True, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Archiving :: Compression', ], url="https://github.com/fonttools/py-zopfli", test_suite="tests", cmdclass={ "build_ext": custom_build_ext, }, setup_requires=["setuptools_scm"], extras_require={"test": ["pytest"]}, python_requires=">=3.8", ) py-zopfli-0.2.3.post1/src/000077500000000000000000000000001470447622300153125ustar00rootroot00000000000000py-zopfli-0.2.3.post1/src/zopfli/000077500000000000000000000000001470447622300166155ustar00rootroot00000000000000py-zopfli-0.2.3.post1/src/zopfli/__init__.py000066400000000000000000000021731470447622300207310ustar00rootroot00000000000000__COMPRESSOR_DOCSTRING__ = """ Args: data: A string to compress verbose: (int 0/1) dump zopfli debugging data to stderr numiterations: Maximum amount of times to rerun forward and backward pass to optimize LZ77 compression cost. Good values: 10, 15 for small files, 5 for files over several MB in size or it will be too slow. blocksplitting: If true, splits the data in multiple deflate blocks with optimal choice for the block boundaries. Block splitting gives better compression. Default: true (1). blocksplittinglast: If true, chooses the optimal block split points only after doing the iterative LZ77 compression. If false, chooses the block split points first, then does iterative LZ77 on each individual block. Depending on the file, either first or last gives the best compression. Default: false (0). blocksplittingmax: Maximum amount of blocks to split into (0 for unlimited, but this can give extreme results that hurt compression on some files). Default value: 15. """ try: from ._version import version as __version__ # type: ignore except ImportError: __version__ = "0.0.0+unknown" py-zopfli-0.2.3.post1/src/zopfli/gzip.py000066400000000000000000000004671470447622300201470ustar00rootroot00000000000000import zopfli import zopfli.zopfli def compress(data, *args, **kwargs): """gzip.compress(data, **kwargs) """ + zopfli.__COMPRESSOR_DOCSTRING__ + """ Returns: String containing a gzip container """ kwargs['gzip_mode'] = 1 return zopfli.zopfli.compress(data, *args, **kwargs) py-zopfli-0.2.3.post1/src/zopfli/png.py000066400000000000000000000120671470447622300177610ustar00rootroot00000000000000import zopfli from zopfli.zopfli import png_optimize as optimize __all__ = ["optimize"] def main(args=None): import argparse import os parser = argparse.ArgumentParser(prog="python -m zopfli.png") parser.add_argument("infile") parser.add_argument("outfile") parser.add_argument("-v", "--verbose", action="store_true", help="print more info") parser.add_argument( "-m", action="store_true", dest="compress_more", help="compress more: use more iterations (depending on file size).", ) parser.add_argument( "-y", dest="overwrite", action="store_true", help="do not ask about overwriting files.", ) parser.add_argument( "--lossy_transparent", action="store_true", help="remove colors behind alpha channel 0. No visual difference.", ) parser.add_argument( "--lossy_8bit", action="store_true", help="convert 16-bit per channel image to 8-bit per channel.", ) parser.add_argument( "--always_zopflify", action="store_true", help="always output the image encoded by Zopfli, even if bigger than original.", ) parser.add_argument( "-q", dest="use_zopfli", action="store_false", help="use quick, but not very good, compression.", ) parser.add_argument( "--iterations", default=None, type=int, help=( "number of iterations, more iterations makes it slower but provides " "slightly better compression. Default: 15 for small files, 5 for large files." ), ) parser.add_argument( "--filters", dest="filter_strategies", help=( "filter strategies to try: " "0-4: give all scanlines PNG filter type 0-4; " "m: minimum sum; " "e: entropy; " "p: predefined (keep from input, this likely overlaps another strategy); " "b: brute force (experimental). " "By default, if this argument is not given, one that is most likely the best " "for this image is chosen by trying faster compression with each type. " "If this argument is used, all given filter types are tried with slow " "compression and the best result retained. " "A good set of filters to try is --filters=0me." ), ) parser.add_argument( "--keepchunks", type=lambda s: s.split(","), help=( "keep metadata chunks with these names that would normally be removed, " "e.g. tEXt,zTXt,iTXt,gAMA, ... Due to adding extra data, this increases " "the result size. Keeping bKGD or sBIT chunks may cause additional worse " "compression due to forcing a certain color type, it is advised to not " "keep these for web images because web browsers do not use these chunks. " "By default ZopfliPNG only keeps (and losslessly modifies) the following " "chunks because they are essential: IHDR, PLTE, tRNS, IDAT and IEND." ), ) options = parser.parse_args(args) log = print if options.verbose else lambda *_: None if options.iterations is not None: num_iterations = num_iterations_large = options.iterations else: # these constants are taken from zopflipng_lib.cc, unlikely to ever change num_iterations, num_iterations_large = 15, 5 if options.compress_more: num_iterations *= 4 num_iterations_large *= 4 with open(options.infile, "rb") as f: input_png = f.read() log(f"Optimizing {options.infile}") result_png = optimize( input_png, verbose=options.verbose, lossy_transparent=options.lossy_transparent, lossy_8bit=options.lossy_8bit, filter_strategies=options.filter_strategies, keepchunks=options.keepchunks, use_zopfli=options.use_zopfli, num_iterations=num_iterations, num_iterations_large=num_iterations_large, ) input_size = len(input_png) log(f"Input size: {input_size} ({input_size // 1024}K)") result_size = len(result_png) percentage = round(result_size / input_size * 100, 3) log( f"Result size: {result_size} ({result_size // 1024}K). " f"Percentage of original: {percentage}%" ) if result_size < input_size: log("Result is smaller") elif result_size == input_size: log("Result has exact same size") else: if options.always_zopflify: log("Original was smaller") else: log("Preserving original PNG since it was smaller") # Set output file to input since zopfli didn't improve it. result_png = input_png if ( not options.overwrite and os.path.isfile(options.outfile) and input(f"File {options.outfile} exists, overwrite? (y/N)\n").strip().lower() != "y" ): return 0 with open(options.outfile, "wb") as f: f.write(result_png) if __name__ == "__main__": main() py-zopfli-0.2.3.post1/src/zopfli/zlib.py000066400000000000000000000004511470447622300201270ustar00rootroot00000000000000import zopfli import zopfli.zopfli def compress(data, **kwargs): """zlib.compress(data, **kwargs) """ + zopfli.__COMPRESSOR_DOCSTRING__ + """ Returns: String containing a zlib container """ kwargs['gzip_mode'] = 0 return zopfli.zopfli.compress(data, **kwargs) py-zopfli-0.2.3.post1/src/zopflimodule.c000066400000000000000000000216111470447622300201700ustar00rootroot00000000000000#define PY_SSIZE_T_CLEAN size_t #include #include #include #ifdef SYSTEM_ZOPFLI #define ZOPFLI_H #define ZOPFLIPNG_H #else #define ZOPFLI_H "../zopfli/src/zopfli/zopfli.h" #define ZOPFLIPNG_H "../zopfli/src/zopflipng/zopflipng_lib.h" #endif #include ZOPFLI_H #include ZOPFLIPNG_H static PyObject * zopfli_compress(PyObject *self, PyObject *args, PyObject *keywrds) { const unsigned char *in; unsigned char *out; size_t insize=0; size_t outsize=0; ZopfliOptions options; int gzip_mode = 0; static char *kwlist[] = {"data", "verbose", "numiterations", "blocksplitting", "blocksplittinglast", "blocksplittingmax", "gzip_mode", NULL}; PyObject *returnValue; ZopfliInitOptions(&options); options.verbose = 0; options.numiterations = 15; options.blocksplitting = 1; options.blocksplittinglast = 0; options.blocksplittingmax = 15; if (!PyArg_ParseTupleAndKeywords(args, keywrds, "s#|iiiiii", kwlist, &in, &insize, &options.verbose, &options.numiterations, &options.blocksplitting, &options.blocksplittinglast, &options.blocksplittingmax, &gzip_mode)) return NULL; if (args) Py_INCREF(args); if (keywrds) Py_INCREF(keywrds); Py_BEGIN_ALLOW_THREADS ZopfliFormat output_type = gzip_mode ? ZOPFLI_FORMAT_GZIP : ZOPFLI_FORMAT_ZLIB; ZopfliCompress(&options, output_type, in, insize, &out, &outsize); Py_END_ALLOW_THREADS if (args) Py_DECREF(args); if (keywrds) Py_DECREF(keywrds); returnValue = PyBytes_FromStringAndSize((char*)out, outsize); free(out); return returnValue; } PyDoc_STRVAR(compress__doc__, "zopfli.zopfli.compress applies zopfli zip or gzip compression to an obj." "" \ "zopfli.zopfli.compress(" " s, **keywrds, verbose=0, numiterations=15, blocksplitting=1, " " blocksplittinglast=0, blocksplittingmax=15, gzip_mode=0)" "" "If gzip_mode is set to a non-zero value, a Gzip compatbile container will " "be generated, otherwise a zlib compatible container will be generated. "); static inline int is_str(PyObject* v) { if (PyUnicode_Check(v)) { return 1; } PyErr_Format(PyExc_TypeError, "expected str, got '%.200s'", Py_TYPE(v)->tp_name); return 0; } static int parse_filter_strategies(CZopfliPNGOptions *options, PyObject *filter_strategies) { int i, num_filter_strategies; PyObject* b = NULL; char* s; if (!is_str(filter_strategies)) { return -1; } b = PyUnicode_AsASCIIString(filter_strategies); if (b == NULL) { return -1; } s = PyBytes_AsString(b); if (s == NULL) { return -1; } num_filter_strategies = strlen(s); options->filter_strategies = (enum ZopfliPNGFilterStrategy*)malloc(num_filter_strategies * sizeof(enum ZopfliPNGFilterStrategy)); if (options->filter_strategies == NULL) { PyErr_SetNone(PyExc_MemoryError); return -1; } for (i = 0; *s != '\0'; ++i, ++s) { enum ZopfliPNGFilterStrategy fs; switch (*s) { case '0': fs = kStrategyZero; break; case '1': fs = kStrategyOne; break; case '2': fs = kStrategyTwo; break; case '3': fs = kStrategyThree; break; case '4': fs = kStrategyFour; break; case 'm': fs = kStrategyMinSum; break; case 'e': fs = kStrategyEntropy; break; case 'p': fs = kStrategyPredefined; break; case 'b': fs = kStrategyBruteForce; break; default: PyErr_Format(PyExc_ValueError, "unknown filter strategy: %c", *s); free(options->filter_strategies); return -1; } options->filter_strategies[i] = fs; } options->num_filter_strategies = num_filter_strategies; options->auto_filter_strategy = 0; return 0; } static int parse_keepchunks(CZopfliPNGOptions *options, PyObject *keepchunks) { int j; PyObject* u = NULL; PyObject* b = NULL; Py_ssize_t i, n = PySequence_Size(keepchunks); if (n < 0) { goto err; } options->keepchunks = (char **)calloc(n, sizeof(char *)); if (options->keepchunks == NULL) { options->num_keepchunks = 0; PyErr_SetNone(PyExc_MemoryError); goto err; } options->num_keepchunks = n; for (i = 0; i < n; ++i) { u = PySequence_GetItem(keepchunks, i); if (u == NULL || !is_str(u)) { goto err; } b = PyUnicode_AsASCIIString(u); if (b == NULL) { goto err; } char* s = PyBytes_AsString(b); if (s == NULL) { goto err; } options->keepchunks[i] = malloc(strlen(s) + 1); if (options->keepchunks[i] == NULL) { PyErr_SetNone(PyExc_MemoryError); goto err; } strcpy(options->keepchunks[i], s); Py_CLEAR(u); Py_CLEAR(b); } return 0; err: Py_XDECREF(u); Py_XDECREF(b); for (j = 0; j < options->num_keepchunks; ++j) { free(options->keepchunks[j]); } free(options->keepchunks); return -1; } static PyObject * zopfli_png_optimize(PyObject *self, PyObject *args, PyObject *keywrds) { PyObject* returnValue = NULL; const unsigned char *in; unsigned char *out; size_t insize = 0; size_t outsize = 0; int err, i; int verbose = 0; PyObject* filter_strategies = Py_None; PyObject* keepchunks = Py_None; static char *kwlist[] = { "data", "verbose", "lossy_transparent", "lossy_8bit", "filter_strategies", "keepchunks", "use_zopfli", "num_iterations", "num_iterations_large", NULL, }; CZopfliPNGOptions options; CZopfliPNGSetDefaults(&options); if (!PyArg_ParseTupleAndKeywords(args, keywrds, "s#|iiiOOiii", kwlist, &in, &insize, &verbose, &options.lossy_transparent, &options.lossy_8bit, &filter_strategies, &keepchunks, &options.use_zopfli, &options.num_iterations, &options.num_iterations_large)) return NULL; if (args) Py_INCREF(args); if (keywrds) Py_INCREF(keywrds); if (filter_strategies != Py_None && parse_filter_strategies(&options, filter_strategies) != 0) { return returnValue; } if (keepchunks != Py_None && parse_keepchunks(&options, keepchunks) != 0) { return returnValue; } Py_BEGIN_ALLOW_THREADS err = CZopfliPNGOptimize(in, insize, &options, verbose, &out, &outsize); Py_END_ALLOW_THREADS if (err) { PyErr_SetString(PyExc_ValueError, "verification failed"); return returnValue; } if (args) Py_DECREF(args); if (keywrds) Py_DECREF(keywrds); returnValue = PyBytes_FromStringAndSize((char*)out, outsize); free(out); free(options.filter_strategies); for (i = 0; i < options.num_keepchunks; ++i) { free(options.keepchunks[i]); } free(options.keepchunks); return returnValue; } PyDoc_STRVAR(png_optimize__doc__, "zopfli.png.optimize(\n" " data,\n" " *,\n" " verbose=False,\n" " lossy_transparent=False,\n" " lossy_8bit=False,\n" " filter_strategies=None,\n" " keepchunks=None,\n" " use_zopfli=True,\n" " num_iterations=15,\n" " num_iterations_large=5,\n" ")\n" "\n" "Args:\n" " data (bytes): input PNG data.\n" " verbose (bool): print more debugging info.\n" " lossy_transparent (bool): remove colors behind alpha channel 0.\n" " lossy_8bit (bool): convert 16-bit per channel image to 8-bit per channel.\n" " filter_strategies (str): filter strategies to try (cf. zopflipng --help)\n" " keepchunks (Sequence[str]): keep metadata chunks with these names that \n" " would normally be removed (cf. zopflipng --help)\n" " num_iterations (int): number of iterations for small files (default: 15).\n" " num_iterations_large (int): number of iterations for large files (default: 5).\n" "Returns:\n" " Bytes string containing the compressed PNG data.\n"); static PyObject *ZopfliError; static PyMethodDef ZopfliMethods[] = { { "compress", (PyCFunction)zopfli_compress, METH_VARARGS | METH_KEYWORDS, compress__doc__}, { "png_optimize", (PyCFunction)zopfli_png_optimize, METH_VARARGS | METH_KEYWORDS, png_optimize__doc__}, { NULL, NULL, 0, NULL} }; PyDoc_STRVAR(zopfli__doc__, "Wrapper around zopfli's ZlibCompress, GzipCompress and ZopfliPNGOptimize methods."); #define INIT_ZOPFLI PyInit_zopfli #define CREATE_ZOPFLI PyModule_Create(&zopfli_module) #define RETURN_ZOPFLI return m static struct PyModuleDef zopfli_module = { PyModuleDef_HEAD_INIT, "zopfli", zopfli__doc__, 0, ZopfliMethods, NULL, NULL, NULL }; PyMODINIT_FUNC INIT_ZOPFLI(void) { PyObject *m = CREATE_ZOPFLI; ZopfliError = PyErr_NewException((char*) "zopfli.error", NULL, NULL); if (ZopfliError != NULL) { Py_INCREF(ZopfliError); PyModule_AddObject(m, "error", ZopfliError); } RETURN_ZOPFLI; } py-zopfli-0.2.3.post1/tests/000077500000000000000000000000001470447622300156655ustar00rootroot00000000000000py-zopfli-0.2.3.post1/tests/__init__.py000066400000000000000000000000001470447622300177640ustar00rootroot00000000000000py-zopfli-0.2.3.post1/tests/data/000077500000000000000000000000001470447622300165765ustar00rootroot00000000000000py-zopfli-0.2.3.post1/tests/data/PngSuite.LICENSE.txt000066400000000000000000000002471470447622300221610ustar00rootroot00000000000000PngSuite -------- Permission to use, copy, modify and distribute these images for any purpose and without fee is hereby granted. (c) Willem van Schaik, 1996, 2011 py-zopfli-0.2.3.post1/tests/data/basn0g01.png000066400000000000000000000002441470447622300206170ustar00rootroot00000000000000PNG  IHDR [GYgAMA1_[IDATx-̱ 0 J z4o< aEQ/ҤlΩ%SS4W!K&=Bs%%^ڲoj0i.)ano0eI//IENDB`py-zopfli-0.2.3.post1/tests/data/basn2c16.png000066400000000000000000000004561470447622300206300ustar00rootroot00000000000000PNG  IHDR 1gAMA1_IDATxՖ 0DA~&fzE=֠B>/drs~='3_Zwt(p3p]`_yt?t(C\l52L̩g I@g.`(`g Dg&((`60Y`zl(P49܀:{z*zȟmt3ΞAO3B^IENDB`py-zopfli-0.2.3.post1/tests/data/tbbn2c16.png000066400000000000000000000037711470447622300206350ustar00rootroot00000000000000PNG  IHDR 1gAMA1_tRNSK2bKGDGeIDATX LeG0nL$QbSbe#v<\" LTºRZ e79N4:qd:f 1fDs6YPA;X 9M6 |M:R@JJuuw[ؘ ;6.\r'("b2dqVUUxlhcgz{LMM_<'pC< TU=n^/ݍAb2k`"Vyzp#$d/ɬ X,侾dn A8t$9$8hѓl#={$ヒ}7z7&R'I.d;xEKjdN p/-ľ}ٳBNMƶDxs;VL?JpX-Ē%v% ͘TxJ^/ {> _TG`!B|qqBzmT;5G8 Nr?X /k]gpELxd\yok04@WĪD!z ٿʐ<X+$ښCxO#bbBӄ7m݌5!¯)/}޾F$Vi-0LD Yw,DY q W aIENDB`py-zopfli-0.2.3.post1/tests/test_zopfli.py000066400000000000000000000100011470447622300205710ustar00rootroot00000000000000#!/usr/bin/env python import gzip import shutil import subprocess import sys import zlib from io import BytesIO from pathlib import Path import zopfli.gzip import zopfli.zlib import zopfli.png import pytest class BaseTests(object): data = (Path(__file__).parent.parent / "README.rst").read_bytes() def test_reversible(self): data = self.data assert self.decompress(self.compress(data)) == data def test_iterations_help(self): data = self.data assert len(self.compress(data, numiterations=1)) > len( self.compress(data, numiterations=1000) ) class TestZlib(BaseTests): compress = staticmethod(zopfli.zlib.compress) decompress = staticmethod(zlib.decompress) class TestGzip(BaseTests): compress = staticmethod(zopfli.gzip.compress) def decompress(self, s): return gzip.GzipFile(fileobj=BytesIO(s)).read() # The first eight bytes of a PNG file always contain the following (decimal) values: # 137 80 78 71 13 10 26 10 # https://www.w3.org/TR/PNG-Structure.html PNG_HEADER = b"\x89PNG\r\n\x1a\n" DATA_DIR = Path(__file__).parent / "data" class TestPngOptimize: @staticmethod def assert_valid_png_header(data): assert len(data) >= 8 assert data[:8] == PNG_HEADER @pytest.fixture(params=list(DATA_DIR.glob("*.png"))) def png_file(self, request): return request.param @pytest.fixture def png_data(self, png_file): png = png_file.read_bytes() self.assert_valid_png_header(png) return png @pytest.mark.parametrize( "kwargs", [ {}, # default {"verbose": True}, {"lossy_transparent": True}, {"lossy_8bit": True}, {"use_zopfli": False}, {"filter_strategies": "01234mepb"}, {"keepchunks": ["gAMA", "bKGD"]}, {"num_iterations": 30}, {"num_iterations_large": 10}, ], ) def test_optimize_with_arguments(self, png_data, kwargs): result_png = zopfli.png.optimize(png_data, **kwargs) self.assert_valid_png_header(result_png) assert len(result_png) < len(png_data) @pytest.mark.parametrize( "options", [ [], # default ["-v"], ["-m"], ["--lossy_transparent", "--lossy_8bit"], ["-q"], ["--always_zopflify"], ["--iterations", "20"], ["--filters", "0me"], ["--keepchunks", "sBIT,bKGD"], ], ) def test_cli(self, png_file, tmp_path, options): output_file = tmp_path / png_file.name cmd = ( [sys.executable, "-m", "zopfli.png"] + options + [str(png_file), str(output_file)] ) p = subprocess.run(cmd, check=True, capture_output=True) if "-v" in options: assert "Result is smaller" in p.stdout.decode() assert output_file.exists() assert output_file.stat().st_size < png_file.stat().st_size @pytest.mark.parametrize( "overwrite, answer", [(True, ""), (False, "y"), (False, "N")] ) def test_cli_overwrite(self, tmp_path, answer, overwrite): input_file = next(DATA_DIR.glob("*.png")) output_file = tmp_path / input_file.name shutil.copy(input_file, output_file) cmd = ( [sys.executable, "-m", "zopfli.png", "-v"] + (["-y"] if overwrite else []) + [str(input_file), str(output_file)] ) p = subprocess.run(cmd, input=answer.encode(), check=True, capture_output=True) stdout = p.stdout.decode() assert "Result is smaller" in stdout assert ("exists, overwrite? (y/N)" in stdout) ^ overwrite if overwrite or answer == "y": assert output_file.stat().st_size < input_file.stat().st_size elif not overwrite and answer == "N": assert output_file.stat().st_size == input_file.stat().st_size if __name__ == "__main__": import sys pytest.main(sys.argv) py-zopfli-0.2.3.post1/tox.ini000066400000000000000000000001641470447622300160370ustar00rootroot00000000000000[tox] envlist = py3{8,9,10,11,12} [testenv] extras = test download = true commands = pytest {posargs:tests} -v py-zopfli-0.2.3.post1/zopfli/000077500000000000000000000000001470447622300160265ustar00rootroot00000000000000