Exemplo n.º 1
0
    # ----- Load logging configuration.
    with open(_MYPARENT.parent / "Resources" / "logging.yml",
              encoding=UTF8) as stream:
        log_config = yaml.load(stream, Loader=yaml.FullLoader)
    logging.config.dictConfig(log_config)

    # ----- Miscellaneous objects.
    arguments = parser.parse_args()
    genres = dict(get_genres())  # type: Mapping[str, int]
    countries = dict(get_countries())  # type: Mapping[str, int]
    languages = dict(get_languages())  # type: Mapping[str, int]
    providers = dict(get_providers())  # type: Mapping[str, int]

    # ----- Templating environment.
    ENVIRONMENT = TemplatingEnvironment(_MYPARENT / "Templates")
    ENVIRONMENT.set_environment(filters={
        "rjustify": rjustify,
        "stringify": stringify
    })

    # ----- Get tracks collection.
    collection = arguments.klass(arguments.db,
                                 *arguments.path,
                                 countries=countries,
                                 genres=genres,
                                 languages=languages,
                                 providers=providers)  # type: Any

    # ----- Print raised exceptions.
    print(
Exemplo n.º 2
0
    def __call__(self, parsobj, namespace, values, option_string=None):
        setattr(namespace, self.dest, list(map(Path, values)))


# =================
# Arguments parser.
# =================
parser = argparse.ArgumentParser()
parser.add_argument("path", nargs="+", action=GetPath)
arguments = parser.parse_args()

# =========
# Template.
# =========
environment = TemplatingEnvironment(_MYPARENT)

# ===============
# Main algorithm.
# ===============

# Get targets collection.
with ExitStack() as stack1:
    json_file = stack1.enter_context(
        open(_MYPARENT / "backup.json", mode=WRITE, encoding=UTF8))
    txt_file = stack1.enter_context(
        open(_MYPARENT.parents[1] / "MyJavaProject" / "Finder" / "targets.txt",
             mode=WRITE,
             encoding="ISO-8859-1"))
    collection = []  # type: List[Tuple[Any, ...]]
    for argument in arguments.path:
Exemplo n.º 3
0
# =================
# Arguments parser.
# =================
parser = argparse.ArgumentParser()
parser.add_argument("collection", type=argparse.FileType(encoding=UTF8))
arguments = parser.parse_args()

# ================
# Local functions.
# ================
rjustify = partial(rjustify_index, width=4)

# =======================
# Templating environment.
# =======================
template = TemplatingEnvironment(_MYPARENT / "Templates")
template.set_environment(filters={"rjustify": rjustify})

# ============
# Main script.
# ============
stream = csv.reader(arguments.collection, CustomDialect())
collection = [(Path(image),
               format_date(LOCAL.localize(parse(datetime.replace(":", '-',
                                                                 2))),
                           template=TEMPLATE2),
               int(parse(datetime.replace(":", '-', 2)).timestamp()))
              for image, datetime in stream]  # type: Any
collection = sorted(collection, key=itemgetter(2))
collection = sorted(collection, key=itemgetter_(0)(attrgetter("parent")))
collection = enumerate(collection, start=1)
Exemplo n.º 4
0
argument = parser.parse_args()

# ========
# Logging.
# ========
with open(os.fspath(_THATFILE.parents[2] / "Resources" / "logging.yml"), encoding="UTF_8") as fp:
    log_config = yaml.load(fp)
with suppress(KeyError):
    log_config["loggers"]["MyPythonProject"]["level"] = _MAPPING[argument.debug].upper()
logging.config.dictConfig(log_config)
logger = logging.getLogger("MyPythonProject.AudioCD.Converter.{0}".format(_THATFILE.stem))

# =========
# Template.
# =========
_template = TemplatingEnvironment(path=os.fspath(_THATFILE.parents[1] / "Templates")).environment.get_template("Tags")

# ============
# Main script.
# ============
logger.debug(mainscript(os.fspath(_THATFILE)))

# Get audio tags from dBpoweramp Batch Converter.
tags = patterns.AudioTags.fromfile(argument.tags)

# Log input tags.
pairs = sorted(tags.items(), key=itemgetter(0))  # type: List[Tuple[str, str]]
if pairs:
    logger.debug("==========")
    logger.debug("INPUT Tags")
    logger.debug("==========")
# =================
# Arguments parser.
# =================
parser = argparse.ArgumentParser()
parser.add_argument("path")
arguments = parser.parse_args()

# ==========
# Variables.
# ==========
dirs, empty_dirs = [], []

# =========
# Template.
# =========
template = TemplatingEnvironment(path=that_file.parents[0] / "Templates", keep_trailing_newline=False)
template.set_environment(filters={"rjustify": rjustify})
template.set_template(template="T01")

# ===============
# Main algorithm.
# ===============
for root, directories, files in os.walk(str(PureWindowsPath(arguments.path))):
    dirs.extend(PureWindowsPath(root) / PureWindowsPath(file) for file in files)
    if not any([directories, files]):
        empty_dirs.extend(PureWindowsPath(root) / PureWindowsPath(directory) for directory in directories)
dirs = sorted(sorted(sorted(dirs, key=byname), key=byextension), key=byparents)
it1, it2 = tee(dirs)
extensions = filter(None, sorted([(key[1:], value) for key, value in count_justify(*Counter(file.suffix for file in it1).items())], key=itemgetter(0)))
directories = filter(None, sorted([(str(key), value) for key, value in count_justify(*Counter(file.parents[0] for file in it2).items())], key=itemgetter(0)))
print(getattr(template, "template").render(root=arguments.path, dirs=dirs, extensions=extensions, directories=directories, empty_directories=empty_dirs))
Exemplo n.º 6
0
    (file, Path(REGEX1.sub(sub_, str(path)))) for file, path in collection
]  # (file1.m4a, file1.ape), (file1.m4a, file1.dsf), (file1.m4a, file1.flac), ...
collection = [
    (file, path.exists()) for file, path in collection
]  # (file1.m4a, False), (file1.m4a, False), (file1.m4a, True), ...
collection = sorted(collection, key=itemgetter(1))
collection = sorted(collection, key=itemgetter(0))
collection = groupby(
    collection, key=itemgetter(0)
)  # (file1.m4a, ((file1.m4a, False), (file1.m4a, False), (file1.m4a, True))), ...
collection = [
    (key, [exist for _, exist in group]) for key, group in collection
]  # (file1.m4a, [False, False, True]), (file2.m4a, [False, False, False]), ...
collection = [
    Path(file).parent.parent for file, exist in collection if not any(exist)
]  # file2.m4a, ...
collection = chain(*[[(path.parent,
                       Path(path.name) / "*" / "*?" / f"*.{extension}",
                       TEMPDIR / "/".join(path.parts[1:]))
                      for extension in ["m4a", "mp3"]]
                     for path in set(collection)])
