Skip to content

Commit

Permalink
- remove unused functions
Browse files Browse the repository at this point in the history
  • Loading branch information
marthamareal committed Sep 26, 2022
1 parent 379d6a8 commit 7895c7b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 83 deletions.
76 changes: 0 additions & 76 deletions geonode/documents/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
#
#########################################################################

import io
import os
import subprocess
import traceback
Expand All @@ -34,85 +33,10 @@ class ConversionError(Exception):
pass


class MissingPILError(Exception):
"""Raise when could not import PIL package."""
pass


def guess_mimetype(document_path):
"""Guess mime type for a file in local filesystem.
Return string containing valid mime type.
"""
document_url = pathname2url(document_path)
return guess_type(document_url)[0]


def render_document(document_path, extension="png"):
"""Render document using `unconv` converter.
Package `unoconv` has to be installed and available on system
path. Return `NamedTemporaryFile` instance.
"""

# workaround: https://github.com/dagwieers/unoconv/issues/167
# first convert a document to PDF and continue
dispose_input = False
if extension != "pdf" and guess_mimetype(document_path) != 'application/pdf':
document_path = render_document(document_path, extension="pdf")
dispose_input = True

# spawn subprocess and render the document
output_path = None
if settings.UNOCONV_ENABLE:
timeout = None
_, output_path = tempfile.mkstemp(suffix=f".{extension}")
try:
unoconv = subprocess.Popen(
[settings.UNOCONV_EXECUTABLE, "-v", "-e", "PageRange=1-2",
"-f", extension, "-o", output_path, document_path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
timeout = Timer(settings.UNOCONV_TIMEOUT, unoconv.kill)
timeout.start()
stdout, stderr = unoconv.communicate()
except Exception as e:
traceback.print_exc()
raise ConversionError(str(e))
finally:
if timeout:
timeout.cancel()
if dispose_input and document_path is not None:
os.remove(document_path)
else:
raise NotImplementedError("unoconv is disabled. Set 'UNOCONV_ENABLE' to enable.")

return output_path


def generate_thumbnail_content(image_path, size=(200, 150)):
"""Generate thumbnail content from an image file.
Return the entire content of the image file.
"""

try:
from PIL import Image, ImageOps
except ImportError:
raise MissingPILError()

try:
image = Image.open(image_path)
source_width, source_height = image.size
target_width, target_height = size

if source_width != target_width or source_width != target_height:
image = ImageOps.fit(image, size, Image.ANTIALIAS)

with io.BytesIO() as output:
image.save(output, format='PNG')
content = output.getvalue()
output.close()
return content
except Exception as e:
raise e
22 changes: 15 additions & 7 deletions geonode/documents/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
import io

from PIL import Image

from celery.utils.log import get_task_logger

from geonode.celery_app import app
from geonode.storage.manager import storage_manager

from ..base.models import ResourceBase
from .models import Document
from .renderers import (generate_thumbnail_content)

logger = get_task_logger(__name__)

Expand Down Expand Up @@ -53,28 +56,33 @@ def create_document_thumbnail(self, object_id):
raise

image_file = None
thumbnail_content = None

if document.is_image:
dname = storage_manager.path(document.files[0])
if storage_manager.exists(dname):
image_file = storage_manager.open(dname, 'rb')

thumbnail_content = None
try:
thumbnail_content = generate_thumbnail_content(image_file)
# Generate thumbnail content from an image file and return the entire content of the image file.
image = Image.open(image_file)

with io.BytesIO() as output:
image.save(output, format='PNG')
content = output.getvalue()
output.close()
thumbnail_content = content
except Exception as e:
logger.debug(f"Could not generate thumbnail, setting thumbnail_url to None: {e}")
ResourceBase.objects.filter(id=document.id).update(thumbnail_url=None)
finally:
if image_file is not None:
image_file.close()

if not thumbnail_content:
logger.warning(f"Thumbnail for document #{object_id} empty.")
if thumbnail_content:
filename = f'document-{document.uuid}-thumb.png'
document.save_thumbnail(filename, thumbnail_content)
logger.debug(f"Thumbnail for document #{object_id} created.")
else:
logger.warning(f"Thumbnail for document #{object_id} is empty.")
ResourceBase.objects.filter(id=document.id).update(thumbnail_url=None)


Expand Down

0 comments on commit 7895c7b

Please sign in to comment.