Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/files.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ In general it's recommended to add a thumbnail using the `thumbnail` attribute o
rather than constructing a `ThumbnailFile` and calling `add_file()` — the `thumbnail`
attribute accepts the same local path or URL and wraps it in a `ThumbnailFile` for you.

The recommended size for thumbnail images is 400px by 225px (aspect ratio 16:9).
Thumbnails are converted to a 400×225 PNG, scaled down to fit and letterboxed with transparency.


File size limits
Expand Down
2 changes: 1 addition & 1 deletion docs/nodes.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ See [languages][./languages.md] to read more about language codes.
### Thumbnails
Thumbnails can be passed in as a local filesystem path to an image file (str),
a URL (str), or a `ThumbnailFile` object.
The recommended size for thumbnail images is 400px by 225px (aspect ratio 16:9).
Thumbnails are converted to a 400×225 PNG, scaled down to fit and letterboxed with transparency.
Use the command line argument `--thumbnails` to automatically generate thumbnails
for all content node that don't have a thumbnail specified.

Expand Down
27 changes: 15 additions & 12 deletions ricecooker/classes/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from ricecooker.utils.images import create_image_from_zip
from ricecooker.utils.images import create_image_from_zip_screenshot
from ricecooker.utils.images import create_tiled_image
from ricecooker.utils.images import THUMBNAIL_RESIZE
from ricecooker.utils.images import ThumbnailGenerationError
from ricecooker.utils.paths import resolve_path_ext
from ricecooker.utils.pipeline import FilePipeline
Expand Down Expand Up @@ -204,6 +205,7 @@ def process_file(self):

class DownloadFile(File):
allowed_formats = None
pipeline_context = {}

def __init__(self, path, context=None, **kwargs):
self.path = path.strip()
Expand All @@ -216,6 +218,7 @@ def __init__(self, path, context=None, **kwargs):
"preserve_kind": True,
"render_html": self.allowed_formats is None
or file_formats.HTML5 in self.allowed_formats,
**self.pipeline_context,
}
self.context.update(context or {})

Expand Down Expand Up @@ -300,7 +303,14 @@ class ImageDownloadFile(DownloadFile):


class ThumbnailFile(ThumbnailPresetMixin, ImageDownloadFile):
allowed_formats = ImageConversionHandler.EXTENSIONS
default_ext = file_formats.PNG
pipeline_context = THUMBNAIL_RESIZE
unconverted_filename = None

def get_unconverted_path(self):
filename = self.get_filename()
return config.get_storage_path(self.unconverted_filename or filename)


def _ffmpeg_context(settings_key, ffmpeg_settings):
Expand Down Expand Up @@ -455,22 +465,18 @@ def __init__(self, path, **kwargs):


class Base64ImageFile(ThumbnailPresetMixin, DownloadFile):
allowed_formats = ImageConversionHandler.EXTENSIONS
default_ext = file_formats.PNG
pipeline_context = THUMBNAIL_RESIZE

def __init__(self, encoding, **kwargs):
super().__init__(encoding, **kwargs)


class _ExerciseBase64ImageFile(Base64ImageFile):
class _ExerciseBase64ImageFile(DownloadFile):
default_ext = file_formats.PNG
default_preset = format_presets.EXERCISE_IMAGE

def get_preset(self):
# Exercise images are attached to a question, not a node, so the
# ThumbnailPresetMixin.get_preset inherited from Base64ImageFile
# (which dereferences self.node) does not apply. Use the exercise
# image preset, mirroring _ExerciseImageFile.
return self.preset or self.default_preset

def get_replacement_str(self):
return self.get_filename() or self.path

Expand Down Expand Up @@ -682,10 +688,7 @@ def generate_tiled_image(self):
else:
return None
config.LOGGER.info("\tGenerating tiled thumbnail.")
images = [
config.get_storage_path(f.get_filename())
for f in self.sources[:num_pictures]
]
images = [f.get_unconverted_path() for f in self.sources[:num_pictures]]
with tempfile.NamedTemporaryFile(
suffix=".{}".format(file_formats.PNG)
) as tempf:
Expand Down
47 changes: 47 additions & 0 deletions ricecooker/utils/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import ebooklib.epub
from pdf2image import convert_from_path
from PIL import Image
from PIL import ImageCms
from PIL import ImageOps

from .thumbscropping import scale_and_crop
from .zip import find_html_entrypoint
Expand All @@ -17,6 +19,12 @@
################################################################################

THUMBNAIL_SIZE = (400, 225) # 16:9 aspect ratio
THUMBNAIL_RESIZE = {
"width": THUMBNAIL_SIZE[0],
"height": THUMBNAIL_SIZE[1],
"maintain_aspect_ratio": True,
}
SRGB_PROFILE = ImageCms.createProfile("sRGB")


def scale_and_crop_thumbnail(image, size=THUMBNAIL_SIZE, crop="smart", **kwargs):
Expand All @@ -34,6 +42,45 @@ def scale_and_crop_thumbnail(image, size=THUMBNAIL_SIZE, crop="smart", **kwargs)
return scale_and_crop(image, size, crop=crop, upscale=True, **kwargs)


