Implement class based converter transformations

This commit is contained in:
Roberto Rosario
2015-06-07 05:29:31 -04:00
parent f4752a3f3f
commit b256758db2
10 changed files with 212 additions and 231 deletions
+132 -59
View File
@@ -1,12 +1,21 @@
from __future__ import unicode_literals
import logging
import io
import os
import subprocess
from tempfile import mkstemp
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from PIL import Image
from django.utils.encoding import smart_str
from django.utils.module_loading import import_string
from django.utils.translation import ugettext_lazy as _
from common.settings import TEMPORARY_DIRECTORY
from common.utils import fs_cleanup
@@ -18,7 +27,6 @@ from .literals import (
DEFAULT_FILE_FORMAT, TRANSFORMATION_CHOICES, TRANSFORMATION_RESIZE,
TRANSFORMATION_ROTATE, TRANSFORMATION_ZOOM, DIMENSION_SEPARATOR
)
from .office_converter import OfficeConverter
from .settings import GRAPHICS_BACKEND, LIBREOFFICE_PATH
CONVERTER_OFFICE_FILE_MIMETYPES = [
@@ -70,44 +78,7 @@ CONVERTER_OFFICE_FILE_MIMETYPES = [
logger = logging.getLogger(__name__)
logger.debug('initializing office backend')
try:
office_converter = OfficeConverter()
except OfficeBackendError as exception:
logger.error('error initializing office backend; %s', exception)
office_converter = None
else:
logger.debug('office_backend initialized')
backend = import_string(GRAPHICS_BACKEND)()
class BaseTransformation(object):
name = 'base_transformation'
arguments = ()
def __init__(self, **kwargs):
for argument_name in self.arguments:
setattr(self, argument_name, kwargs.get(argument_name))
class TransformationResize(BaseTransformation):
name = 'resize'
arguments = ('width', 'height')
class TransformationRotate(BaseTransformation):
name = 'rotate'
arguments = ('degrees',)
class TransformationScale(BaseTransformation):
name = 'scale'
arguments = ('percent',)
class Converter(object):
class ConverterBase(object):
@staticmethod
def soffice(file_object):
"""
@@ -154,38 +125,140 @@ class Converter(object):
def __init__(self, file_object, mime_type=None):
self.file_object = file_object
self.mime_type = mime_type or get_mimetype(file_object=file_object, mimetype_only=False)[0]
self.temporary_files = []
self.soffice_file_object = None
def transform(self, transformations, page=DEFAULT_PAGE_NUMBER):
pass
def seek(self, page_number):
# Starting with #0
self.file_object.seek(0)
try:
self.image = Image.open(self.file_object)
except IOError:
# Cannot identify image file
self.image = self.convert(page_number=page_number)
else:
self.image.seek(page_number)
self.image.load()
def get_page(self, output_format=DEFAULT_FILE_FORMAT):
if not self.image:
self.seek(1)
image_buffer = StringIO()
self.image.save(image_buffer, format=output_format)
image_buffer.seek(0)
return image_buffer
def convert(self, page_number=DEFAULT_PAGE_NUMBER):
self.page_number = page_number
self.mime_type = 'application/pdf'
def convert(self, output_format=DEFAULT_FILE_FORMAT, page=DEFAULT_PAGE_NUMBER):
if self.mime_type in CONVERTER_OFFICE_FILE_MIMETYPES:
if os.path.exists(LIBREOFFICE_PATH):
converted_output = Converter.soffice(self.file_object)
self.file_object.close()
self.file_object = open(converted_output)
self.mime_type = 'application/pdf'
self.temporary_file.append(converted_output)
if not self.soffice_file_object:
converted_output = Converter.soffice(self.file_object)
self.file_object.seek(0)
self.soffice_file_object = open(converted_output)
self.mime_type = 'application/pdf'
fs_cleanup(converted_output)
else:
self.soffice_file_object.seek(0)
else:
# TODO: NO LIBREOFFICE FOUND ERROR
pass
for temporary_file in self.temporary_files:
fs_cleanup(temporary_file)
def transform(self, transformation):
self.image = transformation.execute_on(self.image)
return backend.convert(file_object=self.file_object, mimetype=self.mime_type, output_format=output_format, page=page)
def transform_many(self, transformations):
for transformation in transformations:
self.image = transformation.execute_on(self.image)
def get_page_count(self):
return backend.get_page_count(file_object)
raise NotImplementedError()
'''
def get_available_transformations_choices():
result = []
for transformation in backend.get_available_transformations():
result.append((transformation, TRANSFORMATION_CHOICES[transformation]['label']))
class BaseTransformation(object):
name = 'base_transformation'
arguments = ()
return result
'''
_registry = {}
@classmethod
def get_transformations_classes(cls):
return map(lambda name: getattr(cls, name), filter(lambda entry: entry.startswith('Transform'), dir(cls)))
@classmethod
def get_transformations_choices(cls):
return [(transformation.name, transformation.label) for transformation in cls.get_transformations_classes()]
def __init__(self, **kwargs):
for argument_name in self.arguments:
setattr(self, argument_name, kwargs.get(argument_name))
def execute_on(self, image):
self.image = image
self.aspect = 1.0 * image.size[0] / image.size[1]
class TransformationResize(BaseTransformation):
name = 'resize'
arguments = ('width', 'height')
label = _('Resize')
def execute_on(self, *args, **kwargs):
super(TransformationResize, self).execute_on(*args, **kwargs)
fit = False
width = int(self.width)
height = int(self.height or 1.0 * width * self.aspect)
factor = 1
while self.image.size[0] / factor > 2 * width and self.image.size[1] * 2 / factor > 2 * height:
factor *= 2
if factor > 1:
self.image.thumbnail((self.image.size[0] / factor, self.image.size[1] / factor), Image.NEAREST)
# calculate the cropping box and get the cropped part
if fit:
x1 = y1 = 0
x2, y2 = self.image.size
wRatio = 1.0 * x2 / width
hRatio = 1.0 * y2 / height
if hRatio > wRatio:
y1 = y2 / 2 - height * wRatio / 2
y2 = y2 / 2 + height * wRatio / 2
else:
x1 = x2 / 2 - width * hRatio / 2
x2 = x2 / 2 + width * hRatio / 2
self.image = self.image.crop((x1, y1, x2, y2))
# Resize the image with best quality algorithm ANTI-ALIAS
self.image.thumbnail((width, height), Image.ANTIALIAS)
return self.image
class TransformationRotate(BaseTransformation):
name = 'rotate'
arguments = ('degrees',)
label = _('Rotate')
def execute_on(self, *args, **kwargs):
super(TransformationRotate, self).execute_on(*args, **kwargs)
return self.image.rotate(360 - self.degrees)
class TransformationZoom(BaseTransformation):
name = 'zoom'
arguments = ('percent',)
label = _('Zoom')
def execute_on(self, *args, **kwargs):
super(TransformationZoom, self).execute_on(*args, **kwargs)
decimal_value = float(self.percent) / 100
return self.image.resize((int(self.image.size[0] * decimal_value), int(self.image.size[1] * decimal_value)), Image.ANTIALIAS)