collection = sorted(collection, key=itemgetter(1))
collection = sorted(collection, key=itemgetter(0))
collection = groupby(collection, key=itemgetter(0))

# -----
environment = TemplatingEnvironment(_MYPARENT.parent / "AudioCD" / "Templates")
arguments.commands.write(
    environment.get_template("T00c").render(collection=collection,
                                            tempdir=TEMPDIR))
Exemplo n.º 7
0
    def test_mode(self):
        return self._testmode


# ============
# Main script.
# ============
if __name__ == '__main__':

    _THATFILE = PurePath(os.path.abspath(__file__))

    # Define variables.
    level = 100  # type: int

    # Define template.
    template = TemplatingEnvironment(path=_THATFILE.parent)
    template.set_template(T1="T01")

    # Parse input arguments.
    parser = argparse.ArgumentParser()
    parser.add_argument("outfile",
                        type=argparse.FileType("w", encoding="ISO-8859-1"),
                        nargs="?",
                        default=os.path.join(os.path.expandvars("%TEMP%"), "xxcopy.cmd"),
                        help="XXCOPY commands file")
    arguments = parser.parse_args()

    # Load configuration.
    with open(_THATFILE.parents[1] / "Resources" / "audio_config.yml") as stream:
        configuration = yaml.load(stream)
