-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransform_file.py
88 lines (73 loc) · 2.54 KB
/
transform_file.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# System imports
import glob, os
import argparse
from pathlib import Path
# External imports
from viaa.observability import logging
from viaa.configuration import ConfigParser
# Internal imports
from app.file_transformation import FileTransformer
# from app.file_validation import FileValidator
from app.helpers import (
copy_file,
copy_metadata,
get_metadata_from_image,
get_resize_params,
get_file_extension,
get_icc,
get_image_dimensions,
move_file,
remove_file,
rename_file,
)
"""
Script to apply transformations (crop, resize, convert color space, encode,
add metadata) to an image file.
"""
if __name__ == "__main__":
# Init
configParser = ConfigParser()
parser = argparse.ArgumentParser()
file_transformer = FileTransformer(configParser)
logger = logging.get_logger("transform_file", configParser)
# Get arguments
parser.add_argument(
"--file_path", type=str, default=None, help="Path to input file", required=True
)
parser.add_argument(
"--destination", type=str, default=None, help="Destination output file", required=False
)
args = parser.parse_args()
file_path = args.file_path
destination = args.destination
# Copy file and rename it to external_id.
# File has to be copied so metadata can be added again later.
extension = get_file_extension(file_path)
external_id = Path(file_path).stem
copied_file_path = copy_file(file_path)
file_path = rename_file(file_path, external_id + extension)
# Get metadata from original image
metadata = get_metadata_from_image(file_path)
# Get icc from image here, because it will be lost.
# The original icc is needed to convert the color space to sRGB.
icc = get_icc(file_path)
# Resize file
width, height = get_image_dimensions(file_path)
max_dimensions = None
resize_params = get_resize_params(width, height, max_dimensions)
file_transformer.resize(file_path, resize_params)
# Change color space
file_transformer.convert_to_srgb(file_path, icc)
# Encode to jp2
encoded_file = file_transformer.encode_image(file_path)
logger.debug("Encoded file %s", encoded_file)
# Add metadata to file
copy_metadata(copied_file_path, encoded_file)
# Move file to destination
if destination is not None:
logger.debug("Moving encoded_file file %s to %s", encoded_file, destination)
move_file(encoded_file, destination)
# Cleanup
remove_file(copied_file_path)
for f in glob.glob(copied_file_path + '*'):
os.remove(f)