add init_parser() and init_global_var() function

This commit is contained in:
lmluk
2024-09-05 10:08:19 +02:00
parent 0b3acf7cdb
commit 8b54a0ca83
3 changed files with 134 additions and 3 deletions

View File

@@ -0,0 +1,80 @@
"""Primary application entrypoint.
"""
import locale
import logging
import os
import sys
import warnings
from typing import List, Optional
from pip._internal.cli.autocompletion import autocomplete
from pip._internal.cli.main_parser import parse_command
from pip._internal.commands import create_command
from pip._internal.exceptions import PipError
from pip._internal.utils import deprecation
logger = logging.getLogger(__name__)
# Do not import and use main() directly! Using it directly is actively
# discouraged by pip's maintainers. The name, location and behavior of
# this function is subject to change, so calling it directly is not
# portable across different pip versions.
# In addition, running pip in-process is unsupported and unsafe. This is
# elaborated in detail at
# https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
# That document also provides suggestions that should work for nearly
# all users that are considering importing and using main() directly.
# However, we know that certain users will still want to invoke pip
# in-process. If you understand and accept the implications of using pip
# in an unsupported manner, the best approach is to use runpy to avoid
# depending on the exact location of this entry point.
# The following example shows how to use runpy to invoke pip in that
# case:
#
# sys.argv = ["pip", your, args, here]
# runpy.run_module("pip", run_name="__main__")
#
# Note that this will exit the process after running, unlike a direct
# call to main. As it is not safe to do any processing after calling
# main, this should not be an issue in practice.
def main(args: Optional[List[str]] = None) -> int:
if args is None:
args = sys.argv[1:]
# Suppress the pkg_resources deprecation warning
# Note - we use a module of .*pkg_resources to cover
# the normal case (pip._vendor.pkg_resources) and the
# devendored case (a bare pkg_resources)
warnings.filterwarnings(
action="ignore", category=DeprecationWarning, module=".*pkg_resources"
)
# Configure our deprecation warnings to be sent through loggers
deprecation.install_warning_logger()
autocomplete()
try:
cmd_name, cmd_args = parse_command(args)
except PipError as exc:
sys.stderr.write(f"ERROR: {exc}")
sys.stderr.write(os.linesep)
sys.exit(1)
# Needed for locale.getpreferredencoding(False) to work
# in pip._internal.utils.encoding.auto_decode
try:
locale.setlocale(locale.LC_ALL, "")
except locale.Error as e:
# setlocale can apparently crash if locale are uninitialized
logger.debug("Ignoring error %s when setting locale", e)
command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
return command.main(cmd_args)

View File

@@ -0,0 +1,12 @@
from typing import List, Optional
def main(args: Optional[List[str]] = None) -> int:
"""This is preserved for old console scripts that may still be referencing
it.
For additional details, see https://github.com/pypa/pip/issues/7498.
"""
from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args)

45
main.py
View File

@@ -1,7 +1,36 @@
import json
from exiftool import ExifToolHelper as et
from shutil import copy2 as cp
import datetime
from datetime import datetime as dt
import argparse
def init_parser():
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-t', '--timespan', type=str, help="Exports the given timespan\n"\
"Valid format: 'DD.MM.YYYY-DD.MM.YYYY'\n"\
"Wildcards can be used: 'DD.MM.YYYY-*'")
parser.add_argument('-y', '--year', type=int, help="Exports the given year")
args = parser.parse_args()
if args.year and args.timespan:
print("Timespan will be prioritized")
return args
def init_global_var(args: argparse.Namespace):
global time_span
if args.timespan:
temp_times = args.timespan.strip().split("-")
time_span = ('*' if temp_times[0] == '*' else dt.strptime(temp_times[0], '%d.%m.%Y'),
'*' if temp_times[1] == '*' else dt.strptime(temp_times[1], '%d.%m.%Y'))
elif args.year:
time_span = (dt(args.year, 1, 1), dt(args.year, 12, 31))
def get_img_filename(image: json):
"""
@@ -23,7 +52,7 @@ def apply_memory_on_imgs(memory: json):
Makes a copy of the front and back images and adds information from the memory object as exif tags to the image
"""
memory_dt = get_datetime_from_str(memory['takenTime'])
img_names = ["./out/%s_%s.webp" % (memory_dt.strftime('%Y-%m-%d_%H-%M-%S'), i) for i in ['front', 'back']]
img_names = ["./out/%s_%s.webp" % (memory_dt.strftime('%Y-%m-%d_%H-%M-%S'), temp_times) for temp_times in ['front', 'back']]
cp("./Photos/post/%s" % get_img_filename(memory['frontImage']), img_names[0])
cp("./Photos/post/%s" % get_img_filename(memory['backImage']), img_names[1])
@@ -40,10 +69,20 @@ def apply_memory_on_imgs(memory: json):
params=["-P", "-overwrite_original"])
def export_images(memories: json):
for temp_times in memories:
apply_memory_on_imgs(temp_times)
if __name__ == '__main__':
args = init_parser()
init_global_var(args)
f = open('memories.json')
for i in json.load(f):
apply_memory_on_imgs(i)
# export_images(json.load(f))
f.close()