Exemplo n.º 8
0
# Arguments parser.
# =================
parser = argparse.ArgumentParser()
parser.add_argument("--only_differences", "-d", action="store_true")
arguments = parser.parse_args()

# ==========
# Constants.
# ==========
REPOSITORY = os.path.join(os.path.expandvars("%_COMPUTING%"), "counts")

# ==========
# Variables.
# ==========
collection, extensions, status, total = [], [], 0, 0
template = TemplatingEnvironment(path=PurePath(that_file).parent / "Templates")

# ===============
# Main algorithm.
# ===============
template.set_template(template="T02")

with open(f"{REPOSITORY}.csv", encoding="UTF_8", newline="") as stream:
    reader = csv.DictReader(stream)
    for row in reader:
        extensions.append((row["Extensions"], row["Current"], row["Previous"]))

for extension, current, previous in sorted(extensions, key=itemgetter(0)):
    current = int(current)
    previous = int(previous)
    _extension = "{0: <9}".format(extension)
Exemplo n.º 9
0
parser.add_argument("--collection",
                    default=TEMP / "tmp1n53chv0" / "tmplpg2af5i",
                    nargs="?",
                    action=GetPath)
parser.add_argument("--encoding", default=UTF8, nargs="?")
arguments = parser.parse_args()

# ============
# Main script.
# ============
with open(arguments.collection, encoding=arguments.encoding, newline="") as fr:
    collection = csv.reader(fr, dialect=CustomDialect())  # type: Iterable[Any]
    collection = sorted(collection, key=get_name)
    collection = sorted(collection, key=get_parent)
    collection = sorted(collection, key=itemgetter(1))
    collection = sorted(collection, key=itemgetter(0))
    for key, group in groupby(collection, key=itemgetter(0)):
        environment = TemplatingEnvironment(key)
        for sub_key, sub_group in groupby(group, key=itemgetter(1)):
            with open(TEMP / "tmp1n53chv0" / f"batch{sub_key}.cmd",
                      mode=WRITE,
                      encoding="ISO-8859-1") as fw:
                files = [
                    tuple(compress(item, TEMPLATES.get((Path(key), sub_key))))
                    for item in sub_group
                ]  # type: Iterable[Any]
                files = [tuple(break_(file)) for file in files]
                files = groupby(files, key=itemgetter(0))
                fw.write(
                    environment.get_template(sub_key).render(collection=files))
