Use six.text_type instead of unicode().
[mediagoblin.git] / mediagoblin / media_types / image / processing.py
index 555a0e0a625d25bca6dc0abb8119ebd14c5fec1f..ae9ece2465e5e050cc219f713decfa53c4e2a380 100644 (file)
@@ -14,6 +14,8 @@
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
+
 try:
     from PIL import Image
 except ImportError:
@@ -22,6 +24,8 @@ import os
 import logging
 import argparse
 
+import six
+
 from mediagoblin import mg_globals as mgg
 from mediagoblin.processing import (
     BadMediaFail, FilenameBuilder,
@@ -65,7 +69,7 @@ def resize_image(entry, resized, keyname, target_name, new_size,
         resize_filter = PIL_FILTERS[filter.upper()]
     except KeyError:
         raise Exception('Filter "{0}" not found, choose one of {1}'.format(
-            unicode(filter),
+            six.text_type(filter),
             u', '.join(PIL_FILTERS.keys())))
 
     resized.thumbnail(new_size, resize_filter)
@@ -76,6 +80,14 @@ def resize_image(entry, resized, keyname, target_name, new_size,
         resized.save(resized_file, quality=quality)
     store_public(entry, keyname, tmp_resized_filename, target_name)
 
+    # store the thumb/medium info
+    image_info = {'width': new_size[0],
+                  'height': new_size[1],
+                  'quality': quality,
+                  'filter': filter}
+
+    entry.set_file_metadata(keyname, **image_info)
+
 
 def resize_tool(entry,
                 force, keyname, orig_file, target_name,
@@ -86,6 +98,13 @@ def resize_tool(entry,
         max_height = mgg.global_config['media:' + keyname]['max_height']
         new_size = (max_width, max_height)
 
+    # If thumb or medium is already the same quality and size, then don't
+    # reprocess
+    if _skip_resizing(entry, keyname, new_size, quality, filter):
+        _log.info('{0} of same size and quality already in use, skipping '
+                  'resizing of media {1}.'.format(keyname, entry.id))
+        return
+
     # If the size of the original file exceeds the specified size for the desized
     # file, a target_name file is created and later associated with the media
     # entry.
@@ -99,30 +118,52 @@ def resize_tool(entry,
         or im.size[1] > new_size[1]\
         or exif_image_needs_rotation(exif_tags):
         resize_image(
-            entry, im, unicode(keyname), target_name,
+            entry, im, six.text_type(keyname), target_name,
             tuple(new_size),
             exif_tags, conversions_subdir,
             quality, filter)
 
 
+def _skip_resizing(entry, keyname, size, quality, filter):
+    """
+    Determines wither the saved thumb or medium is of the same quality and size
+    """
+    image_info = entry.get_file_metadata(keyname)
+
+    if not image_info:
+        return False
+
+    skip = True
+
+    if image_info.get('width') != size[0]:
+        skip = False
+
+    elif image_info.get('height') != size[1]:
+        skip = False
+
+    elif image_info.get('filter') != filter:
+        skip = False
+
+    elif image_info.get('quality') != quality:
+        skip = False
+
+    return skip
+
+
 SUPPORTED_FILETYPES = ['png', 'gif', 'jpg', 'jpeg', 'tiff']
 
 
-def sniff_handler(media_file, **kw):
+def sniff_handler(media_file, filename):
     _log.info('Sniffing {0}'.format(MEDIA_TYPE))
-    if kw.get('media') is not None:  # That's a double negative!
-        name, ext = os.path.splitext(kw['media'].filename)
-        clean_ext = ext[1:].lower()  # Strip the . from ext and make lowercase
-
-        if clean_ext in SUPPORTED_FILETYPES:
-            _log.info('Found file extension in supported filetypes')
-            return MEDIA_TYPE
-        else:
-            _log.debug('Media present, extension not found in {0}'.format(
-                    SUPPORTED_FILETYPES))
+    name, ext = os.path.splitext(filename)
+    clean_ext = ext[1:].lower()  # Strip the . from ext and make lowercase
+
+    if clean_ext in SUPPORTED_FILETYPES:
+        _log.info('Found file extension in supported filetypes')
+        return MEDIA_TYPE
     else:
-        _log.warning('Need additional information (keyword argument \'media\')'
-                     ' to be able to handle sniffing')
+        _log.debug('Media present, extension not found in {0}'.format(
+                SUPPORTED_FILETYPES))
 
     return None
 
@@ -144,7 +185,7 @@ class CommonImageProcessor(MediaProcessor):
         ## @@: Should this be two functions?
         # Conversions subdirectory to avoid collisions
         self.conversions_subdir = os.path.join(
-            self.workbench.dir, 'convirsions')
+            self.workbench.dir, 'conversions')
         os.mkdir(self.conversions_subdir)
 
         # Pull down and set up the processing file
@@ -344,5 +385,4 @@ if __name__ == '__main__':
     clean = clean_exif(result)
     useful = get_useful(clean)
 
-    print pp.pprint(
-        clean)
+    print(pp.pprint(clean))