Use absolute imports, remove redundant phototag.INPUT_PATH variable

This commit is contained in:
2023-05-11 02:14:22 -05:00
parent 18933774f2
commit 3d4ec5013a
5 changed files with 33 additions and 43 deletions
+4 -16
View File
@@ -27,26 +27,14 @@ for loggerName in ['__init__', 'app', 'cli', 'config', 'helpers', 'process', 'xm
logger = logging.getLogger(__name__)
# Path Constants
ROOT = os.getcwd()
INPUT_PATH = ROOT
CWD = os.getcwd()
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
TEMP_PATH = os.path.join(ROOT, "temp")
OUTPUT_PATH = os.path.join(ROOT, "output")
TEMP_PATH = os.path.join(CWD, "temp")
OUTPUT_PATH = os.path.join(CWD, "output")
CONFIG_PATH = os.path.join(SCRIPT_ROOT, "config")
logger.info("Path constants built successfully...")
# Environment Variables
try:
if not config.config["google"]["credentials"]:
raise EmptyConfigurationValueError(
"Please use the configuration command to add a Google API authorization file."
)
except (ValueError, AttributeError):
raise InvalidConfigurationError(
"The configuration file appears to be damaged. Please fix, delete or replace it with a valid configuration."
)
else:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.join(CONFIG_PATH, config.config["google"]["credentials"])
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.join(CONFIG_PATH, config.config["google"]["credentials"])
# Extension Constants
RAW_EXTS = ["3fr", "ari", "arw", "bay", "braw", "crw", "cr2", "cr3", "cap", "data", "dcs", "dcr", "dng", "drf", "eip",
+4 -4
View File
@@ -11,9 +11,9 @@ from google.cloud import vision
from rich.progress import Progress, BarColumn
from rich.traceback import install
from . import INPUT_PATH, TEMP_PATH
from .helpers import valid_extension, get_extension, convert_to_bytes
from .process import MasterFileProcessor
from phototag import CWD, TEMP_PATH
from phototag.helpers import valid_extension, get_extension, convert_to_bytes
from phototag.process import MasterFileProcessor
logger = logging.getLogger("app")
install()
@@ -23,7 +23,7 @@ def run():
client = vision.ImageAnnotatorClient()
# Locate valid files
files = os.listdir(INPUT_PATH)
files = os.listdir(CWD)
select = list(filter(lambda file: valid_extension(get_extension(file)), files))
if len(select) == 0:
+4 -4
View File
@@ -13,10 +13,10 @@ import click
from google.cloud import vision
from rich.progress import Progress, BarColumn
from . import config, TEMP_PATH
from .exceptions import InvalidSelectionError
from .helpers import select_files, convert_to_bytes
from .process import MasterFileProcessor
from phototag import config, TEMP_PATH
from phototag.exceptions import InvalidSelectionError
from phototag.helpers import select_files, convert_to_bytes
from phototag.process import MasterFileProcessor
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
+3 -3
View File
@@ -11,7 +11,7 @@ import string
from glob import glob
from typing import List, Optional
from phototag import LOSSY_EXTS, RAW_EXTS, INPUT_PATH
from phototag import LOSSY_EXTS, RAW_EXTS, CWD
from phototag.exceptions import PhototagException, InvalidSelectionError
ALL_EXTENSIONS = RAW_EXTS + LOSSY_EXTS
@@ -95,12 +95,12 @@ def select_files(files: List[str], regex: Optional[str], glob_pattern: Optional[
"""
# Just add all files in current working directory
if all:
files.extend(os.listdir(INPUT_PATH))
files.extend(os.listdir(CWD))
else:
# RegEx option pattern matching
if regex:
files.extend(
filter(lambda filename: re.match(re.compile(regex), filename) is not None, os.listdir(INPUT_PATH))
filter(lambda filename: re.match(re.compile(regex), filename) is not None, os.listdir(CWD))
)
# Glob option pattern matching
+18 -16
View File
@@ -21,10 +21,10 @@ from PIL import Image
from google.cloud import vision
from rich.progress import Progress
from . import TEMP_PATH, INPUT_PATH, RAW_EXTS
from .exceptions import InvalidConfigurationError, NoSidecarFileError
from .helpers import random_characters
from .xmp import XMPParser
from phototag import TEMP_PATH, RAW_EXTS, CWD
from phototag.exceptions import InvalidConfigurationError, NoSidecarFileError
from phototag.helpers import random_characters
from phototag.xmp import XMPParser
logger = logging.getLogger(__name__)
@@ -85,13 +85,15 @@ class MasterFileProcessor(object):
# Check that all files are under the set buffer limit
for key, fp in self.waiting.keys():
if fp.size > self.buffer_size:
raise InvalidConfigurationError("Invalid Configuration - the buffer size is too low. Please raise the buffer size "
"or enable single_override.")
raise InvalidConfigurationError(
"Invalid Configuration - the buffer size is too low. Please raise the buffer size "
"or enable single_override.")
# Check that image_count is at least 1
if self.image_count <= 0:
raise InvalidConfigurationError("Invalid Configuration - the image_count is too low. Please set it to a positive "
"non-zero integer or enable single_override.")
raise InvalidConfigurationError(
"Invalid Configuration - the image_count is too low. Please set it to a positive "
"non-zero integer or enable single_override.")
def _start(self, key: int) -> None:
"""
@@ -228,7 +230,7 @@ class FileProcessor(object):
self.xmp = None
if self.ext.lower() in RAW_EXTS: # if the extension is in the RAW extensions array, it might have an XMP (?)
self.xmp = self.base + ".xmp"
self.input_xmp = os.path.join(INPUT_PATH, self.xmp)
self.input_xmp = os.path.join(CWD, self.xmp)
if not os.path.exists(self.input_xmp):
raise NoSidecarFileError("Sidecar file for '{}' does not exist.".format(self.xmp))
@@ -258,12 +260,12 @@ class FileProcessor(object):
"""
if self.xmp:
# CPU-Bound task, needs threading or async applied
rgb = rawpy.imread(os.path.join(INPUT_PATH, self.file_name))
rgb = rawpy.imread(os.path.join(CWD, self.file_name))
imageio.imsave(self.temp_file_path, rgb.postprocess())
rgb.close()
self._optimize(self.temp_file_path)
else:
self._optimize(os.path.join(INPUT_PATH, self.file_name), copy=self.temp_file_path)
self._optimize(os.path.join(CWD, self.file_name), copy=self.temp_file_path)
def run(self, client: vision.ImageAnnotatorClient, callback: Callable = None) -> None:
"""
@@ -313,16 +315,16 @@ class FileProcessor(object):
# No XMP file is specified, using IPTC tagging
else:
logger.debug(f"Writing {len(labels)} tags to image IPTC")
info = iptcinfo3.IPTCInfo(os.path.join(INPUT_PATH, self.file_name))
info = iptcinfo3.IPTCInfo(os.path.join(CWD, self.file_name))
info["keywords"].extend(labels)
info.save()
# Remove the weird ghost file created by this iptc read/writer.
os.remove(os.path.join(INPUT_PATH, self.file_name + "~"))
os.remove(os.path.join(CWD, self.file_name + "~"))
# Copy dry-run
# shutil.copy2(os.path.join(INPUT_PATH, self.file_name), os.path.join(OUTPUT_PATH, self.file_name))
# os.rename(os.path.join(INPUT_PATH, self.file_name), os.path.join(OUTPUT_PATH, self.file_name))
# shutil.copy2(os.path.join(CWD, self.file_name), os.path.join(OUTPUT_PATH, self.file_name))
# os.rename(os.path.join(CWD, self.file_name), os.path.join(OUTPUT_PATH, self.file_name))
except Exception:
raise
finally:
@@ -343,4 +345,4 @@ class FileProcessor(object):
:return: the number of bytes the shadowed image takes up on the disk
"""
return os.path.getsize(os.path.join(INPUT_PATH, self.file_name))
return os.path.getsize(os.path.join(CWD, self.file_name))