python-gallery/gallery/utils/metadata/__init__.py

103 lines
3 KiB
Python
Raw Normal View History

2023-03-04 21:08:42 +00:00
"""
OnlyLegs - Metadata Parser
2023-03-04 21:08:42 +00:00
Parse metadata from images if available
otherwise get some basic information from the file
"""
import os
from PIL import Image
from PIL.ExifTags import TAGS
2023-03-04 21:08:42 +00:00
from .helpers import *
from .mapping import *
2023-03-04 21:08:42 +00:00
class Metadata:
"""
Metadata parser
"""
2023-04-07 12:35:30 +00:00
2023-03-04 21:08:42 +00:00
def __init__(self, file_path):
"""
Initialize the metadata parser
"""
self.file_path = file_path
img_exif = {}
try:
file = Image.open(file_path)
tags = file._getexif()
img_exif = {}
for tag, value in TAGS.items():
if tag in tags:
img_exif[value] = tags[tag]
2023-04-07 12:35:30 +00:00
img_exif["FileName"] = os.path.basename(file_path)
img_exif["FileSize"] = os.path.getsize(file_path)
img_exif["FileFormat"] = img_exif["FileName"].split(".")[-1]
img_exif["FileWidth"], img_exif["FileHeight"] = file.size
2023-03-04 21:08:42 +00:00
file.close()
except TypeError:
2023-04-07 12:35:30 +00:00
img_exif["FileName"] = os.path.basename(file_path)
img_exif["FileSize"] = os.path.getsize(file_path)
img_exif["FileFormat"] = img_exif["FileName"].split(".")[-1]
img_exif["FileWidth"], img_exif["FileHeight"] = file.size
2023-03-04 21:08:42 +00:00
self.encoded = img_exif
def yoink(self):
"""
Yoinks the metadata from the image
"""
if not os.path.isfile(self.file_path):
return None
return self.format_data(self.encoded)
@staticmethod
def format_data(encoded_exif):
2023-03-04 21:08:42 +00:00
"""
Formats the data into a dictionary
"""
exif = {
2023-04-07 12:35:30 +00:00
"Photographer": {},
"Camera": {},
"Software": {},
"File": {},
2023-03-04 21:08:42 +00:00
}
2023-03-20 17:19:42 +00:00
# Thanks chatGPT xP
2023-04-08 19:38:16 +00:00
# the helper function works, so not sure why it triggers pylint
2023-03-20 17:57:47 +00:00
for key, value in encoded_exif.items():
for mapping_name, mapping_val in EXIF_MAPPING:
if key in mapping_val:
if len(mapping_val[key]) == 2:
exif[mapping_name][mapping_val[key][0]] = {
2023-04-07 12:35:30 +00:00
"raw": value,
"formatted": (
getattr(
2023-04-08 19:38:16 +00:00
helpers, mapping_val[key][1] # pylint: disable=E0602
)(
2023-04-07 12:35:30 +00:00
value
)
),
2023-03-04 21:08:42 +00:00
}
else:
exif[mapping_name][mapping_val[key][0]] = {
2023-04-07 12:35:30 +00:00
"raw": value,
2023-03-04 21:08:42 +00:00
}
continue
2023-03-04 21:08:42 +00:00
# Remove empty keys
2023-04-07 12:35:30 +00:00
if not exif["Photographer"]:
del exif["Photographer"]
if not exif["Camera"]:
del exif["Camera"]
if not exif["Software"]:
del exif["Software"]
if not exif["File"]:
del exif["File"]
2023-03-04 21:08:42 +00:00
return exif