[
  {
    "path": ".github/workflows/lint-and-test.yml",
    "content": "name: Lint and Test\n\non: [push, pull_request]\n\njobs:\n  build:\n\n    runs-on: ubuntu-20.04\n    strategy:\n      fail-fast: false\n      matrix:\n        python-version: [3.6, 3.7, 3.8, 3.9, '3.10', 3.11, 3.12]\n\n    env:\n      exiftool_version: 12.15\n\n    steps:\n    - uses: actions/checkout@v2\n    - name: Set up Python ${{ matrix.python-version }}\n      uses: actions/setup-python@v2\n      with:\n        python-version: ${{ matrix.python-version }}\n        # while https://github.com/actions/setup-python recommends using a specific dependency version to use cache\n        # we'll see if this just uses it in default configuration\n        # this can't be enabled unless a requirements.txt file exists.  PyExifTool doesn't have any hard requirements\n        #cache: 'pip'\n    - name: Cache Perl ExifTool Download\n      # https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows\n      uses: actions/cache@v2\n      env:\n        cache-name: cache-perl-exiftool\n      with:\n        # path where we would extract the ExifTool source files\n        path: Image-ExifTool-${{ env.exiftool_version }}\n        key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ env.exiftool_version }}\n\n    - name: Install dependencies\n      run: |\n        # don't have to do this on the GitHub runner, it's going to always be the latest\n        #python -m pip install --upgrade pip\n        # the setup-python uses it this way instead of calling it via module, so maybe this will cache ...\n        pip install flake8 pytest\n        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi\n\n        # latest version not yet available on Ubuntu Focal 20.04 LTS, but it's better to install it with all dependencies first\n        sudo apt-get install -qq libimage-exiftool-perl\n        # print this in the log\n        exiftool -ver\n\n        # get just the minimum version to build and compile, later we can go with latest version to test\n        # working with cache: only get if the directory doesn't exist\n        if [ ! -d Image-ExifTool-${{ env.exiftool_version }} ]; then wget http://backpan.perl.org/authors/id/E/EX/EXIFTOOL/Image-ExifTool-${{ env.exiftool_version }}.tar.gz; fi\n        # extract if it was downloaded\n        if [ -f Image-ExifTool-${{ env.exiftool_version }}.tar.gz ]; then tar xf Image-ExifTool-${{ env.exiftool_version }}.tar.gz; fi\n\n        cd Image-ExifTool-${{ env.exiftool_version }}/\n\n        # https://exiftool.org/install.html#Unix\n        perl Makefile.PL\n        make test\n\n        export PATH=`pwd`:$PATH\n        cd ..\n        exiftool -ver\n\n        # save this environment for subsequent steps\n        # https://brandur.org/fragments/github-actions-env-vars-in-env-vars\n        echo \"PATH=`pwd`:$PATH\" >> $GITHUB_ENV\n    - name: Install pyexiftool\n      run: |\n        # install all supported json processors for tests\n        python -m pip install .[json,test]\n    - name: Lint with flake8\n      run: |\n        # stop the build if there are Python syntax errors or undefined names\n        flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics\n        # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide\n        flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics\n    - name: Test with pytest\n      run: |\n        pytest\n"
  },
  {
    "path": ".gitignore",
    "content": "*.pyc\n__pycache__/\nbuild/\ndist/\nMANIFEST\n\n*.egg-info/\n\n# pytest-cov db\n.coverage\n\n# tests will be made to write to temp directories with this prefix\ntests/exiftool-tmp-*\n\n# IntelliJ\n.idea\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# PyExifTool Changelog\n\nDate (Timezone)              | Version | Comment\n---------------------------- | ------- | -------\n03/13/2021 01:54:44 PM (PST) | 0.5.0a0 | no functional code changes ... yet.  this is currently on a separate branch referring to [Break down Exiftool into 2+ classes, a raw Exiftool, and helper classes](https://github.com/sylikc/pyexiftool/discussions/10) and [Deprecating Python 2.x compatibility](https://github.com/sylikc/pyexiftool/discussions/9) .  In time this refactor will be the future of PyExifTool, once it stabilizes.  I'll make code-breaking updates in this branch from build to build and take comments to make improvements.  Consider the 0.5.0 \"nightly\" quality.  Also, changelog versions were modified because I noticed that the LAST release from smarnach is tagged with v0.2.0\n02/28/2022 12:39:57 PM (PST) | 0.5.0   | complete refactor of the PyExifTool code.  Lots of changes.  Some code breaking changes.  Not directly backwards-compatible with v0.4.x.  See COMPATIBILITY.TXT to understand all the code-breaking changes.\n03/02/2022 07:07:26 AM (PST) | 0.5.1   | v0.5 Sphinx documentation generation finally working.  Lots of reStructuredText written to make the documentation better!<br>There's no functional changes to PyExifTool, but after several days and hours of effort, every single docstring in ExifTool and ExifToolHelper was updated to reflect all v0.5.0 changes.  ExifToolAlpha was largely untouched because the methods exposed haven't really been updated this time.\n03/03/2022 06:49:31 PM (PST) | 0.5.2   | Predicting the next most requested method: ExifToolHelper now has a set_tags() method similar to the get_tags() method.  This was pulled from ExifToolAlpha, combining the old set_tags/set_tags_batch into one method.<br>Added a new constructor/property to ExifToolHelper: check_execute, which (by default) will raise ExifToolExecuteError when the exit status code from exiftool subprocess is non-zero.  This should help users debug otherwise silent errors.<br>Also updated more docstrings and added maintenance script to generate docs.\n03/26/2022 06:48:01 AM (PDT) | 0.5.3   | Quite a few docstring changes<br>ExifToolHelper's get_tags() and set_tags() checks tag names to prevent inadvertent write behavior<br>Renamed a few of the errors to make sure the errors are explicit<br>ExifToolHelper() has some static helper methods which can be used when extending the class (ExifToolAlpha.set_keywords_batch() demonstrates a sample usage).<br>setup.py tweaked to make it Beta rather than Alpha<br>ExifToolAlpha.get_tag() updated to make it more robust.<br>Fixed ujson compatibility<br>Cleaned up and refactored testing.\n08/27/2022 06:06:32 PM (PDT) | 0.5.4   | New Feature: added raw_bytes parameter to ExifTool.execute() to return bytes only with no decoding conversion.<br>Changed: ExifTool.execute() now accepts both [str,bytes].  When given str, it will encode according to the ExifTool.encoding property.<br>Changed: ExifToolHelper.execute() now accepts Any type, and will do a str() on any non-str parameter.<br>Technical change: Popen() no longer uses an -encoding parameter, therefore working with the socket is back to bytes when interfacing with the exiftool subprocess.  This should be invisible to most users as the default behavior will still be the same.<br>Tests: Created associated test with a custom makernotes example to write and read back bytes.<br>Docs: Updated documentation with comprehensive samples, and a better FAQ section for common problems.\n12/30/2022 02:35:18 PM (PST) | 0.5.5   | No functional changes, only a huge speed improvement with large operations :: Update: Speed up large responses from exiftool.  Instead of using + string concatenation, uses list appends and reverse(), which results in a speedup of 10x+ for large operations.  See more details from the [reported issue](https://github.com/sylikc/pyexiftool/issues/60) and [PR 61](https://github.com/sylikc/pyexiftool/pull/61) by [prutschman](https://github.com/prutschman)\n10/22/2023 03:21:46 PM (PDT) | 0.5.6   | New Feature: added method ExifTool.set_json_loads() which allows setting a method to replace the json.loads() called in ExifTool.execute_json().  Changed: ujson is no longer used by default when available.  Use the set_json_loads() to enable manually<br>This permits passing additional configuration parameters to address the [reported issue](https://github.com/sylikc/pyexiftool/issues/76).<br>All documentation has been updated and two accompanying FAQ entries have been written to describe the new functionality.  Test cases have been written to test the new functionality and some baseline exiftool tests to ensure that the behavior remains consistent across tests.\n\n\nFollow maintenance/release-process.html when releasing a version.\n\n\n# PyExifTool Changelog Archive (v0.2 - v0.4)\n\nDate (Timezone)              | Version | Comment\n---------------------------- | ------- | -------\n07/17/2019 12:26:16 AM (PDT) | 0.2.0   | Source was pulled directly from https://github.com/smarnach/pyexiftool with a complete bare clone to preserve all history.  Because it's no longer being updated, I will pull all merge requests in and make updates accordingly\n07/17/2019 12:50:20 AM (PDT) | 0.2.1   | Convert leading spaces to tabs.  (I'm aware of [PEP 8](https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces) recommending spaces over tabs, but I <3 tabs)\n07/17/2019 12:52:33 AM (PDT) | 0.2.2   | Merge [Pull request #10 \"add copy_tags method\"](https://github.com/smarnach/pyexiftool/pull/10) by [Maik Riechert (letmaik) Cambridge, UK](https://github.com/letmaik) on May 28, 2014<br> *This adds a small convenience method to copy any tags from one file to another. I use it for several month now and it works fine for me.*\n07/17/2019 01:05:37 AM (PDT) | 0.2.3   | Merge [Pull request #25 \"Added option for keeping print conversion active. #25\"](https://github.com/smarnach/pyexiftool/pull/25) by [Bernhard Bliem (bbliem)](https://github.com/bbliem) on Jan 17, 2019<br> *For some tags, disabling print conversion (as was the default before) would not make much sense. For example, if print conversion is deactivated, the value of the Composite:LensID tag could be reported as something like \"8D 44 5C 8E 34 3C 8F 0E\". It is doubtful whether this is useful here, as we would then need to look up what this means in a table supplied with exiftool. We would probably like the human-readable value, which is in this case \"AF-S DX Zoom-Nikkor 18-70mm f/3.5-4.5G IF-ED\".*<br>*Disabling print conversion makes sense for a lot of tags (e.g., it's nicer to get as the exposure time not the string \"1/2\" but the number 0.5). In such cases, even if we enable print conversion, we can disable it for individual tags by appending a # symbol to the tag name.*\n07/17/2019 01:20:15 AM (PDT) | 0.2.4   | Merge with slight modifications to variable names for clarity (sylikc) [Pull request #27 \"Add \"shell\" keyword argument to ExifTool initialization\"](https://github.com/smarnach/pyexiftool/pull/27) by [Douglas Lassance (douglaslassance) Los Angeles, CA](https://github.com/douglaslassance) on 5/29/2019<br>*On Windows this will allow to run exiftool without showing the DOS shell.*<br>**This might break Linux but I don't know for sure**<br>Alternative source location with only this patch: https://github.com/blurstudio/pyexiftool/tree/shell-option\n07/17/2019 01:24:32 AM (PDT) | 0.2.5   | Merge [Pull request #19 \"Correct dependency for building an RPM.\"](https://github.com/smarnach/pyexiftool/pull/19) by [Achim Herwig (Achimh3011) Munich, Germany](https://github.com/Achimh3011) on Aug 25, 2016<br>**I'm not sure if this is entirely necessary, but merging it anyways**\n07/17/2019 02:09:40 AM (PDT) | 0.2.6   | Merge [Pull request #15 \"handling Errno:11 Resource temporarily unavailable\"](https://github.com/smarnach/pyexiftool/pull/15) by [shoyebi](https://github.com/shoyebi) on Jun 12, 2015\n07/18/2019 03:40:39 AM (PDT) | 0.2.7   | set_tags and UTF-8 cmdline - Merge in the first set of changes by Leo Broska related to [Pull request #5 \"add set_tags_batch, set_tags + constructor takes added options\"](https://github.com/smarnach/pyexiftool/pull/5) by [halloleo](https://github.com/halloleo) on Aug 1, 2012<br> but this is sourced from [jmathai/elodie's 6114328 Jun 22,2016 commit](https://github.com/jmathai/elodie/blob/6114328f325660287d1998338a6d5e6ba4ccf069/elodie/external/pyexiftool.py)\n07/18/2019 03:59:02 AM (PDT) | 0.2.8   | Merge another commit fromt he jmathai/elodie [zserg on Mar 12, 2016](https://github.com/jmathai/elodie/blob/af36de091e1746b490bed0adb839adccd4f6d2ef/elodie/external/pyexiftool.py)<br> seems to do UTF-8 encoding on set_tags\n07/18/2019 04:01:18 AM (PDT) | 0.2.9   | minor change it looks like a rename to match PEP8 coding standards by [zserg on Aug 21, 2016](https://github.com/jmathai/elodie/blob/ad1cbefb15077844a6f64dca567ea5600477dd52/elodie/external/pyexiftool.py)\n07/18/2019 04:05:36 AM (PDT) | 0.2.10  | [Fallback to latin if utf-8 decode fails in pyexiftool.py](https://github.com/jmathai/elodie/commit/fe70227c7170e01c8377de7f9770e761eab52036#diff-f9cf0f3eed27e85c9c9469d0e0d431d5) by [jmathai](https://github.com/jmathai/elodie/commits?author=jmathai) on Sep 7, 2016\n07/18/2019 04:14:32 AM (PDT) | 0.2.11  | Merge the test cases from the [Pull request #5 \"add set_tags_batch, set_tags + constructor takes added options\"](https://github.com/smarnach/pyexiftool/pull/5) by [halloleo](https://github.com/halloleo) on Aug 1, 2012\n07/18/2019 04:34:46 AM (PDT) | 0.3.0   | changed the setup.py licensing and updated the version numbering as in changelog<br>changed the version number scheme, as it appears the \"official last release\" was 0.2.0 tagged.  There's going to be a lot of things broken in this current build, and I'll fix it as they come up.  I'm going to start playing with the library and the included tests and such.  <br>There's one more pull request #11 which would be pending, but it duplicates the extra arguments option.  <br>I'm also likely to remove the print conversion as it's now covered by the extra args.  I'll also rename some variable names with the addedargs patch<br>**for my changes (sylikc), I can only guarantee they will work on Python 3.7, because that's my environment... and while I'll try to maintain compatibility, there's no guarantees**\n07/18/2019 05:06:19 AM (PDT) | 0.3.1   | make some minor tweaks to the naming of the extra args variable.  The other pull request 11 names them params, and when I decide how to merge that pull request, I'll probably change the variable names again.\n07/19/2019 12:01:22 AM (PDT) | 0.3.2   | fix the select() problem for windows, and fix all tests\n07/19/2019 12:54:39 AM (PDT) | 0.3.3   | Merge a piece of [Pull request #11 \"Robustness enhancements](https://github.com/smarnach/pyexiftool/pull/11) by [Matthias Kiefer (kiefermat)](https://github.com/kiefermat) on Oct 27, 2014<br>*On linux call prctl in subprocess to be sure that the exiftool child process is killed even if the parent process is killed by itself*<br>also removed print_conversion<br>also merged the common_args and added_args into one args list\n07/19/2019 01:18:26 AM (PDT) | 0.3.4   | Merge the rest of Pull request #11.  Added the other pieces, however, I added them as \"wrappers\" instead of modifying the interface of the original code.  I feel like the additions here are overly done, and as I understand the code more, I'll either remove it or incorporate it into single functions<br>from #11 *When getting json results, verify that the results returned by exiftool actually belong to the correct file by checking the SourceFile property of the returned result*<br>and also *Added possibility to provide different exiftools params for each file separately*\n07/19/2019 01:22:48 AM (PDT) | 0.3.5   | changed a bit of the test_exiftool so all the tests pass again\n01/04/2020 11:59:14 AM (PST) | 0.3.6   | made the tests work with the latest output of ExifTool.  This is the final version which is named \"exiftool\"\n01/04/2020 12:16:51 PM (PST) | 0.4.0   | pyexiftool rename (and make all tests work again) ... I also think that the pyexiftool.py has gotten too big.  I'll probably break it out into a directory structure later to make it more maintainable\n02/01/2020 05:09:43 PM (PST) | 0.4.1   | incorporated pull request #2 and #3 by ickc which added a \"no_output\" feature and an import for ujson if it's installed.  Thanks for the updates!\n04/09/2020 04:25:31 AM (PDT) | 0.4.2   | roll back 0.4.0's pyexiftool rename.  It appears there's no specific PEP to have to to name PyPI projects to be py<something>.  The only convention I found was https://www.python.org/dev/peps/pep-0423/#use-standard-pattern-for-community-contributions which I might look at in more detail\n04/09/2020 05:15:40 AM (PDT) | 0.4.3   | initial work of moving the exiftool.py into a directory preparing to break it down into separate files to make the codebase more manageable\n03/12/2021 01:37:30 PM (PST) | 0.4.4   | no functional code changes.  Revamped the setup.py and related files to release to PyPI.  Added all necessary and recommended files into release\n03/12/2021 02:03:38 PM (PST) | 0.4.5   | no functional code changes.  re-release with new version because I accidentally included the \"test\" package with the PyPI 0.4.4 release.  I deleted it instead of yanking or doing a post release this time... just bumped the version.  \"test\" folder renamed to \"tests\" as per convention, so the build will automatically ignore it\n04/08/2021 03:38:46 PM (PDT) | 0.4.6   | added support for config files in constructor -- Merged pull request #7 from @asielen and fixed a bug referenced in the discussion https://github.com/sylikc/pyexiftool/pull/7\n04/19/2021 02:37:02 PM (PDT) | 0.4.7   | added support for writing a list of values in set_tags_batch() which allows setting individual keywords (and other tags which are exiftool lists) -- contribution from @davidorme referenced in issue https://github.com/sylikc/pyexiftool/issues/12#issuecomment-821879234\n04/28/2021 01:50:59 PM (PDT) | 0.4.8   | no functional changes, only a minor documentation link update -- Merged pull request #16 from @beng\n05/19/2021 09:37:52 PM (PDT) | 0.4.9   | test_tags() parameter encoding bugfix and a new test case TestTagCopying -- Merged pull request #19 from @jangop<br>I also added further updates to README.rst to point to my repo and GH pages<br>I fixed the \"previous versions\" naming to match the v0.2.0 start.  None of them were published, so I changed the version information here just to make it less confusing to a casual observer who might ask \"why did you have 0.1 when you forked off on 0.2.0?\"  Sven Marnach's releases were all 0.1, but he tagged his last release v0.2.0, which is my starting point\n08/22/2021 08:32:30 PM (PDT) | 0.4.10  | logger changed to use logging.getLogger(__name__) instead of the root logger -- Merged pull request #24 from @nyoungstudios\n08/22/2021 08:34:45 PM (PDT) | 0.4.11  | no functional code changes.  Changed setup.py with updated version and Documentation link pointed to sylikc.github.io -- as per issue #27 by @derMart\n08/22/2021 09:02:33 PM (PDT) | 0.4.12  | fixed a bug ExifTool.terminate() where there was a typo.  Kept the unused outs, errs though. -- from suggestion in pull request #26 by @aaronkollasch\n02/13/2022 03:38:45 PM (PST) | 0.4.13  | (NOTE: Barring any critical bug, this is expected to be the LAST Python 2 supported release!)  added GitHub actions.  fixed bug in execute_json_wrapper() 'error' was not defined syntactically properly -- merged pull request #30 by https://github.com/jangop\n\n\n\n\n# Changes around the web\n\nCheck for changes at the following resources to see if anyone has added some nifty features.  While we have the most active fork, I'm just one of the many forks, spoons, and knives!\n\nWe can also direct users here or answer existing questions as to how to use the original version of ExifTool.\n\n(last checked 10/23/2023 all)\n\nsearch \"pyexiftool github\" to see if you find any more random ports/forks\ncheck for updates https://github.com/smarnach/pyexiftool/pulls\ncheck for new open issues https://github.com/smarnach/pyexiftool/issues?q=is%3Aissue+is%3Aopen\n\nanswer relevant issues on stackoverflow (make sure it's related to the latest version) https://stackoverflow.com/search?tab=newest&q=pyexiftool&searchOn=3\n"
  },
  {
    "path": "COMPATIBILITY.txt",
    "content": "PyExifTool does not guarantee source-level compatibility from one release to the next.\n\nThat said, efforts will be made to provide well-documented API-level compatibility,\nand if there are major API changes, migration documentation will be provided, when\npossible.\n\n----\n\nv0.1.x - v0.2.0  = smarnach code, API compatible\nv0.2.1 - v0.4.13 = original v0.2 code with all PRs, a superset of functionality on Exiftool class\nv0.5.0 -         = not API compatible with the v0.4.x series.  Broke down functionality stability by classes.  See comments below:\n\n\n----\nAPI changes between v0.4.x and v0.5.0:\n\n\tPYTHON CHANGE: Old: Python 2.6 supported.  New: Python 3.6+ required\n\n\tCHANGED: Exiftool constructor:\n\t\tRENAME:   \"executable_\" parameter to \"executable\"\n\t\tDEFAULT BEHAVIOR: \"common_args\" defaults to [\"-G\", \"-n\"] instead of None.  Old behavior set -G and -n if \"common_args\" is None.  New behavior \"common_args\" = [] if common_args is None.\n\t\tDEFAULT: Old: \"win_shell\" defaults to True.  New: \"win_shell\" defaults to False.\n\t\tNEW: \"encoding\" parameter\n\t\tNEW: \"logger\" parameter\n\n\tNEW PROPERTY GET/SET: a lot of properties were added to do get/set validation, and parameters can be changed outside of the constructor.\n\n\tMETHOD RENAME: starting the process was renamed from \"start\" to \"run\"\n\n\tMINIMUM TOOL VERSION: exiftool command line utility minimum requirements.  Old: 8.60.  New: 12.15\n\n\tENCODING CHANGE: execute() and execute_json() no longer take bytes, but is guided by the encoding set in constructor/property\n\n\tERROR CHANGE: execute_json() when no json was not returned (such as a set metadata operation) => Old: raised an error.  New: returns custom ExifToolException\n\n\tFEATURE REMOVAL: execute_json() no longer detects the '-w' flag being passed used in common_args.\n\t\tIf a user uses this flag, expect no output.\n\t\t(detection in common_args was clunky anyways because -w can be passed as a per-run param for the same effect)\n\n\n\tall methods other than execute() and execute_json() moved to ExifToolHelper or ExifToolAlpha class.\n\n\tExifToolHelper adds methods:\n\t\tget_metadata()\n\t\tget_tags()\n\n\t\tNEW CONVENTION: all methods take \"files\" first, \"tags\" second (if needed) and \"params\" last\n\n\n\tExifToolAlpha adds all remaining methods in an alpha-quality way\n\n\tNOTE: ExifToolAlpha has not been updated yet to use the new convention, and the edge case code may be removed/changed at any time.\n\t\tIf you depend on functionality provided by ExifToolAlpha, please submit an Issue to start a discussion on cleaning up the code and moving it into ExifToolHelper\n----\n\n"
  },
  {
    "path": "COPYING.BSD",
    "content": "Copyright 2012 Sven Marnach, 2019-2023 Kevin M (sylikc)\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright notice,\n      this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright notice,\n      this list of conditions and the following disclaimer in the documentation\n      and/or other materials provided with the distribution.\n    * The names of its contributors may not be used to endorse or promote\n      products derived from this software without specific prior written\n      permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL SVEN MARNACH BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "COPYING.GPL",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "LICENSE",
    "content": "PyExifTool <http://github.com/sylikc/pyexiftool>\n\nCopyright 2019-2023 Kevin M (sylikc)\nCopyright 2012-2014 Sven Marnach\n\nPyExifTool is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the licence, or\n(at your option) any later version, or the BSD licence.\n\nPyExifTool is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\nSee COPYING.GPL or COPYING.BSD for more details.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include README.rst COPYING doc/Makefile doc/conf.py doc/*.rst\n"
  },
  {
    "path": "README.rst",
    "content": "**********\nPyExifTool\n**********\n\n.. image:: https://img.shields.io/badge/Docs-latest-blueviolet\n\t:alt: GitHub Pages\n\t:target: http://sylikc.github.io/pyexiftool/\n\n\n.. HIDE_FROM_PYPI_START\n\n.. image:: https://github.com/sylikc/pyexiftool/actions/workflows/lint-and-test.yml/badge.svg\n\t:alt: GitHub Actions\n\t:target: https://github.com/sylikc/pyexiftool/actions\n\n.. image:: https://img.shields.io/pypi/v/pyexiftool.svg\n\t:target: https://pypi.org/project/PyExifTool/\n\t:alt: PyPI Version\n\n\n.. HIDE_FROM_PYPI_END\n\n.. image:: https://img.shields.io/pypi/pyversions/pyexiftool.svg\n\t:target: https://pypi.org/project/PyExifTool/\n\t:alt: Supported Python Versions\n\n.. image:: https://pepy.tech/badge/pyexiftool\n\t:target: https://pepy.tech/project/pyexiftool\n\t:alt: Total PyPI Downloads\n\n.. image:: https://static.pepy.tech/personalized-badge/pyexiftool?period=month&units=international_system&left_color=black&right_color=orange&left_text=Downloads%2030d\n\t:target: https://pepy.tech/project/pyexiftool\n\t:alt: PyPI Downloads this month\n\n\n\n.. DESCRIPTION_START\n\n.. BLURB_START\n\nPyExifTool is a Python library to communicate with an instance of\n`Phil Harvey's ExifTool`_ command-line application.\n\n.. _Phil Harvey's ExifTool: https://exiftool.org/\n\n\n.. BLURB_END\n\nThe library provides the class ``exiftool.ExifTool`` that runs the command-line\ntool in batch mode and features methods to send commands to that\nprogram, including methods to extract meta-information from one or\nmore image files.  Since ``exiftool`` is run in batch mode, only a\nsingle instance needs to be launched and can be reused for many\nqueries.  This is much more efficient than launching a separate\nprocess for every single query.\n\n\n.. DESCRIPTION_END\n\n.. contents::\n\t:depth: 2\n\t:backlinks: none\n\nExample Usage\n=============\n\nSimple example: ::\n\n\timport exiftool\n\n\tfiles = [\"a.jpg\", \"b.png\", \"c.tif\"]\n\twith exiftool.ExifToolHelper() as et:\n\t    metadata = et.get_metadata(files)\n\t    for d in metadata:\n\t        print(\"{:20.20} {:20.20}\".format(d[\"SourceFile\"],\n\t                                         d[\"EXIF:DateTimeOriginal\"]))\n\nRefer to documentation for more `Examples and Quick Start Guide`_\n\n.. _`Examples and Quick Start Guide`: http://sylikc.github.io/pyexiftool/examples.html\n\n\n.. INSTALLATION_START\n\nGetting PyExifTool\n==================\n\nPyPI\n------------\n\nEasiest: Install a version from the official `PyExifTool PyPI`_\n\n::\n\n    python -m pip install -U pyexiftool\n\n.. _PyExifTool PyPI: https://pypi.org/project/PyExifTool/\n\n\nFrom Source\n------------\n\n#. Check out the source code from the github repository\n\n\t* ``git clone git://github.com/sylikc/pyexiftool.git``\n\t* Alternatively, you can download a tarball_.\n\n#. Run setup.py to install the module from source\n\n\t* ``python setup.py install [--user|--prefix=<installation-prefix>]``\n\n\n.. _tarball: https://github.com/sylikc/pyexiftool/tarball/master\n\n\nPyExifTool Dependencies\n=======================\n\nPython\n------\n\nPyExifTool runs on **Python 3.6+**.  (If you need Python 2.6 support,\nplease use version v0.4.x).  PyExifTool has been tested on Windows and\nLinux, and probably also runs on other Unix-like platforms.\n\nPhil Harvey's exiftool\n----------------------\n\nFor PyExifTool to function, ``exiftool`` command-line tool must exist on\nthe system.  If ``exiftool`` is not on the ``PATH``, you can specify the full\npathname to it by using ``ExifTool(executable=<full path>)``.\n\nPyExifTool requires a **minimum version of 12.15** (which was the first\nproduction version of exiftool featuring the options to allow exit status\nchecks used in conjuction with ``-echo3`` and ``-echo4`` parameters).\n\nTo check your ``exiftool`` version:\n\n::\n\n    exiftool -ver\n\n\nWindows/Mac\n^^^^^^^^^^^\n\nWindows/Mac users can download the latest version of exiftool:\n\n::\n\n    https://exiftool.org\n\nLinux\n^^^^^\n\nMost current Linux distributions have a package which will install ``exiftool``.\nUnfortunately, some do not have the minimum required version, in which case you\nwill have to `build from source`_.\n\n* Ubuntu\n  ::\n\n    sudo apt install libimage-exiftool-perl\n\n* CentOS/RHEL\n  ::\n\n    yum install perl-Image-ExifTool\n\n.. _build from source: https://exiftool.org/install.html#Unix\n\n\n.. INSTALLATION_END\n\n\nDocumentation\n=============\n\nThe current documentation is available at `sylikc.github.io`_.\n\n::\n\n    http://sylikc.github.io/pyexiftool/\n\n.. _sylikc.github.io: http://sylikc.github.io/pyexiftool/\n\n\nPackage Structure\n-----------------\n\n.. DESIGN_INFO_START\n\nPyExifTool was designed with flexibility and extensibility in mind.  The library consists of a few classes, each with increasingly more features.\n\nThe base ``ExifTool`` class contains the core functionality exposed in the most rudimentary way, and each successive class inherits and adds functionality.\n\n.. DESIGN_INFO_END\n\n.. DESIGN_CLASS_START\n\n* ``exiftool.ExifTool`` is the base class with core logic to interface with PH's ExifTool process.\n  It contains only the core features with no extra fluff.\n  The main methods provided are ``execute()`` and ``execute_json()`` which allows direct interaction with the underlying exiftool process.\n\n  * The API is considered stable and should not change much with future releases.\n\n* ``exiftool.ExifToolHelper`` exposes some of the most commonly used functionality.  It overloads\n  some inherited functions to turn common errors into warnings and adds logic to make\n  ``exiftool.ExifTool`` easier to use.\n  For example, ``ExifToolHelper`` provides wrapper functions to get metadata, and auto-starts the exiftool instance if it's not running (instead of raising an Exception).\n  ``ExifToolHelper`` demonstrates how to extend ``ExifTool`` to your liking if your project demands customizations not directly provided by ``ExifTool``.\n\n  * More methods may be added and/or slight API tweaks may occur with future releases.\n\n* ``exiftool.ExifToolAlpha`` further extends the ``ExifToolHelper`` and includes some community-contributed not-very-well-tested methods.\n  These methods were formerly added ad-hoc by various community contributors, but no longer stand up to the rigor of the current design.\n  ``ExifToolAlpha`` is *not* up to the rigorous testing standard of both\n  ``ExifTool`` or ``ExifToolHelper``.  There may be old, buggy, or defunct code.\n\n  * This is the least polished of the classes and functionality/API may be changed/added/removed on any release.\n\n  * **NOTE: The methods exposed may be changed/removed at any time.**\n\n  * If you are using any of these methods in your project, please `Submit an Issue`_ to start a discussion on making those functions more robust, and making their way into ``ExifToolHelper``.\n    (Think of ``ExifToolAlpha`` as ideas on how to extend ``ExifTool``, where new functionality which may one day make it into the ``ExifToolHelper`` class.)\n\n.. _Submit an Issue: https://github.com/sylikc/pyexiftool/issues\n\n\n.. DESIGN_CLASS_END\n\n\nBrief History\n=============\n\n.. HISTORY_START\n\nPyExifTool was originally developed by `Sven Marnach`_ in 2012 to answer a\nstackoverflow question `Call exiftool from a python script?`_.  Over time,\nSven refined the code, added tests, documentation, and a slew of improvements.\nWhile PyExifTool gained popularity, Sven `never intended to maintain it`_ as\nan active project.  The `original repository`_ was last updated in 2014.\n\nOver the years, numerous issues were filed and several PRs were opened on the\nstagnant repository.  In early 2019, `Martin Čarnogurský`_ created a\n`PyPI release`_ from the 2014 code with some minor updates.  Coincidentally in\nmid 2019, `Kevin M (sylikc)`_ forked the original repository and started merging\nthe PR and issues which were reported on Sven's issues/PR page.\n\nIn late 2019 and early 2020 there was a discussion started to\n`Provide visibility for an active fork`_.  There was a conversation to\ntransfer ownership of the original repository, have a coordinated plan to\ncommunicate to PyExifTool users, amongst other things, but it never materialized.\n\nKevin M (sylikc) made the first release to the PyPI repository in early 2021.\nAt the same time, discussions were started, revolving around\n`Deprecating Python 2.x compatibility`_ and `refactoring the code and classes`_.\n\nThe latest version is the result of all of those discussions, designs,\nand development.  Special thanks to the community contributions, especially\n`Jan Philip Göpfert`_, `Seth P`_, and `Kolen Cheung`_.\n\n.. _Sven Marnach: https://github.com/smarnach/pyexiftool\n.. _Call exiftool from a python script?: https://stackoverflow.com/questions/10075115/call-exiftool-from-a-python-script/10075210#10075210\n.. _never intended to maintain it: https://github.com/smarnach/pyexiftool/pull/31#issuecomment-569238073\n.. _original repository: https://github.com/smarnach/pyexiftool\n.. _Martin Čarnogurský: https://github.com/RootLUG\n.. _PyPI release: https://pypi.org/project/PyExifTool/0.1.1/#history\n.. _Kevin M (sylikc): https://github.com/sylikc\n.. _Provide visibility for an active fork: https://github.com/smarnach/pyexiftool/pull/31\n.. _Deprecating Python 2.x compatibility: https://github.com/sylikc/pyexiftool/discussions/9\n.. _refactoring the code and classes: https://github.com/sylikc/pyexiftool/discussions/10\n.. _Jan Philip Göpfert: https://github.com/jangop\n.. _Seth P: https://github.com/csparker247\n.. _Kolen Cheung: https://github.com/ickc\n\n\n.. HISTORY_END\n\nLicence\n=======\n\n.. LICENSE_START\n\nPyExifTool is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the licence, or\n(at your option) any later version, or the BSD licence.\n\nPyExifTool is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\nSee ``LICENSE`` for more details.\n\n\n.. LICENSE_END\n"
  },
  {
    "path": "docs/.gitignore",
    "content": "_build/\n"
  },
  {
    "path": "docs/Makefile",
    "content": "# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS    =\nSPHINXBUILD   = sphinx-build\nPAPER         =\nSOURCEDIR     = source\nBUILDDIR      = _build\n\n# Internal variables.\nPAPEROPT_a4     = -D latex_paper_size=a4\nPAPEROPT_letter = -D latex_paper_size=letter\nALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n# the i18n builder cannot share the environment and doctrees with the others\nI18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n\n.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext\n\nhelp:\n\t@echo \"Please use \\`make <target>' where <target> is one of\"\n\t@echo \"  html       to make standalone HTML files\"\n\t@echo \"  dirhtml    to make HTML files named index.html in directories\"\n\t@echo \"  singlehtml to make a single large HTML file\"\n\t@echo \"  pickle     to make pickle files\"\n\t@echo \"  json       to make JSON files\"\n\t@echo \"  htmlhelp   to make HTML files and a HTML help project\"\n\t@echo \"  qthelp     to make HTML files and a qthelp project\"\n\t@echo \"  devhelp    to make HTML files and a Devhelp project\"\n\t@echo \"  epub       to make an epub\"\n\t@echo \"  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter\"\n\t@echo \"  latexpdf   to make LaTeX files and run them through pdflatex\"\n\t@echo \"  text       to make text files\"\n\t@echo \"  man        to make manual pages\"\n\t@echo \"  texinfo    to make Texinfo files\"\n\t@echo \"  info       to make Texinfo files and run them through makeinfo\"\n\t@echo \"  gettext    to make PO message catalogs\"\n\t@echo \"  changes    to make an overview of all changed/added/deprecated items\"\n\t@echo \"  linkcheck  to check all external links for integrity\"\n\t@echo \"  doctest    to run all doctests embedded in the documentation (if enabled)\"\n\nclean:\n\t-rm -rf $(BUILDDIR)/*\n\nhtml:\n\t$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/html.\"\n\ndirhtml:\n\t$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/dirhtml.\"\n\nsinglehtml:\n\t$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml\n\t@echo\n\t@echo \"Build finished. The HTML page is in $(BUILDDIR)/singlehtml.\"\n\npickle:\n\t$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle\n\t@echo\n\t@echo \"Build finished; now you can process the pickle files.\"\n\njson:\n\t$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json\n\t@echo\n\t@echo \"Build finished; now you can process the JSON files.\"\n\nhtmlhelp:\n\t$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp\n\t@echo\n\t@echo \"Build finished; now you can run HTML Help Workshop with the\" \\\n\t      \".hhp project file in $(BUILDDIR)/htmlhelp.\"\n\nqthelp:\n\t$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp\n\t@echo\n\t@echo \"Build finished; now you can run \"qcollectiongenerator\" with the\" \\\n\t      \".qhcp project file in $(BUILDDIR)/qthelp, like this:\"\n\t@echo \"# qcollectiongenerator $(BUILDDIR)/qthelp/PyExifTool.qhcp\"\n\t@echo \"To view the help file:\"\n\t@echo \"# assistant -collectionFile $(BUILDDIR)/qthelp/PyExifTool.qhc\"\n\ndevhelp:\n\t$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp\n\t@echo\n\t@echo \"Build finished.\"\n\t@echo \"To view the help file:\"\n\t@echo \"# mkdir -p $$HOME/.local/share/devhelp/PyExifTool\"\n\t@echo \"# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PyExifTool\"\n\t@echo \"# devhelp\"\n\nepub:\n\t$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub\n\t@echo\n\t@echo \"Build finished. The epub file is in $(BUILDDIR)/epub.\"\n\nlatex:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo\n\t@echo \"Build finished; the LaTeX files are in $(BUILDDIR)/latex.\"\n\t@echo \"Run \\`make' in that directory to run these through (pdf)latex\" \\\n\t      \"(use \\`make latexpdf' here to do that automatically).\"\n\nlatexpdf:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through pdflatex...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\ntext:\n\t$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text\n\t@echo\n\t@echo \"Build finished. The text files are in $(BUILDDIR)/text.\"\n\nman:\n\t$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man\n\t@echo\n\t@echo \"Build finished. The manual pages are in $(BUILDDIR)/man.\"\n\ntexinfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo\n\t@echo \"Build finished. The Texinfo files are in $(BUILDDIR)/texinfo.\"\n\t@echo \"Run \\`make' in that directory to run these through makeinfo\" \\\n\t      \"(use \\`make info' here to do that automatically).\"\n\ninfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo \"Running Texinfo files through makeinfo...\"\n\tmake -C $(BUILDDIR)/texinfo info\n\t@echo \"makeinfo finished; the Info files are in $(BUILDDIR)/texinfo.\"\n\ngettext:\n\t$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale\n\t@echo\n\t@echo \"Build finished. The message catalogs are in $(BUILDDIR)/locale.\"\n\nchanges:\n\t$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes\n\t@echo\n\t@echo \"The overview file is in $(BUILDDIR)/changes.\"\n\nlinkcheck:\n\t$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck\n\t@echo\n\t@echo \"Link check complete; look for any errors in the above output \" \\\n\t      \"or in $(BUILDDIR)/linkcheck/output.txt.\"\n\ndoctest:\n\t$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest\n\t@echo \"Testing of doctests in the sources finished, look at the \" \\\n\t      \"results in $(BUILDDIR)/doctest/output.txt.\"\n"
  },
  {
    "path": "docs/make.bat",
    "content": "@ECHO OFF\n\npushd %~dp0\n\nREM Command file for Sphinx documentation\n\nif \"%SPHINXBUILD%\" == \"\" (\n\tset SPHINXBUILD=sphinx-build\n)\nset SOURCEDIR=source\nset BUILDDIR=_build\n\nif \"%1\" == \"\" goto help\n\n%SPHINXBUILD% >NUL 2>NUL\nif errorlevel 9009 (\n\techo.\n\techo.The 'sphinx-build' command was not found. Make sure you have Sphinx\n\techo.installed, then set the SPHINXBUILD environment variable to point\n\techo.to the full path of the 'sphinx-build' executable. Alternatively you\n\techo.may add the Sphinx directory to PATH.\n\techo.\n\techo.If you don't have Sphinx installed, grab it from\n\techo.http://sphinx-doc.org/\n\texit /b 1\n)\n\n%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%\ngoto end\n\n:help\n%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%\n\n:end\npopd\n"
  },
  {
    "path": "docs/source/conf.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# PyExifTool documentation build configuration file, created by\n# sphinx-quickstart on Thu Apr 12 17:42:54 2012.\n#\n# This file is execfile()d with the current directory set to its containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\nimport sys\nfrom pathlib import Path\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parent\n# \"Path.parent is a purely lexical operation\n# If you want to walk an arbitrary filesystem path upwards,\n# it is recommended to first call Path.resolve() so as to\n# resolve symlinks and eliminate .. components.\"\nsys.path.insert(1, Path(__file__).resolve().parent.parent)\n\n\n\n# -- Project information -----------------------------------------------------\n\n# General information about the project.\nproject = 'PyExifTool'\ncopyright = '2023, Kevin M (sylikc)'\nauthor = 'Kevin M (sylikc)'\n\n# read directly from exiftool's version instead of hard coding it here\nimport exiftool\nfrom packaging import version as pv\net_ver = pv.parse(exiftool.__version__)\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = f'{et_ver.major}.{et_ver.minor}'\n# The full version, including alpha/beta/rc tags.\nrelease = exiftool.__version__\n\n\n# -- General configuration -----------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be extensions\n# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.\nextensions = [\n\t'sphinx.ext.autodoc',  # Core library for html generation from docstrings\n\t'sphinx.ext.autodoc.typehints',\n\t#'sphinx.ext.autosummary',  # Create neat summary tables\n\t'autoapi.extension',  # pip install sphinx-autoapi\n\t'sphinx_autodoc_typehints',  # pip install sphinx-autodoc-typehints\n\t'sphinx.ext.inheritance_diagram',\n]\n\n#autosummary_generate = True # Turn on sphinx.ext.autosummary\n\n\n\nautoapi_type = 'python'\nautoapi_dirs = ['../../exiftool']\nautoapi_member_order = 'groupwise'\n#autoapi_python_use_implicit_namespaces = True\n\n# make my life easier, configure the autoapi with specific options for things that I care about ... aka\n# hide 'private-members' - inheriting classes should not have to handle or interfere with private variables\n# hide 'imported-members' - after all i import the submodules into the base namespace - don't need it to show twice\nautoapi_options = [ 'members', 'undoc-members', 'show-inheritance', 'show-inheritance-diagram', 'show-module-summary', 'special-members',  ]\n#autoapi_generate_api_docs = False\nautoapi_python_class_content = 'both'  # show __init__ with class docstring\n\n\n# https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_typehints\n# comment out when all documentation has documented parameters ... sometimes causes duplicates, but that may be a RST problem... always put links at the END of the docstring instead of in the middle\nautodoc_typehints = 'description'\n\ntypehints_defaults = \"comma\"\n\n\n\n# the common names of the classes rather than the absolute paths\ninheritance_alias = {\n\t'exiftool.exiftool.ExifTool': 'exiftool.ExifTool',\n\t'exiftool.helper.ExifToolHelper': 'exiftool.ExifToolHelper',\n\t'exiftool.experimental.ExifToolAlpha': 'exiftool.ExifToolAlpha',\n}\n\n# help on attributes and Graphviz params:\n# https://www.sphinx-doc.org/en/master/usage/extensions/inheritance.html\n# https://graphs.grevian.org/reference\n# https://graphviz.org/doc/info/attrs.html\n#inheritance_graph_attrs = dict(rankdir=\"LR\", size='\"6.0, 8.0\"', fontsize=14, ratio='compress')\ninheritance_graph_attrs = dict(pad=\"0.2\", center=True)\ninheritance_node_attrs = dict(shape='box', fontsize=14, height=0.75, color='dodgerblue1', style='rounded')\n\n\n\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix of source filenames.\nsource_suffix = '.rst'\n\n# The encoding of source files.\n#source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#language = None\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n#today = ''\n# Else, today_fmt is used as the format for a strftime call.\n#today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = ['_build']\n\n# The reST default role (used for this markup: `text`) to use for all documents.\n#default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n#add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\n#add_module_names = True\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n#show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# A list of ignored prefixes for module index sorting.\n#modindex_common_prefix = []\n\n\n# -- Options for HTML output ---------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\nhtml_theme = 'sphinx_rtd_theme'  # pip install sphinx_rtd_theme\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n#html_theme_options = {}\n\n# https://stackoverflow.com/questions/62904172/how-do-i-replace-view-page-source-with-edit-on-github-links-in-sphinx-rtd-th/62904217#62904217\nhtml_context = {\n\t#'display_github': True,\n\t'github_user': 'sylikc',\n\t'github_repo': 'pyexiftool',\n\t'github_version': 'master/docs/source/',\n}\n\n# Add any paths that contain custom themes here, relative to this directory.\n#html_theme_path = []\n\n# The name for this set of Sphinx documents.  If None, it defaults to\n# \"<project> v<release> documentation\".\n#html_title = None\n\n# A shorter title for the navigation bar.  Default is the same as html_title.\n#html_short_title = None\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\n#html_logo = None\n\n# The name of an image file (within the static path) to use as favicon of the\n# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\n#html_favicon = None\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,\n# using the given strftime format.\n#html_last_updated_fmt = '%b %d, %Y'\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n#html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n#html_sidebars = {}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n#html_additional_pages = {}\n\n# If false, no module index is generated.\n#html_domain_indices = True\n\n# If false, no index is generated.\n#html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n#html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n#html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n#html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n#html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a <link> tag referring to it.  The value of this option must be the\n# base URL from which the finished HTML is served.\n#html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n#html_file_suffix = None\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'PyExifTooldoc'\n\n\n# -- Options for LaTeX output --------------------------------------------------\n\nlatex_elements = {\n# The paper size ('letterpaper' or 'a4paper').\n#'papersize': 'letterpaper',\n\n# The font size ('10pt', '11pt' or '12pt').\n#'pointsize': '10pt',\n\n# Additional stuff for the LaTeX preamble.\n#'preamble': '',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title, author, documentclass [howto/manual]).\n\"\"\"\nlatex_documents = [\n\t('index', 'PyExifTool.tex', u'PyExifTool Documentation',\n\t u'Sven Marnach', 'manual'),\n]\n\"\"\"\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n#latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n#latex_use_parts = False\n\n# If true, show page references after internal links.\n#latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n#latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n#latex_appendices = []\n\n# If false, no module index is generated.\n#latex_domain_indices = True\n\n\n# -- Options for manual page output --------------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\n\"\"\"\nman_pages = [\n\t('index', 'pyexiftool', u'PyExifTool Documentation',\n\t [u'Sven Marnach'], 1)\n]\n\"\"\"\n\n# If true, show URL addresses after external links.\n#man_show_urls = False\n\n\n# -- Options for Texinfo output ------------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\n\"\"\"\ntexinfo_documents = [\n\t('index', 'PyExifTool', u'PyExifTool Documentation',\n\t u'Sven Marnach', 'PyExifTool', 'One line description of project.',\n\t 'Miscellaneous'),\n]\n\"\"\"\n\n# Documents to append as an appendix to all manuals.\n#texinfo_appendices = []\n\n# If false, no module index is generated.\n#texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n#texinfo_show_urls = 'footnote'\n"
  },
  {
    "path": "docs/source/examples.rst",
    "content": "**********************\nExamples / Quick Start\n**********************\n\n.. NOTE: No tabs in this file, all spaces, to simplify examples indentation\n\n\nTry it yourself: All of these examples are using the images provided in the `tests directory`_ in the source\n\n.. _`tests directory`: https://github.com/sylikc/pyexiftool/tree/master/tests/images\n\n\n\nUnderstanding input and output from PyExifTool base methods\n===========================================================\n\nAlmost all methods in PyExifTool revolve around the usage of two methods from the base :py:class:`exiftool.ExifTool` class.\n\n\n**It is important to understand the ouput from each of these commands**, so here's a quick summary (you can click through to the API to read more details)\n\n.. note::\n\n    Because both methods are inherited by :py:class:`exiftool.ExifToolHelper` and :py:class:`exiftool.ExifToolAlpha`, you can call it from those classes as well.\n\n\n.. _examples input params:\n\nInput parameters\n----------------\n\nBoth methods take an argument list ``*args``.  Examples:\n\n.. note::\n\n    As a general rule of thumb, if there is an **unquoted space on the command line** to *exiftool*, it's a **separate argument to the method** in PyExifTool.\n\n    If you have a working `exiftool` command-line but having trouble figuring out how to properly separate the arguments, please refer to the :ref:`FAQ <shlex split>`\n\n* Calling directly:\n\n    * exiftool command-line:\n\n        .. code-block:: text\n\n            exiftool -XMPToolKit -Subject rose.jpg\n\n    * PyExifTool:\n\n        .. code-block::\n\n            execute(\"-XMPToolKit\", \"-Subject\", \"rose.jpg\")\n\n* Using argument unpacking of a list:\n\n    * exiftool command-line:\n\n        .. code-block:: text\n\n            exiftool -P -DateTimeOriginal=\"2021:01:02 03:04:05\" -MakerNotes= \"spaces in filename.jpg\"\n\n    * PyExifTool:\n\n        .. note::\n\n            Parameters which need to be quoted on the command line generally do not need to be quoted in the parameters to PyExifTool.  In fact, quoting may have unintended behavior.\n\n            In this example, *DateTimeOriginal* value is not quoted in the parameter to execute().\n\n        .. code-block::\n\n            execute(*[\"-P\", \"-DateTimeOriginal=2021:01:02 03:04:05\", \"-MakerNotes=\", \"spaces in filename.jpg\"])\n\n\n* Getting JSON output using argument unpacking of a list:\n\n    * exiftool command-line:\n\n        .. code-block:: text\n\n            exiftool -j -XMP:all -JFIF:JFIFVersion /path/somefile.jpg\n\n    * PyExifTool:\n\n        .. code-block::\n\n            execute_json(*[\"-XMP:all\", \"-JFIF:JFIFVersion\", \"/path/somefile.jpg\"])\n\n\nOutput values\n-------------\n\n* :py:meth:`exiftool.ExifTool.execute_json`\n\n    * Returns a ``list`` of ``dict``\n    * Each ``dict`` is a result from a file\n    * Each ``dict`` contains a key \"SourceFile\" which points to the relative or absolute file path of file\n    * All other keys/value pairs are requested metadata\n\n* :py:meth:`exiftool.ExifTool.execute`\n\n    * Returns a ``str``\n    * Typically used for **setting tags** as no values are returned in that case.\n\n\nExifToolHelper\n==============\n\nUsing methods provided by :py:class:`exiftool.ExifToolHelper`:\n\nExifToolHelper provides some of the most commonly used operations most people use *exiftool* for\n\nGetting Tags\n------------\n\n* Get all tags on a single file\n\n    .. code-block::\n\n        from exiftool import ExifToolHelper\n        with ExifToolHelper() as et:\n            for d in et.get_metadata(\"rose.jpg\"):\n                for k, v in d.items():\n                    print(f\"Dict: {k} = {v}\")\n\n\n    .. code-block:: text\n\n        Dict: SourceFile = rose.jpg\n        Dict: ExifTool:ExifToolVersion = 12.37\n        Dict: File:FileName = rose.jpg\n        Dict: File:Directory = .\n        Dict: File:FileSize = 4949\n        Dict: File:FileModifyDate = 2022:03:03 17:47:11-08:00\n        Dict: File:FileAccessDate = 2022:03:27 08:28:16-07:00\n        Dict: File:FileCreateDate = 2022:03:03 17:47:11-08:00\n        Dict: File:FilePermissions = 100666\n        Dict: File:FileType = JPEG\n        Dict: File:FileTypeExtension = JPG\n        Dict: File:MIMEType = image/jpeg\n        Dict: File:ImageWidth = 70\n        Dict: File:ImageHeight = 46\n        Dict: File:EncodingProcess = 0\n        Dict: File:BitsPerSample = 8\n        Dict: File:ColorComponents = 3\n        Dict: File:YCbCrSubSampling = 2 2\n        Dict: JFIF:JFIFVersion = 1 1\n        Dict: JFIF:ResolutionUnit = 1\n        Dict: JFIF:XResolution = 72\n        Dict: JFIF:YResolution = 72\n        Dict: XMP:XMPToolkit = Image::ExifTool 8.85\n        Dict: XMP:Subject = Röschen\n        Dict: Composite:ImageSize = 70 46\n        Dict: Composite:Megapixels = 0.00322\n\n* Get some tags in multiple files\n\n    .. code-block::\n\n        from exiftool import ExifToolHelper\n        with ExifToolHelper() as et:\n            for d in et.get_tags([\"rose.jpg\", \"skyblue.png\"], tags=[\"FileSize\", \"ImageSize\"]):\n                for k, v in d.items():\n                    print(f\"Dict: {k} = {v}\")\n\n\n    .. code-block:: text\n\n        Dict: SourceFile = rose.jpg\n        Dict: File:FileSize = 4949\n        Dict: Composite:ImageSize = 70 46\n        Dict: SourceFile = skyblue.png\n        Dict: File:FileSize = 206\n        Dict: Composite:ImageSize = 64 64\n\nSetting Tags\n------------\n\n* Setting date and time of some files to current time, overwriting file, but preserving original mod date\n\n    .. code-block::\n\n        from exiftool import ExifToolHelper\n        from datetime import datetime\n        with ExifToolHelper() as et:\n            now = datetime.strftime(datetime.now(), \"%Y:%m:%d %H:%M:%S\")\n            et.set_tags(\n                [\"rose.jpg\", \"skyblue.png\"],\n                tags={\"DateTimeOriginal\": now},\n                params=[\"-P\", \"-overwrite_original\"]\n            )\n\n    (*No output is returned if successful*)\n\n* Setting keywords for a file.\n\n    .. code-block::\n\n        from exiftool import ExifToolHelper\n        with ExifToolHelper() as et:\n            et.set_tags(\n                [\"rose.jpg\", \"skyblue.png\"],\n                tags={\"Keywords\": [\"sunny\", \"nice day\", \"cool\", \"awesome\"]}\n            )\n\n    (*No output is returned if successful*)\n\n\n\nExceptions\n----------\n\nBy default, ExifToolHelper has some **built-in error checking**, making the methods safer to use than calling the base methods directly.\n\n.. warning::\n\n    While \"safer\", the error checking isn't fool-proof.  There are a lot of cases where *exiftool* just silently ignores bad input and doesn't indicate an error.\n\n* Example using get_tags() on a list which includes a non-existent file\n\n    * ExifToolHelper with error-checking, using :py:meth:`exiftool.ExifToolHelper.get_tags`\n\n        .. code-block::\n\n            from exiftool import ExifToolHelper\n            with ExifToolHelper() as et:\n                print(et.get_tags(\n                    [\"rose.jpg\", \"skyblue.png\", \"non-existent file.tif\"],\n                    tags=[\"FileSize\"]\n                ))\n\n        Output:\n\n        .. code-block:: text\n\n            Traceback (most recent call last):\n              File \"T:\\example.py\", line 7, in <module>\n                et.get_tags([\"rose.jpg\", \"skyblue.png\", \"non-existent file.tif\"], tags=[\"FileSize\"])\n              File \"T:\\pyexiftool\\exiftool\\helper.py\", line 353, in get_tags\n                ret = self.execute_json(*exec_params)\n              File \"T:\\pyexiftool\\exiftool\\exiftool.py\", line 1030, in execute_json\n                result = self.execute(\"-j\", *params)  # stdout\n              File \"T:\\pyexiftool\\exiftool\\helper.py\", line 119, in execute\n                raise ExifToolExecuteError(self._last_status, self._last_stdout, self._last_stderr, params)\n            exiftool.exceptions.ExifToolExecuteError: execute returned a non-zero exit status: 1\n\n\n    * ExifTool only, without error checking, using :py:meth:`exiftool.ExifTool.execute_json` (**Note how the missing file is silently ignored and doesn't show up in returned list.**)\n\n        .. code-block::\n\n            from exiftool import ExifToolHelper\n            with ExifToolHelper() as et:\n                print(et.get_tags(\n                    [\"rose.jpg\", \"skyblue.png\", \"non-existent file.tif\"],\n                    tags=[\"FileSize\"]\n                ))\n\n        Output:\n\n        .. code-block:: text\n\n            [{'SourceFile': 'rose.jpg', 'File:FileSize': 4949}, {'SourceFile': 'skyblue.png', 'File:FileSize': 206}]\n\n\n* Example using :py:meth:`exiftool.ExifToolHelper.get_tags` with a typo.  Let's say you wanted to ``get_tags()``, but accidentally copy/pasted something and left a ``=`` character behind (deletes tag rather than getting!)...\n\n    * Using :py:meth:`exiftool.ExifToolHelper.get_tags`\n\n        .. code-block::\n\n            from exiftool import ExifToolHelper\n            with ExifToolHelper() as et:\n                print(et.get_tags([\"skyblue.png\"], tags=[\"XMP:Subject=hi\"]))\n\n        Output:\n\n        .. code-block:: text\n\n            Traceback (most recent call last):\n              File \"T:\\example.py\", line 7, in <module>\n                print(et.get_tags([\"skyblue.png\"], tags=[\"XMP:Subject=hi\"]))\n              File \"T:\\pyexiftool\\exiftool\\helper.py\", line 341, in get_tags\n                self.__class__._check_tag_list(final_tags)\n              File \"T:\\pyexiftool\\exiftool\\helper.py\", line 574, in _check_tag_list\n                raise ExifToolTagNameError(t)\n            exiftool.exceptions.ExifToolTagNameError: Invalid Tag Name found: \"XMP:Subject=hi\"\n\n    * Using :py:meth:`exiftool.ExifTool.execute_json`.  It still raises an exception, but more cryptic and difficult to debug\n\n        .. code-block::\n\n            from exiftool import ExifTool\n            with ExifTool() as et:\n                print(et.execute_json(*[\"-XMP:Subject=hi\"] + [\"skyblue.png\"]))\n\n        Output:\n\n        .. code-block:: text\n\n            Traceback (most recent call last):\n              File \"T:\\example.py\", line 7, in <module>\n                print(et.execute_json(*[\"-XMP:Subject=hi\"] + [\"skyblue.png\"]))\n              File \"T:\\pyexiftool\\exiftool\\exiftool.py\", line 1052, in execute_json\n                raise ExifToolOutputEmptyError(self._last_status, self._last_stdout, self._last_stderr, params)\n            exiftool.exceptions.ExifToolOutputEmptyError: execute_json expected output on stdout but got none\n\n    * Using :py:meth:`exiftool.ExifTool.execute`.  **No errors, but you have now written to the file instead of reading from it!**\n\n        .. code-block::\n\n            from exiftool import ExifTool\n            with ExifTool() as et:\n                print(et.execute(*[\"-XMP:Subject=hi\"] + [\"skyblue.png\"]))\n\n        Output:\n\n        .. code-block:: text\n\n            1 image files updated\n\nExifTool\n========\n\nUsing methods provided by :py:class:`exiftool.ExifTool`\n\nCalling execute() or execute_json() provides raw functionality for advanced use cases.  Use with care!\n\n\n\n.. TODO show some ExifTool and ExifToolHelper use cases for common exiftool operations\n\n.. TODO show some Advanced use cases, and maybe even some don't-do-this-even-though-you-can cases (like using params for tags)\n\n"
  },
  {
    "path": "docs/source/faq.rst",
    "content": "**************************\nFrequently Asked Questions\n**************************\n\nPyExifTool output is different from the exiftool command line\n=============================================================\n\nOne of the most frequently asked questions relates to the *default output* of PyExifTool.\n\nFor example, using the `rose.jpg in tests`_, let's get **all JFIF tags**:\n\nDefault exiftool output\n-----------------------\n\n$ ``exiftool -JFIF:all rose.jpg``\n\n.. code-block:: text\n\n\tJFIF Version                    : 1.01\n\tResolution Unit                 : inches\n\tX Resolution                    : 72\n\tY Resolution                    : 72\n\n\n.. _`rose.jpg in tests`: https://github.com/sylikc/pyexiftool/blob/master/tests/files/rose.jpg\n\nDefault PyExifTool output\n-------------------------\n\nfrom PyExifTool, using the following code:\n\n.. code-block::\n\n\timport exiftool\n\twith exiftool.ExifTool() as et:\n\t    print(et.execute(\"-JFIF:all\", \"rose.jpg\"))\n\nOutput:\n\n.. code-block:: text\n\n\t[JFIF]          JFIF Version                    : 1 1\n\t[JFIF]          Resolution Unit                 : 1\n\t[JFIF]          X Resolution                    : 72\n\t[JFIF]          Y Resolution                    : 72\n\nWhat's going on?\n----------------\n\nThe reason for the different default output is that PyExifTool, by default, includes two arguments which make *exiftool* easier to use: ``-G, -n``.\n\n.. note::\n\n\tThe ``-n`` disables *print conversion* which displays **raw tag values**, making the output more **machine-parseable**.\n\n\tWhen *print conversion* is enabled, *some* raw values may be translated to prettier **human-readable** text.\n\n\n.. note::\n\tThe ``-G`` enables *group name (level 1)* option which displays a group in the output to help disambiguate tags with the same name in different groups.\n\n\tFor example, *-DateCreated* can be ambiguous if both *-IPTC:DateCreated* and *-XMP:DateCreated* exists and have different values.  ``-G`` would display which one was returned by *exiftool*.\n\n\nRead the documentation for the ExifTool constructor ``common_args`` parameter for more details: :py:meth:`exiftool.ExifTool.__init__`.\n\n(You can also change ``common_args`` on an existing instance using :py:attr:`exiftool.ExifTool.common_args`, as long as the subprocess is not :py:attr:`exiftool.ExifTool.running`)\n\n\n\n\nWays to make the ouptut match\n-----------------------------\n\nSo if you want to have the ouput match (*useful for debugging*) between PyExifTool and exiftool, either:\n\n* **Enable print conversion on exiftool command line**:\n\n\t$ ``exiftool -G -n -JFIF:all rose.jpg``\n\n\t.. code-block:: text\n\n\t\t[JFIF]          JFIF Version                    : 1 1\n\t\t[JFIF]          Resolution Unit                 : 1\n\t\t[JFIF]          X Resolution                    : 72\n\t\t[JFIF]          Y Resolution                    : 72\n\n* **Disable print conversion and group name in PyExifTool**:\n\n\t.. code-block::\n\n\t\timport exiftool\n\t\twith exiftool.ExifTool(common_args=None) as et:\n\t\t    print(et.execute(\"-JFIF:all\", \"rose.jpg\"))\n\n\tOutput:\n\n\t.. code-block:: text\n\n\t\tJFIF Version                    : 1.01\n\t\tResolution Unit                 : inches\n\t\tX Resolution                    : 72\n\t\tY Resolution                    : 72\n\n\n\n.. _shlex split:\n\nI can run this on the command-line but it doesn't work in PyExifTool\n====================================================================\n\nA frequent problem encountered by first-time users, is figuring out how to properly split their arguments into a call to PyExifTool.\n\nAs noted in the :ref:`Quick Start Examples <examples input params>`:\n\n\tIf there is an **unquoted space on the command line** to *exiftool*, it's a **separate argument to the method** in PyExifTool.\n\nSo, what does this look like in practice?\n\nUse `Python's shlex library`_ as a quick and easy way to figure out what the parameters to :py:meth:`exiftool.ExifTool.execute` or :py:meth:`exiftool.ExifTool.execute_json` should be.\n\n* Sample exiftool command line (with multiple quoted and unquoted parameters):\n\n\t.. code-block:: text\n\n\t\texiftool -v0 -preserve -overwrite_original -api largefilesupport=1 -api \"QuickTimeUTC=1\" \"-EXIF:DateTimeOriginal+=1:2:3 4:5:6\" -XMP:DateTimeOriginal=\"2006:05:04 03:02:01\" -gpsaltituderef=\"Above Sea Level\" -make= test.mov\n\n* Using ``shlex`` to figure out the right argument list:\n\n\t.. code-block::\n\n\t\timport shlex, exiftool\n\t\twith exiftool.ExifToolHelper() as et:\n\t\t\tparams = shlex.split('-v0 -preserve -overwrite_original -api largefilesupport=1 \"-EXIF:DateTimeOriginal+=1:2:3 4:5:6\" -XMP:DateTimeOriginal=\"2006:05:04 03:02:01\" -gpsaltituderef=\"Above Sea Level\" -make= test.mov')\n\t\t\tprint(params)\n\t\t\t# Output: ['-v0', '-preserve', '-overwrite_original', '-api', 'largefilesupport=1', '-api', 'QuickTimeUTC=1', '-EXIF:DateTimeOriginal+=1:2:3 4:5:6', '-XMP:DateTimeOriginal=2006:05:04 03:02:01', '-gpsaltituderef=Above Sea Level', '-make=', 'test.mov']\n\t\t\tet.execute(*params)\n\n\t.. note::\n\n\t\t``shlex.split()`` is a useful *tool to simplify discovery* of the correct arguments needed to call PyExifTool.\n\n\t\tHowever, since spliting and constructing immutable strings in Python is **slower than building the parameter list properly**, this method is *only recommended for* **debugging**!\n\n\n.. _`Python's shlex library`: https://docs.python.org/library/shlex.html\n\n.. _set_json_loads faq:\n\nPyExifTool json turns some text fields into numbers\n===================================================\n\nA strange behavior of *exiftool* is documented in the `exiftool documentation`_::\n\n\t-j[[+]=JSONFILE] (-json)\n\n\t\tNote that ExifTool quotes JSON values only if they don't look like numbers\n\t\t(regardless of the original storage format or the relevant metadata specification).\n\n.. _`exiftool documentation`: https://exiftool.org/exiftool_pod.html#OPTIONS\n\nThis causes a peculiar behavior if you set a text metadata field to a string that looks like a number:\n\n.. code-block::\n\n\timport exiftool\n\twith exiftool.ExifToolHelper() as et:\n\t\t# Comment is a STRING field\n\t\tet.set_tags(\"rose.jpg\", {\"Comment\": \"1.10\"})  # string: \"1.10\" != \"1.1\"\n\n\t\t# FocalLength is a FLOAT field\n\t\tet.set_tags(\"rose.jpg\", {\"FocalLength\": 1.10})  # float: 1.10 == 1.1\n\t\tprint(et.get_tags(\"rose.jpg\", [\"Comment\", \"FocalLength\"]))\n\n\t\t# Prints: [{'SourceFile': 'rose.jpg', 'File:Comment': 1.1, 'EXIF:FocalLength': 1.1}]\n\nWorkaround to enable output as string\n-------------------------------------\n\nThere is no universal fix which wouldn't affect other behaviors in PyExifTool, so this is an advanced workaround if you encounter this specific problem.\n\nPyExifTool does not do any processing on the fields returned by *exiftool*.  In effect, what is returned is processed directly by ``json.loads()`` by default.\n\nYou can change the behavior of the json string parser, or specify a different one using :py:meth:`exiftool.ExifTool.set_json_loads`.\n\nThe `documentation of CPython's json.load`_ allows ``parse_float`` to be any parser of choice when a float is encountered in a JSON file.  Thus, you can force the float to be interpreted as a string.\nHowever, as you can see below, it also *changes the behavior of all float fields*.\n\n\n.. _`documentation of CPython's json.load`: https://docs.python.org/3/library/json.html#json.load\n\n.. code-block::\n\n\timport exiftool, json\n\twith exiftool.ExifToolHelper() as et:\n\t\tet.set_json_loads(json.loads, parse_float=str)\n\n\t\t# Comment is a STRING field\n\t\tet.set_tags(\"rose.jpg\", {\"Comment\": \"1.10\"})  # string: \"1.10\" == \"1.10\"\n\n\t\t# FocalLength is a FLOAT field\n\t\tet.set_tags(\"rose.jpg\", {\"FocalLength\": 1.10})  # float: 1.1 != \"1.1\"\n\t\tprint(et.get_tags(\"rose.jpg\", [\"Comment\", \"FocalLength\"]))\n\n\t\t# Prints: [{'SourceFile': 'rose.jpg', 'File:Comment': '1.10', 'EXIF:FocalLength': '1.1'}]\n\n.. warning::\n\n\tUnfortunately you can either change all float fields to a string, or possibly lose some float precision when working with floats in string metadata fields.\n\n\tThere isn't any known universal workaround which wouldn't break one thing or the other, as it is an underlying *exiftool* quirk.\n\nThere are other edge cases which may exhibit quirky behavior when storing numbers and whitespace only to text fields (See `test cases related to numeric tags`_).  Since PyExifTool cannot accommodate all possible edge cases,\nthis workaround will allow you to configure PyExifTool to work in your environment!\n\n.. _`test cases related to numeric tags`: https://github.com/sylikc/pyexiftool/blob/master/tests/test_helper_tags_float.py\n\n\nI would like to use a faster json string parser\n===============================================\n\nBy default, PyExifTool uses the built-in ``json`` library to load the json string returned by *exiftool*.  If you would like to use an alternate library, set it manually using :py:meth:`exiftool.ExifTool.set_json_loads`\n\n\n.. code-block::\n\n\timport exiftool, json\n\twith exiftool.ExifToolHelper() as et:\n\t\tet.set_json_loads(ujson.loads)\n\t\t...\n\n.. note::\n\n\tIn PyExifTool version before 0.5.6, ``ujson`` was supported automatically if the package was installed.\n\n\tTo support any possible alternative JSON library, this behavior has now been changed and it must be enabled manually.\n\n\nI'm getting an error! How do I debug PyExifTool output?\n=======================================================\n\nTo assist debugging, ExifTool has a ``logger`` in the constructor :py:meth:`exiftool.ExifTool.__init__`.  You can also specify the logger after constructing the object by using the :py:attr:`exiftool.ExifTool.logger` property.\n\nFirst construct the logger object.  The example below using the most common way to construct using ``getLogger(__name__)``.  See more examples on `Python logging - Advanced Logging Tutorial`_\n\n\n.. _`Python logging - Advanced Logging Tutorial`: https://docs.python.org/3/howto/logging.html#advanced-logging-tutorial\n\nExample usage:\n\n.. code-block::\n\n\timport logging\n\timport exiftool\n\n\tlogging.basicConfig(level=logging.DEBUG)\n\twith exiftool.ExifToolHelper(logger=logging.getLogger(__name__)) as et:\n\t\tet.execute(\"missingfile.jpg\",)\n\n"
  },
  {
    "path": "docs/source/index.rst",
    "content": ".. PyExifTool documentation master file, created by\n   sphinx-quickstart on Thu Apr 12 17:42:54 2012.\n\nPyExifTool -- Python wrapper for Phil Harvey's ExifTool\n=======================================================\n\n.. include:: ../../README.rst\n\t:start-after: BLURB_START\n\t:end-before: BLURB_END\n\n.. toctree::\n\t:maxdepth: 2\n\t:glob:\n\t:caption: Contents:\n\n\tintro\n\tpackage\n\tinstallation\n\texamples\n\treference/*\n\tFAQ <faq>\n\tautoapi/*\n\tSource code on GitHub <https://github.com/sylikc/pyexiftool>\n\n\n..   maintenance/*\n.. not public at the moment, at least it doesn't have to be in the TOC (adds unnecessary clutter)\n\n\nIndices and tables\n==================\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n"
  },
  {
    "path": "docs/source/installation.rst",
    "content": "************\nInstallation\n************\n\n.. include:: ../../README.rst\n\t:start-after: INSTALLATION_START\n\t:end-before: INSTALLATION_END\n"
  },
  {
    "path": "docs/source/intro.rst",
    "content": "************\nIntroduction\n************\n\n.. _introduction:\n\n.. include:: ../../README.rst\n\t:start-after: DESCRIPTION_START\n\t:end-before: DESCRIPTION_END\n\nConcepts\n========\n\nAs noted in the :ref:`introduction <introduction>`, PyExifTool is used to **communicate** with an instance of the external ExifTool process.\n\n.. note::\n\n\tPyExifTool cannot do what ExifTool does not do.  If you're not yet familiar with the capabilities of PH's ExifTool, please head over to `ExifTool by Phil Harvey`_ homepage and read up on how to use it, and what it's capable of.\n\n.. _ExifTool by Phil Harvey: https://exiftool.org/\n\nWhat PyExifTool Is\n------------------\n\n* ... is a wrapper for PH's Exiftool, hence it can do everything PH's ExifTool can do.\n* ... is a library which adds some helper functionality around ExifTool to make it easier to work with in Python.\n* ... is extensible and you can add functionality on top of the base class for your use case.\n* ... is supported on any platform which PH's ExifTool runs\n\nWhat PyExifTool Is NOT\n----------------------\n\n* ... is NOT a direct subtitute for Phil Harvey's ExifTool.  The `exiftool` executable must still be installed and available for PyExifTool to use.\n* ... is NOT a library which does direct image manipulation (ex. Python Pillow_).\n\n.. _Pillow: https://pillow.readthedocs.io/en/stable/\n\nNomenclature\n============\n\nPyExifTool's namespace is *exiftool*.  Since library name the same name of the tool it's meant to interface with, it can cause some ambiguity when describing it in docs.\nHence, here's some common nomenclature used.\n\nBecause the term `exiftool` is overloaded (lowercase, CapWords case, ...) and can mean several things:\n\n* `PH's ExifTool` = Phil Harvey's ExifTool\n* ``ExifTool`` in context usually implies ``exiftool.ExifTool``\n* `exiftool` when used alone almost always refers to `PH's ExifTool`'s command line executable.  (While Windows is supported with `exiftool.exe` the Linux nomenclature is used throughout the docs)\n\n"
  },
  {
    "path": "docs/source/maintenance/release-process.rst",
    "content": "***************\nRelease Process\n***************\n\nThis page documents the steps to be taken to release a new version of PyExifTool.\n\n\nSource Preparation\n==================\n\n#. Update the version number in ``exiftool/__init__.py``\n#. Update the docs copyright year ``docs/source/conf.py`` and in source files\n#. Add any changelog entries to ``CHANGELOG.md``\n#. Run Tests\n#. Generate docs\n#. Commit and push the changes.\n#. Check that the tests passed on GitHub.\n\n\nPre-Requisites\n==============\n\nMake sure the latest packages are installed.\n\n#. pip: ``python -m pip install --upgrade pip``\n#. build tools: ``python -m pip install --upgrade setuptools build``\n#. for uploading to PyPI: ``python -m pip install --upgrade twine``\n\nRun Tests\n=========\n\n#. Run in standard unittest: ``python -m unittest -v``\n#. Run in PyTest: ``scripts\\pytest.bat``\n\nBuild and Check\n===============\n\n#. Build package: ``python -m build``\n#. `Validating reStructuredText markup`_: ``python -m twine check dist/*``\n\n.. _Validating reStructuredText markup: https://packaging.python.org/guides/making-a-pypi-friendly-readme/#validating-restructuredtext-markup\n\nUpload to Test PyPI\n===================\n\nSet up the ``$HOME/.pypirc`` (Linux) or ``%UserProfile%\\.pypirc`` (Windows)\n\n#. ``python -m twine upload --repository testpypi dist/*``\n#. Check package uploaded properly: `TestPyPI PyExifTool`_\n#. Create a temporary venv to test PyPI and run tests\n\n\t#. ``python -m venv tmp``\n\t#. Activate venv\n\t#. ``python -m pip install -U -i https://test.pypi.org/simple/ PyExifTool``\n\n\t\t* If there is an error with SSL verification, just trust it: ``python -m pip install --trusted-host test-files.pythonhosted.org -U -i https://test.pypi.org/simple/ PyExifTool``\n\t\t* If you want to test a specific version, can specify as ``PyExifTool==<version>``, otherwise it installs the latest by default\n\n\t#. Make sure exiftool is found on PATH\n\t#. Run tests: ``python -m pytext -v <path to tests directory>``\n\n#. Examine files installed to make sure it looks ok\n\n#. Cleanup: ``python -m pip uninstall PyExifTool``, then delete temp venv\n\n\n.. _`TestPyPI PyExifTool`: https://test.pypi.org/project/PyExifTool/#history\n\nRelease\n=======\n\n#. Be very sure all the tests pass and the package is good, because `PyPI does not allow for a filename to be reused`_\n#. Release to production PyPI: ``python -m twine upload dist/*``\n#. If needed, create a tag, and a GitHub release with the *whl* file\n\n\t.. code-block:: bash\n\n\t\tgit tag -a vX.X.X\n\t\tgit push --tags\n\n.. _PyPI does not allow for a filename to be reused: https://pypi.org/help/#file-name-reuse\n\n"
  },
  {
    "path": "docs/source/package.rst",
    "content": "****************\nPackage Overview\n****************\n\nAll classes live under the PyExifTool library namespace: ``exiftool``\n\nDesign\n======\n\n.. include:: ../../README.rst\n\t:start-after: DESIGN_INFO_START\n\t:end-before: DESIGN_INFO_END\n\n.. inheritance-diagram:: exiftool.ExifToolAlpha\n\n.. include:: ../../README.rst\n\t:start-after: DESIGN_CLASS_START\n\t:end-before: DESIGN_CLASS_END\n\n\nFork Origins / Brief History\n============================\n\n.. include:: ../../README.rst\n\t:start-after: HISTORY_START\n\t:end-before: HISTORY_END\n\n\nLicense\n=======\n\n.. include:: ../../README.rst\n\t:start-after: LICENSE_START\n\t:end-before: LICENSE_END\n"
  },
  {
    "path": "docs/source/reference/1-exiftool.rst",
    "content": "***********************\nClass exiftool.ExifTool\n***********************\n\n.. inheritance-diagram:: exiftool.ExifTool\n\n.. autoapimodule:: exiftool.ExifTool\n   :members:\n   :undoc-members:\n   :special-members: __init__\n   :show-inheritance:\n\n..   :private-members:\n.. currently excluding private members\n"
  },
  {
    "path": "docs/source/reference/2-helper.rst",
    "content": "*****************************\nClass exiftool.ExifToolHelper\n*****************************\n\n.. inheritance-diagram:: exiftool.ExifToolHelper\n\n.. autoapimodule:: exiftool.ExifToolHelper\n   :members:\n   :undoc-members:\n   :special-members: __init__\n   :show-inheritance:\n"
  },
  {
    "path": "docs/source/reference/3-alpha.rst",
    "content": "****************************\nClass exiftool.ExifToolAlpha\n****************************\n\n.. inheritance-diagram:: exiftool.ExifToolAlpha\n\n.. autoapimodule:: exiftool.ExifToolAlpha\n   :members:\n   :undoc-members:\n   :special-members: __init__\n   :show-inheritance:\n"
  },
  {
    "path": "exiftool/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# This file is part of PyExifTool.\n#\n# PyExifTool <http://github.com/sylikc/pyexiftool>\n#\n# Copyright 2019-2023 Kevin M (sylikc)\n# Copyright 2012-2014 Sven Marnach\n#\n# Community contributors are listed in the CHANGELOG.md for the PRs\n#\n# PyExifTool is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the licence, or\n# (at your option) any later version, or the BSD licence.\n#\n# PyExifTool is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# See COPYING.GPL or COPYING.BSD for more details.\n\n\"\"\"\nPyExifTool is a Python library to communicate with an instance of Phil\nHarvey's excellent ExifTool_ command-line application.  The library\nprovides the class :py:class:`ExifTool` that runs the command-line\ntool in batch mode and features methods to send commands to that\nprogram, including methods to extract meta-information from one or\nmore image files.  Since ``exiftool`` is run in batch mode, only a\nsingle instance needs to be launched and can be reused for many\nqueries.  This is much more efficient than launching a separate\nprocess for every single query.\n\n.. _ExifTool: https://exiftool.org\n\nThe source code can be checked out from the github repository with\n\n::\n\n\tgit clone git://github.com/sylikc/pyexiftool.git\n\nAlternatively, you can download a tarball_.  There haven't been any\nreleases yet.\n\n.. _tarball: https://github.com/sylikc/pyexiftool/tarball/master\n\nPyExifTool is licenced under GNU GPL version 3 or later, or BSD license.\n\nExample usage::\n\n\timport exiftool\n\n\tfiles = [\"a.jpg\", \"b.png\", \"c.tif\"]\n\twith exiftool.ExifToolHelper() as et:\n\t\tmetadata = et.get_metadata(files)\n\tfor d in metadata:\n\t\tprint(\"{:20.20} {:20.20}\".format(d[\"SourceFile\"],\n                                         d[\"EXIF:DateTimeOriginal\"]))\n\n\"\"\"\n\n# version number using Semantic Versioning 2.0.0 https://semver.org/\n# may not be PEP-440 compliant https://www.python.org/dev/peps/pep-0440/#semantic-versioning\n__version__ = \"0.5.6\"\n\n\n# while we COULD import all the exceptions into the base library namespace,\n# it's best that it lives as exiftool.exceptions, to not pollute the base namespace\nfrom . import exceptions\n\n\n# make all of the original exiftool stuff available in this namespace\nfrom .exiftool import ExifTool\nfrom .helper import ExifToolHelper\nfrom .experimental import ExifToolAlpha\n\n# an old feature of the original class that exposed this variable at the library level\n# TODO may remove and deprecate at a later time\n#from .constants import DEFAULT_EXECUTABLE\n"
  },
  {
    "path": "exiftool/constants.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# This file is part of PyExifTool.\n#\n# PyExifTool <http://github.com/sylikc/pyexiftool>\n#\n# Copyright 2019-2023 Kevin M (sylikc)\n# Copyright 2012-2014 Sven Marnach\n#\n# Community contributors are listed in the CHANGELOG.md for the PRs\n#\n# PyExifTool is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the licence, or\n# (at your option) any later version, or the BSD licence.\n#\n# PyExifTool is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# See COPYING.GPL or COPYING.BSD for more details.\n\n\"\"\"\n\nThis submodule defines constants which are used by other modules in the package\n\n\"\"\"\n\nimport sys\n\n\n##################################\n############# HELPERS ############\n##################################\n\n# instead of comparing everywhere sys.platform, do it all here in the constants (less typo chances)\n# True if Windows\nPLATFORM_WINDOWS: bool = (sys.platform == 'win32')\n\"\"\"sys.platform check, set to True if Windows\"\"\"\n\n# Prior to Python 3.3, the value for any Linux version is always linux2; after, it is linux.\n# https://stackoverflow.com/a/13874620/15384838\nPLATFORM_LINUX: bool = (sys.platform == 'linux' or sys.platform == 'linux2')\n\"\"\"sys.platform check, set to True if Linux\"\"\"\n\n\n\n##################################\n####### PLATFORM DEFAULTS ########\n##################################\n\n\n# specify the extension so exiftool doesn't default to running \"exiftool.py\" on windows (which could happen)\nDEFAULT_EXECUTABLE: str = \"exiftool.exe\" if PLATFORM_WINDOWS else \"exiftool\"\n\"\"\"The name of the default executable to run.\n\n``exiftool.exe`` (Windows) or ``exiftool`` (Linux/Mac/non-Windows platforms)\n\nBy default, the executable is searched for on one of the paths listed in the\n``PATH`` environment variable.  If it's not on the ``PATH``, a full path should be specified in the\n``executable`` argument of the ExifTool constructor (:py:meth:`exiftool.ExifTool.__init__`).\n\"\"\"\n\n\"\"\"\n# flipped the if/else so that the sphinx documentation shows \"exiftool\" rather than \"exiftool.exe\"\nif not PLATFORM_WINDOWS:  # pytest-cov:windows: no cover\n\tDEFAULT_EXECUTABLE = \"exiftool\"\nelse:\n\tDEFAULT_EXECUTABLE = \"exiftool.exe\"\n\"\"\"\n\n\n##################################\n####### STARTUP CONSTANTS ########\n##################################\n\n# for Windows STARTUPINFO\nSW_FORCEMINIMIZE: int = 11\n\"\"\"Windows ShowWindow constant from win32con\n\nIndicates the launched process window should start minimized\n\"\"\"\n\n# for Linux preexec_fn\nPR_SET_PDEATHSIG: int = 1\n\"\"\"Extracted from linux/prctl.h\n\nAllows a kill signal to be sent to child processes when the parent unexpectedly dies\n\"\"\"\n\n\n\n##################################\n######## GLOBAL DEFAULTS #########\n##################################\n\nDEFAULT_BLOCK_SIZE: int = 4096\n\"\"\"The default block size when reading from exiftool.  The standard value\nshould be fine, though other values might give better performance in\nsome cases.\"\"\"\n\nEXIFTOOL_MINIMUM_VERSION: str = \"12.15\"\n\"\"\"this is the minimum *exiftool* version required for current version of PyExifTool\n\n* 8.40 / 8.60 (production): implemented the -stay_open flag\n* 12.10 / 12.15 (production): implemented exit status on -echo4\n\"\"\"\n"
  },
  {
    "path": "exiftool/exceptions.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# This file is part of PyExifTool.\n#\n# PyExifTool <http://github.com/sylikc/pyexiftool>\n#\n# Copyright 2019-2023 Kevin M (sylikc)\n# Copyright 2012-2014 Sven Marnach\n#\n# Community contributors are listed in the CHANGELOG.md for the PRs\n#\n# PyExifTool is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the licence, or\n# (at your option) any later version, or the BSD licence.\n#\n# PyExifTool is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# See COPYING.GPL or COPYING.BSD for more details.\n\n\"\"\"\n\nThis submodule holds all of the custom exceptions which can be raised by PyExifTool\n\n\"\"\"\n\n\n########################################################\n#################### Base Exception ####################\n########################################################\n\n\nclass ExifToolException(Exception):\n\t\"\"\"\n\tGeneric Base class for all ExifTool error classes\n\t\"\"\"\n\n\n#############################################################\n#################### Process State Error ####################\n#############################################################\n\n\nclass ExifToolProcessStateError(ExifToolException):\n\t\"\"\"\n\tBase class for all errors related to the invalid state of `exiftool` subprocess\n\t\"\"\"\n\n\nclass ExifToolRunning(ExifToolProcessStateError):\n\t\"\"\"\n\tExifTool is already running\n\t\"\"\"\n\tdef __init__(self, message: str):\n\t\tsuper().__init__(f\"ExifTool instance is running: {message}\")\n\n\nclass ExifToolNotRunning(ExifToolProcessStateError):\n\t\"\"\"\n\tExifTool is not running\n\t\"\"\"\n\tdef __init__(self, message: str):\n\t\tsuper().__init__(f\"ExifTool instance not running: {message}\")\n\n\n###########################################################\n#################### Execute Exception ####################\n###########################################################\n\n# all of these exceptions are related to something regarding execute\n\nclass ExifToolExecuteException(ExifToolException):\n\t\"\"\"\n\tThis is the base exception class for all execute() associated errors.\n\n\tThis exception is never returned directly from any method, but provides common interface for subclassed errors.\n\n\t(mimics the signature of :py:class:`subprocess.CalledProcessError`)\n\n\t:attribute cmd: Parameters sent to *exiftool* which raised the error\n\t:attribute returncode: Exit Status (Return code) of the ``execute()`` command which raised the error\n\t:attribute stdout: STDOUT stream returned by the command which raised the error\n\t:attribute stderr: STDERR stream returned by the command which raised the error\n\t\"\"\"\n\tdef __init__(self, message, exit_status, cmd_stdout, cmd_stderr, params):\n\t\tsuper().__init__(message)\n\n\t\tself.returncode: int = exit_status\n\t\tself.cmd: list = params\n\t\tself.stdout: str = cmd_stdout\n\t\tself.stderr: str = cmd_stderr\n\n\nclass ExifToolExecuteError(ExifToolExecuteException):\n\t\"\"\"\n\tExifTool executed the command but returned a non-zero exit status.\n\n\t.. note::\n\t\tThere is a similarly named :py:exc:`ExifToolExecuteException` which this Error inherits from.\n\n\t\tThat is a base class and never returned directly.  This is what is raised.\n\t\"\"\"\n\tdef __init__(self, exit_status, cmd_stdout, cmd_stderr, params):\n\t\tsuper().__init__(f\"execute returned a non-zero exit status: {exit_status}\", exit_status, cmd_stdout, cmd_stderr, params)\n\n\n########################################################\n#################### JSON Exception ####################\n########################################################\n\n\nclass ExifToolOutputEmptyError(ExifToolExecuteException):\n\t\"\"\"\n\tExifTool execute_json() expected output, but execute() did not return any output on stdout\n\n\tThis is an error, because if you expect no output, don't use execute_json()\n\n\t.. note::\n\t\tOnly thrown by execute_json()\n\t\"\"\"\n\tdef __init__(self, exit_status, cmd_stdout, cmd_stderr, params):\n\t\tsuper().__init__(\"execute_json expected output on stdout but got none\", exit_status, cmd_stdout, cmd_stderr, params)\n\n\nclass ExifToolJSONInvalidError(ExifToolExecuteException):\n\t\"\"\"\n\tExifTool execute_json() expected valid JSON to be returned, but got invalid JSON.\n\n\tThis is an error, because if you expect non-JSON output, don't use execute_json()\n\n\t.. note::\n\t\tOnly thrown by execute_json()\n\t\"\"\"\n\tdef __init__(self, exit_status, cmd_stdout, cmd_stderr, params):\n\t\tsuper().__init__(\"execute_json received invalid JSON output from exiftool\", exit_status, cmd_stdout, cmd_stderr, params)\n\n\n#########################################################\n#################### Other Exception ####################\n#########################################################\n\nclass ExifToolVersionError(ExifToolException):\n\t\"\"\"\n\tGeneric Error to represent some version mismatch.\n\tPyExifTool is coded to work with a range of exiftool versions.  If the advanced params change in functionality and break PyExifTool, this error will be thrown\n\t\"\"\"\n\n\nclass ExifToolTagNameError(ExifToolException):\n\t\"\"\"\n\tExifToolHelper found an invalid tag name\n\n\tThis error is raised when :py:attr:`exiftool.ExifToolHelper.check_tag_names` is enabled, and a bad tag is provided to a method\n\t\"\"\"\n\tdef __init__(self, bad_tag):\n\t\tsuper().__init__(f\"Invalid Tag Name found: \\\"{bad_tag}\\\"\")\n"
  },
  {
    "path": "exiftool/exiftool.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# This file is part of PyExifTool.\n#\n# PyExifTool <http://github.com/sylikc/pyexiftool>\n#\n# Copyright 2019-2023 Kevin M (sylikc)\n# Copyright 2012-2014 Sven Marnach\n#\n# Community contributors are listed in the CHANGELOG.md for the PRs\n#\n# PyExifTool is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the licence, or\n# (at your option) any later version, or the BSD licence.\n#\n# PyExifTool is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# See COPYING.GPL or COPYING.BSD for more details.\n\n\n\"\"\"\nThis submodule contains the core ``ExifTool`` class of PyExifTool\n\n.. note::\n\t:py:class:`exiftool.helper.ExifTool` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifTool`\n\n\"\"\"\n\n# ---------- standard Python imports ----------\nimport select\nimport subprocess\nimport os\nimport shutil\nfrom pathlib import Path  # requires Python 3.4+\nimport random\nimport locale\nimport warnings\nimport json  # NOTE: to use other json libraries (simplejson/ujson/orjson/...), see :py:meth:`set_json_loads()`\n\n# for the pdeathsig\nimport signal\nimport ctypes\n\n\n\n# ---------- Typing Imports ----------\n# for static analysis / type checking - Python 3.5+\nfrom collections.abc import Callable\nfrom typing import Optional, List, Union\n\n\n\n# ---------- Library Package Imports ----------\n\nfrom . import constants\nfrom .exceptions import ExifToolVersionError, ExifToolRunning, ExifToolNotRunning, ExifToolOutputEmptyError, ExifToolJSONInvalidError\n\n\n# ======================================================================================================================\n\n\n# constants to make typos obsolete!\nENCODING_UTF8: str = \"utf-8\"\n#ENCODING_LATIN1: str = \"latin-1\"\n\n\n# ======================================================================================================================\n\ndef _set_pdeathsig(sig) -> Optional[Callable]:\n\t\"\"\"\n\tUse this method in subprocess.Popen(preexec_fn=set_pdeathsig()) to make sure,\n\tthe exiftool childprocess is stopped if this process dies.\n\tHowever, this only works on linux.\n\t\"\"\"\n\tif constants.PLATFORM_LINUX:\n\t\tdef callable_method():\n\t\t\tlibc = ctypes.CDLL(\"libc.so.6\")\n\t\t\treturn libc.prctl(constants.PR_SET_PDEATHSIG, sig)\n\n\t\treturn callable_method\n\telse:\n\t\treturn None  # pragma: no cover\n\n\n# ======================================================================================================================\n\ndef _get_buffer_end(buffer_list: List[bytes], bytes_needed: int) -> bytes:\n\t\"\"\" Given a list of bytes objects, return the equivalent of\n\t\tb\"\".join(buffer_list)[-bytes_needed:]\n\t\tbut without having to concatenate the entire list.\n\t\"\"\"\n\tif bytes_needed < 1:\n\t\treturn b\"\"  # pragma: no cover\n\n\tbuf_chunks = []\n\tfor buf in reversed(buffer_list):\n\t\tbuf_tail = buf[-bytes_needed:]\n\t\tbuf_chunks.append(buf_tail)\n\t\tbytes_needed -= len(buf_tail)\n\t\tif bytes_needed <= 0:\n\t\t\tbreak\n\n\tbuf_tail_joined = b\"\".join(reversed(buf_chunks))\n\treturn buf_tail_joined\n\n\ndef _read_fd_endswith(fd, b_endswith: bytes, block_size: int) -> bytes:\n\t\"\"\" read an fd and keep reading until it endswith the seq_ends\n\n\t\tthis allows a consolidated read function that is platform indepdent\n\n\t\tif you're not careful, on windows, this will block\n\t\"\"\"\n\toutput_list: List[bytes] = []\n\n\t# if we're only looking at the last few bytes, make it meaningful.  4 is max size of \\r\\n? (or 2)\n\t# this value can be bigger to capture more bytes at the \"tail\" of the read, but if it's too small, the whitespace might miss the detection\n\tendswith_count = len(b_endswith) + 4\n\n\t# I believe doing a splice, then a strip is more efficient in memory hence the original code did it this way.\n\t# need to benchmark to see if in large strings, strip()[-endswithcount:] is more expensive or not\n\twhile not _get_buffer_end(output_list, endswith_count).strip().endswith(b_endswith):\n\t\tif constants.PLATFORM_WINDOWS:\n\t\t\t# windows does not support select() for anything except sockets\n\t\t\t# https://docs.python.org/3.7/library/select.html\n\t\t\toutput_list.append(os.read(fd, block_size))\n\t\telse:  # pytest-cov:windows: no cover\n\t\t\t# this does NOT work on windows... and it may not work on other systems... in that case, put more things to use the original code above\n\t\t\tinputready, outputready, exceptready = select.select([fd], [], [])\n\t\t\tfor i in inputready:\n\t\t\t\tif i == fd:\n\t\t\t\t\toutput_list.append(os.read(fd, block_size))\n\n\treturn b\"\".join(output_list)\n\n\n\n\n\n\n# ======================================================================================================================\n\nclass ExifTool(object):\n\t\"\"\"Run the `exiftool` command-line tool and communicate with it.\n\n\tUse ``common_args`` to enable/disable print conversion by specifying/omitting ``-n``, respectively.\n\tThis determines whether exiftool should perform print conversion,\n\twhich prints values in a human-readable way but\n\tmay be slower. If print conversion is enabled, appending ``#`` to a tag\n\tname disables the print conversion for this particular tag.\n\tSee `Exiftool print conversion FAQ`_ for more details.\n\n\t.. _Exiftool print conversion FAQ: https://exiftool.org/faq.html#Q6\n\n\n\tSome methods of this class are only available after calling\n\t:py:meth:`run()`, which will actually launch the *exiftool* subprocess.\n\tTo avoid leaving the subprocess running, make sure to call\n\t:py:meth:`terminate()` method when finished using the instance.\n\tThis method will also be implicitly called when the instance is\n\tgarbage collected, but there are circumstance when this won't ever\n\thappen, so you should not rely on the implicit process\n\ttermination.  Subprocesses won't be automatically terminated if\n\tthe parent process exits, so a leaked subprocess will stay around\n\tuntil manually killed.\n\n\tA convenient way to make sure that the subprocess is terminated is\n\tto use the :py:class:`ExifTool` instance as a context manager::\n\n\t\twith ExifTool() as et:\n\t\t\t...\n\n\t.. warning::\n\t\tNote that options and parameters are not checked.  There is no error handling or validation of options passed to *exiftool*.\n\n\t\tNonsensical options are mostly silently ignored by exiftool, so there's not\n\t\tmuch that can be done in that regard.  You should avoid passing\n\t\tnon-existent files to any of the methods, since this will lead\n\t\tto undefined behaviour.\n\n\t\"\"\"\n\n\t##############################################################################\n\t#################################### INIT ####################################\n\t##############################################################################\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\n\tdef __init__(self,\n\t  executable: Optional[str] = None,\n\t  common_args: Optional[List[str]] = [\"-G\", \"-n\"],\n\t  win_shell: bool = False,\n\t  config_file: Optional[Union[str, Path]] = None,\n\t  encoding: Optional[str] = None,\n\t  logger = None) -> None:\n\t\t\"\"\"\n\n\t\t:param executable: Specify file name of the *exiftool* executable if it is in your ``PATH``.  Otherwise, specify the full path to the ``exiftool`` executable.\n\n\t\t\tPassed directly into :py:attr:`executable` property.\n\n\t\t\t.. note::\n\t\t\t\tThe default value :py:attr:`exiftool.constants.DEFAULT_EXECUTABLE` will only work if the executable is in your ``PATH``.\n\n\t\t:type executable: str, or None to use default\n\n\n\t\t:param common_args:\n\t\t\tPass in additional parameters for the stay-open instance of exiftool.\n\n\t\t\tDefaults to ``[\"-G\", \"-n\"]`` as this is the most common use case.\n\n\t\t\t* ``-G`` (groupName level 1 enabled) separates the output with *groupName:tag* to disambiguate same-named tags under different groups.\n\t\t\t* ``-n`` (print conversion disabled) improves the speed and consistency of output, and is more machine-parsable\n\n\t\t\tPassed directly into :py:attr:`common_args` property.\n\n\n\t\t\t.. note::\n\t\t\t\tDepending on your use case, there may be other useful grouping levels and options.  Search `Phil Harvey's exiftool documentation`_ for **groupNames** and **groupHeadings** to get more info.\n\n\n\n\t\t\t.. _`Phil Harvey's exiftool documentation`: https://exiftool.org/exiftool_pod.html\n\n\t\t:type common_args: list of str, or None.\n\n\t\t:param bool win_shell: (Windows only) Minimizes the exiftool process.\n\n\t\t\t.. note::\n\t\t\t\tThis parameter may be deprecated in the future\n\n\t\t:param config_file:\n\t\t\tFile path to ``-config`` parameter when starting exiftool process.\n\n\t\t\tPassed directly into :py:attr:`config_file` property.\n\t\t:type config_file: str, Path, or None\n\n\t\t:param encoding: Specify encoding to be used when communicating with\n\t\t\texiftool process.  By default, will use ``locale.getpreferredencoding()``\n\n\t\t\tPassed directly into :py:attr:`encoding` property.\n\n\t\t:param logger: Set a custom logger to log status and debug messages to.\n\n\t\t\tPassed directly into :py:attr:`logger` property.\n\t\t\"\"\"\n\n\t\t# --- default settings / declare member variables ---\n\t\tself._running: bool = False  # is it running?\n\t\t\"\"\"A Boolean value indicating whether this instance is currently\n\t\tassociated with a running subprocess.\"\"\"\n\t\tself._win_shell: bool = win_shell  # do you want to see the shell on Windows?\n\n\t\tself._process = None  # this is set to the process to interact with when _running=True\n\t\tself._ver: Optional[str] = None  # this is set to be the exiftool -v -ver when running\n\n\t\tself._last_stdout: Optional[str] = None  # previous output\n\t\tself._last_stderr: Optional[str] = None  # previous stderr\n\t\tself._last_status: Optional[int] = None  # previous exit status from exiftool (look up EXIT STATUS in exiftool documentation for more information)\n\n\t\tself._block_size: int = constants.DEFAULT_BLOCK_SIZE  # set to default block size\n\n\n\t\t# these are set via properties\n\t\tself._executable: Union[str, Path] = constants.DEFAULT_EXECUTABLE  # executable absolute path (default set to just the executable name, so it can't be None)\n\t\tself._config_file: Optional[str] = None  # config file that can only be set when exiftool is not running\n\t\tself._common_args: Optional[List[str]] = None\n\t\tself._logger = None\n\t\tself._encoding: Optional[str] = None\n\t\tself._json_loads: Callable = json.loads  # variable points to the actual callable method\n\t\tself._json_loads_kwargs: dict = {}  # default optional params to pass into json.loads() call\n\n\n\n\t\t# --- run external library initialization code ---\n\t\trandom.seed(None)  # initialize random number generator\n\n\n\n\n\t\t# --- set variables via properties (which do the error checking) --\n\n\t\t# set first, so that debug and info messages get logged\n\t\tself.logger = logger\n\n\t\t# use the passed in parameter, or the default if not set\n\t\t# error checking is done in the property.setter\n\t\tself.executable = executable or constants.DEFAULT_EXECUTABLE\n\t\tself.encoding = encoding\n\t\tself.common_args = common_args\n\n\t\t# set the property, error checking happens in the property.setter\n\t\tself.config_file = config_file\n\n\n\n\n\t#######################################################################################\n\t#################################### MAGIC METHODS ####################################\n\t#######################################################################################\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\n\tdef __enter__(self):\n\t\tself.run()\n\t\treturn self\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef __exit__(self, exc_type, exc_val, exc_tb) -> None:\n\t\tif self.running:\n\t\t\tself.terminate()\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef __del__(self) -> None:\n\t\tif self.running:\n\t\t\t# indicate that __del__ has been started - allows running alternate code path in terminate()\n\t\t\tself.terminate(_del=True)\n\n\n\n\n\t########################################################################################\n\t#################################### PROPERTIES R/w ####################################\n\t########################################################################################\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef executable(self) -> Union[str, Path]:\n\t\t\"\"\"\n\t\tPath to *exiftool* executable.\n\n\t\t:getter: Returns current exiftool path\n\t\t:setter: Specify just the executable name, or an absolute path to the executable.\n\t\t\tIf path given is not absolute, searches environment ``PATH``.\n\n\t\t\t.. note::\n\t\t\t\tSetting is only available when exiftool process is not running.\n\n\t\t:raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True)\n\t\t:type: str, Path\n\t\t\"\"\"\n\t\treturn self._executable\n\n\t@executable.setter\n\tdef executable(self, new_executable: Union[str, Path]) -> None:\n\t\t# cannot set executable when process is running\n\t\tif self.running:\n\t\t\traise ExifToolRunning(\"Cannot set new executable\")\n\n\t\tabs_path: Optional[str] = None\n\n\t\t# in testing, shutil.which() will work if a complete path is given,\n\t\t# but this isn't clear from documentation, so we explicitly check and\n\t\t# don't search if path exists\n\t\tif Path(new_executable).exists():\n\t\t\tabs_path = new_executable\n\t\telse:\n\t\t\t# Python 3.3+ required\n\t\t\tabs_path = shutil.which(new_executable)\n\n\t\t\tif abs_path is None:\n\t\t\t\traise FileNotFoundError(f'\"{new_executable}\" is not found, on path or as absolute path')\n\n\t\t# absolute path is returned\n\t\tself._executable = str(abs_path)\n\n\t\tif self._logger: self._logger.info(f\"Property 'executable': set to \\\"{abs_path}\\\"\")\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef encoding(self) -> Optional[str]:\n\t\t\"\"\"\n\t\tEncoding of Popen() communication with *exiftool* process.\n\n\t\t:getter: Returns current encoding setting\n\n\t\t:setter: Set a new encoding.\n\n\t\t\t* If *new_encoding* is None, will detect it from ``locale.getpreferredencoding(do_setlocale=False)`` (do_setlocale is set to False as not to affect the caller).\n\t\t\t* Default to ``utf-8`` if nothing is returned by ``getpreferredencoding``\n\n\t\t\t.. warning::\n\t\t\t\tProperty setter does NOT validate the encoding for validity.  It is passed verbatim into subprocess.Popen()\n\n\t\t\t.. note::\n\t\t\t\tSetting is only available when exiftool process is not running.\n\n\t\t:raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True)\n\n\t\t\"\"\"\n\t\treturn self._encoding\n\n\t@encoding.setter\n\tdef encoding(self, new_encoding: Optional[str]) -> None:\n\t\t# cannot set encoding when process is running\n\t\tif self.running:\n\t\t\traise ExifToolRunning(\"Cannot set new encoding\")\n\n\t\t# auto-detect system specific\n\t\tself._encoding = new_encoding or (locale.getpreferredencoding(do_setlocale=False) or ENCODING_UTF8)\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef block_size(self) -> int:\n\t\t\"\"\"\n\t\tBlock size for communicating with *exiftool* subprocess.  Used when reading from the I/O pipe.\n\n\t\t:getter: Returns current block size\n\n\t\t:setter: Set a new block_size.  Does basic error checking to make sure > 0.\n\n\t\t:raises ValueError: If new block size is invalid\n\n\t\t:type: int\n\t\t\"\"\"\n\t\treturn self._block_size\n\n\t@block_size.setter\n\tdef block_size(self, new_block_size: int) -> None:\n\t\tif new_block_size <= 0:\n\t\t\traise ValueError(\"Block Size doesn't make sense to be <= 0\")\n\n\t\tself._block_size = new_block_size\n\n\t\tif self._logger: self._logger.info(f\"Property 'block_size': set to \\\"{new_block_size}\\\"\")\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef common_args(self) -> Optional[List[str]]:\n\t\t\"\"\"\n\t\tCommon Arguments executed with every command passed to *exiftool* subprocess\n\n\t\tThis is the parameter `-common_args`_ that is passed when the *exiftool* process is STARTED\n\n\t\tRead `Phil Harvey's ExifTool documentation`_ to get further information on what options are available / how to use them.\n\n\t\t.. _-common_args: https://exiftool.org/exiftool_pod.html#Advanced-options\n\t\t.. _Phil Harvey's ExifTool documentation: https://exiftool.org/exiftool_pod.html\n\n\t\t:getter: Returns current common_args list\n\n\t\t:setter: If ``None`` is passed in, sets common_args to ``[]``.  Otherwise, sets the given list without any validation.\n\n\t\t\t.. warning::\n\t\t\t\tNo validation is done on the arguments list.  It is passed verbatim to *exiftool*.  Invalid options or combinations may result in undefined behavior.\n\n\t\t\t.. note::\n\t\t\t\tSetting is only available when exiftool process is not running.\n\n\t\t:raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True)\n\t\t:raises TypeError: If setting is not a list\n\n\t\t:type: list[str], None\n\t\t\"\"\"\n\t\treturn self._common_args\n\n\t@common_args.setter\n\tdef common_args(self, new_args: Optional[List[str]]) -> None:\n\n\t\tif self.running:\n\t\t\traise ExifToolRunning(\"Cannot set new common_args\")\n\n\t\tif new_args is None:\n\t\t\tself._common_args = []\n\t\telif isinstance(new_args, list):\n\t\t\t# default parameters to exiftool\n\t\t\t# -n = disable print conversion (speedup)\n\t\t\tself._common_args = new_args\n\t\telse:\n\t\t\traise TypeError(\"common_args not a list of strings\")\n\n\t\tif self._logger: self._logger.info(f\"Property 'common_args': set to \\\"{self._common_args}\\\"\")\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef config_file(self) -> Optional[Union[str, Path]]:\n\t\t\"\"\"\n\t\tPath to config file.\n\n\t\tSee `ExifTool documentation for -config`_ for more details.\n\n\n\t\t:getter: Returns current config file path, or None if not set\n\n\t\t:setter: File existence is checked when setting parameter\n\n\t\t\t* Set to ``None`` to disable the ``-config`` parameter when starting *exiftool*\n\t\t\t* Set to ``\"\"`` has special meaning and disables loading of the default config file.  See `ExifTool documentation for -config`_ for more info.\n\n\t\t\t.. note::\n\t\t\t\tCurrently file is checked for existence when setting.  It is not checked when starting process.\n\n\t\t:raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True)\n\n\t\t:type: str, Path, None\n\n\t\t.. _ExifTool documentation for -config: https://exiftool.org/exiftool_pod.html#Advanced-options\n\t\t\"\"\"\n\t\treturn self._config_file\n\n\t@config_file.setter\n\tdef config_file(self, new_config_file: Optional[Union[str, Path]]) -> None:\n\t\tif self.running:\n\t\t\traise ExifToolRunning(\"Cannot set a new config_file\")\n\n\t\tif new_config_file is None:\n\t\t\tself._config_file = None\n\t\telif new_config_file == \"\":\n\t\t\t# this is VALID usage of -config parameter\n\t\t\t# As per exiftool documentation:  Loading of the default config file may be disabled by setting CFGFILE to an empty string (ie. \"\")\n\t\t\tself._config_file = \"\"\n\t\telif not Path(new_config_file).exists():\n\t\t\traise FileNotFoundError(\"The config file could not be found\")\n\t\telse:\n\t\t\tself._config_file = str(new_config_file)\n\n\t\tif self._logger: self._logger.info(f\"Property 'config_file': set to \\\"{self._config_file}\\\"\")\n\n\n\n\t##############################################################################################\n\t#################################### PROPERTIES Read only ####################################\n\t##############################################################################################\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef running(self) -> bool:\n\t\t\"\"\"\n\t\tRead-only property which indicates whether the *exiftool* subprocess is running or not.\n\n\t\t:getter: Returns current running state\n\n\t\t\t.. note::\n\t\t\t\tThis checks to make sure the process is still alive.\n\n\t\t\t\tIf the process has died since last `running` detection, this property\n\t\t\t\twill detect the state change and reset the status accordingly.\n\t\t\"\"\"\n\t\tif self._running:\n\t\t\t# check if the process is actually alive\n\t\t\tif self._process.poll() is not None:\n\t\t\t\t# process died\n\t\t\t\twarnings.warn(\"ExifTool process was previously running but died\")\n\t\t\t\tself._flag_running_false()\n\n\t\t\t\tif self._logger: self._logger.warning(\"Property 'running': ExifTool process was previously running but died\")\n\n\t\treturn self._running\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef version(self) -> str:\n\t\t\"\"\"\n\t\tRead-only property which is the string returned by ``exiftool -ver``\n\n\t\tThe *-ver* command is ran once at process startup and cached.\n\n\t\t:getter: Returns cached output of ``exiftool -ver``\n\n\t\t:raises ExifToolNotRunning: If attempting to read while not running (:py:attr:`running` == False)\n\t\t\"\"\"\n\n\t\tif not self.running:\n\t\t\traise ExifToolNotRunning(\"Can't get ExifTool version\")\n\n\t\treturn self._ver\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef last_stdout(self) -> Optional[Union[str, bytes]]:\n\t\t\"\"\"\n\t\t``STDOUT`` for most recent result from execute()\n\n\t\t.. note::\n\t\t\tThe return type can be either str or bytes.\n\n\t\t\tIf the most recent call to execute() ``raw_bytes=True``, then this will return ``bytes``.  Otherwise this will be ``str``.\n\n\t\t.. note::\n\t\t\tThis property can be read at any time, and is not dependent on running state of ExifTool.\n\n\t\t\tIt is INTENTIONALLY *NOT* CLEARED on exiftool termination, to allow\n\t\t\tfor executing a command and terminating, but still having the result available.\n\t\t\"\"\"\n\t\treturn self._last_stdout\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef last_stderr(self) -> Optional[Union[str, bytes]]:\n\t\t\"\"\"\n\t\t``STDERR`` for most recent result from execute()\n\n\t\t.. note::\n\t\t\tThe return type can be either ``str`` or ``bytes``.\n\n\t\t\tIf the most recent call to execute() ``raw_bytes=True``, then this will return ``bytes``.  Otherwise this will be ``str``.\n\n\t\t.. note::\n\t\t\tThis property can be read at any time, and is not dependent on running state of ExifTool.\n\n\t\t\tIt is INTENTIONALLY *NOT* CLEARED on exiftool termination, to allow\n\t\t\tfor executing a command and terminating, but still having the result available.\n\t\t\"\"\"\n\t\treturn self._last_stderr\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef last_status(self) -> Optional[int]:\n\t\t\"\"\"\n\t\t``Exit Status Code`` for most recent result from execute()\n\n\t\t.. note::\n\t\t\tThis property can be read at any time, and is not dependent on running state of ExifTool.\n\n\t\t\tIt is INTENTIONALLY *NOT* CLEARED on exiftool termination, to allow\n\t\t\tfor executing a command and terminating, but still having the result available.\n\t\t\"\"\"\n\t\treturn self._last_status\n\n\n\n\n\t###############################################################################################\n\t#################################### PROPERTIES Write only ####################################\n\t###############################################################################################\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef _set_logger(self, new_logger) -> None:\n\t\t\"\"\" set a new user-created logging.Logger object\n\t\t\tcan be set at any time to start logging.\n\n\t\t\tSet to None at any time to stop logging.\n\t\t\"\"\"\n\t\tif new_logger is None:\n\t\t\tself._logger = None\n\t\t\treturn\n\n\t\t# can't check this in case someone passes a drop-in replacement, like loguru, which isn't type logging.Logger\n\t\t#elif not isinstance(new_logger, logging.Logger):\n\t\t#\traise TypeError(\"logger needs to be of type logging.Logger\")\n\n\n\t\t# do some basic checks on methods available in the \"logger\" provided\n\t\tcheck = True\n\t\ttry:\n\t\t\t# ExifTool will probably use all of these logging method calls at some point\n\t\t\t# check all these are callable methods\n\t\t\tcheck = callable(new_logger.info) and \\\n\t\t\t\tcallable(new_logger.warning) and \\\n\t\t\t\tcallable(new_logger.error) and \\\n\t\t\t\tcallable(new_logger.critical) and \\\n\t\t\t\tcallable(new_logger.exception)\n\t\texcept AttributeError:\n\t\t\tcheck = False\n\n\t\tif not check:\n\t\t\traise TypeError(\"logger needs to implement methods (info,warning,error,critical,exception)\")\n\n\t\tself._logger = new_logger\n\n\t# have to run this at the class level to create a special write-only property\n\t# https://stackoverflow.com/questions/17576009/python-class-property-use-setter-but-evade-getter\n\t# https://docs.python.org/3/howto/descriptor.html#properties\n\t# can have it named same or different\n\tlogger = property(fset=_set_logger, doc=\"\"\"Write-only property to set the class of logging.Logger\"\"\")\n\t\"\"\"\n\tWrite-only property to set the class of logging.Logger\n\n\tIf this is set, then status messages will log out to the given class.\n\n\t.. note::\n\t\tThis can be set and unset (set to ``None``) at any time, regardless of whether the subprocess is running (:py:attr:`running` == True) or not.\n\n\t:setter: Specify an object to log to.  The class is not checked, but validation is done to ensure the object has callable methods ``info``, ``warning``, ``error``, ``critical``, ``exception``.\n\n\t:raises AttributeError: If object does not contain one or more of the required methods.\n\t:raises TypeError: If object contains those attributes, but one or more are non-callable methods.\n\n\t:type: Object\n\t\"\"\"\n\n\t#########################################################################################\n\t##################################### SETTER METHODS ####################################\n\t#########################################################################################\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef set_json_loads(self, json_loads, **kwargs) -> None:\n\t\t\"\"\"\n\t\t**Advanced**: Override default built-in ``json.loads()`` method.  The method is only used once in :py:meth:`execute_json`\n\n\t\tThis allows using a different json string parser.\n\n\t\t(Alternate json libraries typically provide faster speed than the\n\t\tbuilt-in implementation, more supported features, and/or different behavior.)\n\n\t\tExamples of json libraries: `orjson`_, `rapidjson`_, `ujson`_, ...\n\n\t\t.. note::\n\t\t\tThis method is designed to be called the same way you would expect to call the provided ``json_loads`` method.\n\n\t\t\tInclude any ``kwargs`` you would in the call.\n\n\t\t\tFor example, to pass additional arguments to ``json.loads()``: ``set_json_loads(json.loads, parse_float=str)``\n\n\t\t.. note::\n\t\t\tThis can be set at any time, regardless of whether the subprocess is running (:py:attr:`running` == True) or not.\n\n\t\t.. warning::\n\t\t\tThis setter does not check whether the method provided actually parses json.  Undefined behavior or crashes may occur if used incorrectly\n\n\t\t\tThis is **advanced configuration** for specific use cases only.\n\n\t\t\tFor an example use case, see the :ref:`FAQ <set_json_loads faq>`\n\n\t\t:param json_loads: A callable method to replace built-in ``json.loads`` used in :py:meth:`execute_json`\n\n\t\t:type json_loads: callable\n\n\t\t:param kwargs: Parameters passed to the ``json_loads`` method call\n\n\t\t:raises TypeError: If ``json_loads`` is not callable\n\n\n\t\t.. _orjson: https://pypi.org/project/orjson/\n\t\t.. _rapidjson: https://pypi.org/project/python-rapidjson/\n\t\t.. _ujson: https://pypi.org/project/ujson/\n\t\t\"\"\"\n\t\tif not callable(json_loads):\n\t\t\t# not a callable method\n\t\t\traise TypeError\n\n\t\tself._json_loads = json_loads\n\t\tself._json_loads_kwargs = kwargs\n\n\n\n\n\t#########################################################################################\n\t#################################### PROCESS CONTROL ####################################\n\t#########################################################################################\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\n\tdef run(self) -> None:\n\t\t\"\"\"Start an *exiftool* subprocess in batch mode.\n\n\t\tThis method will issue a ``UserWarning`` if the subprocess is\n\t\talready running (:py:attr:`running` == True).  The process is started with :py:attr:`common_args` as common arguments,\n\t\twhich are automatically included in every command you run with :py:meth:`execute()`.\n\n\t\tYou can override these default arguments with the\n\t\t``common_args`` parameter in the constructor or setting :py:attr:`common_args` before caaling :py:meth:`run()`.\n\n\t\t.. note::\n\t\t\tIf you have another executable named *exiftool* which isn't Phil Harvey's ExifTool, then you're shooting yourself in the foot as there's no error checking for that\n\n\t\t:raises FileNotFoundError: If *exiftool* is no longer found.  Re-raised from subprocess.Popen()\n\t\t:raises OSError: Re-raised from subprocess.Popen()\n\t\t:raises ValueError: Re-raised from subprocess.Popen()\n\t\t:raises subproccess.CalledProcessError: Re-raised from subprocess.Popen()\n\t\t:raises RuntimeError: Popen() launched process but it died right away\n\t\t:raises ExifToolVersionError: :py:attr:`exiftool.constants.EXIFTOOL_MINIMUM_VERSION` not met.  ExifTool process will be automatically terminated.\n\t\t\"\"\"\n\t\tif self.running:\n\t\t\twarnings.warn(\"ExifTool already running; doing nothing.\", UserWarning)\n\t\t\treturn\n\n\t\t# first the executable ...\n\t\t# TODO should we check the executable for existence here?\n\t\tproc_args = [self._executable, ]\n\n\t\t# If working with a config file, it must be the first argument after the executable per: https://exiftool.org/config.html\n\t\tif self._config_file is not None:\n\t\t\t# must check explicitly for None, as \"\" is valid\n\t\t\t# TODO check that the config file exists here?\n\t\t\tproc_args.extend([\"-config\", self._config_file])\n\n\t\t# this is the required stuff for the stay_open that makes pyexiftool so great!\n\t\tproc_args.extend([\"-stay_open\", \"True\", \"-@\", \"-\"])\n\n\t\t# only if there are any common_args.  [] and None are skipped equally with this\n\t\tif self._common_args:\n\t\t\tproc_args.append(\"-common_args\")  # add this param only if there are common_args\n\t\t\tproc_args.extend(self._common_args)  # add the common arguments\n\n\n\t\t# ---- set platform-specific kwargs for Popen ----\n\t\tkwargs: dict = {}\n\n\t\tif constants.PLATFORM_WINDOWS:\n\t\t\t# TODO: I don't think this code actually does anything ... I've never seen a console pop up on Windows\n\t\t\t# Perhaps need to specify subprocess.STARTF_USESHOWWINDOW to actually have any console pop up?\n\t\t\t# https://docs.python.org/3/library/subprocess.html#windows-popen-helpers\n\t\t\tstartup_info = subprocess.STARTUPINFO()\n\t\t\tif not self._win_shell:\n\t\t\t\t# Adding enum 11 (SW_FORCEMINIMIZE in win32api speak) will\n\t\t\t\t# keep it from throwing up a DOS shell when it launches.\n\t\t\t\tstartup_info.dwFlags |= constants.SW_FORCEMINIMIZE\n\n\t\t\tkwargs[\"startupinfo\"] = startup_info\n\t\telse:  # pytest-cov:windows: no cover\n\t\t\t# assume it's linux\n\t\t\tkwargs[\"preexec_fn\"] = _set_pdeathsig(signal.SIGTERM)\n\t\t\t# Warning: The preexec_fn parameter is not safe to use in the presence of threads in your application.\n\t\t\t# https://docs.python.org/3/library/subprocess.html#subprocess.Popen\n\n\n\t\ttry:\n\t\t\t# NOTE: the encoding= parameter was removed from the Popen() call to support\n\t\t\t# using bytes in the actual communication with exiftool process.\n\t\t\t# Due to the way the code is written, ExifTool only uses stdin.write which would need to be in bytes.\n\t\t\t# The reading is _NOT_ using subprocess.communicate().  This class reads raw bytes using os.read()\n\t\t\t# Therefore, by switching off the encoding= in Popen(), we can support both bytes and str at the\n\t\t\t# same time.  (This change was to support https://github.com/sylikc/pyexiftool/issues/47)\n\n\t\t\t# unify both platform calls into one subprocess.Popen call\n\t\t\tself._process = subprocess.Popen(\n\t\t\t\tproc_args,\n\t\t\t\tstdin=subprocess.PIPE,\n\t\t\t\tstdout=subprocess.PIPE,\n\t\t\t\tstderr=subprocess.PIPE,\n\t\t\t\t**kwargs)\n\t\texcept FileNotFoundError:\n\t\t\traise\n\t\texcept OSError:\n\t\t\traise\n\t\texcept ValueError:\n\t\t\traise\n\t\texcept subprocess.CalledProcessError:\n\t\t\traise\n\t\t# TODO print out more useful error messages to these different errors above\n\n\t\t# check error above before saying it's running\n\t\tif self._process.poll() is not None:\n\t\t\t# the Popen launched, then process terminated\n\t\t\tself._process = None  # unset it as it's now terminated\n\t\t\traise RuntimeError(\"exiftool did not execute successfully\")\n\n\n\t\t# have to set this before doing the checks below, or else execute() will fail\n\t\tself._running = True\n\n\t\t# get ExifTool version here and any Exiftool metadata\n\t\t# this can also verify that it is really ExifTool we ran, not some other random process\n\t\ttry:\n\t\t\t# apparently because .execute() has code that already depends on v12.15+ functionality,\n\t\t\t# _parse_ver() will throw a ValueError immediately with:\n\t\t\t#   ValueError: invalid literal for int() with base 10: '${status}'\n\t\t\tself._ver = self._parse_ver()\n\t\texcept ValueError:\n\t\t\t# trap the error and return it as a minimum version problem\n\t\t\tself.terminate()\n\t\t\traise ExifToolVersionError(f\"Error retrieving Exiftool info.  Is your Exiftool version ('exiftool -ver') >= required version ('{constants.EXIFTOOL_MINIMUM_VERSION}')?\")\n\n\t\tif self._logger: self._logger.info(f\"Method 'run': Exiftool version '{self._ver}' (pid {self._process.pid}) launched with args '{proc_args}'\")\n\n\n\t\t# currently not needed... if it passes -ver check, the rest is OK\n\t\t# may use in the future again if another version feature is needed but the -ver check passes\n\t\t\"\"\"\n\t\t# check that the minimum required version is met, if not, terminate...\n\t\t# if you run against a version which isn't supported, strange errors come up during execute()\n\t\tif not self._exiftool_version_check():\n\t\t\tself.terminate()\n\t\t\tif self._logger: self._logger.error(f\"Method 'run': Exiftool version '{self._ver}' did not meet the required minimum version '{constants.EXIFTOOL_MINIMUM_VERSION}'\")\n\t\t\traise ExifToolVersionError(f\"exiftool version '{self._ver}' < required '{constants.EXIFTOOL_MINIMUM_VERSION}'\")\n\t\t\"\"\"\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef terminate(self, timeout: int = 30, _del: bool = False) -> None:\n\t\t\"\"\"Terminate the *exiftool* subprocess.\n\n\t\tIf the subprocess isn't running, this method will throw a warning, and do nothing.\n\n\t\t.. note::\n\t\t\tThere is a bug in CPython 3.8+ on Windows where terminate() does not work during ``__del__()``\n\n\t\t\tSee CPython issue `starting a thread in __del__ hangs at interpreter shutdown`_ for more info.\n\n\t\t.. _starting a thread in __del__ hangs at interpreter shutdown: https://github.com/python/cpython/issues/87950\n\t\t\"\"\"\n\t\tif not self.running:\n\t\t\twarnings.warn(\"ExifTool not running; doing nothing.\", UserWarning)\n\t\t\treturn\n\n\t\tif _del and constants.PLATFORM_WINDOWS:\n\t\t\t# don't cleanly exit on windows, during __del__ as it'll freeze at communicate()\n\t\t\tself._process.kill()\n\t\t\t#print(\"before comm\", self._process.poll(), self._process)\n\t\t\tself._process.poll()\n\t\t\ttry:\n\t\t\t\t# TODO freezes here on windows if subprocess zombie remains\n\t\t\t\touts, errs = self._process.communicate()  # have to cleanup the process or else .poll() will return None\n\t\t\t\t#print(\"after comm\")\n\t\t\t\t# TODO a bug filed with Python, or user error... this doesn't seem to work at all ... .communicate() still hangs\n\t\t\t\t# https://bugs.python.org/issue43784 , https://github.com/python/cpython/issues/87950... Windows-specific issue affecting Python 3.8-3.10 (as of this time)\n\t\t\texcept RuntimeError:\n\t\t\t\t# Python 3.12 throws a runtime error -- see https://github.com/python/cpython/pull/104826\n\t\t\t\t# RuntimeError: can't create new thread at interpreter shutdown\n\t\t\t\tpass\n\t\telse:\n\t\t\ttry:\n\t\t\t\t\"\"\"\n\t\t\t\t\tOn Windows, running this after __del__ freezes at communicate(), regardless of timeout\n\t\t\t\t\t\tsee the bug filed above for details\n\n\t\t\t\t\tOn Linux, this runs as is, and the process terminates properly\n\t\t\t\t\"\"\"\n\t\t\t\ttry:\n\t\t\t\t\tself._process.communicate(input=b\"-stay_open\\nFalse\\n\", timeout=timeout)  # this is a constant sequence specified by PH's exiftool\n\t\t\t\texcept RuntimeError:\n\t\t\t\t\t# Python 3.12 throws a runtime error -- see https://github.com/python/cpython/pull/104826\n\t\t\t\t\t# RuntimeError: can't create new thread at interpreter shutdown\n\t\t\t\t\tpass\n\t\t\t\tself._process.kill()\n\t\t\texcept subprocess.TimeoutExpired:  # this is new in Python 3.3 (for python 2.x, use the PyPI subprocess32 module)\n\t\t\t\tself._process.kill()\n\t\t\t\touts, errs = self._process.communicate()\n\t\t\t\t# err handling code from https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate\n\n\t\tself._flag_running_false()\n\n\t\t# TODO log / return exit status from exiftool?\n\t\tif self._logger: self._logger.info(\"Method 'terminate': Exiftool terminated successfully.\")\n\n\n\n\n\n\t##################################################################################\n\t#################################### EXECUTE* ####################################\n\t##################################################################################\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef execute(self, *params: Union[str, bytes], raw_bytes: bool = False) -> Union[str, bytes]:\n\t\t\"\"\"Execute the given batch of parameters with *exiftool*.\n\n\t\tThis method accepts any number of parameters and sends them to\n\t\tthe attached ``exiftool`` subprocess.  The process must be\n\t\trunning, otherwise :py:exc:`exiftool.exceptions.ExifToolNotRunning` is raised.  The final\n\t\t``-execute`` necessary to actually run the batch is appended\n\t\tautomatically; see the documentation of :py:meth:`run()` for\n\t\tthe common options.  The ``exiftool`` output is read up to the\n\t\tend-of-output sentinel and returned as a ``str`` decoded\n\t\tbased on the currently set :py:attr:`encoding`,\n\t\texcluding the sentinel.\n\n\t\tThe parameters must be of type ``str`` or ``bytes``.\n\t\t``str`` parameters are encoded to bytes automatically using the :py:attr:`encoding` property.\n\t\tFor filenames, this should be the system's filesystem encoding.\n\t\t``bytes`` parameters are untouched and passed directly to ``exiftool``.\n\n\t\t.. note::\n\t\t\tThis is the core method to interface with the ``exiftool`` subprocess.\n\n\t\t\tNo processing is done on the input or output.\n\n\t\t:param params: One or more parameters to send to the ``exiftool`` subprocess.\n\n\t\t\tTypically passed in via `Unpacking Argument Lists`_\n\n\t\t\t.. note::\n\t\t\t\tThe parameters to this function must be type ``str`` or ``bytes``.\n\n\t\t:type params: one or more string/bytes parameters\n\n\t\t:param raw_bytes: If True, returns bytes.  Default behavior returns a str\n\n\n\t\t:return:\n\t\t\t* STDOUT is returned by the method call, and is also set in :py:attr:`last_stdout`\n\t\t\t* STDERR is set in :py:attr:`last_stderr`\n\t\t\t* Exit Status of the command is set in :py:attr:`last_status`\n\n\t\t:raises ExifToolNotRunning: If attempting to execute when not running (:py:attr:`running` == False)\n\t\t:raises ExifToolVersionError: If unexpected text was returned from the command while parsing out the sentinels\n\t\t:raises UnicodeDecodeError: If the :py:attr:`encoding` is not specified properly, it may be possible for ``.decode()`` method to raise this error\n\t\t:raises TypeError: If ``params`` argument is not ``str`` or ``bytes``\n\n\n\t\t.. _Unpacking Argument Lists: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists\n\t\t\"\"\"\n\t\tif not self.running:\n\t\t\traise ExifToolNotRunning(\"Cannot execute()\")\n\n\n\t\t# ---------- build the special params to execute ----------\n\n\t\t# there's a special usage of execute/ready specified in the manual which make almost ensure we are receiving the right signal back\n\t\t# from exiftool man pages:  When this number is added, -q no longer suppresses the \"{ready}\"\n\t\tsignal_num = random.randint(100000, 999999)  # arbitrary create a 6 digit number (keep it down to save memory maybe)\n\n\t\t# constant special sequences when running -stay_open mode\n\t\tseq_execute = f\"-execute{signal_num}\\n\"  # the default string is b\"-execute\\n\"\n\t\tseq_ready = f\"{{ready{signal_num}}}\"  # the default string is b\"{ready}\"\n\n\t\t# these are special sequences to help with synchronization.  It will print specific text to STDERR before and after processing\n\t\t#SEQ_STDERR_PRE_FMT = \"pre{}\" # can have a PRE sequence too but we don't need it for syncing\n\t\tseq_err_post = f\"post{signal_num}\"  # default there isn't any string\n\n\t\tSEQ_ERR_STATUS_DELIM = \"=\"  # this can be configured to be one or more chacters... the code below will accomodate for longer sequences: len() >= 1\n\t\tseq_err_status = \"${status}\"  # a special sequence, ${status} returns EXIT STATUS as per exiftool documentation - only supported on exiftool v12.10+\n\n\n\t\t# ---------- build the params list and encode the params to bytes, if necessary ----------\n\t\tcmd_params: List[bytes] = []\n\n\t\t# this is necessary as the encoding parameter of Popen() is not specified.  We manually encode as per the .encoding() parameter\n\t\tfor p in params:\n\t\t\t# we use isinstance() over type() not only for subclass, but\n\t\t\t# according to https://switowski.com/blog/type-vs-isinstance\n\t\t\t# isinstance() is 40% faster than type()\n\t\t\tif isinstance(p, bytes):\n\t\t\t\t# no conversion needed, pass in raw (caller has already encoded)\n\t\t\t\tcmd_params.append(p)\n\t\t\telif isinstance(p, str):\n\t\t\t\t# conversion needed, encode based on specified encoding\n\t\t\t\tcmd_params.append(p.encode(self._encoding))\n\t\t\telse:\n\t\t\t\t# technically at this point we could support any object and call str()\n\t\t\t\t# but leave this up to an extended class like ExifToolHelper()\n\t\t\t\traise TypeError(f\"ERROR: Parameter was not bytes/str: {type(p)} => {p}\")\n\n\t\t# f-strings are faster than concatentation of multiple strings -- https://stackoverflow.com/questions/59180574/string-concatenation-with-vs-f-string\n\t\tcmd_params.extend(\n\t\t\t(b\"-echo4\",\n\t\t\tf\"{SEQ_ERR_STATUS_DELIM}{seq_err_status}{SEQ_ERR_STATUS_DELIM}{seq_err_post}\".encode(self._encoding),\n\t\t\tseq_execute.encode(self._encoding))\n\t\t)\n\n\t\tcmd_bytes = b\"\\n\".join(cmd_params)\n\n\n\t\t# ---------- write to the pipe connected with exiftool process ----------\n\n\t\tself._process.stdin.write(cmd_bytes)\n\t\tself._process.stdin.flush()\n\n\t\tif self._logger: self._logger.info(\"Method 'execute': Command sent = {}\".format(cmd_params[:-1]))  # logs without the -execute (it would confuse people to include that)\n\n\n\t\t# ---------- read output from exiftool process until special sequences reached ----------\n\n\t\t# NOTE:\n\t\t#\n\t\t# while subprocess recommends: \"Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.\"\n\t\t#\n\t\t# this raw reading is used instead of Popen.communicate() due to the note:\n\t\t# https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate\n\t\t#\n\t\t# \"The data read is buffered in memory, so do not use this method if the data size is large or unlimited.\"\n\t\t#\n\t\t# The data that comes back from exiftool falls into this, and so unbuffered reads are done with os.read()\n\n\t\tfdout = self._process.stdout.fileno()\n\t\traw_stdout = _read_fd_endswith(fdout, seq_ready.encode(self._encoding), self._block_size)\n\n\t\t# when it's ready, we can safely read all of stderr out, as the command is already done\n\t\tfderr = self._process.stderr.fileno()\n\t\traw_stderr = _read_fd_endswith(fderr, seq_err_post.encode(self._encoding), self._block_size)\n\n\n\t\tif not raw_bytes:\n\t\t\t# decode if not returning bytes\n\t\t\traw_stdout = raw_stdout.decode(self._encoding)\n\t\t\traw_stderr = raw_stderr.decode(self._encoding)\n\n\n\t\t# ---------- parse output ----------\n\n\t\t# save the outputs to some variables first\n\t\tcmd_stdout = raw_stdout.strip()[:-len(seq_ready)]\n\t\tcmd_stderr = raw_stderr.strip()[:-len(seq_err_post)]  # save it in case the error below happens and output can be checked easily\n\n\n\t\t# if raw_bytes is True, the check has to become bytes rather than str\n\t\terr_status_delim = SEQ_ERR_STATUS_DELIM if not raw_bytes else SEQ_ERR_STATUS_DELIM.encode(self._encoding)\n\n\n\t\t# sanity check the status code from the stderr output\n\t\tdelim_len = len(err_status_delim)\n\t\tif cmd_stderr[-delim_len:] != err_status_delim:\n\t\t\t# exiftool is expected to dump out the status code within the delims... if it doesn't, the class doesn't match expected exiftool output for current version\n\t\t\traise ExifToolVersionError(f\"Exiftool expected to return status on stderr, but got unexpected character: {cmd_stderr[-delim_len:]} != {err_status_delim}\")\n\n\t\t# look for the previous delim (we could use regex here to do all this in one step, but it's probably overkill, and could slow down the code significantly)\n\t\t# the other simplification that can be done is that, as of this writing: Exiftool is expected to only return 0, 1, or 2 as per documentation\n\t\t# you could just lop the last 3 characters off... but if the return status changes in the future, then this code would break\n\t\terr_delim_1 = cmd_stderr.rfind(err_status_delim, 0, -delim_len)\n\t\tcmd_status = cmd_stderr[err_delim_1 + delim_len : -delim_len]\n\n\n\t\t# ---------- save the output to class vars for later retrieval ----------\n\n\t\t# lop off the actual status code from stderr\n\t\tself._last_stderr = cmd_stderr[:err_delim_1]\n\t\tself._last_stdout = cmd_stdout\n\t\t# can check .isnumeric() here, but best just to duck-type cast it\n\t\tself._last_status = int(cmd_status)\n\n\n\n\t\tif self._logger:\n\t\t\tself._logger.debug(f\"{self.__class__.__name__}.execute: IN  params = {params}\")\n\t\t\tself._logger.debug(f\"{self.__class__.__name__}.execute: OUT stdout = \\\"{self._last_stdout}\\\"\")\n\t\t\tself._logger.debug(f\"{self.__class__.__name__}.execute: OUT stderr = \\\"{self._last_stderr}\\\"\")\n\t\t\tself._logger.debug(f\"{self.__class__.__name__}.execute: OUT status = {self._last_status}\")\n\n\n\t\t# the standard return: just stdout\n\t\t# if you need other output, retrieve from properties\n\t\treturn self._last_stdout\n\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef execute_json(self, *params: Union[str, bytes]) -> List:\n\t\t\"\"\"Execute the given batch of parameters and parse the JSON output.\n\n\t\tThis method is similar to :py:meth:`execute()`.  It\n\t\tautomatically adds the parameter ``-j`` to request JSON output\n\t\tfrom ``exiftool`` and parses the output.\n\n\t\tThe return value is\n\t\ta list of dictionaries, mapping tag names to the corresponding\n\t\tvalues.  All keys are strings.\n\t\tThe values can have multiple types.  Each dictionary contains the\n\t\tname of the file it corresponds to in the key ``\"SourceFile\"``.\n\n\t\t.. note::\n\t\t\tBy default, the tag names include the group name in the format <group>:<tag> (if using the ``-G`` option).\n\n\t\t\tYou can adjust the output structure with various *exiftool* options.\n\n\t\t.. warning::\n\t\t\tThis method does not verify the exit status code returned by *exiftool*.  That is left up to the caller.\n\n\t\t\tThis will mimic exiftool's default method of operation \"continue on error\" and \"best attempt\" to complete commands given.\n\n\t\t\tIf you want automated error checking, use :py:class:`exiftool.ExifToolHelper`\n\n\t\t:param params: One or more parameters to send to the ``exiftool`` subprocess.\n\n\t\t\tTypically passed in via `Unpacking Argument Lists`_\n\n\t\t\t.. note::\n\t\t\t\tThe parameters to this function must be type ``str`` or ``bytes``.\n\n\t\t:type params: one or more string/bytes parameters\n\n\t\t:return: Valid JSON parsed into a Python list of dicts\n\t\t:raises ExifToolOutputEmptyError: If *exiftool* did not return any STDOUT\n\n\t\t\t.. note::\n\t\t\t\tThis is not necessarily an *exiftool* error, but rather a programmer error.\n\n\t\t\t\tFor example, setting tags can cause this behavior.\n\n\t\t\t\tIf you are executing a command and expect no output, use :py:meth:`execute()` instead.\n\n\t\t:raises ExifToolJSONInvalidError: If *exiftool* returned STDOUT which is invalid JSON.\n\n\t\t\t.. note::\n\t\t\t\tThis is not necessarily an *exiftool* error, but rather a programmer error.\n\n\t\t\t\tFor example, ``-w`` can cause this behavior.\n\n\t\t\t\tIf you are executing a command and expect non-JSON output, use :py:meth:`execute()` instead.\n\n\n\t\t.. _Unpacking Argument Lists: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists\n\t\t\"\"\"\n\n\t\tresult = self.execute(\"-j\", *params)  # stdout\n\n\t\t# NOTE: I have decided NOT to check status code\n\t\t# There are quite a few use cases where it's desirable to have continue-on-error behavior,\n\t\t# as that is exiftool's default mode of operation.  exiftool normally just does what it can\n\t\t# and tells you that it did all this and that, but some files didn't process.  In this case\n\t\t# exit code is non-zero, but exiftool did SOMETHING.  I leave it up to the caller to figure\n\t\t# out what was done or not done.\n\n\n\t\tif len(result) == 0:\n\t\t\t# the output from execute() can be empty under many relatively ambiguous situations\n\t\t\t# * command has no files it worked on\n\t\t\t# * a file specified or files does not exist\n\t\t\t# * some other type of error\n\t\t\t# * a command that does not return anything (like metadata manipulation/setting tags)\n\t\t\t#\n\t\t\t# There's no easy way to check which params are files, or else we have to reproduce the parser exiftool does (so it's hard to detect to raise a FileNotFoundError)\n\n\t\t\t# Returning [] could be ambiguous if Exiftool changes the returned JSON structure in the future\n\t\t\t# Returning None was preferred, because it's the safest as it clearly indicates that nothing came back from execute(), but it means execute_json() doesn't always return JSON\n\t\t\t# Raising an error is the current solution, as that clearly indicates that you used execute_json() expecting output, but got nothing\n\t\t\traise ExifToolOutputEmptyError(self._last_status, self._last_stdout, self._last_stderr, params)\n\n\n\t\ttry:\n\t\t\tparsed = self._json_loads(result, **self._json_loads_kwargs)\n\t\texcept ValueError as e:\n\t\t\t# most known JSON libraries return ValueError or a subclass.\n\t\t\t# built-in json.JSONDecodeError is a subclass of ValueError -- https://docs.python.org/3/library/json.html#json.JSONDecodeError\n\n\t\t\t# if `-w` flag is specified in common_args or params, stdout will not be JSON parseable\n\t\t\t#\n\t\t\t# which will return something like:\n\t\t\t#   x image files read\n\t\t\t#   x output files created\n\n\t\t\t# the user is expected to know this ahead of time, and if -w exists in common_args or as a param, this error will be thrown\n\n\t\t\t# explicit chaining https://www.python.org/dev/peps/pep-3134/\n\t\t\traise ExifToolJSONInvalidError(self._last_status, self._last_stdout, self._last_stderr, params) from e\n\n\t\treturn parsed\n\n\n\t#########################################################################################\n\t#################################### PRIVATE METHODS ####################################\n\t#########################################################################################\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef _flag_running_false(self) -> None:\n\t\t\"\"\" private method that resets the \"running\" state\n\t\t\tIt used to be that there was only self._running to unset, but now it's a trio of variables\n\n\t\t\tThis method makes it less likely a maintainer will leave off a variable if other ones are added in the future\n\t\t\"\"\"\n\t\tself._process = None  # don't delete, just leave as None\n\t\tself._ver = None  # unset the version\n\t\tself._running = False\n\n\t\t# as an FYI, as per the last_* properties, they are intentionally not cleared when process closes\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef _parse_ver(self):\n\t\t\"\"\" private method to run exiftool -ver\n\t\t\tand parse out the information\n\t\t\"\"\"\n\t\tif not self.running:\n\t\t\traise ExifToolNotRunning(\"Cannot get version\")\n\n\n\t\t# -ver is just the version\n\t\t# -v gives you more info (perl version, platform, libraries) but isn't helpful for this library\n\t\t# -v2 gives you even more, but it's less useful at that point\n\t\treturn self.execute(\"-ver\").strip()\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t\"\"\"\n\tdef _exiftool_version_check(self) -> bool:\n\t\t\"\" \" private method to check the minimum required version of ExifTool\n\n\t\treturns false if the version check fails\n\t\treturns true if it's OK\n\n\t\t\"\" \"\n\n\t\t# parse (major, minor) with integers... so far Exiftool versions are all ##.## with no exception\n\t\t# this isn't entirely tested... possibly a version with more \".\" or something might break this parsing\n\t\tarr: List = self._ver.split(\".\", 1)  # split to (major).(whatever)\n\n\t\tversion_nums: List = []\n\t\ttry:\n\t\t\tfor v in arr:\n\t\t\t\tres.append(int(v))\n\t\texcept ValueError:\n\t\t\traise ValueError(f\"Error parsing ExifTool version for version check: '{self._ver}'\")\n\n\t\tif len(version_nums) != 2:\n\t\t\traise ValueError(f\"Expected Major.Minor len()==2, got: {version_nums}\")\n\n\t\tcurr_major, curr_minor = version_nums\n\n\n\t\t# same logic above except on one line\n\t\treq_major, req_minor = [int(x) for x in constants.EXIFTOOL_MINIMUM_VERSION.split(\".\", 1)]\n\n\t\tif curr_major > req_major:\n\t\t\t# major version is bigger\n\t\t\treturn True\n\t\telif curr_major < req_major:\n\t\t\t# major version is smaller\n\t\t\treturn False\n\t\telif curr_minor >= req_minor:\n\t\t\t# major version is equal\n\t\t\t# current minor is equal or better\n\t\t\treturn True\n\t\telse:\n\t\t\t# anything else is False\n\t\t\treturn False\n\t\"\"\"\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n"
  },
  {
    "path": "exiftool/experimental.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# This file is part of PyExifTool.\n#\n# PyExifTool <http://github.com/sylikc/pyexiftool>\n#\n# Copyright 2019-2023 Kevin M (sylikc)\n# Copyright 2012-2014 Sven Marnach\n#\n# Community contributors are listed in the CHANGELOG.md for the PRs\n#\n# PyExifTool is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the licence, or\n# (at your option) any later version, or the BSD licence.\n#\n# PyExifTool is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# See COPYING.GPL or COPYING.BSD for more details.\n\n\n\"\"\"\nThis submodule contains the ``ExifToolAlpha`` class, which extends the ``ExifToolHelper`` class with experimental functionality.\n\n.. note::\n\t:py:class:`exiftool.helper.ExifToolAlpha` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifToolAlpha`\n\n\"\"\"\n\nfrom pathlib import Path\n\nfrom .helper import ExifToolHelper\n\n\ntry:        # Py3k compatibility\n\tbasestring\nexcept NameError:\n\tbasestring = (bytes, str)\n\n# ======================================================================================================================\n\n#def atexit_handler\n\n# constants related to keywords manipulations\nKW_TAGNAME = \"IPTC:Keywords\"\nKW_REPLACE, KW_ADD, KW_REMOVE = range(3)\n\n\n\n\n\n# ======================================================================================================================\n\n\n\n#string helper\ndef strip_nl(s):\n\treturn ' '.join(s.splitlines())\n\n# ======================================================================================================================\n\n# Error checking function\n# very rudimentary checking\n# Note: They are quite fragile, because this just parses the output text from exiftool\ndef check_ok(result):\n\t\"\"\"Evaluates the output from a exiftool write operation (e.g. `set_tags`)\n\n\tThe argument is the result from the execute method.\n\n\tThe result is True or False.\n\t\"\"\"\n\treturn not result is None and (not \"due to errors\" in result)\n\n# ======================================================================================================================\n\ndef format_error(result):\n\t\"\"\"Evaluates the output from a exiftool write operation (e.g. `set_tags`)\n\n\tThe argument is the result from the execute method.\n\n\tThe result is a human readable one-line string.\n\t\"\"\"\n\tif check_ok(result):\n\t\treturn f'exiftool probably finished properly. (\"{strip_nl(result)}\")'\n\telse:\n\t\tif result is None:\n\t\t\treturn \"exiftool operation can't be evaluated: No result given\"\n\t\telse:\n\t\t\treturn f'exiftool finished with error: \"{strip_nl(result)}\"'\n\n\n\n# ======================================================================================================================\n\nclass ExifToolAlpha(ExifToolHelper):\n\t\"\"\"\n\tThis class is for the \"experimental\" functionality.  In the grand scheme of things, this class\n\tcontains \"not well tested\" functionality, methods that are less used, or methods with niche use cases.\n\tIn some methods, edge cases on some of these methods may produce unexpected or ambiguous results.\n\tHowever, if there is increased demand, or robustness improves, functionality may merge into\n\t:py:class:`exiftool.ExifToolHelper` class.\n\n\tThe starting point of this class was to remove all the \"less used\" functionality that was merged in\n\ton some arbitrary pull requests to the original v0.2 PyExifTool repository.  This alpha-quality code is brittle and contains\n\ta lot of \"hacks\" for a niche set of use cases.  As such, it may be buggy and it shouldn't crowd the core functionality\n\tof the :py:class:`exiftool.ExifTool` class or the stable extended functionality of the :py:class:`exiftool.ExifToolHelper` class\n\twith unneeded bloat.\n\n\tThe class heirarchy:  ExifTool -> ExifToolHelper -> ExifToolAlpha\n\n\t* ExifTool - stable base class with CORE functionality\n\t* ExifToolHelper - user friendly class that extends the base class with general functionality not found in the core\n\t* ExifToolAlpha - alpha-quality code which extends the ExifToolHelper to add functionality that is niche, brittle, or not well tested\n\n\tBecause of this heirarchy, you could always use/extend the :py:class:`exiftool.ExifToolAlpha` class to have all functionality,\n\tor at your discretion, use one of the more stable classes above.\n\n\tPlease issue PR to this class to add functionality, even if not tested well.  This class is for experimental code after all!\n\t\"\"\"\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t# i'm not sure if the verification works, but related to pull request (#11)\n\tdef execute_json_wrapper(self, filenames, params=None, retry_on_error=True):\n\t\t# make sure the argument is a list and not a single string\n\t\t# which would lead to strange errors\n\t\tif isinstance(filenames, basestring):\n\t\t\traise TypeError(\"The argument 'filenames' must be an iterable of strings\")\n\n\t\texecute_params = []\n\n\t\tif params:\n\t\t\texecute_params.extend(params)\n\t\texecute_params.extend(filenames)\n\n\t\tresult = self.execute_json(execute_params)\n\n\t\tif result:\n\t\t\ttry:\n\t\t\t\tExifToolAlpha._check_result_filelist(filenames, result)\n\t\t\texcept IOError as error:\n\t\t\t\t# Restart the exiftool child process in these cases since something is going wrong\n\t\t\t\tself.terminate()\n\t\t\t\tself.run()\n\n\t\t\t\tif retry_on_error:\n\t\t\t\t\tresult = self.execute_json_filenames(filenames, params, retry_on_error=False)\n\t\t\t\telse:\n\t\t\t\t\traise error\n\t\telse:\n\t\t\t# Reasons for exiftool to provide an empty result, could be e.g. file not found, etc.\n\t\t\t# What should we do in these cases? We don't have any information what went wrong, therefore\n\t\t\t# we just return empty dictionaries.\n\t\t\tresult = [{} for _ in filenames]\n\n\t\treturn result\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t# allows adding additional checks (#11)\n\tdef get_metadata_batch_wrapper(self, filenames, params=None):\n\t\treturn self.execute_json_wrapper(filenames=filenames, params=params)\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t# (#11)\n\tdef get_metadata_wrapper(self, filename, params=None):\n\t\treturn self.execute_json_wrapper(filenames=[filename], params=params)[0]\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t# (#11)\n\tdef get_tags_batch_wrapper(self, tags, filenames, params=None):\n\t\tparams = (params if params else []) + [\"-\" + t for t in tags]\n\t\treturn self.execute_json_wrapper(filenames=filenames, params=params)\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t# (#11)\n\tdef get_tags_wrapper(self, tags, filename, params=None):\n\t\treturn self.get_tags_batch_wrapper(tags, [filename], params=params)[0]\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t# (#11)\n\tdef get_tag_batch_wrapper(self, tag, filenames, params=None):\n\t\tdata = self.get_tags_batch_wrapper([tag], filenames, params=params)\n\t\tresult = []\n\t\tfor d in data:\n\t\t\td.pop(\"SourceFile\")\n\t\t\tresult.append(next(iter(d.values()), None))\n\t\treturn result\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t# this was a method with good intentions by the original author, but returns some inconsistent results in some cases\n\t# for example, if you passed in a single tag, or a group name, it would return the first tag back instead of the whole group\n\t# try calling get_tag_batch(\"*.mp4\", \"QuickTime\") or \"QuickTime:all\" ... the expected results is a dictionary but a single tag is returned\n\tdef get_tag_batch(self, filenames, tag):\n\t\t\"\"\"Extract a single tag from the given files.\n\n\t\tThe first argument is a single tag name, as usual in the\n\t\tformat <group>:<tag>.\n\n\t\tThe second argument is an iterable of file names.\n\n\t\tThe return value is a list of tag values or ``None`` for\n\t\tnon-existent tags, in the same order as ``filenames``.\n\t\t\"\"\"\n\t\tdata = self.get_tags(filenames, [tag])\n\t\tresult = []\n\t\tfor d in data:\n\t\t\td.pop(\"SourceFile\")\n\t\t\tresult.append(next(iter(d.values()), None))\n\t\treturn result\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t# (#11)\n\tdef get_tag_wrapper(self, tag, filename, params=None):\n\t\treturn self.get_tag_batch_wrapper(tag, [filename], params=params)[0]\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef get_tag(self, filename, tag):\n\t\t\"\"\"\n\t\tExtract a single tag from a single file.\n\n\t\tThe return value is the value of the specified tag, or\n\t\t``None`` if this tag was not found in the file.\n\n\t\tDoes existence checks\n\t\t\"\"\"\n\n\t\t#return self.get_tag_batch([filename], tag)[0]\n\n\t\tp = Path(filename)\n\n\t\tif not p.exists():\n\t\t\traise FileNotFoundError\n\n\t\tdata = self.get_tags(p, tag)\n\t\tif len(data) > 1:\n\t\t\traise RuntimeError(\"one file requested but multiple returned?\")\n\n\t\td = data[0]\n\t\td.pop(\"SourceFile\")\n\n\t\tif len(d.values()) > 1:\n\t\t\traise RuntimeError(\"multiple tag values returned, invalid use case\")\n\n\t\treturn next(iter(d.values()), None)\n\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef copy_tags(self, from_filename, to_filename):\n\t\t\"\"\"Copy all tags from one file to another.\"\"\"\n\t\tparams = [\"-overwrite_original\", \"-TagsFromFile\", str(from_filename), str(to_filename)]\n\t\tself.execute(*params)\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef set_keywords_batch(self, files, mode, keywords):\n\t\t\"\"\"Modifies the keywords tag for the given files.\n\n\t\tThe first argument is the operation mode:\n\n\t\t* KW_REPLACE: Replace (i.e. set) the full keywords tag with `keywords`.\n\t\t* KW_ADD:     Add `keywords` to the keywords tag.\n\t\t\t\t\tIf a keyword is present, just keep it.\n\t\t* KW_REMOVE:  Remove `keywords` from the keywords tag.\n\t\t\t\t\tIf a keyword wasn't present, just leave it.\n\n\t\tThe second argument is an iterable of key words.\n\n\t\tThe third argument is an iterable of file names.\n\n\t\tThe format of the return value is the same as for\n\t\t:py:meth:`execute()`.\n\n\t\tIt can be passed into `check_ok()` and `format_error()`.\n\t\t\"\"\"\n\t\t# Explicitly ruling out strings here because passing in a\n\t\t# string would lead to strange and hard-to-find errors\n\t\tif isinstance(keywords, basestring):\n\t\t\traise TypeError(\"The argument 'keywords' must be \"\n\t\t\t\t\t\t\t\"an iterable of strings\")\n\n\t\t# allow the files argument to be a str, and process it into a list of str\n\t\tfilenames = self.__class__._parse_arg_files(files)\n\n\t\tparams = []\n\n\t\tkw_operation = {KW_REPLACE: \"-%s=%s\",\n\t\t\t\t\t\tKW_ADD: \"-%s+=%s\",\n\t\t\t\t\t\tKW_REMOVE: \"-%s-=%s\"}[mode]\n\n\t\tkw_params = [kw_operation % (KW_TAGNAME, w) for w in keywords]\n\n\t\tparams.extend(kw_params)\n\t\tparams.extend(filenames)\n\t\tif self._logger: self._logger.debug(params)\n\n\t\treturn self.execute(*params)\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef set_keywords(self, filename, mode, keywords):\n\t\t\"\"\"Modifies the keywords tag for the given file.\n\n\t\tThis is a convenience function derived from `set_keywords_batch()`.\n\t\tOnly difference is that it takes as last argument only one file name\n\t\tas a string.\n\t\t\"\"\"\n\t\treturn self.set_keywords_batch([filename], mode, keywords)\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@staticmethod\n\tdef _check_result_filelist(file_paths, result):\n\t\t\"\"\"\n\t\tChecks if the given file paths matches the 'SourceFile' entries in the result returned by\n\t\texiftool. This is done to find possible mix ups in the streamed responses.\n\t\t\"\"\"\n\t\t# do some sanity checks on the results to make sure nothing was mixed up during reading from stdout\n\t\tif len(result) != len(file_paths):\n\t\t\traise IOError(f\"exiftool returned {len(result)} results, but expected was {len(file_paths)}\")\n\n\t\tfor i in range(len(file_paths)):\n\t\t\treturned_source_file = result[i].get('SourceFile')\n\t\t\trequested_file = file_paths[i]\n\n\t\t\tif returned_source_file != requested_file:\n\t\t\t\traise IOError(f\"exiftool returned data for file {returned_source_file}, but expected was {requested_file}\")\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n"
  },
  {
    "path": "exiftool/helper.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# This file is part of PyExifTool.\n#\n# PyExifTool <http://github.com/sylikc/pyexiftool>\n#\n# Copyright 2019-2023 Kevin M (sylikc)\n# Copyright 2012-2014 Sven Marnach\n#\n# Community contributors are listed in the CHANGELOG.md for the PRs\n#\n# PyExifTool is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the licence, or\n# (at your option) any later version, or the BSD licence.\n#\n# PyExifTool is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# See COPYING.GPL or COPYING.BSD for more details.\n\n\n\"\"\"\nThis submodule contains the ``ExifToolHelper`` class, which makes the core ``ExifTool`` class easier, and safer to use.\n\n.. note::\n\t:py:class:`exiftool.helper.ExifToolHelper` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifToolHelper`\n\n\"\"\"\n\nimport re\n\nfrom .exiftool import ExifTool\nfrom .exceptions import ExifToolOutputEmptyError, ExifToolJSONInvalidError, ExifToolExecuteError, ExifToolTagNameError\n\n# basestring makes no sense in Python 3, so renamed tuple to this const\nTUPLE_STR_BYTES: tuple = (str, bytes,)\n\nfrom typing import Any, Union, Optional, List, Dict\n\n\n\n\n# ======================================================================================================================\n\n\ndef _is_iterable(in_param: Any, ignore_str_bytes: bool = False) -> bool:\n\t\"\"\"\n\tChecks if this item is iterable, instead of using isinstance(list), anything iterable can be ok\n\n\t.. note::\n\t\tSTRINGS ARE CONSIDERED ITERABLE by Python\n\n\t\tif you need to consider a code path for strings first, check that before checking if a parameter is iterable via this function\n\n\t\tor specify ``ignore_str_bytes=True``\n\n\t:param in_param: Something to check if iterable or not\n\t:param ignore_str_bytes: str/bytes are iterable.  But usually we don't want to check that.  set ``ignore_str_bytes`` to ``True`` to ignore strings on check\n\t\"\"\"\n\n\tif ignore_str_bytes and isinstance(in_param, TUPLE_STR_BYTES):\n\t\treturn False\n\n\t# a different type of test of iterability, instead of using isinstance(list)\n\t# https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable\n\ttry:\n\t\titerator = iter(in_param)\n\texcept TypeError:\n\t\treturn False\n\n\treturn True\n\n\n\n# ======================================================================================================================\n\nclass ExifToolHelper(ExifTool):\n\t\"\"\"\n\tThis class extends the low-level :py:class:`exiftool.ExifTool` class with 'wrapper'/'helper' functionality\n\n\tIt keeps low-level core functionality with the base class but extends helper functions in a separate class\n\t\"\"\"\n\n\t##########################################################################################\n\t#################################### OVERRIDE METHODS ####################################\n\t##########################################################################################\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef __init__(self, auto_start: bool = True, check_execute: bool = True, check_tag_names: bool = True, **kwargs) -> None:\n\t\t\"\"\"\n\t\t:param bool auto_start: Will automatically start the exiftool process on first command run, defaults to True\n\t\t:param bool check_execute: Will check the exit status (return code) of all commands.  This catches some invalid commands passed to exiftool subprocess, defaults to True.  See :py:attr:`check_execute` for more info.\n\t\t:param bool check_tag_names: Will check the tag names provided to methods which work directly with tag names.  This catches unintended uses and bugs, default to True.  See :py:attr:`check_tag_names` for more info.\n\n\t\t:param kwargs: All other parameters are passed directly to the super-class constructor: :py:meth:`exiftool.ExifTool.__init__()`\n\t\t\"\"\"\n\t\t# call parent's constructor\n\t\tsuper().__init__(**kwargs)\n\n\t\tself._auto_start: bool = auto_start\n\t\tself._check_execute: bool = check_execute\n\t\tself._check_tag_names: bool = check_tag_names\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef execute(self, *params: Any, **kwargs) -> Union[str, bytes]:\n\t\t\"\"\"\n\t\tOverride the :py:meth:`exiftool.ExifTool.execute()` method\n\n\t\tAdds logic to auto-start if not running, if :py:attr:`auto_start` == True\n\n\t\tAdds logic to str() any parameter which is not a str or bytes.  (This allows passing in objects like Path _without_ casting before passing it in.)\n\n\t\t:raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero\n\t\t\"\"\"\n\t\tif self._auto_start and not self.running:\n\t\t\tself.run()\n\n\t\t# by default, any non-(str/bytes) would throw a TypeError from ExifTool.execute(), so they're casted to a string here\n\t\t#\n\t\t# duck-type any given object to string\n\t\t# this was originally to support Path() but it's now generic enough to support any object that str() to something useful\n\t\t#\n\t\t# Thanks @jangop for the single line contribution!\n\t\tstr_bytes_params: Union[str, bytes] = [x if isinstance(x, TUPLE_STR_BYTES) else str(x) for x in params]\n\t\t# TODO: this list copy could be expensive if the input is a very huge list.  Perhaps in the future have a flag that takes the lists in verbatim without any processing?\n\n\n\t\tresult: Union[str, bytes] = super().execute(*str_bytes_params, **kwargs)\n\n\t\t# imitate the subprocess.run() signature.  check=True will check non-zero exit status\n\t\tif self._check_execute and self._last_status:\n\t\t\traise ExifToolExecuteError(self._last_status, self._last_stdout, self._last_stderr, str_bytes_params)\n\n\t\treturn result\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef run(self) -> None:\n\t\t\"\"\"\n\t\toverride the :py:meth:`exiftool.ExifTool.run()` method\n\n\t\tWill not attempt to run if already running (so no warning about 'ExifTool already running' will trigger)\n\t\t\"\"\"\n\t\tif self.running:\n\t\t\treturn\n\n\t\tsuper().run()\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef terminate(self, **opts) -> None:\n\t\t\"\"\"\n\t\tOverrides the :py:meth:`exiftool.ExifTool.terminate()` method.\n\n\t\tWill not attempt to terminate if not running (so no warning about 'ExifTool not running' will trigger)\n\n\t\t:param opts: passed directly to the parent call :py:meth:`exiftool.ExifTool.terminate()`\n\t\t\"\"\"\n\t\tif not self.running:\n\t\t\treturn\n\n\t\tsuper().terminate(**opts)\n\n\n\t########################################################################################\n\t#################################### NEW PROPERTIES ####################################\n\t########################################################################################\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef auto_start(self) -> bool:\n\t\t\"\"\"\n\t\tRead-only property.  Gets the current setting passed into the constructor as to whether auto_start is enabled or not.\n\n\t\t(There's really no point to having this a read-write property, but allowing a read can be helpful at runtime to detect expected behavior.)\n\t\t\"\"\"\n\t\treturn self._auto_start\n\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef check_execute(self) -> bool:\n\t\t\"\"\"\n\t\tFlag to enable/disable checking exit status (return code) on execute\n\n\t\tIf enabled, will raise :py:exc:`exiftool.exceptions.ExifToolExecuteError` if a non-zero exit status is returned during :py:meth:`execute()`\n\n\t\t.. warning::\n\t\t\tWhile this property is provided to give callers an option to enable/disable error checking, it is generally **NOT** recommended to disable ``check_execute``.\n\n\t\t\t**If disabled, exiftool will fail silently, and hard-to-catch bugs may arise.**\n\n\t\t\tThat said, there may be some use cases where continue-on-error behavior is desired.  (Example: dump all exif in a directory with files which don't all have the same tags, exiftool returns exit code 1 for unknown files, but results are valid for other files with those tags)\n\n\t\t:getter: Returns current setting\n\t\t:setter: Enable or Disable the check\n\n\t\t\t.. note::\n\t\t\t\tThis settings can be changed any time and will only affect subsequent calls\n\n\t\t:type: bool\n\t\t\"\"\"\n\t\treturn self._check_execute\n\n\t@check_execute.setter\n\tdef check_execute(self, new_setting: bool) -> None:\n\t\tself._check_execute = new_setting\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@property\n\tdef check_tag_names(self) -> bool:\n\t\t\"\"\"\n\t\tFlag to enable/disable checking of tag names\n\n\t\tIf enabled, will raise :py:exc:`exiftool.exceptions.ExifToolTagNameError` if an invalid tag name is detected.\n\n\t\t.. warning::\n\t\t\tExifToolHelper only checks the validity of the Tag **NAME** based on a simple regex pattern.\n\n\t\t\t* It *does not* validate whether the tag name is actually valid on the file type(s) you're accessing.\n\t\t\t* It *does not* validate whether the tag you passed in that \"looks like\" a tag is actually an option\n\t\t\t* It does support a \"#\" at the end of the tag name to disable print conversion\n\n\t\t\tPlease refer to `ExifTool Tag Names`_ documentation for a complete list of valid tags recognized by ExifTool.\n\n\t\t.. warning::\n\t\t\tWhile this property is provided to give callers an option to enable/disable tag names checking, it is generally **NOT** recommended to disable ``check_tag_names``.\n\n\t\t\t**If disabled, you could accidentally edit a file when you meant to read it.**\n\n\t\t\tExample: ``get_tags(\"a.jpg\", \"tag=value\")`` will call ``execute_json(\"-tag=value\", \"a.jpg\")`` which will inadvertently write to a.jpg instead of reading it!\n\n\t\t\tThat said, if PH's exiftool changes its tag name regex and tag names are being erroneously rejected because of this flag, disabling this could be used as a workaround (more importantly, if this is happening, please `file an issue`_!).\n\n\t\t:getter: Returns current setting\n\t\t:setter: Enable or Disable the check\n\n\t\t\t.. note::\n\t\t\t\tThis settings can be changed any time and will only affect subsequent calls\n\n\t\t:type: bool\n\n\n\t\t.. _file an issue: https://github.com/sylikc/pyexiftool/issues\n\t\t.. _ExifTool Tag Names: https://exiftool.org/TagNames/\n\t\t\"\"\"\n\t\treturn self._check_tag_names\n\n\t@check_tag_names.setter\n\tdef check_tag_names(self, new_setting: bool) -> None:\n\t\tself._check_tag_names = new_setting\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\n\n\n\n\n\n\t#####################################################################################\n\t#################################### NEW METHODS ####################################\n\t#####################################################################################\n\n\n\t# all generic helper functions will follow a convention of\n\t# function(files to be worked on, ... , params=)\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef get_metadata(self, files: Union[str, List], params: Optional[Union[str, List]] = None) -> List:\n\t\t\"\"\"\n\t\tReturn all metadata for the given files.\n\n\t\t.. note::\n\n\t\t\tThis is a convenience method.\n\n\t\t\tThe implementation calls :py:meth:`get_tags()` with ``tags=None``\n\n\t\t:param files: Files parameter matches :py:meth:`get_tags()`\n\n\t\t:param params: Optional parameters to send to *exiftool*\n\t\t:type params: list or None\n\n\t\t:return: The return value will have the format described in the documentation of :py:meth:`get_tags()`.\n\t\t\"\"\"\n\t\treturn self.get_tags(files, None, params=params)\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef get_tags(self, files: Union[Any, List[Any]], tags: Optional[Union[str, List]], params: Optional[Union[str, List]] = None) -> List:\n\t\t\"\"\"\n\t\tReturn only specified tags for the given files.\n\n\t\t:param files: File(s) to be worked on.\n\n\t\t\t* If a non-iterable is provided, it will get tags for a single item (str(non-iterable))\n\t\t\t* If an iterable is provided, the list is passed into :py:meth:`execute_json` verbatim.\n\n\t\t\t.. note::\n\t\t\t\tAny files/params which are not bytes/str will be casted to a str in :py:meth:`execute()`.\n\n\t\t\t.. warning::\n\t\t\t\tCurrently, filenames are NOT checked for existence!  That is left up to the caller.\n\n\t\t\t.. warning::\n\t\t\t\tWildcard strings are valid and passed verbatim to exiftool.\n\n\t\t\t\tHowever, exiftool's wildcard matching/globbing may be different than Python's matching/globbing,\n\t\t\t\twhich may cause unexpected behavior if you're using one and comparing the result to the other.\n\t\t\t\tRead `ExifTool Common Mistakes - Over-use of Wildcards in File Names`_ for some related info.\n\n\t\t:type files: Any or List(Any) - see Note\n\n\n\t\t:param tags: Tag(s) to read.  If tags is None, or [], method will returns all tags\n\n\t\t\t.. note::\n\t\t\t\tThe tag names may include group names, as usual in the format ``<group>:<tag>``.\n\n\t\t:type tags: str, list, or None\n\n\n\t\t:param params: Optional parameter(s) to send to *exiftool*\n\t\t:type params: Any, List[Any], or None\n\n\n\t\t:return: The format of the return value is the same as for :py:meth:`exiftool.ExifTool.execute_json()`.\n\n\n\t\t:raises ValueError: Invalid Parameter\n\t\t:raises TypeError: Invalid Parameter\n\t\t:raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero\n\n\n\t\t.. _ExifTool Common Mistakes - Over-use of Wildcards in File Names: https://exiftool.org/mistakes.html#M2\n\n\t\t\"\"\"\n\n\t\tfinal_tags: Optional[List] = None\n\t\tfinal_files: List = self.__class__._parse_arg_files(files)\n\n\t\tif tags is None:\n\t\t\t# all tags\n\t\t\tfinal_tags = []\n\t\telif isinstance(tags, TUPLE_STR_BYTES):\n\t\t\tfinal_tags = [tags]\n\t\telif _is_iterable(tags):\n\t\t\tfinal_tags = tags\n\t\telse:\n\t\t\traise TypeError(f\"{self.__class__.__name__}.get_tags: argument 'tags' must be a str/bytes or a list\")\n\n\t\tif self._check_tag_names:\n\t\t\t# run check if enabled\n\t\t\tself.__class__._check_tag_list(final_tags)\n\n\t\texec_params: List = []\n\n\t\t# we extend an empty list to avoid modifying any referenced inputs\n\t\tif params:\n\t\t\tif _is_iterable(params, ignore_str_bytes=True):\n\t\t\t\texec_params.extend(params)\n\t\t\telse:\n\t\t\t\texec_params.append(params)\n\n\t\t# tags is always a list by this point.  It will always be iterable... don't have to check for None\n\t\texec_params.extend([f\"-{t}\" for t in final_tags])\n\n\t\texec_params.extend(final_files)\n\n\t\ttry:\n\t\t\tret = self.execute_json(*exec_params)\n\t\texcept ExifToolOutputEmptyError:\n\t\t\traise\n\t\t\t#raise RuntimeError(f\"{self.__class__.__name__}.get_tags: exiftool returned no data\")\n\t\texcept ExifToolJSONInvalidError:\n\t\t\traise\n\t\texcept ExifToolExecuteError:\n\t\t\t# if last_status is <> 0, raise an error that one or more files failed?\n\t\t\traise\n\n\t\treturn ret\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\tdef set_tags(self, files: Union[Any, List[Any]], tags: Dict, params: Optional[Union[str, List]] = None):\n\t\t\"\"\"\n\t\tWrites the values of the specified tags for the given file(s).\n\n\t\t:param files: File(s) to be worked on.\n\n\t\t\t* If a non-iterable is provided, it will get tags for a single item (str(non-iterable))\n\t\t\t* If an iterable is provided, the list is passed into :py:meth:`execute_json` verbatim.\n\n\t\t\t.. note::\n\t\t\t\tAny files/params which are not bytes/str will be casted to a str in :py:meth:`execute()`.\n\n\t\t\t.. warning::\n\t\t\t\tCurrently, filenames are NOT checked for existence!  That is left up to the caller.\n\n\t\t\t.. warning::\n\t\t\t\tWildcard strings are valid and passed verbatim to exiftool.\n\n\t\t\t\tHowever, exiftool's wildcard matching/globbing may be different than Python's matching/globbing,\n\t\t\t\twhich may cause unexpected behavior if you're using one and comparing the result to the other.\n\t\t\t\tRead `ExifTool Common Mistakes - Over-use of Wildcards in File Names`_ for some related info.\n\n\t\t:type files: Any or List(Any) - see Note\n\n\n\t\t:param tags: Tag(s) to write.\n\n\t\t\tDictionary keys = tags, values = tag values (str or list)\n\n\t\t\t* If a value is a str, will set key=value\n\t\t\t* If a value is a list, will iterate over list and set each individual value to the same tag (\n\n\t\t\t.. note::\n\t\t\t\tThe tag names may include group names, as usual in the format ``<group>:<tag>``.\n\n\t\t\t.. note::\n\t\t\t\tValue of the dict can be a list, in which case, the tag will be passed with each item in the list, in the order given\n\n\t\t\t\tThis allows setting things like ``-Keywords=a -Keywords=b -Keywords=c`` by passing in ``tags={\"Keywords\": ['a', 'b', 'c']}``\n\n\t\t:type tags: dict\n\n\n\t\t:param params: Optional parameter(s) to send to *exiftool*\n\t\t:type params: str, list, or None\n\n\n\t\t:return: The format of the return value is the same as for :py:meth:`execute()`.\n\n\n\t\t:raises ValueError: Invalid Parameter\n\t\t:raises TypeError: Invalid Parameter\n\t\t:raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero\n\n\n\t\t.. _ExifTool Common Mistakes - Over-use of Wildcards in File Names: https://exiftool.org/mistakes.html#M2\n\n\t\t\"\"\"\n\t\tfinal_files: List = self.__class__._parse_arg_files(files)\n\n\t\tif not tags:\n\t\t\traise ValueError(f\"{self.__class__.__name__}.set_tags: argument 'tags' cannot be empty\")\n\t\telif not isinstance(tags, dict):\n\t\t\traise TypeError(f\"{self.__class__.__name__}.set_tags: argument 'tags' must be a dict\")\n\n\n\t\tif self._check_tag_names:\n\t\t\t# run check if enabled\n\t\t\tself.__class__._check_tag_list(list(tags))  # gets only the keys (tag names)\n\n\t\texec_params: List = []\n\n\t\t# we extend an empty list to avoid modifying any referenced inputs\n\t\tif params:\n\t\t\tif _is_iterable(params, ignore_str_bytes=True):\n\t\t\t\texec_params.extend(params)\n\t\t\telse:\n\t\t\t\texec_params.append(params)\n\n\t\tfor tag, value in tags.items():\n\t\t\t# contributed by @daviddorme in https://github.com/sylikc/pyexiftool/issues/12#issuecomment-821879234\n\t\t\t# allows setting things like Keywords which require separate directives\n\t\t\t# > exiftool -Keywords=keyword1 -Keywords=keyword2 -Keywords=keyword3 file.jpg\n\t\t\t# which are not supported as duplicate keys in a dictionary\n\t\t\tif isinstance(value, list):\n\t\t\t\tfor item in value:\n\t\t\t\t\texec_params.append(f\"-{tag}={item}\")\n\t\t\telse:\n\t\t\t\texec_params.append(f\"-{tag}={value}\")\n\n\t\texec_params.extend(final_files)\n\n\t\ttry:\n\t\t\treturn self.execute(*exec_params)\n\t\t\t#TODO if execute returns data, then error?\n\t\texcept ExifToolExecuteError:\n\t\t\t# last status non-zero\n\t\t\traise\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\n\n\n\n\n\n\n\t#########################################################################################\n\t#################################### PRIVATE METHODS ####################################\n\t#########################################################################################\n\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@staticmethod\n\tdef _parse_arg_files(files: Union[str, List]) -> List:\n\t\t\"\"\"\n\t\tThis logic to process the files argument is common across most ExifToolHelper methods\n\n\t\tIt can be used by a developer to process the files argument the same way if this class is extended\n\n\t\t:param files: File(s) to be worked on.\n\t\t:type files: str or list\n\n\t\t:return: A list of one or more elements containing strings of files\n\n\t\t:raises ValueError: Files parameter is empty\n\t\t\"\"\"\n\n\t\tfinal_files: List = []\n\n\t\tif not files:\n\t\t\t# Exiftool process would return an error anyways\n\t\t\traise ValueError(\"ERROR: Argument 'files' cannot be empty\")\n\t\telif not _is_iterable(files, ignore_str_bytes=True):\n\t\t\t# if it's not a string but also not iterable\n\t\t\tfinal_files = [files]\n\t\telse:\n\t\t\tfinal_files = files\n\n\n\t\treturn final_files\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\t@staticmethod\n\tdef _check_tag_list(tags: List) -> None:\n\t\t\"\"\"\n\t\tPrivate method.  This method is used to check the validity of a tag list passed in.\n\n\t\tSee any notes/warnings in the property :py:attr:`check_tag_names` to get a better understanding of what this is for and not for.\n\n\t\t:param list tags: List of tags to check\n\n\t\t:return: None if checks passed.  Raises an error otherwise.  (Think of it like an assert statement)\n\t\t\"\"\"\n\t\t# In the future if a specific version changed the match pattern,\n\t\t# we can check self.version ... then this method will no longer\n\t\t# be static and requires the underlying exiftool process to be running to get the self.version\n\t\t#\n\t\t# This is not done right now because the odds of the tag name format changing is very low, and requiring\n\t\t# exiftool to be running during this tag check could introduce unneccesary overhead at this time\n\n\n\n\t\t# According to the exiftool source code, the valid regex on tags is (/^([-\\w*]+:)*([-\\w*?]+)#?$/)\n\t\t# However, it appears that \"-\" may be allowed within a tag name/group (i.e. https://exiftool.org/TagNames/XMP.html Description tags)\n\t\t#\n\t\t# \\w in Perl => https://perldoc.perl.org/perlrecharclass#Backslash-sequences\n\t\t# \\w in Python => https://docs.python.org/3/library/re.html#regular-expression-syntax\n\t\t#\n\t\t# Perl vs Python's \"\\w\" seem to mean slightly different things, so we write our own regex / matching algorithm\n\n\n\t\t# * make sure the first character is not a special one\n\t\t# * \"#\" can only appear at the end\n\t\t# * Tag:Tag:tag is not valid, but passes the simple regex (it's ok, this is not supposed to be a catch-all)... exiftool subprocess accepts it anyways, even if invalid.\n\t\t# * *wildcard* tags are permitted by exiftool\n\t\ttag_regex = r\"[\\w\\*][\\w\\:\\-\\*]*(#|)\"\n\n\t\tfor t in tags:\n\t\t\tif re.fullmatch(tag_regex, t) is None:\n\t\t\t\traise ExifToolTagNameError(t)\n\n\t\t# returns nothing, if no error was raised, the tags passed\n\n\t\t# considering making this...\n\t\t# * can't begin with -\n\t\t# * can't have \"=\" anywhere, and that's it...\n\t\t# there's a lot of variations which might make this code buggy for some edge use cases\n\n\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n"
  },
  {
    "path": "mypy.ini",
    "content": ";[mypy-json.*]\n;ignore_no_redef = True\n"
  },
  {
    "path": "scripts/README.txt",
    "content": "These are standardized scripts/batch files which run tests, code reviews, or other maintenance tasks in a repeatable way.\n\n\nWhile scripts could automatically install requirements, it is left up to the caller:\n\n<script>_requirements.txt files are what extra pip requirements are required to run the <script>\n\n\ninstall with:\n\tpython -m pip install -U -r <requirements file>\n"
  },
  {
    "path": "scripts/flake8.bat",
    "content": "@echo off\n\npushd %~dp0..\n\necho ______________________\necho *** PyExifTool automation ***\necho Flake8 Script\necho;\necho pip's flake8 version\npython.exe -m pip show flake8 | findstr /l /c:\"Version:\"\necho pip's flake8 pep8-naming plugin version\npython.exe -m pip show pep8-naming | findstr /l /c:\"Version:\"\necho flake8 version\npython.exe -m flake8 --version\necho ______________________\n\nREM python.exe -m flake8 -v --config \"%~dp0flake8.ini\" \"exiftool\" \"tests\"\n\npython.exe -m flake8 -v --config \"%~dp0flake8.ini\" --output-file \"%~dp0~flake8_report.txt\" \"exiftool\" \"tests\"\n\npopd\n"
  },
  {
    "path": "scripts/flake8.ini",
    "content": "[flake8]\n;x E302 expected 2 blank lines\n\n\n; E303 too many blank lines\n; E266 too many leading '#' for block comment\n; E501 = error - line too long (* > 79 characters)\n; W191 = warning - indentation contains tabs\n; E301 expected 1 blank line\nignore = E303,E266,E501,W191,E301\n"
  },
  {
    "path": "scripts/flake8_requirements.txt",
    "content": "flake8\n# check for PEP8 Naming Conventions\npep8-naming\n# warnings, not necessarily PEP8, but warn certain things\n# https://github.com/PyCQA/flake8-bugbear\n#flake8-bugbear\n"
  },
  {
    "path": "scripts/mypy.bat",
    "content": "@echo off\n\npushd %~dp0..\n\necho ______________________\necho *** PyExifTool automation ***\necho MyPy Static Analysis Script\necho;\necho pip's MyPy version\npython.exe -m pip show mypy | findstr /l /c:\"Version:\"\necho ______________________\n\npython.exe -m mypy --config-file mypy.ini --strict exiftool/\n\n\npopd\n"
  },
  {
    "path": "scripts/mypy_reqiuirements.txt",
    "content": "mypy\n"
  },
  {
    "path": "scripts/pytest.bat",
    "content": "@echo off\n\npushd %~dp0..\n\necho ______________________\necho *** PyExifTool automation ***\necho PyTest Coverage Script\necho;\necho pip's PyTest version\npython.exe -m pip show pytest | findstr /l /c:\"Version:\"\necho pip's PyTest-cov version\npython.exe -m pip show pytest-cov | findstr /l /c:\"Version:\"\necho ______________________\n\nREM added the --cov= so that it doesn't try to test coverage on the virtualenv directory\nREM add -s to print out stuff from pytest class (don't capture output) -- https://docs.pytest.org/en/latest/how-to/capture-stdout-stderr.html#setting-capturing-methods-or-disabling-capturing\npython.exe -m pytest -v --cov-config=%~dp0windows.coveragerc --cov=exiftool --cov-report term-missing tests/\n\npopd\n"
  },
  {
    "path": "scripts/pytest_requirements.txt",
    "content": "# pytest can run unittest scripts\npytest\n# coverage addon\npytest-cov\n"
  },
  {
    "path": "scripts/sphinx_docs.bat",
    "content": "@echo off\n\nREM script takes ONE optional parameter, which is the path to the Graphviz dot.exe\nREM it is only used if dot.exe does not exist on your PATH\n\nsetlocal\n\npushd %~dp0..\\docs\n\necho ______________________\necho *** PyExifTool automation ***\necho Generate Sphinx Docs\necho;\ncall :PIP_SHOW_VER packaging\ncall :PIP_SHOW_VER sphinx\ncall :PIP_SHOW_VER sphinx-autoapi\ncall :PIP_SHOW_VER sphinx-rtd-theme\ncall :PIP_SHOW_VER sphinx-autodoc-typehints\necho ______________________\n\nREM add some opts, -v = more verbose\nSET SPHINXOPTS=-v\n\necho;\necho ** Searching for Graphviz's dot **\nSET INPUT_DOT=dot.exe\nwhere dot.exe 2>nul\nIF NOT ERRORLEVEL 1 (\n\tREM no need to set more opts\n\tgoto FOUND_DOT\n)\n\n\nREM check %1 to see if a path to dot.exe was provided\nSET INPUT_DOT=%~1\nIF EXIST \"%INPUT_DOT%\" (\n\tSET SPHINXOPTS=%SPHINXOPTS% -D graphviz_dot=\"%INPUT_DOT%\"\n\tgoto FOUND_DOT\n)\n\necho Graphviz's dot.exe was not found.  Either have it on your PATH, or specify with %%1\n\nREM docs still generate without it, but all the graphics are missing, and so it sort of fails silently!\n\nexit /b 1\n\n:FOUND_DOT\n\necho;\necho ** Graphviz dot.exe version **\n%INPUT_DOT% -V\n\n\necho;\necho ** Clean build **\ncall make.bat clean\n\necho;\necho ** Build HTML **\necho ___________________________________________________________________\ncall make.bat html\n\necho ___________________________________________________________________\necho MAKE SURE TO CHECK FOR ANY ERRORS ABOVE!!! Sphinx fails silently!\n\npopd\n\nexit /b %errorlevel%\n\n\nREM -------------------------------------------\n:PIP_SHOW_VER\n\necho pip's %1 version\npython.exe -m pip show %1 | findstr /l /c:\"Version:\"\n\nexit /b 0\n"
  },
  {
    "path": "scripts/unittest.bat",
    "content": "@echo off\n\npushd %~dp0..\n\necho ______________________\necho *** PyExifTool automation ***\necho Python Built-in Unittest Script\necho ______________________\n\npython.exe -m unittest -v\n\npopd\n"
  },
  {
    "path": "scripts/windows.coveragerc",
    "content": "; some exclusions so it doesn't print stuff for Linux, since you can't get that coverage on windows, ever\n; the list of regex is hardcoded to skip things for coverage report\n[report]\nexclude_lines =\n\tpragma: no cover\n\tif constants.PLATFORM_LINUX\n\tdef set_pdeathsig\n\tDEFAULT_EXECUTABLE = \"exiftool\"\n\tpytest-cov:windows: no cover\n[run]\nomit =\n#\texiftool/experimental.py\n"
  },
  {
    "path": "setup.cfg",
    "content": "[metadata]\nversion = attr: exiftool.__version__\n\n[bdist_rpm]\nrequires = exiftool\n"
  },
  {
    "path": "setup.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# This file is part of PyExifTool.\n#\n# PyExifTool <http://github.com/sylikc/pyexiftool>\n#\n# Copyright 2019-2023 Kevin M (sylikc)\n# Copyright 2012-2014 Sven Marnach\n#\n# Community contributors are listed in the CHANGELOG.md for the PRs\n#\n# PyExifTool is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the licence, or\n# (at your option) any later version, or the BSD licence.\n#\n# PyExifTool is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# See COPYING.GPL or COPYING.BSD for more details.\n\n\n# this \"could\" still be used, but not the industry recommended option -- https://stackoverflow.com/questions/25337706/setuptools-vs-distutils-why-is-distutils-still-a-thing\n#from distutils.core import setup\n\n# recommended packager, though must be installed via PyPI\n# https://packaging.python.org/tutorials/packaging-projects/#configuring-metadata\nfrom setuptools import setup, find_packages\n\nimport re\n\ndef get_long_desc():\n\t\"\"\" read README.rst skipping some of the badges (don't need those showing up on PyPI) \"\"\"\n\n\twith open(\"README.rst\", \"r\", encoding=\"utf-8\") as fh:\n\t\tlong_desc = fh.read()\n\n\t# crop out the portion between HIDE_FROM_PYPI_START and HIDE_FROM_PYPI_END\n\tsub_pattern = r\"^\\.\\. HIDE_FROM_PYPI_START.+\\.\\. HIDE_FROM_PYPI_END$\"\n\tlong_desc = re.sub(sub_pattern, \"\", long_desc, flags=re.MULTILINE | re.DOTALL)\n\n\treturn long_desc\n\n\nsetup(\n\t# detailed list of options:\n\t# https://packaging.python.org/guides/distributing-packages-using-setuptools/\n\n\t# overview\n\tname=\"PyExifTool\",\n\t# version is configured in setup.cfg - https://packaging.python.org/en/latest/guides/single-sourcing-package-version/\n\t#version=,\n\tlicense=\"GPLv3+/BSD\",\n\turl=\"http://github.com/sylikc/pyexiftool\",\n\tpython_requires=\">=3.6\",\n\n\t# authors\n\tauthor=\"Kevin M (sylikc), Sven Marnach, various contributors\",\n\tauthor_email=\"sylikc@gmail.com\",\n\n\t# info\n\tdescription=\"Python wrapper for exiftool\",\n\tlong_description=get_long_desc(),\n\tlong_description_content_type=\"text/x-rst\",\n\tkeywords=\"exiftool image exif metadata photo video photography\",\n\n\tproject_urls={\n\t\t# this seems to get populated in PyPI in reverse order\n\t\t\"Source\": \"https://github.com/sylikc/pyexiftool\",\n\t\t\"Tracker\": \"https://github.com/sylikc/pyexiftool/issues\",\n\t\t\"Changelog\": \"https://github.com/sylikc/pyexiftool/blob/master/CHANGELOG.md\",\n\t\t\"Documentation\": \"https://sylikc.github.io/pyexiftool/\",\n\t},\n\n\n\tclassifiers=[\n\t\t# list is here:\n\t\t# https://pypi.org/classifiers/\n\n\t\t\"Development Status :: 4 - Beta\",\n\n\t\t\"Intended Audience :: Developers\",\n\n\t\t\"License :: OSI Approved :: BSD License\",\n\t\t\"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",\n\n\t\t\"Operating System :: OS Independent\",\n\n\t\t\"Programming Language :: Python\",\n\t\t\"Programming Language :: Python :: 3\",\n\t\t\"Programming Language :: Python :: 3 :: Only\",\n\t\t\"Programming Language :: Python :: 3.6\",\n\t\t\"Programming Language :: Python :: 3.7\",\n\t\t\"Programming Language :: Python :: 3.8\",\n\t\t\"Programming Language :: Python :: 3.9\",\n\t\t\"Programming Language :: Python :: 3.10\",\n\t\t\"Programming Language :: Python :: 3.11\",\n\t\t\"Programming Language :: Python :: 3.12\",\n\n\t\t\"Topic :: Multimedia\",\n\t\t\"Topic :: Utilities\",\n\t],\n\n\n\t# include is more robust that exclude\n\tpackages=find_packages(\n\t\t#where=\".\",\n\t\t#exclude = ['test*','doc*'],\n\t\tinclude=['exiftool', 'exiftool.*'],\n\t),\n\n\textras_require={\n\t\t\"json\": [\"ujson\", \"simplejson\", \"orjson\"],  # any supported alternative json parser for ExifTool\n\t\t\"test\": [\"packaging\"],  # dependencies to do tests\n\t\t\"docs\": [\"packaging\", \"sphinx\", \"sphinx-autoapi\", \"sphinx-rtd-theme\", \"sphinx-autodoc-typehints\"],  # dependencies to build docs\n\t},\n\n\t#package_dir={'exiftool': 'exiftool'},\n\n\t#py_modules=[\"exiftool\"], - it is now the exiftool module\n)\n"
  },
  {
    "path": "tests/README.txt",
    "content": "Tests are broken down into separate files to have cleaner imports.\n\nIt's easier to find which tests we're looking at, and may make it easier to run only specific tests and not the whole suite every time\n\n\nThe refactor of the tests layout was primarily to facilitate functionality/features moving between the three classes.\nIt should make it easier to test the functionality in a different class just by changing the declaration in setUp() rather than cut/paste to a different file\n"
  },
  {
    "path": "tests/__init__.py",
    "content": "# Dummy file to make this directory a package.\n"
  },
  {
    "path": "tests/common_util.py",
    "content": "# -*- coding: utf-8 -*-\n\n\"\"\"\nThis file contains some common utility functions which are used by multiple tests\n\nHaving it all in one place makes things easier to fix, and less duplicate code\n\"\"\"\n\nfrom pathlib import Path\nimport tempfile\nimport os\n\nfrom typing import Optional, Tuple, Any\n\n# ---------------------------------------------------------------------------------------------------------\n\n# default is False.  Change here to have all tests persist their output... then change it back to False before committing!\nPERSISTENT_TMP_DIR: bool = False\n\"\"\" if set to ``True``, will not delete temp dir after tests (useful for debugging test output) \"\"\"\n\n\nSCRIPT_PATH = Path(__file__).resolve().parent\n\n# location to images directory\nTEST_IMAGE_DIR = SCRIPT_PATH / \"files\"\n\n\n# Find example image (note: JPG is listed explicitly, as it may have different tags than other file types)\n# listed here in common so that if the path changes, just change it here\nTEST_IMAGE_JPG = TEST_IMAGE_DIR / \"rose.jpg\"\n\n\n# ---------------------------------------------------------------------------------------------------------\n\ndef et_get_temp_dir(suffix: Optional[str] = None, base_path: Optional[Path] = None, persist: Optional[bool] = None) -> Tuple[Optional[Any], Path]:\n\t\"\"\"\n\tsuffix is optional str to append to the temp dir creation.  This is useful to figure out which test created the output folder\n\tbase_path is optional Path to point to the path where the temp dir is to be created.  None=SCRIPT_PATH\n\tpersist is optional bool.  If set to a value, this method will honor that value.  None = use default up above (useful if you're writing a particular test and you only want that one to persist when testing)\n\n\treturns (temp_obj, temp_dir)\n\n\ttemp_obj = Object which needs to be saved somewhere or else the TemporaryDirectory gets garbage collected\n\ttemp_dir = Path() of the temp dir returned\n\t\"\"\"\n\t# Prepare temporary directory for file modifications.\n\tprefix = \"exiftool-tmp-\"\n\n\tkwargs = {\n\t\t\"prefix\": prefix if suffix is None else f\"{prefix}{suffix}-\",\n\t\t\"dir\": SCRIPT_PATH if base_path is None else base_path,\n\t}\n\n\t# if not specified, take default, else take what was given\n\tdo_persist = PERSISTENT_TMP_DIR if persist is None else persist\n\n\t# mkdtemp requires cleanup or else it remains on the system\n\tif do_persist:\n\t\ttemp_obj = None\n\t\ttemp_dir = Path(tempfile.mkdtemp(**kwargs))\n\telse:\n\t\t# have to save the object or else garbage collection cleans it up and dir gets deleted\n\t\t# https://simpleit.rocks/python/test-files-creating-a-temporal-directory-in-python-unittests/\n\t\ttemp_obj = tempfile.TemporaryDirectory(**kwargs)\n\t\ttemp_dir = Path(temp_obj.name)\n\n\treturn (temp_obj, temp_dir)\n\n# ---------------------------------------------------------------------------------------------------------\n\n\ndef create_random_bin_file(filepath: Path, size: int):\n\t\"\"\"\n\tgenerate random binary file with the specified size in bytes\n\n\t:param filename: the filename\n\t:param size: the size in bytes\n\n\t:return: filepath\n\t\"\"\"\n\t# https://www.bswen.com/2018/04/python-How-to-generate-random-large-file-using-python.html\n\n\tif filepath.exists():\n\t\traise FileExistsError\n\n\twith open(filepath, 'wb') as f:\n\t\tf.write(os.urandom(size))\n\n\treturn filepath\n\n# ---------------------------------------------------------------------------------------------------------\n"
  },
  {
    "path": "tests/files/README.txt",
    "content": "This folder contains images/files used in tests.\n\nMore may be added at a later time to test different file formats.\n\nTry to keep the files small (find or create smaller files!)... exiftool is for metdata manipulation, not image data!\n"
  },
  {
    "path": "tests/files/my_makernotes.config",
    "content": "# find sample file here -- https://exiftool.org/config.html\n\n# this file was created from a Phil Harvey example here: https://exiftool.org/forum/index.php?topic=5563.msg26986#msg26986\n\n%Image::ExifTool::UserDefined = (\n\t'Image::ExifTool::Exif::Main' => {\n\t\t0x927c => {\n\t\t\tName => 'MyMakerNotes',\n\t\t\tWritable => 'undef',\n\t\t\tBinary => 1,\n\t\t},\n\t},\n);\n1; # end\n"
  },
  {
    "path": "tests/test_alpha.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifToolAlpha - misc tests\n\"\"\"\n\n# standard\nimport unittest\nfrom pathlib import Path\nimport shutil\n\n# pip\n#from packaging import version\n\n# test helpers\nfrom tests.common_util import et_get_temp_dir, TEST_IMAGE_DIR\n\n# custom\nimport exiftool\n\n\n\n\nclass TestAlphaTagCopying(unittest.TestCase):\n    \"\"\"\n    We duplicate an image with metadata, erase all metadata in the copy, and then copy the tags.\n    \"\"\"\n\n    def setUp(self):\n        # Prepare exiftool\n        self.exiftool = exiftool.ExifToolAlpha(encoding=\"UTF-8\")\n        self.exiftool.run()\n\n        # Find example image.\n        self.tag_source = TEST_IMAGE_DIR / \"rose.jpg\"\n\n        # Prepare path of copy.\n        (self.temp_obj, self.temp_dir) = et_get_temp_dir(suffix=\"ttc\")\n        self.tag_target = self.temp_dir / \"rose-tagcopy.jpg\"\n\n        # Copy image.\n        shutil.copyfile(self.tag_source, self.tag_target)\n\n        # Clear tags in copy.\n        params = [\"-overwrite_original\", \"-all=\", str(self.tag_target)]\n        self.exiftool.execute(*params)\n\n    def tearDown(self):\n        self.exiftool.terminate()  # Apparently, Windows needs this.  CPython bug\n\n    def test_tag_copying(self):\n        tag = \"XMP:Subject\"\n        expected_value = \"Röschen\"\n\n        # Ensure source image has correct tag.\n        original_value = self.exiftool.get_tag(self.tag_source, tag)\n        self.assertEqual(original_value, expected_value)\n\n        # Ensure target image does not already have that tag.\n        value_before_copying = self.exiftool.get_tag(self.tag_target, tag)\n        self.assertNotEqual(value_before_copying, expected_value)\n\n        # Copy tags.\n        self.exiftool.copy_tags(self.tag_source, self.tag_target)\n\n        value_after_copying = self.exiftool.get_tag(self.tag_target, tag)\n        self.assertEqual(value_after_copying, expected_value)\n\n\nclass TestAlphaSetKeywords(unittest.TestCase):\n    def setUp(self):\n        self.et = exiftool.ExifToolAlpha(\n            common_args=[\"-G\", \"-n\", \"-overwrite_original\"],\n            encoding=\"UTF-8\"\n        )\n\n\n    def tearDown(self):\n        self.et.terminate()\n\n\n    def test_set_keywords(self):\n        (temp_obj, temp_dir) = et_get_temp_dir(suffix=\"setkw\")\n\n        kw_to_add = [\"added\"]\n        mod_prefix = \"newkw_\"\n        expected_data = [\n            {\"SourceFile\": Path(\"rose.jpg\"), \"Keywords\": [\"nature\", \"red plant\"]}\n        ]\n        source_files = []\n\n        for d in expected_data:\n            d[\"SourceFile\"] = f = TEST_IMAGE_DIR / d[\"SourceFile\"]\n            self.assertTrue(f.exists())\n            f_mod = temp_dir / (mod_prefix + f.name)\n            f_mod_str = str(f_mod)\n            self.assertFalse(\n                f_mod.exists(),\n                \"%s should not exist before the test. Please delete.\" % f_mod,\n            )\n\n            shutil.copyfile(f, f_mod)\n            source_files.append(f_mod)\n            with self.et:\n                self.et.set_keywords(\n                    f_mod_str, exiftool.experimental.KW_REPLACE, d[\"Keywords\"]\n                )\n                kwtag0 = self.et.get_tag(f_mod_str, \"IPTC:Keywords\")\n                kwrest = d[\"Keywords\"][1:]\n                self.et.set_keywords(f_mod_str, exiftool.experimental.KW_REMOVE, kwrest)\n                kwtag1 = self.et.get_tag(f_mod_str, \"IPTC:Keywords\")\n                self.et.set_keywords(f_mod_str, exiftool.experimental.KW_ADD, kw_to_add)\n                kwtag2 = self.et.get_tag(f_mod_str, \"IPTC:Keywords\")\n            # f_mod.unlink()  # don't delete file, tempdir will take care of it\n            self.assertEqual(kwtag0, d[\"Keywords\"])\n            self.assertEqual(kwtag1, d[\"Keywords\"][0])\n            self.assertEqual(kwtag2, [d[\"Keywords\"][0]] + kw_to_add)\n\n\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "tests/test_exiftool_attr.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifTool base class - misc attribute validation tests\n\"\"\"\n\n# standard\nimport unittest\nfrom pathlib import Path\n\n# test helpers\nfrom tests.common_util import TEST_IMAGE_JPG\n\n# custom\nimport exiftool\nfrom exiftool.exceptions import ExifToolRunning, ExifToolNotRunning\n\n\nclass TestExifToolAttrValidation(unittest.TestCase):\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifTool(common_args=[\"-G\", \"-n\", \"-overwrite_original\"])\n\n\tdef tearDown(self):\n\t\tif self.et.running:\n\t\t\tself.et.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_running_attribute(self):\n\t\t# test if we can read \"running\" but can't set it\n\t\tself.assertFalse(self.et.running)\n\t\twith self.assertRaises(AttributeError):\n\t\t\tself.et.running = True\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_executable_attribute(self):\n\t\t# test if we can read \"running\" but can't set it\n\t\tself.assertFalse(self.et.running)\n\t\tself.et.run()\n\t\tself.assertTrue(self.et.running)\n\n\t\t# if it's running, the executable has to exist (test coverage on reading the property)\n\t\te = self.et.executable\n\t\tself.assertTrue(Path(e).exists())\n\n\t\twith self.assertRaises(ExifToolRunning):\n\t\t\tself.et.executable = \"foo.bar\"\n\t\tself.et.terminate()\n\n\t\twith self.assertRaises(FileNotFoundError):\n\t\t\tself.et.executable = \"foo.bar\"\n\n\t\t# specify the executable explicitly with the one known to exist (test coverage)\n\t\tself.et.executable = e\n\t\tself.assertEqual(self.et.executable, e)  # absolute path set should not change\n\n\t\tself.assertFalse(self.et.running)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_blocksize_attribute(self):\n\t\tcurrent = self.et.block_size\n\n\t\t# arbitrary\n\t\tself.et.block_size = 4\n\t\tself.assertEqual(self.et.block_size, 4)\n\n\t\twith self.assertRaises(ValueError):\n\t\t\tself.et.block_size = -1\n\n\t\twith self.assertRaises(ValueError):\n\t\t\tself.et.block_size = 0\n\n\t\t# restore\n\t\tself.et.block_size = current\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_encoding_attribute(self):\n\t\tcurrent = self.et.encoding\n\n\t\tself.et.run()\n\n\t\t# cannot set when running\n\t\twith self.assertRaises(ExifToolRunning):\n\t\t\tself.et.encoding = \"foo.bar\"\n\t\tself.et.terminate()\n\n\t\tself.et.encoding = \"foo\"\n\t\tself.assertEqual(self.et.encoding, \"foo\")\n\n\t\t# restore\n\t\tself.et.encoding = current\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_common_args_attribute(self):\n\n\t\tself.et.run()\n\t\twith self.assertRaises(ExifToolRunning):\n\t\t\tself.et.common_args = []\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_version_attribute(self):\n\t\tself.et.run()\n\t\t# no error\n\t\ta = self.et.version\n\n\t\tself.et.terminate()\n\n\t\t# version is invalid when not running\n\t\twith self.assertRaises(ExifToolNotRunning):\n\t\t\ta = self.et.version\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_laststdout_attr(self):\n\t\t\"\"\" is the attribute available after a run? \"\"\"\n\t\tself.et.run()\n\n\t\tstdo = self.et.execute(str(TEST_IMAGE_JPG))\n\t\tstde = self.et.last_stderr\n\n\t\tself.et.terminate()\n\n\t\tself.assertFalse(self.et.running)\n\n\t\tself.assertEqual(self.et.last_stdout, stdo)\n\t\tself.assertEqual(self.et.last_stderr, stde)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_exiftool_bytes.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifTool base class - execute() using raw_bytes parameter\n\"\"\"\n\n# standard\nimport unittest\nimport shutil\n\n# test helpers\nfrom tests.common_util import et_get_temp_dir, TEST_IMAGE_DIR, TEST_IMAGE_JPG, create_random_bin_file\n\n# custom\nimport exiftool\n\nclass TestExifToolBytes(unittest.TestCase):\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifTool(common_args=[\"-G\", \"-n\", \"-overwrite_original\"], config_file=TEST_IMAGE_DIR / \"my_makernotes.config\")\n\n\t\t(self.temp_obj, self.temp_dir) = et_get_temp_dir(suffix=\"etbytes\")\n\n\tdef tearDown(self):\n\t\tif self.et.running:\n\t\t\tself.et.terminate()\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\tdef test_read_write_binary(self):\n\t\t\"\"\" test reading and writing binary data \"\"\"\n\t\tself.assertFalse(self.et.running)\n\t\tself.et.run()\n\n\t\t### set up files ###\n\n\t\t# write a binary file to test with ... we can make it random or the same, shouldn't matter\n\t\tBIN_FILE_SIZE = 1024\n\n\t\tp_bin_file = self.temp_dir / \"test_data.bin\"\n\t\tcreate_random_bin_file(p_bin_file, BIN_FILE_SIZE)\n\n\t\tp_jpg_file = self.temp_dir / \"rose.jpg\"\n\t\tshutil.copyfile(TEST_IMAGE_JPG, p_jpg_file)\n\n\t\t### write the binary data ###\n\t\tself.et.execute(f\"-MyMakerNotes<={p_bin_file}\", str(p_jpg_file))\n\t\tself.assertEqual(self.et.last_status, 0)\n\n\t\t### read the binary data and compare ###\n\t\twith open(p_bin_file, 'rb') as f:\n\t\t\tbin_file_data = f.read()\n\n\t\t# make sure it's the right amount of bytes wrote in originally\n\t\tself.assertEqual(len(bin_file_data), BIN_FILE_SIZE)\n\n\t\t# get the custom tag\n\t\twritten_bin_data = self.et.execute(\"-b\", \"-MyMakerNotes\", str(p_jpg_file), raw_bytes=True)\n\n\t\t# check that they are equal\n\t\tself.assertEqual(bin_file_data, written_bin_data)\n\n\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_exiftool_configfile.py",
    "content": "\"\"\"\nTest :: ExifTool base class - config_file attribute\n\"\"\"\n# standard\nimport unittest\n\n# test helpers\nfrom tests.common_util import et_get_temp_dir\n\n# custom\nimport exiftool\nfrom exiftool.exceptions import ExifToolRunning\n\n\n\n\nclass TestExifToolConfigFile(unittest.TestCase):\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifTool(common_args=[\"-G\", \"-n\", \"-overwrite_original\"])\n\n\tdef tearDown(self):\n\t\tif self.et.running:\n\t\t\tself.et.terminate()\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\tdef test_configfile_attribute(self):\n\t\tcurrent = self.et.config_file\n\n\t\twith self.assertRaises(FileNotFoundError):\n\t\t\tself.et.config_file = \"foo.bar\"\n\n\t\t# see if Python 3.9.5 fixed this ... raises OSError right now and is a pathlib glitch https://bugs.python.org/issue35306\n\t\t#self.et.config_file = \"\\\"C:\\\\\\\"\\\"C:\\\\\"\n\n\t\t# then restore current config_file\n\t\tself.et.config_file = current\n\n\t\tself.assertFalse(self.et.running)\n\t\tself.et.run()\n\t\tself.assertTrue(self.et.running)\n\n\t\twith self.assertRaises(ExifToolRunning):\n\t\t\tself.et.config_file = None\n\n\t\tself.et.terminate()\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_configfile_set(self):\n\t\t(temp_obj, temp_dir) = et_get_temp_dir(suffix=\"config\")\n\n\t\t# set config file to empty, which is valid (should not throw error)\n\t\tself.et.config_file = \"\"\n\n\t\t# create a config file, and set it and test that it works\n\t\t# a file that returns 1 is valid as a config file\n\t\ttmp_config_file = temp_dir / \"config_test.txt\"\n\t\twith open(tmp_config_file, 'w') as f:\n\t\t\tf.write(\"1;\\n\")\n\n\t\tself.et.config_file = tmp_config_file\n\n\t\tself.et.run()\n\t\tself.assertTrue(self.et.running)\n\n\t\tself.et.terminate()\n\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_exiftool_logger.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifTool base class - logger tests\n\"\"\"\n\n# standard\nimport unittest\nimport logging\n\n# custom\nimport exiftool\n\n\n\nclass TestExifToolLogger(unittest.TestCase):\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifTool(common_args=[\"-G\", \"-n\", \"-overwrite_original\"])\n\n\tdef tearDown(self):\n\t\tif self.et.running:\n\t\t\tself.et.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_logger(self):\n\t\t\"\"\" TODO improve this test, currently very rudimentary \"\"\"\n\t\tlog = logging.getLogger(\"log_test\")\n\t\t#log.level = logging.WARNING\n\n\t\t#logpath = TMP_DIR / 'exiftool_test.log'\n\t\t#fh = logging.FileHandler(logpath)\n\n\t\t#log.addHandler(fh)\n\n\t\tself.et.logger = log\n\t\t# no errors\n\n\t\tlog = \"bad log\" # not a logger object\n\t\twith self.assertRaises(TypeError):\n\t\t\tself.et.logger = log\n\n\t\tself.et.run()  # get some coverage by doing stuff\n\n\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_exiftool_misc.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifTool base class - misc tests\n\"\"\"\n\n# standard\nimport unittest\nimport warnings\nfrom pathlib import Path\n\n# test helpers\nfrom tests.common_util import TEST_IMAGE_JPG\n\n# custom\nimport exiftool\nfrom exiftool.exceptions import ExifToolNotRunning\n\n\nclass TestExifToolMisc(unittest.TestCase):\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifTool(common_args=[\"-G\", \"-n\", \"-overwrite_original\"])\n\n\tdef tearDown(self):\n\t\tif self.et.running:\n\t\t\tself.et.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_get_version_protected(self):\n\t\t\"\"\" test the protected method which can't be called when exiftool not running \"\"\"\n\t\tself.assertFalse(self.et.running)\n\t\tself.assertRaises(ExifToolNotRunning, self.et._parse_ver)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_invalid_args_list(self):\n\t\t# test to make sure passing in an invalid args list will cause it to error out\n\t\twith self.assertRaises(TypeError):\n\t\t\texiftool.ExifTool(common_args=\"not a list\")\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_common_args(self):\n\t\t# test to make sure passing in an invalid args list will cause it to error out\n\t\twith self.assertRaises(TypeError):\n\t\t\texiftool.ExifTool(common_args={})\n\n\t\t# set to common_args=None == []\n\t\tself.assertEqual(exiftool.ExifTool(common_args=None).common_args, [])\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_run_twice(self):\n\t\t\"\"\" test that a UserWarning is thrown when run() is called twice \"\"\"\n\t\tself.assertFalse(self.et.running)\n\t\tself.et.run()\n\n\t\twith warnings.catch_warnings(record=True) as w:\n\t\t\tself.assertTrue(self.et.running)\n\t\t\tself.et.run()\n\t\t\tself.assertEqual(len(w), 1)\n\t\t\tself.assertTrue(issubclass(w[0].category, UserWarning))\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_execute_types(self):\n\t\t\"\"\" test execute with different types \"\"\"\n\t\tself.assertFalse(self.et.running)\n\t\tself.et.run()\n\n\t\t# no error with str\n\t\tself.et.execute(\"-ver\")\n\n\t\t# no error with bytes\n\t\tself.et.execute(b\"-ver\")\n\n\t\t# no error with str\n\t\tself.et.execute(str(TEST_IMAGE_JPG))\n\n\t\t# error with Path\n\t\twith self.assertRaises(TypeError):\n\t\t\tself.et.execute(Path(TEST_IMAGE_JPG))\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\n\n\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_exiftool_process.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifTool base class - process-related tests\n\"\"\"\n\n# standard\nimport unittest\nimport warnings\n\n# custom\nimport exiftool\nfrom exiftool.exceptions import ExifToolNotRunning\n\n\n# bool which is set to True when running on Windows\n# used below to workaround a Windows buggy interaction with exiftool subprocess\nfrom exiftool.constants import PLATFORM_WINDOWS\n\n\nclass TestExifToolProcess(unittest.TestCase):\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifTool(common_args=[\"-G\", \"-n\", \"-overwrite_original\"])\n\n\tdef tearDown(self):\n\t\tif hasattr(self, \"et\"):\n\t\t\tif self.et.running:\n\t\t\t\tself.et.terminate()\n\t\tif hasattr(self, \"process\"):\n\t\t\tif self.process.poll() is None:\n\t\t\t\tself.process.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_termination_cm(self):\n\t\t# Test correct subprocess start and termination when using\n\t\t# self.et as a context manager\n\t\tself.assertFalse(self.et.running)\n\t\tself.assertRaises(ExifToolNotRunning, self.et.execute)\n\t\twith self.et:\n\t\t\tself.assertTrue(self.et.running)\n\t\t\twith warnings.catch_warnings(record=True) as w:\n\t\t\t\tself.et.run()\n\t\t\t\tself.assertEqual(len(w), 1)\n\t\t\t\tself.assertTrue(issubclass(w[0].category, UserWarning))\n\t\t\tself.process = self.et._process\n\t\t\tself.assertEqual(self.process.poll(), None)\n\t\tself.assertFalse(self.et.running)\n\t\tself.assertNotEqual(self.process.poll(), None)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_termination_explicit(self):\n\t\t# Test correct subprocess start and termination when\n\t\t# explicitly using start() and terminate()\n\t\tself.et.run()\n\t\tself.process = self.et._process\n\t\tself.assertEqual(self.process.poll(), None)\n\t\tself.et.terminate()\n\t\tself.assertNotEqual(self.process.poll(), None)\n\n\t\t# terminate when not running\n\t\twith warnings.catch_warnings(record=True) as w:\n\t\t\tself.et.terminate()\n\t\t\tself.assertEqual(len(w), 1)\n\t\t\tself.assertTrue(issubclass(w[0].category, UserWarning))\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_process_died_running_status(self):\n\t\t\"\"\" Test correct .running status if process dies by itself \"\"\"\n\n\t\t# There is a very weird bug triggered on WINDOWS only which I've described here: https://exiftool.org/forum/index.php?topic=12472.0\n\t\t# it happens specifically when you forcefully kill the process, but at least one command has run since launching, the exiftool wrapper on windows does not terminate the child process\n\t\t# it's a very strange interaction and causes a zombie process to remain, and python hangs\n\t\t#\n\t\t# either kill the tree with psutil, or do it this way...\n\n\t\t# WINDOWS WORKAROUND: take out the method that is called on load (probably not the way to do this well... you can take out this line and watch Python interpreter hang at .kill() below\n\t\tif PLATFORM_WINDOWS:\n\t\t\tself.et._parse_ver = lambda: None\n\n\n\t\tself.et.run()\n\t\tself.process = self.et._process\n\t\tself.assertTrue(self.et.running)\n\n\t\t# kill the process, out of ExifTool's control\n\t\tself.process.kill()\n\t\t# TODO freeze here on windows if there is a zombie process b/c killing immediate exiftool does not kill the spawned subprocess\n\t\touts, errs = self.process.communicate()\n\n\t\twith warnings.catch_warnings(record=True) as w:\n\t\t\tself.assertFalse(self.et.running)\n\t\t\tself.assertEqual(len(w), 1)\n\t\t\tself.assertTrue(issubclass(w[0].category, UserWarning))\n\n\t\t# after removing that function, delete the object so it gets recreated cleanly\n\t\tdel self.et\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_termination_implicit(self):\n\t\t# Test implicit process termination on garbage collection\n\n\t\t# WINDOWS WORKAROUND: take out the method that is called on load (see test_process_died_running_status())\n\t\tif PLATFORM_WINDOWS:\n\t\t\tself.et._parse_ver = lambda: None\n\n\t\tself.et.run()\n\t\tself.process = self.et._process\n\t\t# TODO freze here on windows for same reason as in test_process_died_running_status() as a zombie process remains\n\t\tdel self.et\n\t\tself.assertNotEqual(self.process.poll(), None)\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_helper_checkexecute.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifToolHelper - misc tests\n\"\"\"\n\n# standard\nimport unittest\n\n# test helpers\nfrom tests.common_util import et_get_temp_dir, TEST_IMAGE_JPG\n\n# custom\nimport exiftool\nfrom exiftool.exceptions import ExifToolOutputEmptyError, ExifToolJSONInvalidError, ExifToolExecuteError\n\n\nclass TestHelperCheckExecute(unittest.TestCase):\n\t@classmethod\n\tdef setUp(self) -> None:\n\t\tself.eth = exiftool.ExifToolHelper(common_args=['-G', '-n', '-overwrite_original'])\n\t\tself.eth.run()\n\n\tdef tearDown(self):\n\t\tself.eth.terminate()\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_read_all_from_nonexistent_file_no_checkexecute(self):\n\t\t\"\"\"\n\t\t`get_metadata`/`get_tags` raises an error if None comes back from execute_json()\n\n\t\tExifToolHelper DOES NOT check each individual file in the list for existence.  If you pass invalid files to exiftool, undefined behavior can occur\n\t\t\"\"\"\n\t\tself.eth.check_execute = False\n\n\t\twith self.assertRaises(ExifToolOutputEmptyError):\n\t\t\tself.eth.get_metadata(['foo.bar'])\n\n\t\twith self.assertRaises(ExifToolOutputEmptyError):\n\t\t\tself.eth.get_tags('foo.bar', 'DateTimeOriginal')\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\tdef test_read_all_from_nonexistent_file_yes_checkexecute(self):\n\t\t# run above test again with check_execute = True\n\n\t\tself.eth.check_execute = True\n\n\t\twith self.assertRaises(ExifToolExecuteError):\n\t\t\tself.eth.get_metadata(['foo.bar'])\n\n\t\twith self.assertRaises(ExifToolExecuteError):\n\t\t\tself.eth.get_tags('foo.bar', 'DateTimeOriginal')\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\tdef test_w_flag(self):\n\t\t\"\"\"\n\t\ttest passing a -w flag to write some output\n\t\t\"\"\"\n\t\t(temp_obj, temp_dir) = et_get_temp_dir(suffix=\"wflag\")\n\n\t\twith self.assertRaises(ExifToolJSONInvalidError):\n\t\t\tself.eth.get_metadata(TEST_IMAGE_JPG, params=[\"-w\", f\"{temp_dir}/%f.txt\"])\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_helper_checktagnames.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifToolHelper - tag name validation tests\n\"\"\"\n\n# standard\nimport unittest\nimport shutil\n\n# test helpers\nfrom tests.common_util import et_get_temp_dir\nfrom tests.common_util import TEST_IMAGE_JPG\n\n# custom\nimport exiftool\nfrom exiftool.exceptions import ExifToolOutputEmptyError, ExifToolTagNameError\n\n\n\nclass TagNameReadTest(unittest.TestCase):\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifToolHelper(common_args=[\"-G\", \"-n\", \"-overwrite_original\"])\n\n\tdef tearDown(self):\n\t\tself.et.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_check_tag_names(self):\n\t\t\"\"\" simple read test for tag names \"\"\"\n\n\t\twith self.assertRaises(ExifToolTagNameError):\n\t\t\tself.et.get_tags(TEST_IMAGE_JPG, \"-Comment\")\n\n\t\tself.et.get_tags(TEST_IMAGE_JPG, \"Comment#\")\n\n\t\twith self.assertRaises(ExifToolTagNameError):\n\t\t\tself.et.get_tags(TEST_IMAGE_JPG, \"Com#ment\")\n\n\t\t# valid tags\n\t\tself.et.get_tags(TEST_IMAGE_JPG, \"test:tag\")\n\t\tself.et.get_tags(TEST_IMAGE_JPG, \"*date*\")\n\n\t\t# non-sensical, but even exiftool lets these slide with no errors\n\t\tself.et.get_tags(TEST_IMAGE_JPG, \"C-o:m:m:ent#\")\n\t\tself.et.get_tags(TEST_IMAGE_JPG, \"Comment-\")\n\t\tself.et.get_tags(TEST_IMAGE_JPG, \"test:-tag\")\n\t\tself.et.get_tags(TEST_IMAGE_JPG, \"t-e-st:-tag---\")\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\n\n\nclass TagNameWriteTest(unittest.TestCase):\n\t\"\"\" these tests are to ensure the robustness of the check_tag_names feature \"\"\"\n\n\t@classmethod\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifToolHelper(\n\t\t\tcommon_args=[\"-G\", \"-n\", \"-overwrite_original\"], encoding=\"UTF-8\"\n\t\t)\n\n\t\t# standardize, all these need the example file copied to a temp directory\n\t\t(self.temp_obj, self.temp_dir) = et_get_temp_dir(suffix=\"tagname\")\n\n\t\tself.test_file = self.temp_dir / \"test_rose.jpg\"\n\n\t\tshutil.copyfile(TEST_IMAGE_JPG, self.test_file)\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\tdef test_write_comment(self):\n\n\t\ttest_file = self.test_file\n\t\tmy_tag = \"File:Comment\"\n\t\tmy_comment = \"foo.bar/comment\"\n\t\tbad_comment = \"lorem ipsum\"\n\n\t\tself.et.set_tags(test_file, {my_tag: my_comment})\n\n\t\tself.assertEqual(my_comment, self.et.get_tags(test_file, my_tag)[0][my_tag])\n\n\t\tself.assertTrue(self.et.check_tag_names)\n\t\twith self.assertRaises(ExifToolTagNameError):\n\t\t\t# this was what the flag was meant to prevent\n\t\t\tself.et.get_tags(test_file, f\"Comment={bad_comment}\")\n\n\t\tself.assertEqual(my_comment, self.et.get_tags(test_file, my_tag)[0][my_tag])\n\n\n\t\t# turn off that tag check (this is what you DON'T WANT to happen)\n\t\tself.et.check_tag_names = False\n\t\tself.assertFalse(self.et.check_tag_names)\n\t\twith self.assertRaises(ExifToolOutputEmptyError):\n\t\t\tself.et.get_tags(test_file, f\"Comment={bad_comment}\")\n\t\tself.assertEqual(bad_comment, self.et.get_tags(test_file, my_tag)[0][my_tag])\n\n\n\t\tself.et.check_tag_names = True\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\tdef test_tag_name_hyphen(self):\n\t\t\"\"\" this is cited on some examples on exiftool's documentation\n\n\t\tthis example also demonstrates how what you ask for as a tag isn't what you get back sometimes... the tag comes back in the case that's defined inside exiftool\n\t\t\"\"\"\n\n\t\ttest_file = self.test_file\n\t\tmy_tag = \"xmp:description-de\"\n\t\tmy_value = \"k&uuml;hl\"\n\n\t\t# note how what you asked for isn't always what you get\n\t\tmy_tag_case = \"XMP:Description-de\"\n\t\tmy_utf8 = \"kühl\"\n\n\t\tself.et.set_tags(test_file, {my_tag: my_value}, params=\"-E\")\n\n\t\tself.assertEqual(my_utf8, self.et.get_tags(test_file, my_tag)[0][my_tag_case])\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_helper_gettags.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifToolHelper - get_metadata/get_tags tests\n\"\"\"\n\n# standard\nimport unittest\nfrom pathlib import Path\n\n# pip\nfrom packaging import version\n\n# test helpers\nfrom tests.common_util import TEST_IMAGE_DIR, TEST_IMAGE_JPG\n\n# custom\nimport exiftool\nfrom exiftool.exceptions import ExifToolExecuteError\n\n\n\nclass TestHelperGetTags(unittest.TestCase):\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifToolHelper(common_args=[\"-G\", \"-n\", \"-overwrite_original\"])\n\n\tdef tearDown(self):\n\t\tself.et.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_get_tags_no_files(self):\n\t\t\"\"\"\n\t\t`get_metadata`/`get_tags` should return an error when no files specified.\n\t\t\"\"\"\n\n\t\twith self.assertRaises(ValueError):\n\t\t\t# files can't be None\n\t\t\tself.et.get_tags(None, None)\n\t\t\tself.et.get_tags([], None)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_invalid_tags_arg(self):\n\t\twith self.assertRaises(TypeError):\n\t\t\tself.et.get_tags(TEST_IMAGE_JPG, object())\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_get_tags_params(self):\n\t\t\"\"\" test params argument \"\"\"\n\t\t# lots of metadata on the file\n\t\tfull_metadata = self.et.get_metadata(TEST_IMAGE_JPG)[0]\n\n\t\t# use params to get tag (basically using params to specify a tag)\n\t\tparam_metadata = self.et.get_metadata(TEST_IMAGE_JPG, params=\"-XMPToolkit\")[0]\n\n\t\t# the list should be significantly smaller\n\t\tself.assertGreater(len(full_metadata), len(param_metadata))\n\n\n\t\tparam_metadata = self.et.get_metadata(TEST_IMAGE_JPG, params=[\"-XMPToolkit\"])[0]\n\t\tself.assertGreater(len(full_metadata), len(param_metadata))\n\n\n\t\t# this class is an arbitrary object that returns a string\n\t\tclass TestClass(object):\n\t\t\tdef __str__(self):\n\t\t\t\treturn \"-n\"\n\n\t\t# this is now permitted, params can be anything castable\n\t\tself.et.get_metadata(TEST_IMAGE_JPG, params=TestClass())\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_get_metadata_file_mixed_existence(self):\n\t\t\"\"\"\n\t\tthis tests for errors behavior when some files exist, and others don't\n\n\t\tthis is less of a test for the class itself but expected exit status interaction with exiftool\n\t\t\"\"\"\n\t\t# expected no error\n\t\tself.et.get_metadata(TEST_IMAGE_JPG)\n\n\t\tself.et.check_execute = False\n\t\t# expected no error\n\t\tself.et.get_metadata([TEST_IMAGE_JPG, \"foo.bar\"])\n\n\t\t# running same command with check_execute enabled\n\t\tself.et.check_execute = True\n\t\twith self.assertRaises(ExifToolExecuteError):\n\t\t\tself.et.get_metadata([TEST_IMAGE_JPG, \"foo.bar\"])\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_get_metadata(self):\n\t\t\"\"\"\n\t\ttest that a read is returning expected data\n\t\t\"\"\"\n\t\texpected_data = [\n\t\t\t{\n\t\t\t\t\"SourceFile\": \"rose.jpg\",\n\t\t\t\t\"File:FileType\": \"JPEG\",\n\t\t\t\t\"File:ImageWidth\": 70,\n\t\t\t\t\"File:ImageHeight\": 46,\n\t\t\t\t\"XMP:Subject\": \"Röschen\",\n\t\t\t\t\"Composite:ImageSize\": \"70 46\",\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"SourceFile\": \"skyblue.png\",\n\t\t\t\t\"File:FileType\": \"PNG\",\n\t\t\t\t\"PNG:ImageWidth\": 64,\n\t\t\t\t\"PNG:ImageHeight\": 64,\n\t\t\t\t\"Composite:ImageSize\": \"64 64\",\n\t\t\t},\n\t\t]\n\t\tsource_files = []\n\n\t\t# encoding required for this to pass is UTF-8, that's because the compared strings are encoded in UTF-8 (this file is UTF-8)\n\t\tself.et.encoding = 'UTF-8'\n\n\t\tfor d in expected_data:\n\t\t\td[\"SourceFile\"] = f = TEST_IMAGE_DIR / d[\"SourceFile\"]\n\t\t\tself.assertTrue(f.exists())\n\t\t\tsource_files.append(f)\n\n\t\twith self.et:\n\t\t\tactual_data = self.et.get_metadata(source_files)\n\t\t\ttags0 = self.et.get_tags(source_files[0], [\"XMP:Subject\"])[0]\n\t\t\t#tag0 = self.et.get_tag(source_files[0], \"XMP:Subject\")\n\n\t\trequired_version = version.parse(\"8.40\")\n\t\tfor expected, actual in zip(expected_data, actual_data):\n\t\t\tactual_version = version.parse(str(actual[\"ExifTool:ExifToolVersion\"]))\n\t\t\tself.assertGreaterEqual(actual_version, required_version)\n\t\t\tactual[\"SourceFile\"] = Path(actual[\"SourceFile\"]).resolve()\n\t\t\tfor k, v in expected.items():\n\t\t\t\tself.assertEqual(actual[k], v)\n\n\t\ttags0[\"SourceFile\"] = Path(tags0[\"SourceFile\"]).resolve()\n\t\tself.assertEqual(\n\t\t\ttags0, dict((k, expected_data[0][k]) for k in [\"SourceFile\", \"XMP:Subject\"])\n\t\t)\n\t\t#self.assertEqual(tag0, expected_data[0][\"XMP:Subject\"])\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_helper_misc.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifToolHelper - misc tests\n\"\"\"\n\n# standard\nimport unittest\nfrom pathlib import Path\n\n# test helpers\nfrom tests.common_util import TEST_IMAGE_JPG\n\n# custom\nimport exiftool\n\n\nclass HelperInitializationTest(unittest.TestCase):\n\tdef test_initialization(self):\n\t\t\"\"\"\n\t\tInitialization with all arguments at their default values.\n\n\t\tthis is to test that the constructor passes the right values to the base class (ensure that the class inheritence working as expected even if underlying base class parameters change)\n\t\t\"\"\"\n\t\texif_tool_helper = exiftool.ExifToolHelper()\n\t\texif_tool_helper.run()\n\n\t\tself.assertTrue(exif_tool_helper.running)\n\t\texif_tool_helper.terminate()\n\t\tself.assertFalse(exif_tool_helper.running)\n\n\n# ---------------------------------------------------------------------------------------------------------\n\nclass TestExifToolHelperMisc(unittest.TestCase):\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifToolHelper(common_args=[\"-G\", \"-n\", \"-overwrite_original\"])\n\n\tdef tearDown(self):\n\t\tif self.et.running:\n\t\t\tself.et.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_execute_types(self):\n\t\t\"\"\" test execute with different types (exact same as the test with ExifTool, except the last one passes) \"\"\"\n\t\tself.assertFalse(self.et.running)\n\n\t\t# no error with str\n\t\tself.et.execute(\"-ver\")\n\n\t\t# no error with bytes\n\t\tself.et.execute(b\"-ver\")\n\n\t\t# no error with str\n\t\tself.et.execute(str(TEST_IMAGE_JPG))\n\n\t\t# error with Path\n\t\tself.et.execute(Path(TEST_IMAGE_JPG))\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_helper_run.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifToolHelper - Helper's start/run wrappers tests\n\"\"\"\n\n# standard\nimport unittest\n\n# test helpers\nfrom tests.common_util import TEST_IMAGE_JPG\n\n# custom\nimport exiftool\nfrom exiftool.exceptions import ExifToolNotRunning\n\n\n\n\nclass TestHelperRunWrappers(unittest.TestCase):\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifToolHelper(common_args=[\"-G\", \"-n\", \"-overwrite_original\"])\n\n\tdef tearDown(self):\n\t\tself.et.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_run(self):\n\t\t# no warnings when terminating when not running\n\t\tself.assertFalse(self.et.running)\n\t\tself.et.run()\n\t\tself.assertTrue(self.et.running)\n\t\tself.et.run()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_terminate(self):\n\t\t# no warnings when terminating when not running\n\t\tself.assertFalse(self.et.running)\n\t\tself.et.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_auto_start(self):\n\n\t\t# test that a RuntimeError gets thrown if auto_start is false\n\t\tself.et = exiftool.ExifToolHelper(auto_start=False)\n\t\tself.assertFalse(self.et.auto_start)\n\t\twith self.assertRaises(ExifToolNotRunning):\n\t\t\tself.et.get_metadata(TEST_IMAGE_JPG)\n\n\t\t# test that no errors returned if auto_start=True\n\t\tself.et = exiftool.ExifToolHelper(auto_start=True)\n\t\tself.assertTrue(self.et.auto_start)\n\t\tmetadata = self.et.get_metadata(TEST_IMAGE_JPG)\n\t\tself.assertEqual(type(metadata), list)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_helper_settags.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifToolHelper - set_tags tests\n\"\"\"\n\n# standard\nimport unittest\nimport shutil\n\n# test helpers\nfrom tests.common_util import et_get_temp_dir, TEST_IMAGE_DIR, TEST_IMAGE_JPG\n\n# custom\nimport exiftool\nfrom exiftool.exceptions import ExifToolExecuteError\n\n\n\nclass TestHelperSetTags(unittest.TestCase):\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifToolHelper(\n\t\t\tcommon_args=[\"-G\", \"-n\", \"-overwrite_original\"],\n\t\t\tencoding=\"UTF-8\"\n\t\t)\n\n\tdef tearDown(self):\n\t\tself.et.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_set_tags(self):\n\t\t(temp_obj, temp_dir) = et_get_temp_dir(suffix=\"settag\")\n\n\t\tmod_prefix = \"newcap_\"\n\t\texpected_data = [\n\t\t\t{\n\t\t\t\t\"SourceFile\": \"rose.jpg\",\n\t\t\t\t\"Caption-Abstract\": \"Ein Röschen ganz allein\",\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"SourceFile\": \"skyblue.png\",\n\t\t\t\t\"Caption-Abstract\": \"Blauer Himmel\"\n\t\t\t},\n\t\t]\n\t\tsource_files = []\n\n\t\tfor d in expected_data:\n\t\t\td[\"SourceFile\"] = f = TEST_IMAGE_DIR / d[\"SourceFile\"]\n\t\t\tself.assertTrue(f.exists())\n\n\t\t\tf_mod = temp_dir / (mod_prefix + f.name)\n\n\t\t\tself.assertFalse(\n\t\t\t\tf_mod.exists(),\n\t\t\t\tf\"{f_mod} should not exist before the test. Please delete.\",\n\t\t\t)\n\n\t\t\tshutil.copyfile(f, f_mod)\n\t\t\tsource_files.append(f_mod)\n\t\t\twith self.et:\n\t\t\t\tself.et.set_tags([f_mod], {\"Caption-Abstract\": d[\"Caption-Abstract\"]})\n\t\t\t\tresult = self.et.get_tags([f_mod], \"IPTC:Caption-Abstract\")[0]\n\t\t\t\ttag0 = list(result.values())[1]\n\t\t\t#f_mod.unlink()  # don't delete file, tempdir will take care of it\n\t\t\tself.assertEqual(tag0, d[\"Caption-Abstract\"])\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_set_tags_file_existence(self):\n\t\t\"\"\" test setting tags on a non-existent file \"\"\"\n\t\t(temp_obj, temp_dir) = et_get_temp_dir(suffix=\"settagfe\")\n\n\t\tself.assertTrue(self.et.check_execute)\n\n\t\tjunk_tag = {\"not_a_valid_tag_foo_bar\": \"lorem ipsum\"}\n\n\t\t# set up temp working file\n\t\tmod_prefix = \"test_\"\n\t\tf = TEST_IMAGE_DIR / \"rose.jpg\"\n\t\tf_mod = temp_dir / (mod_prefix + f.name)\n\t\tself.assertTrue(f.exists())\n\t\tself.assertFalse(f_mod.exists())\n\t\tshutil.copyfile(f, f_mod)\n\n\n\t\tself.et.check_execute = False\n\n\t\t# no errors (aka exiftool fails silently, even though file doesn't exist)\n\t\tself.et.set_tags(\"foo.bar\", junk_tag)\n\n\t\t# no errors (aka exiftool fails silently, even though it can't set this tag)\n\t\tself.et.set_tags(f_mod, junk_tag)\n\n\n\n\t\tself.et.check_execute = True\n\n\t\t# proper error handling, should raise error\n\t\twith self.assertRaises(ExifToolExecuteError):\n\t\t\tself.et.set_tags(\"foo.bar\", junk_tag)\n\n\n\t\t# proper error handling, should also raise error\n\t\twith self.assertRaises(ExifToolExecuteError):\n\t\t\tself.et.set_tags(f_mod, junk_tag)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_set_tags_files_invalid(self):\n\t\t\"\"\" test to cover the files == None \"\"\"\n\n\t\twith self.assertRaises(ValueError):\n\t\t\tself.et.set_tags(None, [])\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_set_tags_tags_invalid(self):\n\t\t\"\"\" test to cover the files == None \"\"\"\n\n\t\twith self.assertRaises(ValueError):\n\t\t\tself.et.set_tags(\"rose.jpg\", None)\n\n\n\t\twith self.assertRaises(TypeError):\n\t\t\tself.et.set_tags(\"rose.jpg\", object())\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_set_tags_list_keywords(self):\n\t\t\"\"\"\n\t\ttest that covers setting keywords in set_tags() using a list (not using the ExifToolAlpha's keywords functionality directly)\n\t\t\"\"\"\n\t\t(temp_obj, temp_dir) = et_get_temp_dir(suffix=\"settagkw\")\n\n\t\tmod_prefix = \"newkw_\"\n\t\texpected_data = [{\"SourceFile\": \"rose.jpg\",\n\t\t\t\t\t\t  \"Keywords\": [\"nature\", \"red plant\", \"flower\"]}]\n\t\tsource_files = []\n\n\t\tfor d in expected_data:\n\t\t\tf = TEST_IMAGE_DIR / d[\"SourceFile\"]\n\t\t\tself.assertTrue(f.exists())\n\t\t\tf_mod = temp_dir / (mod_prefix + f.name)\n\t\t\tself.assertFalse(\n\t\t\t\tf_mod.exists(),\n\t\t\t\tf\"{f_mod} should not exist before the test. Please delete.\",\n\t\t\t)\n\n\t\t\tshutil.copyfile(f, f_mod)\n\t\t\tsource_files.append(f_mod)\n\n\t\t\twith self.et:\n\t\t\t\tself.et.set_tags(f_mod, {\"Keywords\": d[\"Keywords\"]})\n\t\t\t\tret_data = self.et.get_tags(f_mod, \"IPTC:Keywords\")\n\n\t\t\t#f_mod.unlink()  # don't delete file, tempdir will take care of it\n\n\t\t\tself.assertEqual(ret_data[0][\"IPTC:Keywords\"], d[\"Keywords\"])\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_set_tags_delete_all(self):\n\t\t\"\"\" delete tags with set tags is valid \"\"\"\n\n\t\t(temp_obj, temp_dir) = et_get_temp_dir(suffix=\"settagdel\")\n\t\ttest_file = temp_dir / \"test_rose.jpg\"\n\t\tshutil.copyfile(TEST_IMAGE_JPG, test_file)\n\n\n\t\tmy_tag = \"XMP:Subject\"\n\n\t\toriginal_subject = self.et.get_tags(test_file, my_tag)[0][my_tag]\n\n\t\tself.et.set_tags(test_file, {\"all\": \"\"})\n\n\t\t# deleted\n\t\tself.assertTrue(my_tag not in self.et.get_tags(test_file, my_tag)[0])\n\t\t#self.assertNotEqual(original_subject, )\n\n\n\n\t\t# just to get coverage on this arbitary object param\n\n\t\t# this class is an arbitrary object that returns a string\n\t\tclass TestClass(object):\n\t\t\tdef __str__(self):\n\t\t\t\treturn \"-n\"\n\n\t\tself.et.set_tags(test_file, {\"all\": \"\"}, params=[TestClass()])\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  },
  {
    "path": "tests/test_helper_tags_float.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nTest :: ExifToolHelper - numeric tags tests\n\"\"\"\n\n# standard\nimport unittest\nimport shutil\nimport json\nfrom decimal import Decimal\n\n# test helpers\nfrom tests.common_util import et_get_temp_dir, TEST_IMAGE_DIR, TEST_IMAGE_JPG\n\n# custom\nimport exiftool\n\n# test well known alternative JSON processors\ntry:\n\timport ujson\n\thas_ujson = True\nexcept ImportError:\n\thas_ujson = False\n\ntry:\n\timport simplejson\n\thas_simplejson = True\nexcept ImportError:\n\thas_simplejson = False\n\ntry:\n\timport orjson\n\thas_orjson = True\nexcept ImportError:\n\thas_orjson = False\n\n# TODO rapidjson, but I think the result will be the same\n\n\nclass TestHelperFloatTags(unittest.TestCase):\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef setUp(self):\n\t\tself.et = exiftool.ExifToolHelper(\n\t\t\tcommon_args=[\"-n\", \"-overwrite_original\"],\n\t\t\tencoding=\"UTF-8\"\n\t\t)\n\n\t\t# set up the file to write tags to to test\n\t\t# for this test, we write to the same file\n\t\t(self.temp_obj, self.temp_dir) = et_get_temp_dir(suffix=\"tagcommentnum\")\n\n\t\tself.jpg_file = self.temp_dir / (\"tagnum_\" + TEST_IMAGE_JPG.name)\n\n\t\tshutil.copyfile(TEST_IMAGE_JPG, self.jpg_file)\n\n\t\t# all tests use the same test for this comment number thing\n\t\tself.test_data_str = [\n\t\t\t{\"Comment\": 1},\n\t\t\t{\"Comment\": -1},\n\t\t\t{\"Comment\": 1.1},\n\t\t\t{\"Comment\": -1.1},\n\n\t\t\t{\"Comment\": \"10\"},\n\t\t\t{\"Comment\": \"-10\"},\n\t\t\t{\"Comment\": \"1.10\"},\n\t\t\t{\"Comment\": \"-1.10\"},\n\t\t\t{\"Comment\": \"0.1000\"},\n\t\t\t{\"Comment\": \"1.33700e+40\"},\n\n\t\t\t{\"Comment\": \"1       \"},\n\t\t\t#{\"Comment\": \" -1\"},  #possible exiftool bug, see blow on test cases\n\n\t\t\t[{\"Comment\": Decimal('935733.817019799357333475932629142801644788893573383506621454627967')}, '935733.817019799357333475932629142801644788893573383506621454627967'],\n\t\t\t[{\"Comment\": Decimal('935733.81701979935')}, '935733.81701979935'],\n\n\t\t\t# numbers are as is\n\t\t\t[{\"FocalLength\": \"00.1000\"}, 0.1],\n\t\t\t[{\"FocalLength\": \"010\"}, 10],\n\t\t\t[{\"FocalLength\": \"01.0\"}, 1],\n\t\t]\n\n\n\tdef tearDown(self):\n\t\tself.et.terminate()\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef check_testdata(self, test_data, compare_str=False):\n\t\t\"\"\"\n\t\tcheck test_data in a specific format specified below\n\n\t\tthis routine allows us to check numerous cases in different configurations\n\t\t\"\"\"\n\n\t\twith self.et:\n\t\t\tfor d in test_data:\n\t\t\t\t\"\"\"\n\t\t\t\tformat of test_data is a LIST of either:\n\t\t\t\t\tDICT = {\"tag\": <value to set, and compare>}\n\t\t\t\t\tLIST = [{\"tag\": <value to set>}, value to check]\n\n\t\t\t\tonly one tag to set, this is all just for testing\n\t\t\t\t\"\"\"\n\t\t\t\tset_tag_dict = None\n\t\t\t\tcheck_tag_value = None\n\t\t\t\tset_tag_key = None\n\n\t\t\t\tif isinstance(d, dict):\n\t\t\t\t\tset_tag_dict = d\n\n\t\t\t\t\t# unpack into key/value\n\t\t\t\t\t# https://stackoverflow.com/questions/58129118/how-to-unpack-dict-with-one-key-value-pair-to-two-variables-more-elegantly\n\t\t\t\t\tset_tag_key, check_tag_value = next(iter(set_tag_dict.items()))\n\t\t\t\telse:\n\t\t\t\t\tset_tag_dict = d[0]\n\t\t\t\t\tcheck_tag_value = d[1]\n\n\t\t\t\t\t# unpack into key/value, ignore value\n\t\t\t\t\tset_tag_key = next(iter(set_tag_dict.items()))[0]\n\n\t\t\t\t# set the data\n\t\t\t\tself.et.set_tags(self.jpg_file, set_tag_dict)\n\n\t\t\t\t# get the data\n\t\t\t\tr = self.et.get_tags(self.jpg_file, set_tag_key)\n\t\t\t\t#print(r)\n\n\t\t\t\t# check\n\t\t\t\tif compare_str:\n\t\t\t\t\t# if compare by str only, a shorthand for the tests which will return str\n\t\t\t\t\tself.assertEqual(str(r[0][set_tag_key]), str(check_tag_value))\n\t\t\t\telse:\n\t\t\t\t\tself.assertEqual(r[0][set_tag_key], check_tag_value)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_baseline_exiftool_behavior(self):\n\t\t\"\"\"\n\t\ttest baseline exiftool behavior\n\n\t\tIf this test has failed, it means that exiftool returned output that has changed behavior since\n\t\tthis test was written.  You should investigate what changed before trying to fix any other tests\n\t\t\"\"\"\n\n\t\t# set default\n\t\tself.et.set_json_loads(json.loads)\n\n\n\n\t\ttest_data = [\n\t\t\t# baseline tests, exiftool returns a str in json\n\n\t\t\t## notice how the default exiftool behavior is different depending on field type\n\n\t\t\t# Comment is a string field\n\t\t\t# FocalLength is a float field\n\n\t\t\t{\"Comment\": \"01\"},\n\t\t\t{\"Comment\": \"0000001\"},\n\t\t\t{\"Comment\": \"00.1\"},\n\t\t\t{\"Comment\": \"00.1000\"},\n\t\t\t{\"Comment\": \"NaN\"},\n\t\t\t{\"Comment\": \"Infinity\"},\n\t\t\t{\"Comment\": \"-Infinity\"},\n\t\t\t{\"Comment\": \"nan\"},\n\t\t\t{\"Comment\": \"inf\"},\n\t\t\t[{\"Comment\": Decimal('935733.817019799357333475932629142801644788893573383506621454627967')}, '935733.817019799357333475932629142801644788893573383506621454627967'],\n\t\t\t[{\"Comment\": \"   1      \"}, \"  1      \"],  # exiftool removes a space (might be an exiftool bug)  TODO more investigation on this specific case, and report bug if it is\n\t\t\t[{\"Comment\": \"    -1\"}, \"   -1\"],  # exiftool removes a leading space\n\t\t\t{\"Comment\": \"1      \"},\n\n\t\t\t[{\"FocalLength\": \"00.1000\"}, 0.1],\n\t\t\t[{\"FocalLength\": \"010\"}, 10],\n\t\t\t[{\"FocalLength\": \"01.0\"}, 1],\n\t\t\t[{\"FocalLength\": \"blahblahblah\"}, 1],  # this is ignored by exiftool, so it uses previous set value\n\n\t\t\t# exiftool returns a number here (text field)\n\t\t\t[{\"Comment\": \" 1\"}, 1],\n\t\t\t[{\"Comment\": \" -1\"}, -1],\n\t\t\t{\"Comment\": 1},\n\t\t\t{\"Comment\": -1},\n\t\t\t{\"Comment\": 1.1},\n\t\t\t{\"Comment\": -1.1},\n\n\t\t\t[{\"Comment\": \"10\"}, 10],\n\t\t\t[{\"Comment\": \"-10\"}, -10],\n\t\t\t[{\"Comment\": \"1.10\"}, 1.1],\n\t\t\t[{\"Comment\": \"-1.10\"}, -1.1],\n\t\t\t[{\"Comment\": \"0.1000\"}, 0.1],\n\t\t\t[{\"Comment\": \"1.337e+40\"}, 1.337e+40],\n\t\t\t[{\"Comment\": \"1.33700e+40\"}, 1.337e+40],\n\n\t\t\t[{\"Comment\": Decimal('935733.81701979935')}, 935733.8170197994],  # notice that exiftool rounds here\n\n\t\t]\n\n\t\tself.check_testdata(test_data)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_json_tag_comment_number(self):\n\t\t\"\"\"\n\t\ttest that covers a numeric tag causing data mismatch\n\n\t\twith the parameters to get it to pass (default json processor)\n\n\t\tAddresses: https://github.com/sylikc/pyexiftool/issues/76\n\t\t\"\"\"\n\n\t\tself.et.set_json_loads(json.loads, parse_float=str)\n\n\t\t# should return all strings\n\t\tself.check_testdata(self.test_data_str, compare_str=True)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\t@unittest.skipIf(has_simplejson is False, \"simplejson not installed\")\n\tdef test_simplejson_tag_comment_number(self):\n\t\t\"\"\"\n\t\ttest that covers a numeric tag causing data mismatch\n\n\t\tsimplejson is the CPython json implementation in pure python (slower)\n\t\t\"\"\"\n\n\t\tself.et.set_json_loads(simplejson.loads, parse_float=str)\n\n\t\tself.check_testdata(self.test_data_str, compare_str=True)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\t@unittest.skipIf(has_ujson is False, \"ujson not installed\")\n\t@unittest.expectedFailure\n\tdef test_ujson_tag_comment_number(self):\n\t\t\"\"\"\n\t\ttest that covers a numeric tag causing data mismatch\n\n\t\tujson does not support the parse_float, and it's an outstanding bug\n\t\t\thttps://github.com/ultrajson/ultrajson/issues/401\n\t\t\thttps://github.com/ultrajson/ultrajson/issues/600\n\t\t\"\"\"\n\n\t\tself.et.set_json_loads(ujson.loads)\n\n\t\t#ujson.loads('{\"test\": 1}', parse_float=str)\n\n\t\tself.check_testdata(self.test_data_str, compare_str=True)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\t@unittest.skipIf(has_orjson is False, \"orjson not installed\")\n\t@unittest.expectedFailure\n\tdef test_orjson_tag_comment_number(self):\n\t\t\"\"\"\n\t\ttest that covers a numeric tag causing data mismatch\n\n\t\torjson does not support this type of processing\n\t\t\thttps://github.com/ijl/orjson/issues/21\n\t\t\"\"\"\n\n\t\tself.et.set_json_loads(orjson.loads)\n\n\t\tself.check_testdata(self.test_data_str, compare_str=True)\n\n\n\t# ---------------------------------------------------------------------------------------------------------\n\tdef test_json_loads_invalid(self):\n\t\t\"\"\"\n\t\ttests that an invalid set is caught (coverage test)\n\t\t\"\"\"\n\t\twith self.assertRaises(TypeError):\n\t\t\tself.et.set_json_loads(\"hi\")\n\n\n# ---------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n\tunittest.main()\n"
  }
]