def resize_image(image, width=None, height=None, maintain_aspect_ratio=True):
"""
Letterboxing with both dimensions and ``maintain_aspect_ratio`` matches
Studio's thumbnails (learningequality/studio#6351).
"""
bound = max(width or image.width, height or image.height)
image.draft(None, (bound, bound))
icc_profile = image.info.get("icc_profile")
ImageOps.exif_transpose(image, in_place=True)
if icc_profile:
image = _to_srgb(image, icc_profile)
if image.mode.startswith("I"):
image = image.convert("I").point(lambda v: v / 256).convert("L")
image = image.convert("RGBA")
size = (width or image.width, height or image.height)
if not maintain_aspect_ratio:
return image.resize(size, Image.LANCZOS)
image.thumbnail(size, Image.LANCZOS)
if not (width and height):
return image
canvas = Image.new("RGBA", size, (0, 0, 0, 0))
canvas.paste(image, ((width - image.width) // 2, (height - image.height) // 2))
return canvas


def _to_srgb(image, icc_profile):
if image.mode == "P" or "transparency" in image.info:
image = image.convert("RGBA")
try:
return ImageCms.profileToProfile(
image,
ImageCms.getOpenProfile(BytesIO(icc_profile)),
SRGB_PROFILE,
outputMode="RGBA" if image.mode == "RGBA" else "RGB",
)
except ImageCms.PyCMSError:
return image


# THUMBNAILS FOR CONTENT KINDS
################################################################################

Expand Down
1 change: 1 addition & 0 deletions ricecooker/utils/pipeline/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class FileMetadata:
filename: Optional[str] = None
path: Optional[str] = None
original_filename: Optional[str] = None
unconverted_filename: Optional[str] = None
language: Optional[str] = None
duration: Optional[int] = None
license: Optional[str] = None
Expand Down
30 changes: 27 additions & 3 deletions ricecooker/utils/pipeline/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
from ricecooker.utils.audio import compress_audio
from ricecooker.utils.caching import generate_key
from ricecooker.utils.encodings import parse_xml
from ricecooker.utils.images import resize_image
from ricecooker.utils.imscp import collapse_single_children
from ricecooker.utils.imscp import contained_path
from ricecooker.utils.imscp import IMSCP_MANIFEST
Expand Down Expand Up @@ -987,11 +988,19 @@ def handle_file(self, path):
raise InvalidFileException("PDF has no pages")


class ImageConversionContextMetadata(ContextMetadata):
width: Optional[int] = None
height: Optional[int] = None
maintain_aspect_ratio: bool = True


class ImageConversionHandler(ExtensionMatchingHandler):
"""
A FileHandler that converts image files to supported formats.
"""

CONTEXT_CLASS = ImageConversionContextMetadata

SUPPORTED_IMAGE_EXTENSIONS = {
file_formats.PNG,
file_formats.JPG,
Expand All @@ -1009,7 +1018,16 @@ class ImageConversionHandler(ExtensionMatchingHandler):
- VideoCompressionHandler.EXTENSIONS
)

def handle_file(self, path):
def get_cache_key(
self, path, width=None, height=None, maintain_aspect_ratio=True, **kwargs
) -> str:
key = super().get_cache_key(path, **kwargs)
if width is None and height is None:
return key
return f"{key}:{width}x{height}:{'fit' if maintain_aspect_ratio else 'stretch'}"

def handle_file(self, path, width=None, height=None, maintain_aspect_ratio=True):
resize = width is not None or height is not None
preferred_extension = extract_path_ext(path)
file_type_guess = filetype.guess(path)
extension = file_type_guess.extension if file_type_guess else None
Expand All @@ -1022,17 +1040,23 @@ def handle_file(self, path):
try:
with Image.open(path) as im:
im.verify()
if extension in self.SUPPORTED_IMAGE_EXTENSIONS:
if extension in self.SUPPORTED_IMAGE_EXTENSIONS and not resize:
return
with Image.open(path) as im:
converted = im.convert("RGB")
converted = (
resize_image(im, width, height, maintain_aspect_ratio)
if resize
else im.convert("RGB")
)
# PIL raises these for a truncated, corrupt or oversized image.
except (OSError, SyntaxError, ValueError, Image.DecompressionBombError):
raise InvalidFileException(
"Image file did not pass verification: not a recognized image"
)
with self.write_file(file_formats.PNG) as tempf:
converted.save(tempf, file_formats.PNG)
if resize:
return FileMetadata(unconverted_filename=os.path.basename(path))


class SVGValidationHandler(ExtensionMatchingHandler):
Expand Down
14 changes: 9 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from le_utils.constants import exercises
from le_utils.constants import licenses
from le_utils.constants import roles
from PIL import Image

try:
from vcr.stubs import VCRHTTPResponse
Expand Down Expand Up @@ -41,6 +42,7 @@
from ricecooker.classes.nodes import VideoNode
from ricecooker.classes.questions import InputQuestion
from ricecooker.classes.questions import SingleSelectQuestion
from ricecooker.utils.images import THUMBNAIL_SIZE

# GLOBAL TEST SETUP/TEARDOWN UTILS
################################################################################
Expand Down Expand Up @@ -789,11 +791,6 @@ def thumbnail_file():
return ThumbnailFile(local_path)


@pytest.fixture
def thumbnail_filename():
return "eb79354ddd5774bb3436f9a19c282bff.png"


@pytest.fixture
def fake_thumbnail_file():
local_path = os.path.abspath(
Expand Down Expand Up @@ -907,6 +904,13 @@ def exercise_graphie_filename():
SAMPLES_DIR = os.path.join(os.path.dirname(__file__), "testcontent", "samples")


def assert_letterboxed_png(path):
with Image.open(path) as im:
assert (im.format, im.mode, im.size) == ("PNG", "RGBA", THUMBNAIL_SIZE)
assert im.getpixel((0, 0))[3] == 0
assert im.getpixel((200, 112))[3] == 255


def sample_path(*parts):
"""Absolute path to a committed sample fixture under tests/testcontent/samples/."""
path = os.path.join(SAMPLES_DIR, *parts)
Expand Down
Loading
Loading