Manuel Barkhau avatar Manuel Barkhau committed 6d466cd

finished packaging

Comments (0)

Files changed (7)

 *.pyo
 tinypng.keys
 *sublime*
-*.png
+*.png
+build/*
+dist/*
+*egg*
+MANIFEST
 Copyright (c) 2012 Vladimir Keleshev, <vladimir@keleshev.com>
 
-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:
+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 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,
+include LICENSE
+include README.markdown
+include setup.py
+include scripts/tinypng
+include tinypng/__init__.py
 
 Python module and command line tool for [tinypng.org][1]
 
+Shrink PNG files. Advanced lossy compression for PNG images
+that preserves full alpha transparency.
+
 Note: This project is not affiliated with [tinypng.org][1] or [Voormedia B.V.][2]
 
 Important: You require an API key which you may obtain from
+#!/usr/bin/env python
+"""TinyPNG API
+
+Python module and command line tool for api.tinypng.org
+
+Shrink PNG files. Advanced lossy compression for PNG images
+that preserves full alpha transparency.
+
+Note: This project is not affiliated with tinypng.org or Voormedia B.V.
+
+Important: You require an API key which you may obtain from
+info@tinypng.org (as of October 2012).
+
+Besides specifying keys via command line arguments you can
+    1. Set the environment variable TINYPNG_API_KEY
+    2. Create a .tinypng.keys file in your home directory
+    3. Create a tinypng.keys file in the current directory
+
+Keyfiles must have one key per line. Invalid keys should
+be removed as they slow down requests.
+
+Usage:
+    tinypng.py <png_files>...
+    tinypng.py <png_files>...
+    tinypng.py --key=<key> <png_files>...
+    tinypng.py --apikeys=<keyfile> <png_files>...
+    tinypng.py -h | --help
+    tinypng.py --version
+
+Options:
+    --key=<key>                 API Key
+    --apikeys=<keyfile>         File with one key per line
+    --extension=<extension>     Suffix of new images [default: .tiny.png]
+    -h --help                   Show this screen
+    -v --verbose                Display output about written files
+    --version                   Show version.
+"""
+
+import sys
+from tinypng import shrink_file, find_keys, __version__
+
+
+def main(argv=sys.argv):
+    if argv is None:
+        argv = sys.argv
+
+    from docopt import docopt
+
+    version = 'TinyPNG API ' + __version__
+    opts, args = docopt(__doc__, argv=argv[1:], version=version)
+    keys = find_keys(opts, args)
+
+    if keys is None:
+        print("Error: Could not find API key (see help).")
+        return 1
+
+    for fpath in args.png_files:
+        for key in keys:
+            try:
+                info = shrink_file(fpath, key)
+                if opts.verbose:
+                    out = out_info['output']
+                    print("Shrunk file %s saved %02d %")
+                break
+            except ValueError:
+                print('Invalid Key "%s"' % key)
+
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())
 from setuptools import setup
 from os.path import join, dirname
+from tinypng import __version__
 
 
 def read(fname):
 
 setup(
     name='tinypng',
-    version='1.0',
+    version=__version__,
     description='Access api.tinypng.org from the shell and python scripts',
-    long_description=read('README'),
+    long_description=read('README.markdown'),
     author='Manuel Barkhau',
     author_email='mbarkhau@gmail.com',
     url='http://bitbucket.org/mbarkhau/tinypng/',
     license="MIT",
     packages=['tinypng'],
-    requires=['docopt'],
-    entry_points={'console_scripts': ["tinypng = tinypng:main"]},
-    keywords="png image compression",
+    requires=['docopt (>=0.5.0)'],
+    scripts=['scripts/tinypng'],
+    keywords="png image compression tinypng shrink",
     classifiers=[
         'Development Status :: 4 - Beta',
         'Environment :: Console',

tinypng/__init__.py

 #!/usr/bin/env python
-"""TinyPNG API
-
-Python module and command line tool for api.tinypng.org
-
-Important: You require an API key which you may obtain from
-info@tinypng.org (as of October 2012).
-
-Besides specifying keys via command line arguments you can
-    1. Set the environment variable TINYPNG_API_KEY
-    2. Create a .tinypng.keys file in your home directory
-    3. Create a tinypng.keys file in the current directory
-
-Keyfiles must have one key per line. Invalid keys should
-be removed as they slow down requests.
-
-Usage:
-    tinypng.py <png_files>...
-    tinypng.py <png_files>...
-    tinypng.py --key=<key> <png_files>...
-    tinypng.py --apikeys=<keyfile> <png_files>...
-    tinypng.py -h | --help
-    tinypng.py --version
-
-Options:
-    --key=<key>                 API Key
-    --apikeys=<keyfile>         File with one key per line
-    --extension=<extension>     Suffix of new images [default: .tiny.png]
-    -h --help                   Show this screen
-    --version                   Show version.
-"""
 from __future__ import print_function
+__version__ = "1.0.5"
 
 import os
-import sys
 import json
 from os.path import abspath, isfile, join, expanduser
 from base64 import standard_b64encode
 
 try:
-    from urllib2 import Request, HTTPError, urlopen
-except ImportError:
     from urllib.request import Request, urlopen
     from urllib.error import HTTPError
+except ImportError:
+    from urllib2 import Request, HTTPError, urlopen
 
 
 TINY_URL = "http://api.tinypng.org/api/shrink"
 _invalid_keys = set()
 
 
-def tinypng_info(in_data, api_key):
+def find_keys(opts=None, args=None):
+    """Get keys specified in arguments
+
+    returns list of keys or None
+    """
+    def readkeys(filepath):
+        with open(filepath) as kf:
+            return [k.strip() for k in kf.readlines()]
+
+    if opts.key:
+        return [opts.key]
+
+    if opts.apikeys:
+        return readkeys(opts.apikeys)
+
+    envkey = os.environ.get('TINYPNG_API_KEY', None)
+    if envkey:
+        return [envkey]
+
+    local_keys = join(abspath("."), "tinypng.keys")
+    home_keys = join(expanduser("~/.tinypng.keys"))
+
+    if isfile(local_keys):
+        return readkeys(local_keys)
+    if isfile(home_keys):
+        return readkeys(local_keys)
+
+    return None
+
+
+def shrink(in_data, api_key):
     if api_key is None:
-        msg = "tinypng() requirs the 'api_key' argument. "
+        msg = "Missing required argument 'api_key' for tinypng.shrink_*()."
         msg += "You may get a key from info@tinypng.org."
         raise TypeError(msg)
 
+    if api_key in _invalid_keys:
+        raise ValueError("Invalid argument api key")
+
     raw_key = ("api:" + api_key).encode('ascii')
     enc_key = standard_b64encode(raw_key).decode('ascii')
     request = Request(TINY_URL, in_data)
         return json.loads(result.read().decode('utf8'))
     except HTTPError as err:
         if err.code == 403:
+            _invalid_keys.add(api_key)
             raise ValueError("Invalid argument api key")
 
         print("TinyPNG Error: ", err.code)
         return
 
 
-def tinypng_data(in_data, api_key):
-    info = tinypng_info(in_data, api_key)
+def shrink_data(in_data, api_key):
+    info = shrink(in_data, api_key)
     out_url = info['output']['url']
     try:
         return info, urlopen(out_url).read()
         raise exc
 
 
-def tinypng_file(in_filepath, out_filepath=None, api_key=None):
+def shrink_file(in_filepath, out_filepath=None, api_key=None):
     if out_filepath is None:
         out_filepath = in_filepath
         if out_filepath.endswith(".png"):
 
     in_data = open(in_filepath, 'rb').read()
 
-    out_info, out_data = tinypng_data(in_data, api_key)
+    out_info, out_data = shrink_data(in_data, api_key)
     out_info['output']['filepath'] = abspath(out_filepath)
-
     with open(out_filepath, 'wb') as f:
         f.write(out_data)
 
     return out_info
-
-
-def findkeys(opts=None, args=None):
-    """Get keys specified in arguments
-
-    returns list of keys or None
-    """
-    def readkeys(filepath):
-        with open(filepath) as kf:
-            return [k.strip() for k in kf.readlines()]
-
-    if opts.key:
-        return [opts.key]
-
-    if opts.apikeys:
-        return readkeys(opts.apikeys)
-
-    envkey = os.environ.get('TINYPNG_API_KEY', None)
-    if envkey:
-        return [envkey]
-
-    local_keys = join(abspath("."), "tinypng.keys")
-    home_keys = join(expanduser("~/.tinypng.keys"))
-
-    if isfile(local_keys):
-        return readkeys(local_keys)
-    if isfile(home_keys):
-        return readkeys(local_keys)
-
-    return None
-
-
-def main(argv=sys.argv):
-    if argv is None:
-        argv = sys.argv
-
-    from docopt import docopt
-
-    opts, args = docopt(__doc__, argv=argv[1:], version='TinyPNG API 1.0')
-    keys = findkeys(opts, args)
-
-    if keys is None:
-        print("Error: Could not find API key (see help).")
-        return 1
-
-    print(keys)
-
-
-if __name__ == "__main__":
-    sys.exit(main())
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.