コード例 #1
0
ファイル: metadata.py プロジェクト: domdfcoding/imgsorter
def get_metadata_for_file(filename: PathLike) -> Dict[str, Any]:
    """
	Returns the EXIF metadata for ``filename``, as a ``key: value`` mapping.

	:param filename:
	"""

    filename = PathPlus(filename)

    if not filename.is_file():
        raise FileNotFoundError(filename)

    # get the tags
    with filename.open("rb") as fp:
        data = exifread.process_file(fp, details=False, debug=False)

    if data:
        return {k: str(v) for k, v in data.items()}

    else:
        # using exiftool as a backup for some files including videos
        with exiftool.ExifTool() as et:
            try:
                data = et.get_metadata(str(filename))
            except json.decoder.JSONDecodeError:
                raise ValueError(
                    f"Could not parse EXIF data for {filename} or no EXIF data found."
                )

    return dict(data)
コード例 #2
0
    def run(self, filename: PathLike):
        """
		Parse configuration from the given file.

		:param filename: The filename of the YAML configuration file.
		"""

        filename = PathPlus(filename)

        if not filename.is_file():
            raise FileNotFoundError(str(filename))

        with tempfile.TemporaryDirectory() as tmpdir:
            tmpdir_p = PathPlus(tmpdir)
            schema_file = tmpdir_p / "schema.json"
            schema = make_schema(*self.config_vars)
            schema["additionalProperties"] = self.allow_unknown_keys
            schema_file.dump_json(schema)
            validate_files(schema_file, filename)

        parsed_config_vars: MutableMapping[str, Any] = {}

        with filename.open() as file:
            raw_config_vars: Mapping[str, Any] = YAML(typ="safe",
                                                      pure=True).load(file)

        for var in self.config_vars:
            parsed_config_vars[var.__name__] = getattr(
                self, f"visit_{var.__name__}", var.get)(raw_config_vars)

        return self.custom_parsing(raw_config_vars, parsed_config_vars,
                                   filename)
コード例 #3
0
ファイル: xml.py プロジェクト: PyMassSpec/mh_utils
def get_validated_tree(xml_file: PathLike, schema_file: Optional[PathLike] = None) -> _ElementTree:
	"""
	Returns a validated lxml objectify from the given XML file, validated against the schema file.

	:param xml_file: The XML file to validate.
	:param schema_file: The schema file to validate against.

	:returns: An lxml ElementTree object. When .getroot() us called on the tree the root will be an instance of
		:class:`lxml.objectify.ObjectifiedElement`.
	"""

	if not isinstance(xml_file, pathlib.Path):
		xml_file = pathlib.Path(xml_file)

	if not xml_file.is_file():
		raise FileNotFoundError(f"XML file '{xml_file}' not found.")

	schema: Optional[etree.XMLSchema] = None

	if schema_file is not None:

		if not isinstance(schema_file, pathlib.Path):
			schema_file = pathlib.Path(schema_file)

		if not schema_file.is_file():
			raise FileNotFoundError(f"XML schema '{schema_file}' not found.")

		schema = etree.XMLSchema(etree.parse(str(schema_file)))

	parser = objectify.makeparser(schema=schema)
	tree: _ElementTree = objectify.parse(str(xml_file), parser=parser)

	if schema:
		assert schema.validate(tree)

	return tree