Files
faceswap/lib/Serializer.py
T
Lev Velykoivanenko f8bf47ad43 Refactor lib/Serializer.py, and other improvements. (#394)
All:
Set correct python3 shebang.

lib/cli.py:
Fix some help documentation formatting and typos.
Set 'json' as the default value for '--serializer' argument.

lib/Serializer.py:
Refactor to properly handle PyYAML not being available.
Add docstring at top of the file.
Improve PEP8 conformity.

scripts/fsmedia.py:
Modify lib/Serializer.py method call to match new name.
Modify lib/Serializer.py method call to match not needing a default.

tools/sort.py:
Add new group by 'face-yaw' method.
Add docstring at top of the file.
Re-arrange argument order to make more sense.
Fix typos and line length issues in help documentation.
Change to use lib/Serializer.py to set the serializer and to write the log file.
Allow sort logging to use PyYAML.
2018-05-16 23:40:15 +01:00

95 lines
2.2 KiB
Python

#!/usr/bin/env python3
"""
Library providing convenient classes and methods for writing data to files.
"""
import sys
import json
import pickle
try:
import yaml
except ImportError:
yaml = None
class Serializer(object):
ext = ""
woptions = ""
roptions = ""
@classmethod
def marshal(cls, input_data):
raise NotImplementedError()
@classmethod
def unmarshal(cls, input_string):
raise NotImplementedError()
class YAMLSerializer(Serializer):
ext = "yml"
woptions = "w"
roptions = "r"
@classmethod
def marshal(cls, input_data):
return yaml.dump(input_data, default_flow_style=False)
@classmethod
def unmarshal(cls, input_string):
return yaml.load(input_string)
class JSONSerializer(Serializer):
ext = "json"
woptions = "w"
roptions = "r"
@classmethod
def marshal(cls, input_data):
return json.dumps(input_data, indent=2)
@classmethod
def unmarshal(cls, input_string):
return json.loads(input_string)
class PickleSerializer(Serializer):
ext = "p"
woptions = "wb"
roptions = "rb"
@classmethod
def marshal(cls, input_data):
return pickle.dumps(input_data)
@classmethod
def unmarshal(cls, input_bytes):
return pickle.loads(input_bytes)
def get_serializer(serializer):
if serializer == "json":
return JSONSerializer
elif serializer == "pickle":
return PickleSerializer
elif serializer == "yaml" and yaml is not None:
return YAMLSerializer
elif serializer == "yaml" and yaml is None:
print("You must have PyYAML installed to use YAML as the serializer.\n"
"Switching to JSON as the serializer.", file=sys.stderr)
return JSONSerializer
def get_serializer_from_ext(ext):
if ext == ".json":
return JSONSerializer
elif ext == ".p":
return PickleSerializer
elif ext in (".yaml", ".yml") and yaml is not None:
return YAMLSerializer
elif ext in (".yaml", ".yml") and yaml is None:
print("You must have PyYAML installed to use YAML as the serializer.\n"
"Switching to JSON as the serializer.", file=sys.stderr)
return JSONSerializer