Exemplo n.º 10
0
# Local constants.
# ================
LETTERS = dict(enumerate(list("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), start=1))

# ================
# Local variables.
# ================
descendants, content, empty = {}, [], [
]  # type: Dict[str, int], List[Tuple[str, str, Iterator[Any]]], List[Path]
index = 0  # type: int

# ===============
# Local template.
# ===============
environment = TemplatingEnvironment(_MYPARENT / "Templates",
                                    keep_trailing_newline=False,
                                    filters={"rjustify": rjustify})

# ============
# Main script.
# ============
excluded = None  # type: Any
if arguments.extensions:
    excluded = filterfalse_(filter_extensions(*arguments.extensions))

# 1. Get files collection.
collection = Files(arguments.path, excluded=excluded)  # type: Any

# 2. Count primary descendants content.
with ChangeLocalCurrentDirectory(arguments.path):
    for directory in os.scandir():
Exemplo n.º 11
0
    def test_mode(self):
        return self._testmode


# ============
# Main script.
# ============
if __name__ == '__main__':

    _THATFILE = PurePath(os.path.abspath(__file__))

    # Define variables.
    level = 100  # type: int

    # Define template.
    template = TemplatingEnvironment(path=_THATFILE.parent)

    # Parse input arguments.
    parser = argparse.ArgumentParser()
    parser.add_argument("outfile",
                        type=argparse.FileType("w", encoding="ISO-8859-1"),
                        nargs="?",
                        default=os.path.join(os.path.expandvars("%TEMP%"),
                                             "xxcopy.cmd"),
                        help="XXCOPY commands file")
    arguments = parser.parse_args()

    # Load configuration.
    with open(_THATFILE.parents[1] / "Resources" /
              "audio_config.yml") as stream:
        configuration = yaml.load(stream, Loader=yaml.FullLoader)
Exemplo n.º 12
0
        for file, ts in container:
            yield file, ts


# =================
# Arguments parser.
# =================
parser = argparse.ArgumentParser()
parser.add_argument("files", type=argparse.FileType(encoding="ISO-8859-1"))
parser.add_argument("pattern", action=CompilePattern)
parser.add_argument("--pprint", action="store_true")

# =======================
# Templating environment.
# =======================
environment = TemplatingEnvironment(_MYPARENT)
environment.set_environment(filters={"format_": format_index_})

# ===========
# Main logic.
# ===========

# Initialize variables.
master_collection, level = [], 100  # type: List[Any], int

# Get arguments.
arguments = parser.parse_args()

# Run script.
for target, group in groupby(csv.reader(arguments.files, CustomDialect()),
                             key=itemgetter(0)):
Exemplo n.º 13
0
from Applications.decorators import itemgetter_
from Applications.shared import TemplatingEnvironment

__author__ = 'Xavier ROSSET'
__maintainer__ = 'Xavier ROSSET'
__email__ = '*****@*****.**'
__status__ = "Production"

_ME = Path(os.path.abspath(__file__))
_MYNAME = Path(os.path.abspath(__file__)).stem
_MYPARENT = Path(os.path.abspath(__file__)).parent

# ===================
# Jinja2 environment.
# ===================
environment = TemplatingEnvironment(_MYPARENT.parent / "Templates")

# ============
# Main script.
# ============
collection: Any = sorted(
    shared.get_targets(
        Path(os.path.expandvars("%_BACKUP%")) / "workspace.music"),
    key=itemgetter(0)
)  # (target1, 1234), (target2, 5678), (target3, 9012), (target4, 3456), ...

# -----
collection1: Any = filter(
    itemgetter_(0)(match_(
        re.compile(r"\bspringsteen\b", re.IGNORECASE).search)),
    collection)  # (target1, 1234), (target2, 5678), ...
Exemplo n.º 14
0
    LOGGERS = ["MyPythonProject"]
    MAPPING = {True: "debug", False: "info"}

    # Parse arguments.
    parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
    parser.set_defaults(console=True)
    parser.add_argument("year", type=validyear)
    parser.add_argument("--debug", action="store_true")
    arguments = vars(parser.parse_args())

    # Logging.
    with open(THAT_SCRIPT.parents[1] / "Resources" / "logging.yml", encoding=UTF8) as fp:
        config = yaml.load(fp)

    # Template.
    template = TemplatingEnvironment(path=PureWindowsPath(expandvars("%_PYTHONPROJECT%")) / "Images")
    template.set_template(T1="T01", T2="T02")

    # -----
    for logger in LOGGERS:
        with suppress(KeyError):
            config["loggers"][logger]["level"] = MAPPING[arguments.get("debug", False)].upper()

    # -----
    # if arguments.get("console", False):
    #
    #     # Set up a specific stream handler.
    #     for logger in LOGGERS:
    #         with suppress(KeyError):
    #             config["loggers"][logger]["handlers"] = ["file", "console"]
    #     with suppress(KeyError):