././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1698016597.5749817 PyExifTool-0.5.6/0000777000000000000000000000000000000000000010457 5ustar00././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/COPYING.BSD0000666000000000000000000000273500000000000012130 0ustar00Copyright 2012 Sven Marnach, 2019-2023 Kevin M (sylikc) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SVEN MARNACH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1629159857.0 PyExifTool-0.5.6/COPYING.GPL0000666000000000000000000010575500000000000012150 0ustar00 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/LICENSE0000666000000000000000000000115700000000000011470 0ustar00PyExifTool Copyright 2019-2023 Kevin M (sylikc) Copyright 2012-2014 Sven Marnach PyExifTool is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the licence, or (at your option) any later version, or the BSD licence. PyExifTool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See COPYING.GPL or COPYING.BSD for more details. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1629159857.0 PyExifTool-0.5.6/MANIFEST.in0000666000000000000000000000007700000000000012221 0ustar00include README.rst COPYING doc/Makefile doc/conf.py doc/*.rst ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1698016597.5739849 PyExifTool-0.5.6/PKG-INFO0000666000000000000000000002674200000000000011567 0ustar00Metadata-Version: 2.1 Name: PyExifTool Version: 0.5.6 Summary: Python wrapper for exiftool Home-page: http://github.com/sylikc/pyexiftool Author: Kevin M (sylikc), Sven Marnach, various contributors Author-email: sylikc@gmail.com License: GPLv3+/BSD Project-URL: Source, https://github.com/sylikc/pyexiftool Project-URL: Tracker, https://github.com/sylikc/pyexiftool/issues Project-URL: Changelog, https://github.com/sylikc/pyexiftool/blob/master/CHANGELOG.md Project-URL: Documentation, https://sylikc.github.io/pyexiftool/ Keywords: exiftool image exif metadata photo video photography Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Topic :: Multimedia Classifier: Topic :: Utilities Requires-Python: >=3.6 Description-Content-Type: text/x-rst License-File: LICENSE License-File: COPYING.BSD License-File: COPYING.GPL Provides-Extra: json Requires-Dist: ujson; extra == "json" Requires-Dist: simplejson; extra == "json" Requires-Dist: orjson; extra == "json" Provides-Extra: test Requires-Dist: packaging; extra == "test" Provides-Extra: docs Requires-Dist: packaging; extra == "docs" Requires-Dist: sphinx; extra == "docs" Requires-Dist: sphinx-autoapi; extra == "docs" Requires-Dist: sphinx-rtd-theme; extra == "docs" Requires-Dist: sphinx-autodoc-typehints; extra == "docs" ********** PyExifTool ********** .. image:: https://img.shields.io/badge/Docs-latest-blueviolet :alt: GitHub Pages :target: http://sylikc.github.io/pyexiftool/ .. image:: https://img.shields.io/pypi/pyversions/pyexiftool.svg :target: https://pypi.org/project/PyExifTool/ :alt: Supported Python Versions .. image:: https://pepy.tech/badge/pyexiftool :target: https://pepy.tech/project/pyexiftool :alt: Total PyPI Downloads .. image:: https://static.pepy.tech/personalized-badge/pyexiftool?period=month&units=international_system&left_color=black&right_color=orange&left_text=Downloads%2030d :target: https://pepy.tech/project/pyexiftool :alt: PyPI Downloads this month .. DESCRIPTION_START .. BLURB_START PyExifTool is a Python library to communicate with an instance of `Phil Harvey's ExifTool`_ command-line application. .. _Phil Harvey's ExifTool: https://exiftool.org/ .. BLURB_END The library provides the class ``exiftool.ExifTool`` that runs the command-line tool in batch mode and features methods to send commands to that program, including methods to extract meta-information from one or more image files. Since ``exiftool`` is run in batch mode, only a single instance needs to be launched and can be reused for many queries. This is much more efficient than launching a separate process for every single query. .. DESCRIPTION_END .. contents:: :depth: 2 :backlinks: none Example Usage ============= Simple example: :: import exiftool files = ["a.jpg", "b.png", "c.tif"] with exiftool.ExifToolHelper() as et: metadata = et.get_metadata(files) for d in metadata: print("{:20.20} {:20.20}".format(d["SourceFile"], d["EXIF:DateTimeOriginal"])) Refer to documentation for more `Examples and Quick Start Guide`_ .. _`Examples and Quick Start Guide`: http://sylikc.github.io/pyexiftool/examples.html .. INSTALLATION_START Getting PyExifTool ================== PyPI ------------ Easiest: Install a version from the official `PyExifTool PyPI`_ :: python -m pip install -U pyexiftool .. _PyExifTool PyPI: https://pypi.org/project/PyExifTool/ From Source ------------ #. Check out the source code from the github repository * ``git clone git://github.com/sylikc/pyexiftool.git`` * Alternatively, you can download a tarball_. #. Run setup.py to install the module from source * ``python setup.py install [--user|--prefix=]`` .. _tarball: https://github.com/sylikc/pyexiftool/tarball/master PyExifTool Dependencies ======================= Python ------ PyExifTool runs on **Python 3.6+**. (If you need Python 2.6 support, please use version v0.4.x). PyExifTool has been tested on Windows and Linux, and probably also runs on other Unix-like platforms. Phil Harvey's exiftool ---------------------- For PyExifTool to function, ``exiftool`` command-line tool must exist on the system. If ``exiftool`` is not on the ``PATH``, you can specify the full pathname to it by using ``ExifTool(executable=)``. PyExifTool requires a **minimum version of 12.15** (which was the first production version of exiftool featuring the options to allow exit status checks used in conjuction with ``-echo3`` and ``-echo4`` parameters). To check your ``exiftool`` version: :: exiftool -ver Windows/Mac ^^^^^^^^^^^ Windows/Mac users can download the latest version of exiftool: :: https://exiftool.org Linux ^^^^^ Most current Linux distributions have a package which will install ``exiftool``. Unfortunately, some do not have the minimum required version, in which case you will have to `build from source`_. * Ubuntu :: sudo apt install libimage-exiftool-perl * CentOS/RHEL :: yum install perl-Image-ExifTool .. _build from source: https://exiftool.org/install.html#Unix .. INSTALLATION_END Documentation ============= The current documentation is available at `sylikc.github.io`_. :: http://sylikc.github.io/pyexiftool/ .. _sylikc.github.io: http://sylikc.github.io/pyexiftool/ Package Structure ----------------- .. DESIGN_INFO_START PyExifTool was designed with flexibility and extensibility in mind. The library consists of a few classes, each with increasingly more features. The base ``ExifTool`` class contains the core functionality exposed in the most rudimentary way, and each successive class inherits and adds functionality. .. DESIGN_INFO_END .. DESIGN_CLASS_START * ``exiftool.ExifTool`` is the base class with core logic to interface with PH's ExifTool process. It contains only the core features with no extra fluff. The main methods provided are ``execute()`` and ``execute_json()`` which allows direct interaction with the underlying exiftool process. * The API is considered stable and should not change much with future releases. * ``exiftool.ExifToolHelper`` exposes some of the most commonly used functionality. It overloads some inherited functions to turn common errors into warnings and adds logic to make ``exiftool.ExifTool`` easier to use. 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). ``ExifToolHelper`` demonstrates how to extend ``ExifTool`` to your liking if your project demands customizations not directly provided by ``ExifTool``. * More methods may be added and/or slight API tweaks may occur with future releases. * ``exiftool.ExifToolAlpha`` further extends the ``ExifToolHelper`` and includes some community-contributed not-very-well-tested methods. These methods were formerly added ad-hoc by various community contributors, but no longer stand up to the rigor of the current design. ``ExifToolAlpha`` is *not* up to the rigorous testing standard of both ``ExifTool`` or ``ExifToolHelper``. There may be old, buggy, or defunct code. * This is the least polished of the classes and functionality/API may be changed/added/removed on any release. * **NOTE: The methods exposed may be changed/removed at any time.** * 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``. (Think of ``ExifToolAlpha`` as ideas on how to extend ``ExifTool``, where new functionality which may one day make it into the ``ExifToolHelper`` class.) .. _Submit an Issue: https://github.com/sylikc/pyexiftool/issues .. DESIGN_CLASS_END Brief History ============= .. HISTORY_START PyExifTool was originally developed by `Sven Marnach`_ in 2012 to answer a stackoverflow question `Call exiftool from a python script?`_. Over time, Sven refined the code, added tests, documentation, and a slew of improvements. While PyExifTool gained popularity, Sven `never intended to maintain it`_ as an active project. The `original repository`_ was last updated in 2014. Over the years, numerous issues were filed and several PRs were opened on the stagnant repository. In early 2019, `Martin Čarnogurský`_ created a `PyPI release`_ from the 2014 code with some minor updates. Coincidentally in mid 2019, `Kevin M (sylikc)`_ forked the original repository and started merging the PR and issues which were reported on Sven's issues/PR page. In late 2019 and early 2020 there was a discussion started to `Provide visibility for an active fork`_. There was a conversation to transfer ownership of the original repository, have a coordinated plan to communicate to PyExifTool users, amongst other things, but it never materialized. Kevin M (sylikc) made the first release to the PyPI repository in early 2021. At the same time, discussions were started, revolving around `Deprecating Python 2.x compatibility`_ and `refactoring the code and classes`_. The latest version is the result of all of those discussions, designs, and development. Special thanks to the community contributions, especially `Jan Philip Göpfert`_, `Seth P`_, and `Kolen Cheung`_. .. _Sven Marnach: https://github.com/smarnach/pyexiftool .. _Call exiftool from a python script?: https://stackoverflow.com/questions/10075115/call-exiftool-from-a-python-script/10075210#10075210 .. _never intended to maintain it: https://github.com/smarnach/pyexiftool/pull/31#issuecomment-569238073 .. _original repository: https://github.com/smarnach/pyexiftool .. _Martin Čarnogurský: https://github.com/RootLUG .. _PyPI release: https://pypi.org/project/PyExifTool/0.1.1/#history .. _Kevin M (sylikc): https://github.com/sylikc .. _Provide visibility for an active fork: https://github.com/smarnach/pyexiftool/pull/31 .. _Deprecating Python 2.x compatibility: https://github.com/sylikc/pyexiftool/discussions/9 .. _refactoring the code and classes: https://github.com/sylikc/pyexiftool/discussions/10 .. _Jan Philip Göpfert: https://github.com/jangop .. _Seth P: https://github.com/csparker247 .. _Kolen Cheung: https://github.com/ickc .. HISTORY_END Licence ======= .. LICENSE_START PyExifTool is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the licence, or (at your option) any later version, or the BSD licence. PyExifTool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See ``LICENSE`` for more details. .. LICENSE_END ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1698016597.4984972 PyExifTool-0.5.6/PyExifTool.egg-info/0000777000000000000000000000000000000000000014213 5ustar00././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698016597.0 PyExifTool-0.5.6/PyExifTool.egg-info/PKG-INFO0000666000000000000000000002674200000000000015323 0ustar00Metadata-Version: 2.1 Name: PyExifTool Version: 0.5.6 Summary: Python wrapper for exiftool Home-page: http://github.com/sylikc/pyexiftool Author: Kevin M (sylikc), Sven Marnach, various contributors Author-email: sylikc@gmail.com License: GPLv3+/BSD Project-URL: Source, https://github.com/sylikc/pyexiftool Project-URL: Tracker, https://github.com/sylikc/pyexiftool/issues Project-URL: Changelog, https://github.com/sylikc/pyexiftool/blob/master/CHANGELOG.md Project-URL: Documentation, https://sylikc.github.io/pyexiftool/ Keywords: exiftool image exif metadata photo video photography Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Topic :: Multimedia Classifier: Topic :: Utilities Requires-Python: >=3.6 Description-Content-Type: text/x-rst License-File: LICENSE License-File: COPYING.BSD License-File: COPYING.GPL Provides-Extra: json Requires-Dist: ujson; extra == "json" Requires-Dist: simplejson; extra == "json" Requires-Dist: orjson; extra == "json" Provides-Extra: test Requires-Dist: packaging; extra == "test" Provides-Extra: docs Requires-Dist: packaging; extra == "docs" Requires-Dist: sphinx; extra == "docs" Requires-Dist: sphinx-autoapi; extra == "docs" Requires-Dist: sphinx-rtd-theme; extra == "docs" Requires-Dist: sphinx-autodoc-typehints; extra == "docs" ********** PyExifTool ********** .. image:: https://img.shields.io/badge/Docs-latest-blueviolet :alt: GitHub Pages :target: http://sylikc.github.io/pyexiftool/ .. image:: https://img.shields.io/pypi/pyversions/pyexiftool.svg :target: https://pypi.org/project/PyExifTool/ :alt: Supported Python Versions .. image:: https://pepy.tech/badge/pyexiftool :target: https://pepy.tech/project/pyexiftool :alt: Total PyPI Downloads .. image:: https://static.pepy.tech/personalized-badge/pyexiftool?period=month&units=international_system&left_color=black&right_color=orange&left_text=Downloads%2030d :target: https://pepy.tech/project/pyexiftool :alt: PyPI Downloads this month .. DESCRIPTION_START .. BLURB_START PyExifTool is a Python library to communicate with an instance of `Phil Harvey's ExifTool`_ command-line application. .. _Phil Harvey's ExifTool: https://exiftool.org/ .. BLURB_END The library provides the class ``exiftool.ExifTool`` that runs the command-line tool in batch mode and features methods to send commands to that program, including methods to extract meta-information from one or more image files. Since ``exiftool`` is run in batch mode, only a single instance needs to be launched and can be reused for many queries. This is much more efficient than launching a separate process for every single query. .. DESCRIPTION_END .. contents:: :depth: 2 :backlinks: none Example Usage ============= Simple example: :: import exiftool files = ["a.jpg", "b.png", "c.tif"] with exiftool.ExifToolHelper() as et: metadata = et.get_metadata(files) for d in metadata: print("{:20.20} {:20.20}".format(d["SourceFile"], d["EXIF:DateTimeOriginal"])) Refer to documentation for more `Examples and Quick Start Guide`_ .. _`Examples and Quick Start Guide`: http://sylikc.github.io/pyexiftool/examples.html .. INSTALLATION_START Getting PyExifTool ================== PyPI ------------ Easiest: Install a version from the official `PyExifTool PyPI`_ :: python -m pip install -U pyexiftool .. _PyExifTool PyPI: https://pypi.org/project/PyExifTool/ From Source ------------ #. Check out the source code from the github repository * ``git clone git://github.com/sylikc/pyexiftool.git`` * Alternatively, you can download a tarball_. #. Run setup.py to install the module from source * ``python setup.py install [--user|--prefix=]`` .. _tarball: https://github.com/sylikc/pyexiftool/tarball/master PyExifTool Dependencies ======================= Python ------ PyExifTool runs on **Python 3.6+**. (If you need Python 2.6 support, please use version v0.4.x). PyExifTool has been tested on Windows and Linux, and probably also runs on other Unix-like platforms. Phil Harvey's exiftool ---------------------- For PyExifTool to function, ``exiftool`` command-line tool must exist on the system. If ``exiftool`` is not on the ``PATH``, you can specify the full pathname to it by using ``ExifTool(executable=)``. PyExifTool requires a **minimum version of 12.15** (which was the first production version of exiftool featuring the options to allow exit status checks used in conjuction with ``-echo3`` and ``-echo4`` parameters). To check your ``exiftool`` version: :: exiftool -ver Windows/Mac ^^^^^^^^^^^ Windows/Mac users can download the latest version of exiftool: :: https://exiftool.org Linux ^^^^^ Most current Linux distributions have a package which will install ``exiftool``. Unfortunately, some do not have the minimum required version, in which case you will have to `build from source`_. * Ubuntu :: sudo apt install libimage-exiftool-perl * CentOS/RHEL :: yum install perl-Image-ExifTool .. _build from source: https://exiftool.org/install.html#Unix .. INSTALLATION_END Documentation ============= The current documentation is available at `sylikc.github.io`_. :: http://sylikc.github.io/pyexiftool/ .. _sylikc.github.io: http://sylikc.github.io/pyexiftool/ Package Structure ----------------- .. DESIGN_INFO_START PyExifTool was designed with flexibility and extensibility in mind. The library consists of a few classes, each with increasingly more features. The base ``ExifTool`` class contains the core functionality exposed in the most rudimentary way, and each successive class inherits and adds functionality. .. DESIGN_INFO_END .. DESIGN_CLASS_START * ``exiftool.ExifTool`` is the base class with core logic to interface with PH's ExifTool process. It contains only the core features with no extra fluff. The main methods provided are ``execute()`` and ``execute_json()`` which allows direct interaction with the underlying exiftool process. * The API is considered stable and should not change much with future releases. * ``exiftool.ExifToolHelper`` exposes some of the most commonly used functionality. It overloads some inherited functions to turn common errors into warnings and adds logic to make ``exiftool.ExifTool`` easier to use. 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). ``ExifToolHelper`` demonstrates how to extend ``ExifTool`` to your liking if your project demands customizations not directly provided by ``ExifTool``. * More methods may be added and/or slight API tweaks may occur with future releases. * ``exiftool.ExifToolAlpha`` further extends the ``ExifToolHelper`` and includes some community-contributed not-very-well-tested methods. These methods were formerly added ad-hoc by various community contributors, but no longer stand up to the rigor of the current design. ``ExifToolAlpha`` is *not* up to the rigorous testing standard of both ``ExifTool`` or ``ExifToolHelper``. There may be old, buggy, or defunct code. * This is the least polished of the classes and functionality/API may be changed/added/removed on any release. * **NOTE: The methods exposed may be changed/removed at any time.** * 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``. (Think of ``ExifToolAlpha`` as ideas on how to extend ``ExifTool``, where new functionality which may one day make it into the ``ExifToolHelper`` class.) .. _Submit an Issue: https://github.com/sylikc/pyexiftool/issues .. DESIGN_CLASS_END Brief History ============= .. HISTORY_START PyExifTool was originally developed by `Sven Marnach`_ in 2012 to answer a stackoverflow question `Call exiftool from a python script?`_. Over time, Sven refined the code, added tests, documentation, and a slew of improvements. While PyExifTool gained popularity, Sven `never intended to maintain it`_ as an active project. The `original repository`_ was last updated in 2014. Over the years, numerous issues were filed and several PRs were opened on the stagnant repository. In early 2019, `Martin Čarnogurský`_ created a `PyPI release`_ from the 2014 code with some minor updates. Coincidentally in mid 2019, `Kevin M (sylikc)`_ forked the original repository and started merging the PR and issues which were reported on Sven's issues/PR page. In late 2019 and early 2020 there was a discussion started to `Provide visibility for an active fork`_. There was a conversation to transfer ownership of the original repository, have a coordinated plan to communicate to PyExifTool users, amongst other things, but it never materialized. Kevin M (sylikc) made the first release to the PyPI repository in early 2021. At the same time, discussions were started, revolving around `Deprecating Python 2.x compatibility`_ and `refactoring the code and classes`_. The latest version is the result of all of those discussions, designs, and development. Special thanks to the community contributions, especially `Jan Philip Göpfert`_, `Seth P`_, and `Kolen Cheung`_. .. _Sven Marnach: https://github.com/smarnach/pyexiftool .. _Call exiftool from a python script?: https://stackoverflow.com/questions/10075115/call-exiftool-from-a-python-script/10075210#10075210 .. _never intended to maintain it: https://github.com/smarnach/pyexiftool/pull/31#issuecomment-569238073 .. _original repository: https://github.com/smarnach/pyexiftool .. _Martin Čarnogurský: https://github.com/RootLUG .. _PyPI release: https://pypi.org/project/PyExifTool/0.1.1/#history .. _Kevin M (sylikc): https://github.com/sylikc .. _Provide visibility for an active fork: https://github.com/smarnach/pyexiftool/pull/31 .. _Deprecating Python 2.x compatibility: https://github.com/sylikc/pyexiftool/discussions/9 .. _refactoring the code and classes: https://github.com/sylikc/pyexiftool/discussions/10 .. _Jan Philip Göpfert: https://github.com/jangop .. _Seth P: https://github.com/csparker247 .. _Kolen Cheung: https://github.com/ickc .. HISTORY_END Licence ======= .. LICENSE_START PyExifTool is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the licence, or (at your option) any later version, or the BSD licence. PyExifTool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See ``LICENSE`` for more details. .. LICENSE_END ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698016597.0 PyExifTool-0.5.6/PyExifTool.egg-info/SOURCES.txt0000666000000000000000000000167000000000000016103 0ustar00COPYING.BSD COPYING.GPL LICENSE MANIFEST.in README.rst setup.cfg setup.py PyExifTool.egg-info/PKG-INFO PyExifTool.egg-info/SOURCES.txt PyExifTool.egg-info/dependency_links.txt PyExifTool.egg-info/requires.txt PyExifTool.egg-info/top_level.txt exiftool/__init__.py exiftool/constants.py exiftool/exceptions.py exiftool/exiftool.py exiftool/experimental.py exiftool/helper.py pyexiftool.egg-info/PKG-INFO pyexiftool.egg-info/SOURCES.txt pyexiftool.egg-info/dependency_links.txt pyexiftool.egg-info/requires.txt pyexiftool.egg-info/top_level.txt tests/test_alpha.py tests/test_exiftool_attr.py tests/test_exiftool_bytes.py tests/test_exiftool_configfile.py tests/test_exiftool_logger.py tests/test_exiftool_misc.py tests/test_exiftool_process.py tests/test_helper_checkexecute.py tests/test_helper_checktagnames.py tests/test_helper_gettags.py tests/test_helper_misc.py tests/test_helper_run.py tests/test_helper_settags.py tests/test_helper_tags_float.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698016597.0 PyExifTool-0.5.6/PyExifTool.egg-info/dependency_links.txt0000666000000000000000000000000100000000000020261 0ustar00 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698016597.0 PyExifTool-0.5.6/PyExifTool.egg-info/requires.txt0000666000000000000000000000020400000000000016607 0ustar00 [docs] packaging sphinx sphinx-autoapi sphinx-rtd-theme sphinx-autodoc-typehints [json] ujson simplejson orjson [test] packaging ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698016597.0 PyExifTool-0.5.6/PyExifTool.egg-info/top_level.txt0000666000000000000000000000001100000000000016735 0ustar00exiftool ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1672442253.0 PyExifTool-0.5.6/README.rst0000666000000000000000000002371700000000000012160 0ustar00********** PyExifTool ********** .. image:: https://img.shields.io/badge/Docs-latest-blueviolet :alt: GitHub Pages :target: http://sylikc.github.io/pyexiftool/ .. HIDE_FROM_PYPI_START .. image:: https://github.com/sylikc/pyexiftool/actions/workflows/lint-and-test.yml/badge.svg :alt: GitHub Actions :target: https://github.com/sylikc/pyexiftool/actions .. image:: https://img.shields.io/pypi/v/pyexiftool.svg :target: https://pypi.org/project/PyExifTool/ :alt: PyPI Version .. HIDE_FROM_PYPI_END .. image:: https://img.shields.io/pypi/pyversions/pyexiftool.svg :target: https://pypi.org/project/PyExifTool/ :alt: Supported Python Versions .. image:: https://pepy.tech/badge/pyexiftool :target: https://pepy.tech/project/pyexiftool :alt: Total PyPI Downloads .. image:: https://static.pepy.tech/personalized-badge/pyexiftool?period=month&units=international_system&left_color=black&right_color=orange&left_text=Downloads%2030d :target: https://pepy.tech/project/pyexiftool :alt: PyPI Downloads this month .. DESCRIPTION_START .. BLURB_START PyExifTool is a Python library to communicate with an instance of `Phil Harvey's ExifTool`_ command-line application. .. _Phil Harvey's ExifTool: https://exiftool.org/ .. BLURB_END The library provides the class ``exiftool.ExifTool`` that runs the command-line tool in batch mode and features methods to send commands to that program, including methods to extract meta-information from one or more image files. Since ``exiftool`` is run in batch mode, only a single instance needs to be launched and can be reused for many queries. This is much more efficient than launching a separate process for every single query. .. DESCRIPTION_END .. contents:: :depth: 2 :backlinks: none Example Usage ============= Simple example: :: import exiftool files = ["a.jpg", "b.png", "c.tif"] with exiftool.ExifToolHelper() as et: metadata = et.get_metadata(files) for d in metadata: print("{:20.20} {:20.20}".format(d["SourceFile"], d["EXIF:DateTimeOriginal"])) Refer to documentation for more `Examples and Quick Start Guide`_ .. _`Examples and Quick Start Guide`: http://sylikc.github.io/pyexiftool/examples.html .. INSTALLATION_START Getting PyExifTool ================== PyPI ------------ Easiest: Install a version from the official `PyExifTool PyPI`_ :: python -m pip install -U pyexiftool .. _PyExifTool PyPI: https://pypi.org/project/PyExifTool/ From Source ------------ #. Check out the source code from the github repository * ``git clone git://github.com/sylikc/pyexiftool.git`` * Alternatively, you can download a tarball_. #. Run setup.py to install the module from source * ``python setup.py install [--user|--prefix=]`` .. _tarball: https://github.com/sylikc/pyexiftool/tarball/master PyExifTool Dependencies ======================= Python ------ PyExifTool runs on **Python 3.6+**. (If you need Python 2.6 support, please use version v0.4.x). PyExifTool has been tested on Windows and Linux, and probably also runs on other Unix-like platforms. Phil Harvey's exiftool ---------------------- For PyExifTool to function, ``exiftool`` command-line tool must exist on the system. If ``exiftool`` is not on the ``PATH``, you can specify the full pathname to it by using ``ExifTool(executable=)``. PyExifTool requires a **minimum version of 12.15** (which was the first production version of exiftool featuring the options to allow exit status checks used in conjuction with ``-echo3`` and ``-echo4`` parameters). To check your ``exiftool`` version: :: exiftool -ver Windows/Mac ^^^^^^^^^^^ Windows/Mac users can download the latest version of exiftool: :: https://exiftool.org Linux ^^^^^ Most current Linux distributions have a package which will install ``exiftool``. Unfortunately, some do not have the minimum required version, in which case you will have to `build from source`_. * Ubuntu :: sudo apt install libimage-exiftool-perl * CentOS/RHEL :: yum install perl-Image-ExifTool .. _build from source: https://exiftool.org/install.html#Unix .. INSTALLATION_END Documentation ============= The current documentation is available at `sylikc.github.io`_. :: http://sylikc.github.io/pyexiftool/ .. _sylikc.github.io: http://sylikc.github.io/pyexiftool/ Package Structure ----------------- .. DESIGN_INFO_START PyExifTool was designed with flexibility and extensibility in mind. The library consists of a few classes, each with increasingly more features. The base ``ExifTool`` class contains the core functionality exposed in the most rudimentary way, and each successive class inherits and adds functionality. .. DESIGN_INFO_END .. DESIGN_CLASS_START * ``exiftool.ExifTool`` is the base class with core logic to interface with PH's ExifTool process. It contains only the core features with no extra fluff. The main methods provided are ``execute()`` and ``execute_json()`` which allows direct interaction with the underlying exiftool process. * The API is considered stable and should not change much with future releases. * ``exiftool.ExifToolHelper`` exposes some of the most commonly used functionality. It overloads some inherited functions to turn common errors into warnings and adds logic to make ``exiftool.ExifTool`` easier to use. 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). ``ExifToolHelper`` demonstrates how to extend ``ExifTool`` to your liking if your project demands customizations not directly provided by ``ExifTool``. * More methods may be added and/or slight API tweaks may occur with future releases. * ``exiftool.ExifToolAlpha`` further extends the ``ExifToolHelper`` and includes some community-contributed not-very-well-tested methods. These methods were formerly added ad-hoc by various community contributors, but no longer stand up to the rigor of the current design. ``ExifToolAlpha`` is *not* up to the rigorous testing standard of both ``ExifTool`` or ``ExifToolHelper``. There may be old, buggy, or defunct code. * This is the least polished of the classes and functionality/API may be changed/added/removed on any release. * **NOTE: The methods exposed may be changed/removed at any time.** * 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``. (Think of ``ExifToolAlpha`` as ideas on how to extend ``ExifTool``, where new functionality which may one day make it into the ``ExifToolHelper`` class.) .. _Submit an Issue: https://github.com/sylikc/pyexiftool/issues .. DESIGN_CLASS_END Brief History ============= .. HISTORY_START PyExifTool was originally developed by `Sven Marnach`_ in 2012 to answer a stackoverflow question `Call exiftool from a python script?`_. Over time, Sven refined the code, added tests, documentation, and a slew of improvements. While PyExifTool gained popularity, Sven `never intended to maintain it`_ as an active project. The `original repository`_ was last updated in 2014. Over the years, numerous issues were filed and several PRs were opened on the stagnant repository. In early 2019, `Martin Čarnogurský`_ created a `PyPI release`_ from the 2014 code with some minor updates. Coincidentally in mid 2019, `Kevin M (sylikc)`_ forked the original repository and started merging the PR and issues which were reported on Sven's issues/PR page. In late 2019 and early 2020 there was a discussion started to `Provide visibility for an active fork`_. There was a conversation to transfer ownership of the original repository, have a coordinated plan to communicate to PyExifTool users, amongst other things, but it never materialized. Kevin M (sylikc) made the first release to the PyPI repository in early 2021. At the same time, discussions were started, revolving around `Deprecating Python 2.x compatibility`_ and `refactoring the code and classes`_. The latest version is the result of all of those discussions, designs, and development. Special thanks to the community contributions, especially `Jan Philip Göpfert`_, `Seth P`_, and `Kolen Cheung`_. .. _Sven Marnach: https://github.com/smarnach/pyexiftool .. _Call exiftool from a python script?: https://stackoverflow.com/questions/10075115/call-exiftool-from-a-python-script/10075210#10075210 .. _never intended to maintain it: https://github.com/smarnach/pyexiftool/pull/31#issuecomment-569238073 .. _original repository: https://github.com/smarnach/pyexiftool .. _Martin Čarnogurský: https://github.com/RootLUG .. _PyPI release: https://pypi.org/project/PyExifTool/0.1.1/#history .. _Kevin M (sylikc): https://github.com/sylikc .. _Provide visibility for an active fork: https://github.com/smarnach/pyexiftool/pull/31 .. _Deprecating Python 2.x compatibility: https://github.com/sylikc/pyexiftool/discussions/9 .. _refactoring the code and classes: https://github.com/sylikc/pyexiftool/discussions/10 .. _Jan Philip Göpfert: https://github.com/jangop .. _Seth P: https://github.com/csparker247 .. _Kolen Cheung: https://github.com/ickc .. HISTORY_END Licence ======= .. LICENSE_START PyExifTool is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the licence, or (at your option) any later version, or the BSD licence. PyExifTool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See ``LICENSE`` for more details. .. LICENSE_END ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1698016597.533092 PyExifTool-0.5.6/exiftool/0000777000000000000000000000000000000000000012310 5ustar00././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/exiftool/__init__.py0000666000000000000000000000540600000000000014426 0ustar00# -*- coding: utf-8 -*- # # This file is part of PyExifTool. # # PyExifTool # # Copyright 2019-2023 Kevin M (sylikc) # Copyright 2012-2014 Sven Marnach # # Community contributors are listed in the CHANGELOG.md for the PRs # # PyExifTool is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the licence, or # (at your option) any later version, or the BSD licence. # # PyExifTool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See COPYING.GPL or COPYING.BSD for more details. """ PyExifTool is a Python library to communicate with an instance of Phil Harvey's excellent ExifTool_ command-line application. The library provides the class :py:class:`ExifTool` that runs the command-line tool in batch mode and features methods to send commands to that program, including methods to extract meta-information from one or more image files. Since ``exiftool`` is run in batch mode, only a single instance needs to be launched and can be reused for many queries. This is much more efficient than launching a separate process for every single query. .. _ExifTool: https://exiftool.org The source code can be checked out from the github repository with :: git clone git://github.com/sylikc/pyexiftool.git Alternatively, you can download a tarball_. There haven't been any releases yet. .. _tarball: https://github.com/sylikc/pyexiftool/tarball/master PyExifTool is licenced under GNU GPL version 3 or later, or BSD license. Example usage:: import exiftool files = ["a.jpg", "b.png", "c.tif"] with exiftool.ExifToolHelper() as et: metadata = et.get_metadata(files) for d in metadata: print("{:20.20} {:20.20}".format(d["SourceFile"], d["EXIF:DateTimeOriginal"])) """ # version number using Semantic Versioning 2.0.0 https://semver.org/ # may not be PEP-440 compliant https://www.python.org/dev/peps/pep-0440/#semantic-versioning __version__ = "0.5.6" # while we COULD import all the exceptions into the base library namespace, # it's best that it lives as exiftool.exceptions, to not pollute the base namespace from . import exceptions # make all of the original exiftool stuff available in this namespace from .exiftool import ExifTool from .helper import ExifToolHelper from .experimental import ExifToolAlpha # an old feature of the original class that exposed this variable at the library level # TODO may remove and deprecate at a later time #from .constants import DEFAULT_EXECUTABLE ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/exiftool/constants.py0000666000000000000000000000623600000000000014705 0ustar00# -*- coding: utf-8 -*- # # This file is part of PyExifTool. # # PyExifTool # # Copyright 2019-2023 Kevin M (sylikc) # Copyright 2012-2014 Sven Marnach # # Community contributors are listed in the CHANGELOG.md for the PRs # # PyExifTool is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the licence, or # (at your option) any later version, or the BSD licence. # # PyExifTool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See COPYING.GPL or COPYING.BSD for more details. """ This submodule defines constants which are used by other modules in the package """ import sys ################################## ############# HELPERS ############ ################################## # instead of comparing everywhere sys.platform, do it all here in the constants (less typo chances) # True if Windows PLATFORM_WINDOWS: bool = (sys.platform == 'win32') """sys.platform check, set to True if Windows""" # Prior to Python 3.3, the value for any Linux version is always linux2; after, it is linux. # https://stackoverflow.com/a/13874620/15384838 PLATFORM_LINUX: bool = (sys.platform == 'linux' or sys.platform == 'linux2') """sys.platform check, set to True if Linux""" ################################## ####### PLATFORM DEFAULTS ######## ################################## # specify the extension so exiftool doesn't default to running "exiftool.py" on windows (which could happen) DEFAULT_EXECUTABLE: str """The name of the default executable to run. ``exiftool`` (Linux) or ``exiftool.exe`` (Windows) By default, the executable is searched for on one of the paths listed in the ``PATH`` environment variable. If it's not on the ``PATH``, a full path should be given to the ExifTool constructor. """ if PLATFORM_WINDOWS: DEFAULT_EXECUTABLE = "exiftool.exe" else: # pytest-cov:windows: no cover DEFAULT_EXECUTABLE = "exiftool" ################################## ####### STARTUP CONSTANTS ######## ################################## # for Windows STARTUPINFO SW_FORCEMINIMIZE: int = 11 """Windows ShowWindow constant from win32con Indicates the launched process window should start minimized """ # for Linux preexec_fn PR_SET_PDEATHSIG: int = 1 """Extracted from linux/prctl.h Allows a kill signal to be sent to child processes when the parent unexpectedly dies """ ################################## ######## GLOBAL DEFAULTS ######### ################################## DEFAULT_BLOCK_SIZE: int = 4096 """The default block size when reading from exiftool. The standard value should be fine, though other values might give better performance in some cases.""" EXIFTOOL_MINIMUM_VERSION = "12.15" """this is the minimum *exiftool* version required for current version of PyExifTool * 8.40 / 8.60 (production): implemented the -stay_open flag * 12.10 / 12.15 (production): implemented exit status on -echo4 """ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/exiftool/exceptions.py0000666000000000000000000001262500000000000015051 0ustar00# -*- coding: utf-8 -*- # # This file is part of PyExifTool. # # PyExifTool # # Copyright 2019-2023 Kevin M (sylikc) # Copyright 2012-2014 Sven Marnach # # Community contributors are listed in the CHANGELOG.md for the PRs # # PyExifTool is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the licence, or # (at your option) any later version, or the BSD licence. # # PyExifTool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See COPYING.GPL or COPYING.BSD for more details. """ This submodule holds all of the custom exceptions which can be raised by PyExifTool """ ######################################################## #################### Base Exception #################### ######################################################## class ExifToolException(Exception): """ Generic Base class for all ExifTool error classes """ ############################################################# #################### Process State Error #################### ############################################################# class ExifToolProcessStateError(ExifToolException): """ Base class for all errors related to the invalid state of `exiftool` subprocess """ class ExifToolRunning(ExifToolProcessStateError): """ ExifTool is already running """ def __init__(self, message: str): super().__init__(f"ExifTool instance is running: {message}") class ExifToolNotRunning(ExifToolProcessStateError): """ ExifTool is not running """ def __init__(self, message: str): super().__init__(f"ExifTool instance not running: {message}") ########################################################### #################### Execute Exception #################### ########################################################### # all of these exceptions are related to something regarding execute class ExifToolExecuteException(ExifToolException): """ This is the base exception class for all execute() associated errors. This exception is never returned directly from any method, but provides common interface for subclassed errors. (mimics the signature of :py:class:`subprocess.CalledProcessError`) :attribute cmd: Parameters sent to *exiftool* which raised the error :attribute returncode: Exit Status (Return code) of the ``execute()`` command which raised the error :attribute stdout: STDOUT stream returned by the command which raised the error :attribute stderr: STDERR stream returned by the command which raised the error """ def __init__(self, message, exit_status, cmd_stdout, cmd_stderr, params): super().__init__(message) self.returncode: int = exit_status self.cmd: list = params self.stdout: str = cmd_stdout self.stderr: str = cmd_stderr class ExifToolExecuteError(ExifToolExecuteException): """ ExifTool executed the command but returned a non-zero exit status. .. note:: There is a similarly named :py:exc:`ExifToolExecuteException` which this Error inherits from. That is a base class and never returned directly. This is what is raised. """ def __init__(self, exit_status, cmd_stdout, cmd_stderr, params): super().__init__(f"execute returned a non-zero exit status: {exit_status}", exit_status, cmd_stdout, cmd_stderr, params) ######################################################## #################### JSON Exception #################### ######################################################## class ExifToolOutputEmptyError(ExifToolExecuteException): """ ExifTool execute_json() expected output, but execute() did not return any output on stdout This is an error, because if you expect no output, don't use execute_json() .. note:: Only thrown by execute_json() """ def __init__(self, exit_status, cmd_stdout, cmd_stderr, params): super().__init__("execute_json expected output on stdout but got none", exit_status, cmd_stdout, cmd_stderr, params) class ExifToolJSONInvalidError(ExifToolExecuteException): """ ExifTool execute_json() expected valid JSON to be returned, but got invalid JSON. This is an error, because if you expect non-JSON output, don't use execute_json() .. note:: Only thrown by execute_json() """ def __init__(self, exit_status, cmd_stdout, cmd_stderr, params): super().__init__("execute_json received invalid JSON output from exiftool", exit_status, cmd_stdout, cmd_stderr, params) ######################################################### #################### Other Exception #################### ######################################################### class ExifToolVersionError(ExifToolException): """ Generic Error to represent some version mismatch. PyExifTool 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 """ class ExifToolTagNameError(ExifToolException): """ ExifToolHelper found an invalid tag name This error is raised when :py:attr:`exiftool.ExifToolHelper.check_tag_names` is enabled, and a bad tag is provided to a method """ def __init__(self, bad_tag): super().__init__(f"Invalid Tag Name found: \"{bad_tag}\"") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/exiftool/exiftool.py0000666000000000000000000015206100000000000014520 0ustar00# -*- coding: utf-8 -*- # # This file is part of PyExifTool. # # PyExifTool # # Copyright 2019-2023 Kevin M (sylikc) # Copyright 2012-2014 Sven Marnach # # Community contributors are listed in the CHANGELOG.md for the PRs # # PyExifTool is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the licence, or # (at your option) any later version, or the BSD licence. # # PyExifTool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See COPYING.GPL or COPYING.BSD for more details. """ This submodule contains the core ``ExifTool`` class of PyExifTool .. note:: :py:class:`exiftool.helper.ExifTool` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifTool` """ # ---------- standard Python imports ---------- import select import subprocess import os import shutil from pathlib import Path # requires Python 3.4+ import random import locale import warnings import json # NOTE: to use other json libraries (simplejson/ujson/orjson/...), see :py:meth:`set_json_loads()` # for the pdeathsig import signal import ctypes # ---------- Typing Imports ---------- # for static analysis / type checking - Python 3.5+ from collections.abc import Callable from typing import Optional, List, Union # ---------- Library Package Imports ---------- from . import constants from .exceptions import ExifToolVersionError, ExifToolRunning, ExifToolNotRunning, ExifToolOutputEmptyError, ExifToolJSONInvalidError # ====================================================================================================================== # constants to make typos obsolete! ENCODING_UTF8: str = "utf-8" #ENCODING_LATIN1: str = "latin-1" # ====================================================================================================================== def _set_pdeathsig(sig) -> Optional[Callable]: """ Use this method in subprocess.Popen(preexec_fn=set_pdeathsig()) to make sure, the exiftool childprocess is stopped if this process dies. However, this only works on linux. """ if constants.PLATFORM_LINUX: def callable_method(): libc = ctypes.CDLL("libc.so.6") return libc.prctl(constants.PR_SET_PDEATHSIG, sig) return callable_method else: return None # pragma: no cover # ====================================================================================================================== def _get_buffer_end(buffer_list: List[bytes], bytes_needed: int) -> bytes: """ Given a list of bytes objects, return the equivalent of b"".join(buffer_list)[-bytes_needed:] but without having to concatenate the entire list. """ if bytes_needed < 1: return b"" # pragma: no cover buf_chunks = [] for buf in reversed(buffer_list): buf_tail = buf[-bytes_needed:] buf_chunks.append(buf_tail) bytes_needed -= len(buf_tail) if bytes_needed <= 0: break buf_tail_joined = b"".join(reversed(buf_chunks)) return buf_tail_joined def _read_fd_endswith(fd, b_endswith: bytes, block_size: int) -> bytes: """ read an fd and keep reading until it endswith the seq_ends this allows a consolidated read function that is platform indepdent if you're not careful, on windows, this will block """ output_list: List[bytes] = [] # if we're only looking at the last few bytes, make it meaningful. 4 is max size of \r\n? (or 2) # 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 endswith_count = len(b_endswith) + 4 # I believe doing a splice, then a strip is more efficient in memory hence the original code did it this way. # need to benchmark to see if in large strings, strip()[-endswithcount:] is more expensive or not while not _get_buffer_end(output_list, endswith_count).strip().endswith(b_endswith): if constants.PLATFORM_WINDOWS: # windows does not support select() for anything except sockets # https://docs.python.org/3.7/library/select.html output_list.append(os.read(fd, block_size)) else: # pytest-cov:windows: no cover # 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 inputready, outputready, exceptready = select.select([fd], [], []) for i in inputready: if i == fd: output_list.append(os.read(fd, block_size)) return b"".join(output_list) # ====================================================================================================================== class ExifTool(object): """Run the `exiftool` command-line tool and communicate with it. Use ``common_args`` to enable/disable print conversion by specifying/omitting ``-n``, respectively. This determines whether exiftool should perform print conversion, which prints values in a human-readable way but may be slower. If print conversion is enabled, appending ``#`` to a tag name disables the print conversion for this particular tag. See `Exiftool print conversion FAQ`_ for more details. .. _Exiftool print conversion FAQ: https://exiftool.org/faq.html#Q6 Some methods of this class are only available after calling :py:meth:`run()`, which will actually launch the *exiftool* subprocess. To avoid leaving the subprocess running, make sure to call :py:meth:`terminate()` method when finished using the instance. This method will also be implicitly called when the instance is garbage collected, but there are circumstance when this won't ever happen, so you should not rely on the implicit process termination. Subprocesses won't be automatically terminated if the parent process exits, so a leaked subprocess will stay around until manually killed. A convenient way to make sure that the subprocess is terminated is to use the :py:class:`ExifTool` instance as a context manager:: with ExifTool() as et: ... .. warning:: Note that options and parameters are not checked. There is no error handling or validation of options passed to *exiftool*. Nonsensical options are mostly silently ignored by exiftool, so there's not much that can be done in that regard. You should avoid passing non-existent files to any of the methods, since this will lead to undefined behaviour. """ ############################################################################## #################################### INIT #################################### ############################################################################## # ---------------------------------------------------------------------------------------------------------------------- def __init__(self, executable: Optional[str] = None, common_args: Optional[List[str]] = ["-G", "-n"], win_shell: bool = False, config_file: Optional[Union[str, Path]] = None, encoding: Optional[str] = None, logger = None) -> None: """ :param executable: Specify file name of the *exiftool* executable if it is in your ``PATH``. Otherwise, specify the full path to the ``exiftool`` executable. Passed directly into :py:attr:`executable` property. .. note:: The default value :py:attr:`exiftool.constants.DEFAULT_EXECUTABLE` will only work if the executable is in your ``PATH``. :type executable: str, or None to use default :param common_args: Pass in additional parameters for the stay-open instance of exiftool. Defaults to ``["-G", "-n"]`` as this is the most common use case. * ``-G`` (groupName level 1 enabled) separates the output with *groupName:tag* to disambiguate same-named tags under different groups. * ``-n`` (print conversion disabled) improves the speed and consistency of output, and is more machine-parsable Passed directly into :py:attr:`common_args` property. .. note:: Depending 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. .. _`Phil Harvey's exiftool documentation`: https://exiftool.org/exiftool_pod.html :type common_args: list of str, or None. :param bool win_shell: (Windows only) Minimizes the exiftool process. .. note:: This parameter may be deprecated in the future :param config_file: File path to ``-config`` parameter when starting exiftool process. Passed directly into :py:attr:`config_file` property. :type config_file: str, Path, or None :param encoding: Specify encoding to be used when communicating with exiftool process. By default, will use ``locale.getpreferredencoding()`` Passed directly into :py:attr:`encoding` property. :param logger: Set a custom logger to log status and debug messages to. Passed directly into :py:attr:`logger` property. """ # --- default settings / declare member variables --- self._running: bool = False # is it running? """A Boolean value indicating whether this instance is currently associated with a running subprocess.""" self._win_shell: bool = win_shell # do you want to see the shell on Windows? self._process = None # this is set to the process to interact with when _running=True self._ver: Optional[str] = None # this is set to be the exiftool -v -ver when running self._last_stdout: Optional[str] = None # previous output self._last_stderr: Optional[str] = None # previous stderr self._last_status: Optional[int] = None # previous exit status from exiftool (look up EXIT STATUS in exiftool documentation for more information) self._block_size: int = constants.DEFAULT_BLOCK_SIZE # set to default block size # these are set via properties self._executable: Union[str, Path] = constants.DEFAULT_EXECUTABLE # executable absolute path (default set to just the executable name, so it can't be None) self._config_file: Optional[str] = None # config file that can only be set when exiftool is not running self._common_args: Optional[List[str]] = None self._logger = None self._encoding: Optional[str] = None self._json_loads: Callable = json.loads # variable points to the actual callable method self._json_loads_kwargs: dict = {} # default optional params to pass into json.loads() call # --- run external library initialization code --- random.seed(None) # initialize random number generator # --- set variables via properties (which do the error checking) -- # set first, so that debug and info messages get logged self.logger = logger # use the passed in parameter, or the default if not set # error checking is done in the property.setter self.executable = executable or constants.DEFAULT_EXECUTABLE self.encoding = encoding self.common_args = common_args # set the property, error checking happens in the property.setter self.config_file = config_file ####################################################################################### #################################### MAGIC METHODS #################################### ####################################################################################### # ---------------------------------------------------------------------------------------------------------------------- def __enter__(self): self.run() return self # ---------------------------------------------------------------------------------------------------------------------- def __exit__(self, exc_type, exc_val, exc_tb) -> None: if self.running: self.terminate() # ---------------------------------------------------------------------------------------------------------------------- def __del__(self) -> None: if self.running: # indicate that __del__ has been started - allows running alternate code path in terminate() self.terminate(_del=True) ######################################################################################## #################################### PROPERTIES R/w #################################### ######################################################################################## # ---------------------------------------------------------------------------------------------------------------------- @property def executable(self) -> Union[str, Path]: """ Path to *exiftool* executable. :getter: Returns current exiftool path :setter: Specify just the executable name, or an absolute path to the executable. If path given is not absolute, searches environment ``PATH``. .. note:: Setting is only available when exiftool process is not running. :raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True) :type: str, Path """ return self._executable @executable.setter def executable(self, new_executable: Union[str, Path]) -> None: # cannot set executable when process is running if self.running: raise ExifToolRunning("Cannot set new executable") abs_path: Optional[str] = None # in testing, shutil.which() will work if a complete path is given, # but this isn't clear from documentation, so we explicitly check and # don't search if path exists if Path(new_executable).exists(): abs_path = new_executable else: # Python 3.3+ required abs_path = shutil.which(new_executable) if abs_path is None: raise FileNotFoundError(f'"{new_executable}" is not found, on path or as absolute path') # absolute path is returned self._executable = str(abs_path) if self._logger: self._logger.info(f"Property 'executable': set to \"{abs_path}\"") # ---------------------------------------------------------------------------------------------------------------------- @property def encoding(self) -> Optional[str]: """ Encoding of Popen() communication with *exiftool* process. :getter: Returns current encoding setting :setter: Set a new encoding. * 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). * Default to ``utf-8`` if nothing is returned by ``getpreferredencoding`` .. warning:: Property setter does NOT validate the encoding for validity. It is passed verbatim into subprocess.Popen() .. note:: Setting is only available when exiftool process is not running. :raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True) """ return self._encoding @encoding.setter def encoding(self, new_encoding: Optional[str]) -> None: # cannot set encoding when process is running if self.running: raise ExifToolRunning("Cannot set new encoding") # auto-detect system specific self._encoding = new_encoding or (locale.getpreferredencoding(do_setlocale=False) or ENCODING_UTF8) # ---------------------------------------------------------------------------------------------------------------------- @property def block_size(self) -> int: """ Block size for communicating with *exiftool* subprocess. Used when reading from the I/O pipe. :getter: Returns current block size :setter: Set a new block_size. Does basic error checking to make sure > 0. :raises ValueError: If new block size is invalid :type: int """ return self._block_size @block_size.setter def block_size(self, new_block_size: int) -> None: if new_block_size <= 0: raise ValueError("Block Size doesn't make sense to be <= 0") self._block_size = new_block_size if self._logger: self._logger.info(f"Property 'block_size': set to \"{new_block_size}\"") # ---------------------------------------------------------------------------------------------------------------------- @property def common_args(self) -> Optional[List[str]]: """ Common Arguments executed with every command passed to *exiftool* subprocess This is the parameter `-common_args`_ that is passed when the *exiftool* process is STARTED Read `Phil Harvey's ExifTool documentation`_ to get further information on what options are available / how to use them. .. _-common_args: https://exiftool.org/exiftool_pod.html#Advanced-options .. _Phil Harvey's ExifTool documentation: https://exiftool.org/exiftool_pod.html :getter: Returns current common_args list :setter: If ``None`` is passed in, sets common_args to ``[]``. Otherwise, sets the given list without any validation. .. warning:: No validation is done on the arguments list. It is passed verbatim to *exiftool*. Invalid options or combinations may result in undefined behavior. .. note:: Setting is only available when exiftool process is not running. :raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True) :raises TypeError: If setting is not a list :type: list[str], None """ return self._common_args @common_args.setter def common_args(self, new_args: Optional[List[str]]) -> None: if self.running: raise ExifToolRunning("Cannot set new common_args") if new_args is None: self._common_args = [] elif isinstance(new_args, list): # default parameters to exiftool # -n = disable print conversion (speedup) self._common_args = new_args else: raise TypeError("common_args not a list of strings") if self._logger: self._logger.info(f"Property 'common_args': set to \"{self._common_args}\"") # ---------------------------------------------------------------------------------------------------------------------- @property def config_file(self) -> Optional[Union[str, Path]]: """ Path to config file. See `ExifTool documentation for -config`_ for more details. :getter: Returns current config file path, or None if not set :setter: File existence is checked when setting parameter * Set to ``None`` to disable the ``-config`` parameter when starting *exiftool* * Set to ``""`` has special meaning and disables loading of the default config file. See `ExifTool documentation for -config`_ for more info. .. note:: Currently file is checked for existence when setting. It is not checked when starting process. :raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True) :type: str, Path, None .. _ExifTool documentation for -config: https://exiftool.org/exiftool_pod.html#Advanced-options """ return self._config_file @config_file.setter def config_file(self, new_config_file: Optional[Union[str, Path]]) -> None: if self.running: raise ExifToolRunning("Cannot set a new config_file") if new_config_file is None: self._config_file = None elif new_config_file == "": # this is VALID usage of -config parameter # As per exiftool documentation: Loading of the default config file may be disabled by setting CFGFILE to an empty string (ie. "") self._config_file = "" elif not Path(new_config_file).exists(): raise FileNotFoundError("The config file could not be found") else: self._config_file = str(new_config_file) if self._logger: self._logger.info(f"Property 'config_file': set to \"{self._config_file}\"") ############################################################################################## #################################### PROPERTIES Read only #################################### ############################################################################################## # ---------------------------------------------------------------------------------------------------------------------- @property def running(self) -> bool: """ Read-only property which indicates whether the *exiftool* subprocess is running or not. :getter: Returns current running state .. note:: This checks to make sure the process is still alive. If the process has died since last `running` detection, this property will detect the state change and reset the status accordingly. """ if self._running: # check if the process is actually alive if self._process.poll() is not None: # process died warnings.warn("ExifTool process was previously running but died") self._flag_running_false() if self._logger: self._logger.warning("Property 'running': ExifTool process was previously running but died") return self._running # ---------------------------------------------------------------------------------------------------------------------- @property def version(self) -> str: """ Read-only property which is the string returned by ``exiftool -ver`` The *-ver* command is ran once at process startup and cached. :getter: Returns cached output of ``exiftool -ver`` :raises ExifToolNotRunning: If attempting to read while not running (:py:attr:`running` == False) """ if not self.running: raise ExifToolNotRunning("Can't get ExifTool version") return self._ver # ---------------------------------------------------------------------------------------------------------------------- @property def last_stdout(self) -> Optional[Union[str, bytes]]: """ ``STDOUT`` for most recent result from execute() .. note:: The return type can be either str or bytes. If the most recent call to execute() ``raw_bytes=True``, then this will return ``bytes``. Otherwise this will be ``str``. .. note:: This property can be read at any time, and is not dependent on running state of ExifTool. It is INTENTIONALLY *NOT* CLEARED on exiftool termination, to allow for executing a command and terminating, but still having the result available. """ return self._last_stdout # ---------------------------------------------------------------------------------------------------------------------- @property def last_stderr(self) -> Optional[Union[str, bytes]]: """ ``STDERR`` for most recent result from execute() .. note:: The return type can be either ``str`` or ``bytes``. If the most recent call to execute() ``raw_bytes=True``, then this will return ``bytes``. Otherwise this will be ``str``. .. note:: This property can be read at any time, and is not dependent on running state of ExifTool. It is INTENTIONALLY *NOT* CLEARED on exiftool termination, to allow for executing a command and terminating, but still having the result available. """ return self._last_stderr # ---------------------------------------------------------------------------------------------------------------------- @property def last_status(self) -> Optional[int]: """ ``Exit Status Code`` for most recent result from execute() .. note:: This property can be read at any time, and is not dependent on running state of ExifTool. It is INTENTIONALLY *NOT* CLEARED on exiftool termination, to allow for executing a command and terminating, but still having the result available. """ return self._last_status ############################################################################################### #################################### PROPERTIES Write only #################################### ############################################################################################### # ---------------------------------------------------------------------------------------------------------------------- def _set_logger(self, new_logger) -> None: """ set a new user-created logging.Logger object can be set at any time to start logging. Set to None at any time to stop logging. """ if new_logger is None: self._logger = None return # can't check this in case someone passes a drop-in replacement, like loguru, which isn't type logging.Logger #elif not isinstance(new_logger, logging.Logger): # raise TypeError("logger needs to be of type logging.Logger") # do some basic checks on methods available in the "logger" provided check = True try: # ExifTool will probably use all of these logging method calls at some point # check all these are callable methods check = callable(new_logger.info) and \ callable(new_logger.warning) and \ callable(new_logger.error) and \ callable(new_logger.critical) and \ callable(new_logger.exception) except AttributeError: check = False if not check: raise TypeError("logger needs to implement methods (info,warning,error,critical,exception)") self._logger = new_logger # have to run this at the class level to create a special write-only property # https://stackoverflow.com/questions/17576009/python-class-property-use-setter-but-evade-getter # https://docs.python.org/3/howto/descriptor.html#properties # can have it named same or different logger = property(fset=_set_logger, doc="""Write-only property to set the class of logging.Logger""") """ Write-only property to set the class of logging.Logger If this is set, then status messages will log out to the given class. .. note:: This can be set and unset (set to ``None``) at any time, regardless of whether the subprocess is running (:py:attr:`running` == True) or not. :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``. :raises AttributeError: If object does not contain one or more of the required methods. :raises TypeError: If object contains those attributes, but one or more are non-callable methods. :type: Object """ ######################################################################################### ##################################### SETTER METHODS #################################### ######################################################################################### # ---------------------------------------------------------------------------------------------------------------------- def set_json_loads(self, json_loads, **kwargs) -> None: """ **Advanced**: Override default built-in ``json.loads()`` method. The method is only used once in :py:meth:`execute_json` This allows using a different json string parser. (Alternate json libraries typically provide faster speed than the built-in implementation, more supported features, and/or different behavior.) Examples of json libraries: `orjson`_, `rapidjson`_, `ujson`_, ... .. note:: This method is designed to be called the same way you would expect to call the provided ``json_loads`` method. Include any ``kwargs`` you would in the call. For example, to pass additional arguments to ``json.loads()``: ``set_json_loads(json.loads, parse_float=str)`` .. note:: This can be set at any time, regardless of whether the subprocess is running (:py:attr:`running` == True) or not. .. warning:: This setter does not check whether the method provided actually parses json. Undefined behavior or crashes may occur if used incorrectly This is **advanced configuration** for specific use cases only. For an example use case, see the :ref:`FAQ ` :param json_loads: A callable method to replace built-in ``json.loads`` used in :py:meth:`execute_json` :type json_loads: callable :param kwargs: Parameters passed to the ``json_loads`` method call :raises TypeError: If ``json_loads`` is not callable .. _orjson: https://pypi.org/project/orjson/ .. _rapidjson: https://pypi.org/project/python-rapidjson/ .. _ujson: https://pypi.org/project/ujson/ """ if not callable(json_loads): # not a callable method raise TypeError self._json_loads = json_loads self._json_loads_kwargs = kwargs ######################################################################################### #################################### PROCESS CONTROL #################################### ######################################################################################### # ---------------------------------------------------------------------------------------------------------------------- def run(self) -> None: """Start an *exiftool* subprocess in batch mode. This method will issue a ``UserWarning`` if the subprocess is already running (:py:attr:`running` == True). The process is started with :py:attr:`common_args` as common arguments, which are automatically included in every command you run with :py:meth:`execute()`. You can override these default arguments with the ``common_args`` parameter in the constructor or setting :py:attr:`common_args` before caaling :py:meth:`run()`. .. note:: If 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 :raises FileNotFoundError: If *exiftool* is no longer found. Re-raised from subprocess.Popen() :raises OSError: Re-raised from subprocess.Popen() :raises ValueError: Re-raised from subprocess.Popen() :raises subproccess.CalledProcessError: Re-raised from subprocess.Popen() :raises RuntimeError: Popen() launched process but it died right away :raises ExifToolVersionError: :py:attr:`exiftool.constants.EXIFTOOL_MINIMUM_VERSION` not met. ExifTool process will be automatically terminated. """ if self.running: warnings.warn("ExifTool already running; doing nothing.", UserWarning) return # first the executable ... # TODO should we check the executable for existence here? proc_args = [self._executable, ] # If working with a config file, it must be the first argument after the executable per: https://exiftool.org/config.html if self._config_file is not None: # must check explicitly for None, as "" is valid # TODO check that the config file exists here? proc_args.extend(["-config", self._config_file]) # this is the required stuff for the stay_open that makes pyexiftool so great! proc_args.extend(["-stay_open", "True", "-@", "-"]) # only if there are any common_args. [] and None are skipped equally with this if self._common_args: proc_args.append("-common_args") # add this param only if there are common_args proc_args.extend(self._common_args) # add the common arguments # ---- set platform-specific kwargs for Popen ---- kwargs: dict = {} if constants.PLATFORM_WINDOWS: # TODO: I don't think this code actually does anything ... I've never seen a console pop up on Windows # Perhaps need to specify subprocess.STARTF_USESHOWWINDOW to actually have any console pop up? # https://docs.python.org/3/library/subprocess.html#windows-popen-helpers startup_info = subprocess.STARTUPINFO() if not self._win_shell: # Adding enum 11 (SW_FORCEMINIMIZE in win32api speak) will # keep it from throwing up a DOS shell when it launches. startup_info.dwFlags |= constants.SW_FORCEMINIMIZE kwargs["startupinfo"] = startup_info else: # pytest-cov:windows: no cover # assume it's linux kwargs["preexec_fn"] = _set_pdeathsig(signal.SIGTERM) # Warning: The preexec_fn parameter is not safe to use in the presence of threads in your application. # https://docs.python.org/3/library/subprocess.html#subprocess.Popen try: # NOTE: the encoding= parameter was removed from the Popen() call to support # using bytes in the actual communication with exiftool process. # Due to the way the code is written, ExifTool only uses stdin.write which would need to be in bytes. # The reading is _NOT_ using subprocess.communicate(). This class reads raw bytes using os.read() # Therefore, by switching off the encoding= in Popen(), we can support both bytes and str at the # same time. (This change was to support https://github.com/sylikc/pyexiftool/issues/47) # unify both platform calls into one subprocess.Popen call self._process = subprocess.Popen( proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) except FileNotFoundError: raise except OSError: raise except ValueError: raise except subprocess.CalledProcessError: raise # TODO print out more useful error messages to these different errors above # check error above before saying it's running if self._process.poll() is not None: # the Popen launched, then process terminated self._process = None # unset it as it's now terminated raise RuntimeError("exiftool did not execute successfully") # have to set this before doing the checks below, or else execute() will fail self._running = True # get ExifTool version here and any Exiftool metadata # this can also verify that it is really ExifTool we ran, not some other random process try: # apparently because .execute() has code that already depends on v12.15+ functionality, # _parse_ver() will throw a ValueError immediately with: # ValueError: invalid literal for int() with base 10: '${status}' self._ver = self._parse_ver() except ValueError: # trap the error and return it as a minimum version problem self.terminate() raise ExifToolVersionError(f"Error retrieving Exiftool info. Is your Exiftool version ('exiftool -ver') >= required version ('{constants.EXIFTOOL_MINIMUM_VERSION}')?") if self._logger: self._logger.info(f"Method 'run': Exiftool version '{self._ver}' (pid {self._process.pid}) launched with args '{proc_args}'") # currently not needed... if it passes -ver check, the rest is OK # may use in the future again if another version feature is needed but the -ver check passes """ # check that the minimum required version is met, if not, terminate... # if you run against a version which isn't supported, strange errors come up during execute() if not self._exiftool_version_check(): self.terminate() if self._logger: self._logger.error(f"Method 'run': Exiftool version '{self._ver}' did not meet the required minimum version '{constants.EXIFTOOL_MINIMUM_VERSION}'") raise ExifToolVersionError(f"exiftool version '{self._ver}' < required '{constants.EXIFTOOL_MINIMUM_VERSION}'") """ # ---------------------------------------------------------------------------------------------------------------------- def terminate(self, timeout: int = 30, _del: bool = False) -> None: """Terminate the *exiftool* subprocess. If the subprocess isn't running, this method will throw a warning, and do nothing. .. note:: There is a bug in CPython 3.8+ on Windows where terminate() does not work during ``__del__()`` See CPython issue `starting a thread in __del__ hangs at interpreter shutdown`_ for more info. .. _starting a thread in __del__ hangs at interpreter shutdown: https://github.com/python/cpython/issues/87950 """ if not self.running: warnings.warn("ExifTool not running; doing nothing.", UserWarning) return if _del and constants.PLATFORM_WINDOWS: # don't cleanly exit on windows, during __del__ as it'll freeze at communicate() self._process.kill() #print("before comm", self._process.poll(), self._process) self._process.poll() # TODO freezes here on windows if subprocess zombie remains outs, errs = self._process.communicate() # have to cleanup the process or else .poll() will return None #print("after comm") # TODO a bug filed with Python, or user error... this doesn't seem to work at all ... .communicate() still hangs # https://bugs.python.org/issue43784 ... Windows-specific issue affecting Python 3.8-3.10 (as of this time) else: try: """ On Windows, running this after __del__ freezes at communicate(), regardless of timeout see the bug filed above for details On Linux, this runs as is, and the process terminates properly """ self._process.communicate(input=b"-stay_open\nFalse\n", timeout=timeout) # this is a constant sequence specified by PH's exiftool self._process.kill() except subprocess.TimeoutExpired: # this is new in Python 3.3 (for python 2.x, use the PyPI subprocess32 module) self._process.kill() outs, errs = self._process.communicate() # err handling code from https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate self._flag_running_false() # TODO log / return exit status from exiftool? if self._logger: self._logger.info("Method 'terminate': Exiftool terminated successfully.") ################################################################################## #################################### EXECUTE* #################################### ################################################################################## # ---------------------------------------------------------------------------------------------------------------------- def execute(self, *params: Union[str, bytes], raw_bytes: bool = False) -> Union[str, bytes]: """Execute the given batch of parameters with *exiftool*. This method accepts any number of parameters and sends them to the attached ``exiftool`` subprocess. The process must be running, otherwise :py:exc:`exiftool.exceptions.ExifToolNotRunning` is raised. The final ``-execute`` necessary to actually run the batch is appended automatically; see the documentation of :py:meth:`run()` for the common options. The ``exiftool`` output is read up to the end-of-output sentinel and returned as a ``str`` decoded based on the currently set :py:attr:`encoding`, excluding the sentinel. The parameters must be of type ``str`` or ``bytes``. ``str`` parameters are encoded to bytes automatically using the :py:attr:`encoding` property. For filenames, this should be the system's filesystem encoding. ``bytes`` parameters are untouched and passed directly to ``exiftool``. .. note:: This is the core method to interface with the ``exiftool`` subprocess. No processing is done on the input or output. :param params: One or more parameters to send to the ``exiftool`` subprocess. Typically passed in via `Unpacking Argument Lists`_ .. note:: The parameters to this function must be type ``str`` or ``bytes``. :type params: one or more string/bytes parameters :param raw_bytes: If True, returns bytes. Default behavior returns a str :return: * STDOUT is returned by the method call, and is also set in :py:attr:`last_stdout` * STDERR is set in :py:attr:`last_stderr` * Exit Status of the command is set in :py:attr:`last_status` :raises ExifToolNotRunning: If attempting to execute when not running (:py:attr:`running` == False) :raises ExifToolVersionError: If unexpected text was returned from the command while parsing out the sentinels :raises UnicodeDecodeError: If the :py:attr:`encoding` is not specified properly, it may be possible for ``.decode()`` method to raise this error :raises TypeError: If ``params`` argument is not ``str`` or ``bytes`` .. _Unpacking Argument Lists: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists """ if not self.running: raise ExifToolNotRunning("Cannot execute()") # ---------- build the special params to execute ---------- # there's a special usage of execute/ready specified in the manual which make almost ensure we are receiving the right signal back # from exiftool man pages: When this number is added, -q no longer suppresses the "{ready}" signal_num = random.randint(100000, 999999) # arbitrary create a 6 digit number (keep it down to save memory maybe) # constant special sequences when running -stay_open mode seq_execute = f"-execute{signal_num}\n" # the default string is b"-execute\n" seq_ready = f"{{ready{signal_num}}}" # the default string is b"{ready}" # these are special sequences to help with synchronization. It will print specific text to STDERR before and after processing #SEQ_STDERR_PRE_FMT = "pre{}" # can have a PRE sequence too but we don't need it for syncing seq_err_post = f"post{signal_num}" # default there isn't any string SEQ_ERR_STATUS_DELIM = "=" # this can be configured to be one or more chacters... the code below will accomodate for longer sequences: len() >= 1 seq_err_status = "${status}" # a special sequence, ${status} returns EXIT STATUS as per exiftool documentation - only supported on exiftool v12.10+ # ---------- build the params list and encode the params to bytes, if necessary ---------- cmd_params: List[bytes] = [] # this is necessary as the encoding parameter of Popen() is not specified. We manually encode as per the .encoding() parameter for p in params: # we use isinstance() over type() not only for subclass, but # according to https://switowski.com/blog/type-vs-isinstance # isinstance() is 40% faster than type() if isinstance(p, bytes): # no conversion needed, pass in raw (caller has already encoded) cmd_params.append(p) elif isinstance(p, str): # conversion needed, encode based on specified encoding cmd_params.append(p.encode(self._encoding)) else: # technically at this point we could support any object and call str() # but leave this up to an extended class like ExifToolHelper() raise TypeError(f"ERROR: Parameter was not bytes/str: {type(p)} => {p}") # f-strings are faster than concatentation of multiple strings -- https://stackoverflow.com/questions/59180574/string-concatenation-with-vs-f-string cmd_params.extend( (b"-echo4", f"{SEQ_ERR_STATUS_DELIM}{seq_err_status}{SEQ_ERR_STATUS_DELIM}{seq_err_post}".encode(self._encoding), seq_execute.encode(self._encoding)) ) cmd_bytes = b"\n".join(cmd_params) # ---------- write to the pipe connected with exiftool process ---------- self._process.stdin.write(cmd_bytes) self._process.stdin.flush() if self._logger: self._logger.info("Method 'execute': Command sent = {}".format(cmd_params[:-1])) # logs without the -execute (it would confuse people to include that) # ---------- read output from exiftool process until special sequences reached ---------- # NOTE: # # 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." # # this raw reading is used instead of Popen.communicate() due to the note: # https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate # # "The data read is buffered in memory, so do not use this method if the data size is large or unlimited." # # The data that comes back from exiftool falls into this, and so unbuffered reads are done with os.read() fdout = self._process.stdout.fileno() raw_stdout = _read_fd_endswith(fdout, seq_ready.encode(self._encoding), self._block_size) # when it's ready, we can safely read all of stderr out, as the command is already done fderr = self._process.stderr.fileno() raw_stderr = _read_fd_endswith(fderr, seq_err_post.encode(self._encoding), self._block_size) if not raw_bytes: # decode if not returning bytes raw_stdout = raw_stdout.decode(self._encoding) raw_stderr = raw_stderr.decode(self._encoding) # ---------- parse output ---------- # save the outputs to some variables first cmd_stdout = raw_stdout.strip()[:-len(seq_ready)] cmd_stderr = raw_stderr.strip()[:-len(seq_err_post)] # save it in case the error below happens and output can be checked easily # if raw_bytes is True, the check has to become bytes rather than str err_status_delim = SEQ_ERR_STATUS_DELIM if not raw_bytes else SEQ_ERR_STATUS_DELIM.encode(self._encoding) # sanity check the status code from the stderr output delim_len = len(err_status_delim) if cmd_stderr[-delim_len:] != err_status_delim: # 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 raise ExifToolVersionError(f"Exiftool expected to return status on stderr, but got unexpected character: {cmd_stderr[-delim_len:]} != {err_status_delim}") # 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) # 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 # you could just lop the last 3 characters off... but if the return status changes in the future, then this code would break err_delim_1 = cmd_stderr.rfind(err_status_delim, 0, -delim_len) cmd_status = cmd_stderr[err_delim_1 + delim_len : -delim_len] # ---------- save the output to class vars for later retrieval ---------- # lop off the actual status code from stderr self._last_stderr = cmd_stderr[:err_delim_1] self._last_stdout = cmd_stdout # can check .isnumeric() here, but best just to duck-type cast it self._last_status = int(cmd_status) if self._logger: self._logger.debug(f"{self.__class__.__name__}.execute: IN params = {params}") self._logger.debug(f"{self.__class__.__name__}.execute: OUT stdout = \"{self._last_stdout}\"") self._logger.debug(f"{self.__class__.__name__}.execute: OUT stderr = \"{self._last_stderr}\"") self._logger.debug(f"{self.__class__.__name__}.execute: OUT status = {self._last_status}") # the standard return: just stdout # if you need other output, retrieve from properties return self._last_stdout # ---------------------------------------------------------------------------------------------------------------------- def execute_json(self, *params: Union[str, bytes]) -> List: """Execute the given batch of parameters and parse the JSON output. This method is similar to :py:meth:`execute()`. It automatically adds the parameter ``-j`` to request JSON output from ``exiftool`` and parses the output. The return value is a list of dictionaries, mapping tag names to the corresponding values. All keys are strings. The values can have multiple types. Each dictionary contains the name of the file it corresponds to in the key ``"SourceFile"``. .. note:: By default, the tag names include the group name in the format : (if using the ``-G`` option). You can adjust the output structure with various *exiftool* options. .. warning:: This method does not verify the exit status code returned by *exiftool*. That is left up to the caller. This will mimic exiftool's default method of operation "continue on error" and "best attempt" to complete commands given. If you want automated error checking, use :py:class:`exiftool.ExifToolHelper` :param params: One or more parameters to send to the ``exiftool`` subprocess. Typically passed in via `Unpacking Argument Lists`_ .. note:: The parameters to this function must be type ``str`` or ``bytes``. :type params: one or more string/bytes parameters :return: Valid JSON parsed into a Python list of dicts :raises ExifToolOutputEmptyError: If *exiftool* did not return any STDOUT .. note:: This is not necessarily an *exiftool* error, but rather a programmer error. For example, setting tags can cause this behavior. If you are executing a command and expect no output, use :py:meth:`execute()` instead. :raises ExifToolJSONInvalidError: If *exiftool* returned STDOUT which is invalid JSON. .. note:: This is not necessarily an *exiftool* error, but rather a programmer error. For example, ``-w`` can cause this behavior. If you are executing a command and expect non-JSON output, use :py:meth:`execute()` instead. .. _Unpacking Argument Lists: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists """ result = self.execute("-j", *params) # stdout # NOTE: I have decided NOT to check status code # There are quite a few use cases where it's desirable to have continue-on-error behavior, # as that is exiftool's default mode of operation. exiftool normally just does what it can # and tells you that it did all this and that, but some files didn't process. In this case # exit code is non-zero, but exiftool did SOMETHING. I leave it up to the caller to figure # out what was done or not done. if len(result) == 0: # the output from execute() can be empty under many relatively ambiguous situations # * command has no files it worked on # * a file specified or files does not exist # * some other type of error # * a command that does not return anything (like metadata manipulation/setting tags) # # 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) # Returning [] could be ambiguous if Exiftool changes the returned JSON structure in the future # 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 # Raising an error is the current solution, as that clearly indicates that you used execute_json() expecting output, but got nothing raise ExifToolOutputEmptyError(self._last_status, self._last_stdout, self._last_stderr, params) try: parsed = self._json_loads(result, **self._json_loads_kwargs) except ValueError as e: # most known JSON libraries return ValueError or a subclass. # built-in json.JSONDecodeError is a subclass of ValueError -- https://docs.python.org/3/library/json.html#json.JSONDecodeError # if `-w` flag is specified in common_args or params, stdout will not be JSON parseable # # which will return something like: # x image files read # x output files created # 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 # explicit chaining https://www.python.org/dev/peps/pep-3134/ raise ExifToolJSONInvalidError(self._last_status, self._last_stdout, self._last_stderr, params) from e return parsed ######################################################################################### #################################### PRIVATE METHODS #################################### ######################################################################################### # ---------------------------------------------------------------------------------------------------------------------- def _flag_running_false(self) -> None: """ private method that resets the "running" state It used to be that there was only self._running to unset, but now it's a trio of variables This method makes it less likely a maintainer will leave off a variable if other ones are added in the future """ self._process = None # don't delete, just leave as None self._ver = None # unset the version self._running = False # as an FYI, as per the last_* properties, they are intentionally not cleared when process closes # ---------------------------------------------------------------------------------------------------------------------- def _parse_ver(self): """ private method to run exiftool -ver and parse out the information """ if not self.running: raise ExifToolNotRunning("Cannot get version") # -ver is just the version # -v gives you more info (perl version, platform, libraries) but isn't helpful for this library # -v2 gives you even more, but it's less useful at that point return self.execute("-ver").strip() # ---------------------------------------------------------------------------------------------------------------------- """ def _exiftool_version_check(self) -> bool: "" " private method to check the minimum required version of ExifTool returns false if the version check fails returns true if it's OK "" " # parse (major, minor) with integers... so far Exiftool versions are all ##.## with no exception # this isn't entirely tested... possibly a version with more "." or something might break this parsing arr: List = self._ver.split(".", 1) # split to (major).(whatever) version_nums: List = [] try: for v in arr: res.append(int(v)) except ValueError: raise ValueError(f"Error parsing ExifTool version for version check: '{self._ver}'") if len(version_nums) != 2: raise ValueError(f"Expected Major.Minor len()==2, got: {version_nums}") curr_major, curr_minor = version_nums # same logic above except on one line req_major, req_minor = [int(x) for x in constants.EXIFTOOL_MINIMUM_VERSION.split(".", 1)] if curr_major > req_major: # major version is bigger return True elif curr_major < req_major: # major version is smaller return False elif curr_minor >= req_minor: # major version is equal # current minor is equal or better return True else: # anything else is False return False """ # ---------------------------------------------------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/exiftool/experimental.py0000666000000000000000000003142000000000000015357 0ustar00# -*- coding: utf-8 -*- # # This file is part of PyExifTool. # # PyExifTool # # Copyright 2019-2023 Kevin M (sylikc) # Copyright 2012-2014 Sven Marnach # # Community contributors are listed in the CHANGELOG.md for the PRs # # PyExifTool is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the licence, or # (at your option) any later version, or the BSD licence. # # PyExifTool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See COPYING.GPL or COPYING.BSD for more details. """ This submodule contains the ``ExifToolAlpha`` class, which extends the ``ExifToolHelper`` class with experimental functionality. .. note:: :py:class:`exiftool.helper.ExifToolAlpha` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifToolAlpha` """ from pathlib import Path from .helper import ExifToolHelper try: # Py3k compatibility basestring except NameError: basestring = (bytes, str) # ====================================================================================================================== #def atexit_handler # constants related to keywords manipulations KW_TAGNAME = "IPTC:Keywords" KW_REPLACE, KW_ADD, KW_REMOVE = range(3) # ====================================================================================================================== #string helper def strip_nl(s): return ' '.join(s.splitlines()) # ====================================================================================================================== # Error checking function # very rudimentary checking # Note: They are quite fragile, because this just parses the output text from exiftool def check_ok(result): """Evaluates the output from a exiftool write operation (e.g. `set_tags`) The argument is the result from the execute method. The result is True or False. """ return not result is None and (not "due to errors" in result) # ====================================================================================================================== def format_error(result): """Evaluates the output from a exiftool write operation (e.g. `set_tags`) The argument is the result from the execute method. The result is a human readable one-line string. """ if check_ok(result): return f'exiftool probably finished properly. ("{strip_nl(result)}")' else: if result is None: return "exiftool operation can't be evaluated: No result given" else: return f'exiftool finished with error: "{strip_nl(result)}"' # ====================================================================================================================== class ExifToolAlpha(ExifToolHelper): """ This class is for the "experimental" functionality. In the grand scheme of things, this class contains "not well tested" functionality, methods that are less used, or methods with niche use cases. In some methods, edge cases on some of these methods may produce unexpected or ambiguous results. However, if there is increased demand, or robustness improves, functionality may merge into :py:class:`exiftool.ExifToolHelper` class. The starting point of this class was to remove all the "less used" functionality that was merged in on some arbitrary pull requests to the original v0.2 PyExifTool repository. This alpha-quality code is brittle and contains a lot of "hacks" for a niche set of use cases. As such, it may be buggy and it shouldn't crowd the core functionality of the :py:class:`exiftool.ExifTool` class or the stable extended functionality of the :py:class:`exiftool.ExifToolHelper` class with unneeded bloat. The class heirarchy: ExifTool -> ExifToolHelper -> ExifToolAlpha * ExifTool - stable base class with CORE functionality * ExifToolHelper - user friendly class that extends the base class with general functionality not found in the core * ExifToolAlpha - alpha-quality code which extends the ExifToolHelper to add functionality that is niche, brittle, or not well tested Because of this heirarchy, you could always use/extend the :py:class:`exiftool.ExifToolAlpha` class to have all functionality, or at your discretion, use one of the more stable classes above. Please issue PR to this class to add functionality, even if not tested well. This class is for experimental code after all! """ # ---------------------------------------------------------------------------------------------------------------------- # i'm not sure if the verification works, but related to pull request (#11) def execute_json_wrapper(self, filenames, params=None, retry_on_error=True): # make sure the argument is a list and not a single string # which would lead to strange errors if isinstance(filenames, basestring): raise TypeError("The argument 'filenames' must be an iterable of strings") execute_params = [] if params: execute_params.extend(params) execute_params.extend(filenames) result = self.execute_json(execute_params) if result: try: ExifToolAlpha._check_result_filelist(filenames, result) except IOError as error: # Restart the exiftool child process in these cases since something is going wrong self.terminate() self.run() if retry_on_error: result = self.execute_json_filenames(filenames, params, retry_on_error=False) else: raise error else: # Reasons for exiftool to provide an empty result, could be e.g. file not found, etc. # What should we do in these cases? We don't have any information what went wrong, therefore # we just return empty dictionaries. result = [{} for _ in filenames] return result # ---------------------------------------------------------------------------------------------------------------------- # allows adding additional checks (#11) def get_metadata_batch_wrapper(self, filenames, params=None): return self.execute_json_wrapper(filenames=filenames, params=params) # ---------------------------------------------------------------------------------------------------------------------- # (#11) def get_metadata_wrapper(self, filename, params=None): return self.execute_json_wrapper(filenames=[filename], params=params)[0] # ---------------------------------------------------------------------------------------------------------------------- # (#11) def get_tags_batch_wrapper(self, tags, filenames, params=None): params = (params if params else []) + ["-" + t for t in tags] return self.execute_json_wrapper(filenames=filenames, params=params) # ---------------------------------------------------------------------------------------------------------------------- # (#11) def get_tags_wrapper(self, tags, filename, params=None): return self.get_tags_batch_wrapper(tags, [filename], params=params)[0] # ---------------------------------------------------------------------------------------------------------------------- # (#11) def get_tag_batch_wrapper(self, tag, filenames, params=None): data = self.get_tags_batch_wrapper([tag], filenames, params=params) result = [] for d in data: d.pop("SourceFile") result.append(next(iter(d.values()), None)) return result # ---------------------------------------------------------------------------------------------------------------------- # this was a method with good intentions by the original author, but returns some inconsistent results in some cases # 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 # try calling get_tag_batch("*.mp4", "QuickTime") or "QuickTime:all" ... the expected results is a dictionary but a single tag is returned def get_tag_batch(self, filenames, tag): """Extract a single tag from the given files. The first argument is a single tag name, as usual in the format :. The second argument is an iterable of file names. The return value is a list of tag values or ``None`` for non-existent tags, in the same order as ``filenames``. """ data = self.get_tags(filenames, [tag]) result = [] for d in data: d.pop("SourceFile") result.append(next(iter(d.values()), None)) return result # ---------------------------------------------------------------------------------------------------------------------- # (#11) def get_tag_wrapper(self, tag, filename, params=None): return self.get_tag_batch_wrapper(tag, [filename], params=params)[0] # ---------------------------------------------------------------------------------------------------------------------- def get_tag(self, filename, tag): """ Extract a single tag from a single file. The return value is the value of the specified tag, or ``None`` if this tag was not found in the file. Does existence checks """ #return self.get_tag_batch([filename], tag)[0] p = Path(filename) if not p.exists(): raise FileNotFoundError data = self.get_tags(p, tag) if len(data) > 1: raise RuntimeError("one file requested but multiple returned?") d = data[0] d.pop("SourceFile") if len(d.values()) > 1: raise RuntimeError("multiple tag values returned, invalid use case") return next(iter(d.values()), None) # ---------------------------------------------------------------------------------------------------------------------- def copy_tags(self, from_filename, to_filename): """Copy all tags from one file to another.""" params = ["-overwrite_original", "-TagsFromFile", str(from_filename), str(to_filename)] self.execute(*params) # ---------------------------------------------------------------------------------------------------------------------- def set_keywords_batch(self, files, mode, keywords): """Modifies the keywords tag for the given files. The first argument is the operation mode: * KW_REPLACE: Replace (i.e. set) the full keywords tag with `keywords`. * KW_ADD: Add `keywords` to the keywords tag. If a keyword is present, just keep it. * KW_REMOVE: Remove `keywords` from the keywords tag. If a keyword wasn't present, just leave it. The second argument is an iterable of key words. The third argument is an iterable of file names. The format of the return value is the same as for :py:meth:`execute()`. It can be passed into `check_ok()` and `format_error()`. """ # Explicitly ruling out strings here because passing in a # string would lead to strange and hard-to-find errors if isinstance(keywords, basestring): raise TypeError("The argument 'keywords' must be " "an iterable of strings") # allow the files argument to be a str, and process it into a list of str filenames = self.__class__._parse_arg_files(files) params = [] kw_operation = {KW_REPLACE: "-%s=%s", KW_ADD: "-%s+=%s", KW_REMOVE: "-%s-=%s"}[mode] kw_params = [kw_operation % (KW_TAGNAME, w) for w in keywords] params.extend(kw_params) params.extend(filenames) if self._logger: self._logger.debug(params) return self.execute(*params) # ---------------------------------------------------------------------------------------------------------------------- def set_keywords(self, filename, mode, keywords): """Modifies the keywords tag for the given file. This is a convenience function derived from `set_keywords_batch()`. Only difference is that it takes as last argument only one file name as a string. """ return self.set_keywords_batch([filename], mode, keywords) # ---------------------------------------------------------------------------------------------------------------------- @staticmethod def _check_result_filelist(file_paths, result): """ Checks if the given file paths matches the 'SourceFile' entries in the result returned by exiftool. This is done to find possible mix ups in the streamed responses. """ # do some sanity checks on the results to make sure nothing was mixed up during reading from stdout if len(result) != len(file_paths): raise IOError(f"exiftool returned {len(result)} results, but expected was {len(file_paths)}") for i in range(len(file_paths)): returned_source_file = result[i].get('SourceFile') requested_file = file_paths[i] if returned_source_file != requested_file: raise IOError(f"exiftool returned data for file {returned_source_file}, but expected was {requested_file}") # ---------------------------------------------------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/exiftool/helper.py0000666000000000000000000005463600000000000014157 0ustar00# -*- coding: utf-8 -*- # # This file is part of PyExifTool. # # PyExifTool # # Copyright 2019-2023 Kevin M (sylikc) # Copyright 2012-2014 Sven Marnach # # Community contributors are listed in the CHANGELOG.md for the PRs # # PyExifTool is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the licence, or # (at your option) any later version, or the BSD licence. # # PyExifTool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See COPYING.GPL or COPYING.BSD for more details. """ This submodule contains the ``ExifToolHelper`` class, which makes the core ``ExifTool`` class easier, and safer to use. .. note:: :py:class:`exiftool.helper.ExifToolHelper` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifToolHelper` """ import re from .exiftool import ExifTool from .exceptions import ExifToolOutputEmptyError, ExifToolJSONInvalidError, ExifToolExecuteError, ExifToolTagNameError # basestring makes no sense in Python 3, so renamed tuple to this const TUPLE_STR_BYTES = (bytes, str) from typing import Any, Union, Optional, List, Dict # ====================================================================================================================== def _is_iterable(in_param: Any, ignore_str_bytes: bool = False) -> bool: """ Checks if this item is iterable, instead of using isinstance(list), anything iterable can be ok .. note:: STRINGS ARE CONSIDERED ITERABLE by Python if you need to consider a code path for strings first, check that before checking if a parameter is iterable via this function or specify ``ignore_str_bytes=True`` :param in_param: Something to check if iterable or not :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 """ if ignore_str_bytes and isinstance(in_param, TUPLE_STR_BYTES): return False # a different type of test of iterability, instead of using isinstance(list) # https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable try: iterator = iter(in_param) except TypeError: return False return True # ====================================================================================================================== class ExifToolHelper(ExifTool): """ This class extends the low-level :py:class:`exiftool.ExifTool` class with 'wrapper'/'helper' functionality It keeps low-level core functionality with the base class but extends helper functions in a separate class """ ########################################################################################## #################################### OVERRIDE METHODS #################################### ########################################################################################## # ---------------------------------------------------------------------------------------------------------------------- def __init__(self, auto_start: bool = True, check_execute: bool = True, check_tag_names: bool = True, **kwargs) -> None: """ :param bool auto_start: Will automatically start the exiftool process on first command run, defaults to True :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. :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. :param kwargs: All other parameters are passed directly to the super-class constructor: :py:meth:`exiftool.ExifTool.__init__()` """ # call parent's constructor super().__init__(**kwargs) self._auto_start: bool = auto_start self._check_execute: bool = check_execute self._check_tag_names: bool = check_tag_names # ---------------------------------------------------------------------------------------------------------------------- def execute(self, *params: Any, **kwargs) -> Union[str, bytes]: """ Override the :py:meth:`exiftool.ExifTool.execute()` method Adds logic to auto-start if not running, if :py:attr:`auto_start` == True Adds 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.) :raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero """ if self._auto_start and not self.running: self.run() # by default, any non-(str/bytes) would throw a TypeError from ExifTool.execute(), so they're casted to a string here # # duck-type any given object to string # this was originally to support Path() but it's now generic enough to support any object that str() to something useful # # Thanks @jangop for the single line contribution! str_bytes_params = [x if isinstance(x, TUPLE_STR_BYTES) else str(x) for x in params] # 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? result: Union[str, bytes] = super().execute(*str_bytes_params, **kwargs) # imitate the subprocess.run() signature. check=True will check non-zero exit status if self._check_execute and self._last_status: raise ExifToolExecuteError(self._last_status, self._last_stdout, self._last_stderr, str_bytes_params) return result # ---------------------------------------------------------------------------------------------------------------------- def run(self) -> None: """ override the :py:meth:`exiftool.ExifTool.run()` method Will not attempt to run if already running (so no warning about 'ExifTool already running' will trigger) """ if self.running: return super().run() # ---------------------------------------------------------------------------------------------------------------------- def terminate(self, **opts) -> None: """ Overrides the :py:meth:`exiftool.ExifTool.terminate()` method. Will not attempt to terminate if not running (so no warning about 'ExifTool not running' will trigger) :param opts: passed directly to the parent call :py:meth:`exiftool.ExifTool.terminate()` """ if not self.running: return super().terminate(**opts) ######################################################################################## #################################### NEW PROPERTIES #################################### ######################################################################################## # ---------------------------------------------------------------------------------------------------------------------- @property def auto_start(self) -> bool: """ Read-only property. Gets the current setting passed into the constructor as to whether auto_start is enabled or not. (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.) """ return self._auto_start # ---------------------------------------------------------------------------------------------------------------------- @property def check_execute(self) -> bool: """ Flag to enable/disable checking exit status (return code) on execute If enabled, will raise :py:exc:`exiftool.exceptions.ExifToolExecuteError` if a non-zero exit status is returned during :py:meth:`execute()` .. warning:: While this property is provided to give callers an option to enable/disable error checking, it is generally **NOT** recommended to disable ``check_execute``. **If disabled, exiftool will fail silently, and hard-to-catch bugs may arise.** That 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) :getter: Returns current setting :setter: Enable or Disable the check .. note:: This settings can be changed any time and will only affect subsequent calls :type: bool """ return self._check_execute @check_execute.setter def check_execute(self, new_setting: bool) -> None: self._check_execute = new_setting # ---------------------------------------------------------------------------------------------------------------------- @property def check_tag_names(self) -> bool: """ Flag to enable/disable checking of tag names If enabled, will raise :py:exc:`exiftool.exceptions.ExifToolTagNameError` if an invalid tag name is detected. .. warning:: ExifToolHelper only checks the validity of the Tag **NAME** based on a simple regex pattern. * It *does not* validate whether the tag name is actually valid on the file type(s) you're accessing. * It *does not* validate whether the tag you passed in that "looks like" a tag is actually an option * It does support a "#" at the end of the tag name to disable print conversion Please refer to `ExifTool Tag Names`_ documentation for a complete list of valid tags recognized by ExifTool. .. warning:: While 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``. **If disabled, you could accidentally edit a file when you meant to read it.** Example: ``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! That 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`_!). :getter: Returns current setting :setter: Enable or Disable the check .. note:: This settings can be changed any time and will only affect subsequent calls :type: bool .. _file an issue: https://github.com/sylikc/pyexiftool/issues .. _ExifTool Tag Names: https://exiftool.org/TagNames/ """ return self._check_tag_names @check_tag_names.setter def check_tag_names(self, new_setting: bool) -> None: self._check_tag_names = new_setting # ---------------------------------------------------------------------------------------------------------------------- ##################################################################################### #################################### NEW METHODS #################################### ##################################################################################### # all generic helper functions will follow a convention of # function(files to be worked on, ... , params=) # ---------------------------------------------------------------------------------------------------------------------- def get_metadata(self, files: Union[str, List], params: Optional[Union[str, List]] = None) -> List: """ Return all metadata for the given files. .. note:: This is a convenience method. The implementation calls :py:meth:`get_tags()` with ``tags=None`` :param files: Files parameter matches :py:meth:`get_tags()` :param params: Optional parameters to send to *exiftool* :type params: list or None :return: The return value will have the format described in the documentation of :py:meth:`get_tags()`. """ return self.get_tags(files, None, params=params) # ---------------------------------------------------------------------------------------------------------------------- def get_tags(self, files: Union[Any, List[Any]], tags: Optional[Union[str, List]], params: Optional[Union[str, List]] = None) -> List: """ Return only specified tags for the given files. :param files: File(s) to be worked on. * If a non-iterable is provided, it will get tags for a single item (str(non-iterable)) * If an iterable is provided, the list is passed into :py:meth:`execute_json` verbatim. .. note:: Any files/params which are not bytes/str will be casted to a str in :py:meth:`execute()`. .. warning:: Currently, filenames are NOT checked for existence! That is left up to the caller. .. warning:: Wildcard strings are valid and passed verbatim to exiftool. However, exiftool's wildcard matching/globbing may be different than Python's matching/globbing, which may cause unexpected behavior if you're using one and comparing the result to the other. Read `ExifTool Common Mistakes - Over-use of Wildcards in File Names`_ for some related info. :type files: Any or List(Any) - see Note :param tags: Tag(s) to read. If tags is None, or [], method will returns all tags .. note:: The tag names may include group names, as usual in the format ``:``. :type tags: str, list, or None :param params: Optional parameter(s) to send to *exiftool* :type params: Any, List[Any], or None :return: The format of the return value is the same as for :py:meth:`exiftool.ExifTool.execute_json()`. :raises ValueError: Invalid Parameter :raises TypeError: Invalid Parameter :raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero .. _ExifTool Common Mistakes - Over-use of Wildcards in File Names: https://exiftool.org/mistakes.html#M2 """ final_tags: Optional[List] = None final_files: List = self.__class__._parse_arg_files(files) if tags is None: # all tags final_tags = [] elif isinstance(tags, TUPLE_STR_BYTES): final_tags = [tags] elif _is_iterable(tags): final_tags = tags else: raise TypeError(f"{self.__class__.__name__}.get_tags: argument 'tags' must be a str/bytes or a list") if self._check_tag_names: # run check if enabled self.__class__._check_tag_list(final_tags) exec_params: List = [] # we extend an empty list to avoid modifying any referenced inputs if params: if _is_iterable(params, ignore_str_bytes=True): exec_params.extend(params) else: exec_params.append(params) # tags is always a list by this point. It will always be iterable... don't have to check for None exec_params.extend([f"-{t}" for t in final_tags]) exec_params.extend(final_files) try: ret = self.execute_json(*exec_params) except ExifToolOutputEmptyError: raise #raise RuntimeError(f"{self.__class__.__name__}.get_tags: exiftool returned no data") except ExifToolJSONInvalidError: raise except ExifToolExecuteError: # if last_status is <> 0, raise an error that one or more files failed? raise return ret # ---------------------------------------------------------------------------------------------------------------------- def set_tags(self, files: Union[Any, List[Any]], tags: Dict, params: Optional[Union[str, List]] = None): """ Writes the values of the specified tags for the given file(s). :param files: File(s) to be worked on. * If a non-iterable is provided, it will get tags for a single item (str(non-iterable)) * If an iterable is provided, the list is passed into :py:meth:`execute_json` verbatim. .. note:: Any files/params which are not bytes/str will be casted to a str in :py:meth:`execute()`. .. warning:: Currently, filenames are NOT checked for existence! That is left up to the caller. .. warning:: Wildcard strings are valid and passed verbatim to exiftool. However, exiftool's wildcard matching/globbing may be different than Python's matching/globbing, which may cause unexpected behavior if you're using one and comparing the result to the other. Read `ExifTool Common Mistakes - Over-use of Wildcards in File Names`_ for some related info. :type files: Any or List(Any) - see Note :param tags: Tag(s) to write. Dictionary keys = tags, values = tag values (str or list) * If a value is a str, will set key=value * If a value is a list, will iterate over list and set each individual value to the same tag ( .. note:: The tag names may include group names, as usual in the format ``:``. .. note:: Value 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 This allows setting things like ``-Keywords=a -Keywords=b -Keywords=c`` by passing in ``tags={"Keywords": ['a', 'b', 'c']}`` :type tags: dict :param params: Optional parameter(s) to send to *exiftool* :type params: str, list, or None :return: The format of the return value is the same as for :py:meth:`execute()`. :raises ValueError: Invalid Parameter :raises TypeError: Invalid Parameter :raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero .. _ExifTool Common Mistakes - Over-use of Wildcards in File Names: https://exiftool.org/mistakes.html#M2 """ final_files: List = self.__class__._parse_arg_files(files) if not tags: raise ValueError(f"{self.__class__.__name__}.set_tags: argument 'tags' cannot be empty") elif not isinstance(tags, dict): raise TypeError(f"{self.__class__.__name__}.set_tags: argument 'tags' must be a dict") if self._check_tag_names: # run check if enabled self.__class__._check_tag_list(list(tags)) # gets only the keys (tag names) exec_params: List = [] # we extend an empty list to avoid modifying any referenced inputs if params: if _is_iterable(params, ignore_str_bytes=True): exec_params.extend(params) else: exec_params.append(params) for tag, value in tags.items(): # contributed by @daviddorme in https://github.com/sylikc/pyexiftool/issues/12#issuecomment-821879234 # allows setting things like Keywords which require separate directives # > exiftool -Keywords=keyword1 -Keywords=keyword2 -Keywords=keyword3 file.jpg # which are not supported as duplicate keys in a dictionary if isinstance(value, list): for item in value: exec_params.append(f"-{tag}={item}") else: exec_params.append(f"-{tag}={value}") exec_params.extend(final_files) try: return self.execute(*exec_params) #TODO if execute returns data, then error? except ExifToolExecuteError: # last status non-zero raise # ---------------------------------------------------------------------------------------------------------------------- ######################################################################################### #################################### PRIVATE METHODS #################################### ######################################################################################### # ---------------------------------------------------------------------------------------------------------------------- @staticmethod def _parse_arg_files(files: Union[str, List]) -> List: """ This logic to process the files argument is common across most ExifToolHelper methods It can be used by a developer to process the files argument the same way if this class is extended :param files: File(s) to be worked on. :type files: str or list :return: A list of one or more elements containing strings of files :raises ValueError: Files parameter is empty """ final_files: List = [] if not files: # Exiftool process would return an error anyways raise ValueError("ERROR: Argument 'files' cannot be empty") elif not _is_iterable(files, ignore_str_bytes=True): # if it's not a string but also not iterable final_files = [files] else: final_files = files return final_files # ---------------------------------------------------------------------------------------------------------------------- @staticmethod def _check_tag_list(tags: List) -> None: """ Private method. This method is used to check the validity of a tag list passed in. See any notes/warnings in the property :py:attr:`check_tag_names` to get a better understanding of what this is for and not for. :param list tags: List of tags to check :return: None if checks passed. Raises an error otherwise. (Think of it like an assert statement) """ # In the future if a specific version changed the match pattern, # we can check self.version ... then this method will no longer # be static and requires the underlying exiftool process to be running to get the self.version # # This is not done right now because the odds of the tag name format changing is very low, and requirin # exiftool to be running during this tag check could introduce unneccesary overhead at this time # According to the exiftool source code, the valid regex on tags is (/^([-\w*]+:)*([-\w*?]+)#?$/) # However, it appears that "-" may be allowed within a tag name/group (i.e. https://exiftool.org/TagNames/XMP.html Description tags) # # \w in Perl => https://perldoc.perl.org/perlrecharclass#Backslash-sequences # \w in Python => https://docs.python.org/3/library/re.html#regular-expression-syntax # # Perl vs Python's "\w" seem to mean slightly different things, so we write our own regex / matching algo # * make sure the first character is not a special one # * "#" can only appear at the end # * 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. # * *wildcard* tags are permitted by exiftool tag_regex = r"[\w\*][\w\:\-\*]*(#|)" for t in tags: if re.fullmatch(tag_regex, t) is None: raise ExifToolTagNameError(t) # returns nothing, if no error was raised, the tags passed # considering making this... # * can't begin with - # * can't have "=" anywhere, and that's it... # there's a lot of variations which might make this code buggy for some edge use cases # ---------------------------------------------------------------------------------------------------------------------- ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1698016597.576977 PyExifTool-0.5.6/setup.cfg0000666000000000000000000000020200000000000012272 0ustar00[metadata] version = attr: exiftool.__version__ [bdist_rpm] requires = exiftool [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/setup.py0000666000000000000000000000760000000000000012174 0ustar00# -*- coding: utf-8 -*- # # This file is part of PyExifTool. # # PyExifTool # # Copyright 2019-2023 Kevin M (sylikc) # Copyright 2012-2014 Sven Marnach # # Community contributors are listed in the CHANGELOG.md for the PRs # # PyExifTool is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the licence, or # (at your option) any later version, or the BSD licence. # # PyExifTool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See COPYING.GPL or COPYING.BSD for more details. # 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 #from distutils.core import setup # recommended packager, though must be installed via PyPI # https://packaging.python.org/tutorials/packaging-projects/#configuring-metadata from setuptools import setup, find_packages import re def get_long_desc(): """ read README.rst skipping some of the badges (don't need those showing up on PyPI) """ with open("README.rst", "r", encoding="utf-8") as fh: long_desc = fh.read() # crop out the portion between HIDE_FROM_PYPI_START and HIDE_FROM_PYPI_END sub_pattern = r"^\.\. HIDE_FROM_PYPI_START.+\.\. HIDE_FROM_PYPI_END$" long_desc = re.sub(sub_pattern, "", long_desc, flags=re.MULTILINE | re.DOTALL) return long_desc setup( # detailed list of options: # https://packaging.python.org/guides/distributing-packages-using-setuptools/ # overview name="PyExifTool", # version is configured in setup.cfg - https://packaging.python.org/en/latest/guides/single-sourcing-package-version/ #version=, license="GPLv3+/BSD", url="http://github.com/sylikc/pyexiftool", python_requires=">=3.6", # authors author="Kevin M (sylikc), Sven Marnach, various contributors", author_email="sylikc@gmail.com", # info description="Python wrapper for exiftool", long_description=get_long_desc(), long_description_content_type="text/x-rst", keywords="exiftool image exif metadata photo video photography", project_urls={ # this seems to get populated in PyPI in reverse order "Source": "https://github.com/sylikc/pyexiftool", "Tracker": "https://github.com/sylikc/pyexiftool/issues", "Changelog": "https://github.com/sylikc/pyexiftool/blob/master/CHANGELOG.md", "Documentation": "https://sylikc.github.io/pyexiftool/", }, classifiers=[ # list is here: # https://pypi.org/classifiers/ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Topic :: Multimedia", "Topic :: Utilities", ], # include is more robust that exclude packages=find_packages( #where=".", #exclude = ['test*','doc*'], include=['exiftool', 'exiftool.*'], ), extras_require={ "json": ["ujson", "simplejson", "orjson"], # any supported alternative json parser for ExifTool "test": ["packaging"], # dependencies to do tests "docs": ["packaging", "sphinx", "sphinx-autoapi", "sphinx-rtd-theme", "sphinx-autodoc-typehints"], # dependencies to build docs }, #package_dir={'exiftool': 'exiftool'}, #py_modules=["exiftool"], - it is now the exiftool module ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1698016597.5719903 PyExifTool-0.5.6/tests/0000777000000000000000000000000000000000000011621 5ustar00././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/tests/test_alpha.py0000666000000000000000000000750500000000000014326 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifToolAlpha - misc tests """ # standard import unittest from pathlib import Path import shutil # pip #from packaging import version # test helpers from tests.common_util import et_get_temp_dir, TEST_IMAGE_DIR # custom import exiftool class TestAlphaTagCopying(unittest.TestCase): """ We duplicate an image with metadata, erase all metadata in the copy, and then copy the tags. """ def setUp(self): # Prepare exiftool self.exiftool = exiftool.ExifToolAlpha(encoding="UTF-8") self.exiftool.run() # Find example image. self.tag_source = TEST_IMAGE_DIR / "rose.jpg" # Prepare path of copy. (self.temp_obj, self.temp_dir) = et_get_temp_dir(suffix="ttc") self.tag_target = self.temp_dir / "rose-tagcopy.jpg" # Copy image. shutil.copyfile(self.tag_source, self.tag_target) # Clear tags in copy. params = ["-overwrite_original", "-all=", str(self.tag_target)] self.exiftool.execute(*params) def tearDown(self): self.exiftool.terminate() # Apparently, Windows needs this. CPython bug def test_tag_copying(self): tag = "XMP:Subject" expected_value = "Röschen" # Ensure source image has correct tag. original_value = self.exiftool.get_tag(self.tag_source, tag) self.assertEqual(original_value, expected_value) # Ensure target image does not already have that tag. value_before_copying = self.exiftool.get_tag(self.tag_target, tag) self.assertNotEqual(value_before_copying, expected_value) # Copy tags. self.exiftool.copy_tags(self.tag_source, self.tag_target) value_after_copying = self.exiftool.get_tag(self.tag_target, tag) self.assertEqual(value_after_copying, expected_value) class TestAlphaSetKeywords(unittest.TestCase): def setUp(self): self.et = exiftool.ExifToolAlpha( common_args=["-G", "-n", "-overwrite_original"], encoding="UTF-8" ) def tearDown(self): self.et.terminate() def test_set_keywords(self): (temp_obj, temp_dir) = et_get_temp_dir(suffix="setkw") kw_to_add = ["added"] mod_prefix = "newkw_" expected_data = [ {"SourceFile": Path("rose.jpg"), "Keywords": ["nature", "red plant"]} ] source_files = [] for d in expected_data: d["SourceFile"] = f = TEST_IMAGE_DIR / d["SourceFile"] self.assertTrue(f.exists()) f_mod = temp_dir / (mod_prefix + f.name) f_mod_str = str(f_mod) self.assertFalse( f_mod.exists(), "%s should not exist before the test. Please delete." % f_mod, ) shutil.copyfile(f, f_mod) source_files.append(f_mod) with self.et: self.et.set_keywords( f_mod_str, exiftool.experimental.KW_REPLACE, d["Keywords"] ) kwtag0 = self.et.get_tag(f_mod_str, "IPTC:Keywords") kwrest = d["Keywords"][1:] self.et.set_keywords(f_mod_str, exiftool.experimental.KW_REMOVE, kwrest) kwtag1 = self.et.get_tag(f_mod_str, "IPTC:Keywords") self.et.set_keywords(f_mod_str, exiftool.experimental.KW_ADD, kw_to_add) kwtag2 = self.et.get_tag(f_mod_str, "IPTC:Keywords") # f_mod.unlink() # don't delete file, tempdir will take care of it self.assertEqual(kwtag0, d["Keywords"]) self.assertEqual(kwtag1, d["Keywords"][0]) self.assertEqual(kwtag2, [d["Keywords"][0]] + kw_to_add) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1661648545.0 PyExifTool-0.5.6/tests/test_exiftool_attr.py0000666000000000000000000000773100000000000016125 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifTool base class - misc attribute validation tests """ # standard import unittest from pathlib import Path # test helpers from tests.common_util import TEST_IMAGE_JPG # custom import exiftool from exiftool.exceptions import ExifToolRunning, ExifToolNotRunning class TestExifToolAttrValidation(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifTool(common_args=["-G", "-n", "-overwrite_original"]) def tearDown(self): if self.et.running: self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_running_attribute(self): # test if we can read "running" but can't set it self.assertFalse(self.et.running) with self.assertRaises(AttributeError): self.et.running = True # --------------------------------------------------------------------------------------------------------- def test_executable_attribute(self): # test if we can read "running" but can't set it self.assertFalse(self.et.running) self.et.run() self.assertTrue(self.et.running) # if it's running, the executable has to exist (test coverage on reading the property) e = self.et.executable self.assertTrue(Path(e).exists()) with self.assertRaises(ExifToolRunning): self.et.executable = "foo.bar" self.et.terminate() with self.assertRaises(FileNotFoundError): self.et.executable = "foo.bar" # specify the executable explicitly with the one known to exist (test coverage) self.et.executable = e self.assertEqual(self.et.executable, e) # absolute path set should not change self.assertFalse(self.et.running) # --------------------------------------------------------------------------------------------------------- def test_blocksize_attribute(self): current = self.et.block_size # arbitrary self.et.block_size = 4 self.assertEqual(self.et.block_size, 4) with self.assertRaises(ValueError): self.et.block_size = -1 with self.assertRaises(ValueError): self.et.block_size = 0 # restore self.et.block_size = current # --------------------------------------------------------------------------------------------------------- def test_encoding_attribute(self): current = self.et.encoding self.et.run() # cannot set when running with self.assertRaises(ExifToolRunning): self.et.encoding = "foo.bar" self.et.terminate() self.et.encoding = "foo" self.assertEqual(self.et.encoding, "foo") # restore self.et.encoding = current # --------------------------------------------------------------------------------------------------------- def test_common_args_attribute(self): self.et.run() with self.assertRaises(ExifToolRunning): self.et.common_args = [] # --------------------------------------------------------------------------------------------------------- def test_version_attribute(self): self.et.run() # no error a = self.et.version self.et.terminate() # version is invalid when not running with self.assertRaises(ExifToolNotRunning): a = self.et.version # --------------------------------------------------------------------------------------------------------- def test_laststdout_attr(self): """ is the attribute available after a run? """ self.et.run() stdo = self.et.execute(str(TEST_IMAGE_JPG)) stde = self.et.last_stderr self.et.terminate() self.assertFalse(self.et.running) self.assertEqual(self.et.last_stdout, stdo) self.assertEqual(self.et.last_stderr, stde) # --------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1661648545.0 PyExifTool-0.5.6/tests/test_exiftool_bytes.py0000666000000000000000000000406000000000000016271 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifTool base class - execute() using raw_bytes parameter """ # standard import unittest import shutil # test helpers from tests.common_util import et_get_temp_dir, TEST_IMAGE_DIR, TEST_IMAGE_JPG, create_random_bin_file # custom import exiftool class TestExifToolBytes(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifTool(common_args=["-G", "-n", "-overwrite_original"], config_file=TEST_IMAGE_DIR / "my_makernotes.config") (self.temp_obj, self.temp_dir) = et_get_temp_dir(suffix="etbytes") def tearDown(self): if self.et.running: self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_read_write_binary(self): """ test reading and writing binary data """ self.assertFalse(self.et.running) self.et.run() ### set up files ### # write a binary file to test with ... we can make it random or the same, shouldn't matter BIN_FILE_SIZE = 1024 p_bin_file = self.temp_dir / "test_data.bin" create_random_bin_file(p_bin_file, BIN_FILE_SIZE) p_jpg_file = self.temp_dir / "rose.jpg" shutil.copyfile(TEST_IMAGE_JPG, p_jpg_file) ### write the binary data ### self.et.execute(f"-MyMakerNotes<={p_bin_file}", str(p_jpg_file)) self.assertEqual(self.et.last_status, 0) ### read the binary data and compare ### with open(p_bin_file, 'rb') as f: bin_file_data = f.read() # make sure it's the right amount of bytes wrote in originally self.assertEqual(len(bin_file_data), BIN_FILE_SIZE) # get the custom tag written_bin_data = self.et.execute("-b", "-MyMakerNotes", str(p_jpg_file), raw_bytes=True) # check that they are equal self.assertEqual(bin_file_data, written_bin_data) # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/tests/test_exiftool_configfile.py0000666000000000000000000000406100000000000017251 0ustar00""" Test :: ExifTool base class - config_file attribute """ # standard import unittest # test helpers from tests.common_util import et_get_temp_dir # custom import exiftool from exiftool.exceptions import ExifToolRunning class TestExifToolConfigFile(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifTool(common_args=["-G", "-n", "-overwrite_original"]) def tearDown(self): if self.et.running: self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_configfile_attribute(self): current = self.et.config_file with self.assertRaises(FileNotFoundError): self.et.config_file = "foo.bar" # see if Python 3.9.5 fixed this ... raises OSError right now and is a pathlib glitch https://bugs.python.org/issue35306 #self.et.config_file = "\"C:\\\"\"C:\\" # then restore current config_file self.et.config_file = current self.assertFalse(self.et.running) self.et.run() self.assertTrue(self.et.running) with self.assertRaises(ExifToolRunning): self.et.config_file = None self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_configfile_set(self): (temp_obj, temp_dir) = et_get_temp_dir(suffix="config") # set config file to empty, which is valid (should not throw error) self.et.config_file = "" # create a config file, and set it and test that it works # a file that returns 1 is valid as a config file tmp_config_file = temp_dir / "config_test.txt" with open(tmp_config_file, 'w') as f: f.write("1;\n") self.et.config_file = tmp_config_file self.et.run() self.assertTrue(self.et.running) self.et.terminate() # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1646966505.0 PyExifTool-0.5.6/tests/test_exiftool_logger.py0000666000000000000000000000232300000000000016422 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifTool base class - logger tests """ # standard import unittest import logging # custom import exiftool class TestExifToolLogger(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifTool(common_args=["-G", "-n", "-overwrite_original"]) def tearDown(self): if self.et.running: self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_logger(self): """ TODO improve this test, currently very rudimentary """ log = logging.getLogger("log_test") #log.level = logging.WARNING #logpath = TMP_DIR / 'exiftool_test.log' #fh = logging.FileHandler(logpath) #log.addHandler(fh) self.et.logger = log # no errors log = "bad log" # not a logger object with self.assertRaises(TypeError): self.et.logger = log self.et.run() # get some coverage by doing stuff # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1661648545.0 PyExifTool-0.5.6/tests/test_exiftool_misc.py0000666000000000000000000000562200000000000016103 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifTool base class - misc tests """ # standard import unittest import warnings from pathlib import Path # test helpers from tests.common_util import TEST_IMAGE_JPG # custom import exiftool from exiftool.exceptions import ExifToolNotRunning class TestExifToolMisc(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifTool(common_args=["-G", "-n", "-overwrite_original"]) def tearDown(self): if self.et.running: self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_get_version_protected(self): """ test the protected method which can't be called when exiftool not running """ self.assertFalse(self.et.running) self.assertRaises(ExifToolNotRunning, self.et._parse_ver) # --------------------------------------------------------------------------------------------------------- def test_invalid_args_list(self): # test to make sure passing in an invalid args list will cause it to error out with self.assertRaises(TypeError): exiftool.ExifTool(common_args="not a list") # --------------------------------------------------------------------------------------------------------- def test_common_args(self): # test to make sure passing in an invalid args list will cause it to error out with self.assertRaises(TypeError): exiftool.ExifTool(common_args={}) # set to common_args=None == [] self.assertEqual(exiftool.ExifTool(common_args=None).common_args, []) # --------------------------------------------------------------------------------------------------------- def test_run_twice(self): """ test that a UserWarning is thrown when run() is called twice """ self.assertFalse(self.et.running) self.et.run() with warnings.catch_warnings(record=True) as w: self.assertTrue(self.et.running) self.et.run() self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, UserWarning)) # --------------------------------------------------------------------------------------------------------- def test_execute_types(self): """ test execute with different types """ self.assertFalse(self.et.running) self.et.run() # no error with str self.et.execute("-ver") # no error with bytes self.et.execute(b"-ver") # no error with str self.et.execute(str(TEST_IMAGE_JPG)) # error with Path with self.assertRaises(TypeError): self.et.execute(Path(TEST_IMAGE_JPG)) # --------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1646966347.0 PyExifTool-0.5.6/tests/test_exiftool_process.py0000666000000000000000000001074700000000000016632 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifTool base class - process-related tests """ # standard import unittest import warnings # custom import exiftool from exiftool.exceptions import ExifToolNotRunning # bool which is set to True when running on Windows # used below to workaround a Windows buggy interaction with exiftool subprocess from exiftool.constants import PLATFORM_WINDOWS class TestExifToolProcess(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifTool(common_args=["-G", "-n", "-overwrite_original"]) def tearDown(self): if hasattr(self, "et"): if self.et.running: self.et.terminate() if hasattr(self, "process"): if self.process.poll() is None: self.process.terminate() # --------------------------------------------------------------------------------------------------------- def test_termination_cm(self): # Test correct subprocess start and termination when using # self.et as a context manager self.assertFalse(self.et.running) self.assertRaises(ExifToolNotRunning, self.et.execute) with self.et: self.assertTrue(self.et.running) with warnings.catch_warnings(record=True) as w: self.et.run() self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, UserWarning)) self.process = self.et._process self.assertEqual(self.process.poll(), None) self.assertFalse(self.et.running) self.assertNotEqual(self.process.poll(), None) # --------------------------------------------------------------------------------------------------------- def test_termination_explicit(self): # Test correct subprocess start and termination when # explicitly using start() and terminate() self.et.run() self.process = self.et._process self.assertEqual(self.process.poll(), None) self.et.terminate() self.assertNotEqual(self.process.poll(), None) # terminate when not running with warnings.catch_warnings(record=True) as w: self.et.terminate() self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, UserWarning)) # --------------------------------------------------------------------------------------------------------- def test_process_died_running_status(self): """ Test correct .running status if process dies by itself """ # There is a very weird bug triggered on WINDOWS only which I've described here: https://exiftool.org/forum/index.php?topic=12472.0 # 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 # it's a very strange interaction and causes a zombie process to remain, and python hangs # # either kill the tree with psutil, or do it this way... # 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 if PLATFORM_WINDOWS: self.et._parse_ver = lambda: None self.et.run() self.process = self.et._process self.assertTrue(self.et.running) # kill the process, out of ExifTool's control self.process.kill() # TODO freeze here on windows if there is a zombie process b/c killing immediate exiftool does not kill the spawned subprocess outs, errs = self.process.communicate() with warnings.catch_warnings(record=True) as w: self.assertFalse(self.et.running) self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, UserWarning)) # after removing that function, delete the object so it gets recreated cleanly del self.et # --------------------------------------------------------------------------------------------------------- def test_termination_implicit(self): # Test implicit process termination on garbage collection # WINDOWS WORKAROUND: take out the method that is called on load (see test_process_died_running_status()) if PLATFORM_WINDOWS: self.et._parse_ver = lambda: None self.et.run() self.process = self.et._process # TODO freze here on windows for same reason as in test_process_died_running_status() as a zombie process remains del self.et self.assertNotEqual(self.process.poll(), None) # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1646973867.0 PyExifTool-0.5.6/tests/test_helper_checkexecute.py0000666000000000000000000000446300000000000017240 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifToolHelper - misc tests """ # standard import unittest # test helpers from tests.common_util import et_get_temp_dir, TEST_IMAGE_JPG # custom import exiftool from exiftool.exceptions import ExifToolOutputEmptyError, ExifToolJSONInvalidError, ExifToolExecuteError class TestHelperCheckExecute(unittest.TestCase): @classmethod def setUp(self) -> None: self.eth = exiftool.ExifToolHelper(common_args=['-G', '-n', '-overwrite_original']) self.eth.run() def tearDown(self): self.eth.terminate() # --------------------------------------------------------------------------------------------------------- def test_read_all_from_nonexistent_file_no_checkexecute(self): """ `get_metadata`/`get_tags` raises an error if None comes back from execute_json() ExifToolHelper DOES NOT check each individual file in the list for existence. If you pass invalid files to exiftool, undefined behavior can occur """ self.eth.check_execute = False with self.assertRaises(ExifToolOutputEmptyError): self.eth.get_metadata(['foo.bar']) with self.assertRaises(ExifToolOutputEmptyError): self.eth.get_tags('foo.bar', 'DateTimeOriginal') # --------------------------------------------------------------------------------------------------------- def test_read_all_from_nonexistent_file_yes_checkexecute(self): # run above test again with check_execute = True self.eth.check_execute = True with self.assertRaises(ExifToolExecuteError): self.eth.get_metadata(['foo.bar']) with self.assertRaises(ExifToolExecuteError): self.eth.get_tags('foo.bar', 'DateTimeOriginal') # --------------------------------------------------------------------------------------------------------- def test_w_flag(self): """ test passing a -w flag to write some output """ (temp_obj, temp_dir) = et_get_temp_dir(suffix="wflag") with self.assertRaises(ExifToolJSONInvalidError): self.eth.get_metadata(TEST_IMAGE_JPG, params=["-w", f"{temp_dir}/%f.txt"]) # --------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/tests/test_helper_checktagnames.py0000666000000000000000000001022400000000000017365 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifToolHelper - tag name validation tests """ # standard import unittest import shutil # test helpers from tests.common_util import et_get_temp_dir from tests.common_util import TEST_IMAGE_JPG # custom import exiftool from exiftool.exceptions import ExifToolOutputEmptyError, ExifToolTagNameError class TagNameReadTest(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifToolHelper(common_args=["-G", "-n", "-overwrite_original"]) def tearDown(self): self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_check_tag_names(self): """ simple read test for tag names """ with self.assertRaises(ExifToolTagNameError): self.et.get_tags(TEST_IMAGE_JPG, "-Comment") self.et.get_tags(TEST_IMAGE_JPG, "Comment#") with self.assertRaises(ExifToolTagNameError): self.et.get_tags(TEST_IMAGE_JPG, "Com#ment") # valid tags self.et.get_tags(TEST_IMAGE_JPG, "test:tag") self.et.get_tags(TEST_IMAGE_JPG, "*date*") # non-sensical, but even exiftool lets these slide with no errors self.et.get_tags(TEST_IMAGE_JPG, "C-o:m:m:ent#") self.et.get_tags(TEST_IMAGE_JPG, "Comment-") self.et.get_tags(TEST_IMAGE_JPG, "test:-tag") self.et.get_tags(TEST_IMAGE_JPG, "t-e-st:-tag---") # --------------------------------------------------------------------------------------------------------- class TagNameWriteTest(unittest.TestCase): """ these tests are to ensure the robustness of the check_tag_names feature """ @classmethod def setUp(self): self.et = exiftool.ExifToolHelper( common_args=["-G", "-n", "-overwrite_original"], encoding="UTF-8" ) # standardize, all these need the example file copied to a temp directory (self.temp_obj, self.temp_dir) = et_get_temp_dir(suffix="tagname") self.test_file = self.temp_dir / "test_rose.jpg" shutil.copyfile(TEST_IMAGE_JPG, self.test_file) # --------------------------------------------------------------------------------------------------------- def test_write_comment(self): test_file = self.test_file my_tag = "File:Comment" my_comment = "foo.bar/comment" bad_comment = "lorem ipsum" self.et.set_tags(test_file, {my_tag: my_comment}) self.assertEqual(my_comment, self.et.get_tags(test_file, my_tag)[0][my_tag]) self.assertTrue(self.et.check_tag_names) with self.assertRaises(ExifToolTagNameError): # this was what the flag was meant to prevent self.et.get_tags(test_file, f"Comment={bad_comment}") self.assertEqual(my_comment, self.et.get_tags(test_file, my_tag)[0][my_tag]) # turn off that tag check (this is what you DON'T WANT to happen) self.et.check_tag_names = False self.assertFalse(self.et.check_tag_names) with self.assertRaises(ExifToolOutputEmptyError): self.et.get_tags(test_file, f"Comment={bad_comment}") self.assertEqual(bad_comment, self.et.get_tags(test_file, my_tag)[0][my_tag]) self.et.check_tag_names = True # --------------------------------------------------------------------------------------------------------- def test_tag_name_hyphen(self): """ this is cited on some examples on exiftool's documentation this 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 """ test_file = self.test_file my_tag = "xmp:description-de" my_value = "kühl" # note how what you asked for isn't always what you get my_tag_case = "XMP:Description-de" my_utf8 = "kühl" self.et.set_tags(test_file, {my_tag: my_value}, params="-E") self.assertEqual(my_utf8, self.et.get_tags(test_file, my_tag)[0][my_tag_case]) # --------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/tests/test_helper_gettags.py0000666000000000000000000001151000000000000016225 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifToolHelper - get_metadata/get_tags tests """ # standard import unittest from pathlib import Path # pip from packaging import version # test helpers from tests.common_util import TEST_IMAGE_DIR, TEST_IMAGE_JPG # custom import exiftool from exiftool.exceptions import ExifToolExecuteError class TestHelperGetTags(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifToolHelper(common_args=["-G", "-n", "-overwrite_original"]) def tearDown(self): self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_get_tags_no_files(self): """ `get_metadata`/`get_tags` should return an error when no files specified. """ with self.assertRaises(ValueError): # files can't be None self.et.get_tags(None, None) self.et.get_tags([], None) # --------------------------------------------------------------------------------------------------------- def test_invalid_tags_arg(self): with self.assertRaises(TypeError): self.et.get_tags(TEST_IMAGE_JPG, object()) # --------------------------------------------------------------------------------------------------------- def test_get_tags_params(self): """ test params argument """ # lots of metadata on the file full_metadata = self.et.get_metadata(TEST_IMAGE_JPG)[0] # use params to get tag (basically using params to specify a tag) param_metadata = self.et.get_metadata(TEST_IMAGE_JPG, params="-XMPToolkit")[0] # the list should be significantly smaller self.assertGreater(len(full_metadata), len(param_metadata)) param_metadata = self.et.get_metadata(TEST_IMAGE_JPG, params=["-XMPToolkit"])[0] self.assertGreater(len(full_metadata), len(param_metadata)) # this class is an arbitrary object that returns a string class TestClass(object): def __str__(self): return "-n" # this is now permitted, params can be anything castable self.et.get_metadata(TEST_IMAGE_JPG, params=TestClass()) # --------------------------------------------------------------------------------------------------------- def test_get_metadata_file_mixed_existence(self): """ this tests for errors behavior when some files exist, and others don't this is less of a test for the class itself but expected exit status interaction with exiftool """ # expected no error self.et.get_metadata(TEST_IMAGE_JPG) self.et.check_execute = False # expected no error self.et.get_metadata([TEST_IMAGE_JPG, "foo.bar"]) # running same command with check_execute enabled self.et.check_execute = True with self.assertRaises(ExifToolExecuteError): self.et.get_metadata([TEST_IMAGE_JPG, "foo.bar"]) # --------------------------------------------------------------------------------------------------------- def test_get_metadata(self): """ test that a read is returning expected data """ expected_data = [ { "SourceFile": "rose.jpg", "File:FileType": "JPEG", "File:ImageWidth": 70, "File:ImageHeight": 46, "XMP:Subject": "Röschen", "Composite:ImageSize": "70 46", }, { "SourceFile": "skyblue.png", "File:FileType": "PNG", "PNG:ImageWidth": 64, "PNG:ImageHeight": 64, "Composite:ImageSize": "64 64", }, ] source_files = [] # 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) self.et.encoding = 'UTF-8' for d in expected_data: d["SourceFile"] = f = TEST_IMAGE_DIR / d["SourceFile"] self.assertTrue(f.exists()) source_files.append(f) with self.et: actual_data = self.et.get_metadata(source_files) tags0 = self.et.get_tags(source_files[0], ["XMP:Subject"])[0] #tag0 = self.et.get_tag(source_files[0], "XMP:Subject") required_version = version.parse("8.40") for expected, actual in zip(expected_data, actual_data): actual_version = version.parse(str(actual["ExifTool:ExifToolVersion"])) self.assertGreaterEqual(actual_version, required_version) actual["SourceFile"] = Path(actual["SourceFile"]).resolve() for k, v in expected.items(): self.assertEqual(actual[k], v) tags0["SourceFile"] = Path(tags0["SourceFile"]).resolve() self.assertEqual( tags0, dict((k, expected_data[0][k]) for k in ["SourceFile", "XMP:Subject"]) ) #self.assertEqual(tag0, expected_data[0]["XMP:Subject"]) # --------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1661648545.0 PyExifTool-0.5.6/tests/test_helper_misc.py0000666000000000000000000000375700000000000015540 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifToolHelper - misc tests """ # standard import unittest from pathlib import Path # test helpers from tests.common_util import TEST_IMAGE_JPG # custom import exiftool class HelperInitializationTest(unittest.TestCase): def test_initialization(self): """ Initialization with all arguments at their default values. this 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) """ exif_tool_helper = exiftool.ExifToolHelper() exif_tool_helper.run() self.assertTrue(exif_tool_helper.running) exif_tool_helper.terminate() self.assertFalse(exif_tool_helper.running) # --------------------------------------------------------------------------------------------------------- class TestExifToolHelperMisc(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifToolHelper(common_args=["-G", "-n", "-overwrite_original"]) def tearDown(self): if self.et.running: self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_execute_types(self): """ test execute with different types (exact same as the test with ExifTool, except the last one passes) """ self.assertFalse(self.et.running) # no error with str self.et.execute("-ver") # no error with bytes self.et.execute(b"-ver") # no error with str self.et.execute(str(TEST_IMAGE_JPG)) # error with Path self.et.execute(Path(TEST_IMAGE_JPG)) # --------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1646974628.0 PyExifTool-0.5.6/tests/test_helper_run.py0000666000000000000000000000377600000000000015412 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifToolHelper - Helper's start/run wrappers tests """ # standard import unittest # test helpers from tests.common_util import TEST_IMAGE_JPG # custom import exiftool from exiftool.exceptions import ExifToolNotRunning class TestHelperRunWrappers(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifToolHelper(common_args=["-G", "-n", "-overwrite_original"]) def tearDown(self): self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_run(self): # no warnings when terminating when not running self.assertFalse(self.et.running) self.et.run() self.assertTrue(self.et.running) self.et.run() # --------------------------------------------------------------------------------------------------------- def test_terminate(self): # no warnings when terminating when not running self.assertFalse(self.et.running) self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_auto_start(self): # test that a RuntimeError gets thrown if auto_start is false self.et = exiftool.ExifToolHelper(auto_start=False) self.assertFalse(self.et.auto_start) with self.assertRaises(ExifToolNotRunning): self.et.get_metadata(TEST_IMAGE_JPG) # test that no errors returned if auto_start=True self.et = exiftool.ExifToolHelper(auto_start=True) self.assertTrue(self.et.auto_start) metadata = self.et.get_metadata(TEST_IMAGE_JPG) self.assertEqual(type(metadata), list) # --------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/tests/test_helper_settags.py0000666000000000000000000001337100000000000016250 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifToolHelper - set_tags tests """ # standard import unittest import shutil # test helpers from tests.common_util import et_get_temp_dir, TEST_IMAGE_DIR, TEST_IMAGE_JPG # custom import exiftool from exiftool.exceptions import ExifToolExecuteError class TestHelperSetTags(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifToolHelper( common_args=["-G", "-n", "-overwrite_original"], encoding="UTF-8" ) def tearDown(self): self.et.terminate() # --------------------------------------------------------------------------------------------------------- def test_set_tags(self): (temp_obj, temp_dir) = et_get_temp_dir(suffix="settag") mod_prefix = "newcap_" expected_data = [ { "SourceFile": "rose.jpg", "Caption-Abstract": "Ein Röschen ganz allein", }, { "SourceFile": "skyblue.png", "Caption-Abstract": "Blauer Himmel" }, ] source_files = [] for d in expected_data: d["SourceFile"] = f = TEST_IMAGE_DIR / d["SourceFile"] self.assertTrue(f.exists()) f_mod = temp_dir / (mod_prefix + f.name) self.assertFalse( f_mod.exists(), f"{f_mod} should not exist before the test. Please delete.", ) shutil.copyfile(f, f_mod) source_files.append(f_mod) with self.et: self.et.set_tags([f_mod], {"Caption-Abstract": d["Caption-Abstract"]}) result = self.et.get_tags([f_mod], "IPTC:Caption-Abstract")[0] tag0 = list(result.values())[1] #f_mod.unlink() # don't delete file, tempdir will take care of it self.assertEqual(tag0, d["Caption-Abstract"]) # --------------------------------------------------------------------------------------------------------- def test_set_tags_file_existence(self): """ test setting tags on a non-existent file """ (temp_obj, temp_dir) = et_get_temp_dir(suffix="settagfe") self.assertTrue(self.et.check_execute) junk_tag = {"not_a_valid_tag_foo_bar": "lorem ipsum"} # set up temp working file mod_prefix = "test_" f = TEST_IMAGE_DIR / "rose.jpg" f_mod = temp_dir / (mod_prefix + f.name) self.assertTrue(f.exists()) self.assertFalse(f_mod.exists()) shutil.copyfile(f, f_mod) self.et.check_execute = False # no errors (aka exiftool fails silently, even though file doesn't exist) self.et.set_tags("foo.bar", junk_tag) # no errors (aka exiftool fails silently, even though it can't set this tag) self.et.set_tags(f_mod, junk_tag) self.et.check_execute = True # proper error handling, should raise error with self.assertRaises(ExifToolExecuteError): self.et.set_tags("foo.bar", junk_tag) # proper error handling, should also raise error with self.assertRaises(ExifToolExecuteError): self.et.set_tags(f_mod, junk_tag) # --------------------------------------------------------------------------------------------------------- def test_set_tags_files_invalid(self): """ test to cover the files == None """ with self.assertRaises(ValueError): self.et.set_tags(None, []) # --------------------------------------------------------------------------------------------------------- def test_set_tags_tags_invalid(self): """ test to cover the files == None """ with self.assertRaises(ValueError): self.et.set_tags("rose.jpg", None) with self.assertRaises(TypeError): self.et.set_tags("rose.jpg", object()) # --------------------------------------------------------------------------------------------------------- def test_set_tags_list_keywords(self): """ test that covers setting keywords in set_tags() using a list (not using the ExifToolAlpha's keywords functionality directly) """ (temp_obj, temp_dir) = et_get_temp_dir(suffix="settagkw") mod_prefix = "newkw_" expected_data = [{"SourceFile": "rose.jpg", "Keywords": ["nature", "red plant", "flower"]}] source_files = [] for d in expected_data: f = TEST_IMAGE_DIR / d["SourceFile"] self.assertTrue(f.exists()) f_mod = temp_dir / (mod_prefix + f.name) self.assertFalse( f_mod.exists(), f"{f_mod} should not exist before the test. Please delete.", ) shutil.copyfile(f, f_mod) source_files.append(f_mod) with self.et: self.et.set_tags(f_mod, {"Keywords": d["Keywords"]}) ret_data = self.et.get_tags(f_mod, "IPTC:Keywords") #f_mod.unlink() # don't delete file, tempdir will take care of it self.assertEqual(ret_data[0]["IPTC:Keywords"], d["Keywords"]) # --------------------------------------------------------------------------------------------------------- def test_set_tags_delete_all(self): """ delete tags with set tags is valid """ (temp_obj, temp_dir) = et_get_temp_dir(suffix="settagdel") test_file = temp_dir / "test_rose.jpg" shutil.copyfile(TEST_IMAGE_JPG, test_file) my_tag = "XMP:Subject" original_subject = self.et.get_tags(test_file, my_tag)[0][my_tag] self.et.set_tags(test_file, {"all": ""}) # deleted self.assertTrue(my_tag not in self.et.get_tags(test_file, my_tag)[0]) #self.assertNotEqual(original_subject, ) # just to get coverage on this arbitary object param # this class is an arbitrary object that returns a string class TestClass(object): def __str__(self): return "-n" self.et.set_tags(test_file, {"all": ""}, params=[TestClass()]) # --------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698015999.0 PyExifTool-0.5.6/tests/test_helper_tags_float.py0000666000000000000000000002045300000000000016720 0ustar00# -*- coding: utf-8 -*- """ Test :: ExifToolHelper - numeric tags tests """ # standard import unittest import shutil import json from decimal import Decimal # test helpers from tests.common_util import et_get_temp_dir, TEST_IMAGE_DIR, TEST_IMAGE_JPG # custom import exiftool # test well known alternative JSON processors try: import ujson has_ujson = True except ImportError: has_ujson = False try: import simplejson has_simplejson = True except ImportError: has_simplejson = False try: import orjson has_orjson = True except ImportError: has_orjson = False # TODO rapidjson, but I think the result will be the same class TestHelperFloatTags(unittest.TestCase): # --------------------------------------------------------------------------------------------------------- def setUp(self): self.et = exiftool.ExifToolHelper( common_args=["-n", "-overwrite_original"], encoding="UTF-8" ) # set up the file to write tags to to test # for this test, we write to the same file (self.temp_obj, self.temp_dir) = et_get_temp_dir(suffix="tagcommentnum") self.jpg_file = self.temp_dir / ("tagnum_" + TEST_IMAGE_JPG.name) shutil.copyfile(TEST_IMAGE_JPG, self.jpg_file) # all tests use the same test for this comment number thing self.test_data_str = [ {"Comment": 1}, {"Comment": -1}, {"Comment": 1.1}, {"Comment": -1.1}, {"Comment": "10"}, {"Comment": "-10"}, {"Comment": "1.10"}, {"Comment": "-1.10"}, {"Comment": "0.1000"}, {"Comment": "1.33700e+40"}, {"Comment": "1 "}, #{"Comment": " -1"}, #possible exiftool bug, see blow on test cases [{"Comment": Decimal('935733.817019799357333475932629142801644788893573383506621454627967')}, '935733.817019799357333475932629142801644788893573383506621454627967'], [{"Comment": Decimal('935733.81701979935')}, '935733.81701979935'], # numbers are as is [{"FocalLength": "00.1000"}, 0.1], [{"FocalLength": "010"}, 10], [{"FocalLength": "01.0"}, 1], ] def tearDown(self): self.et.terminate() # --------------------------------------------------------------------------------------------------------- def check_testdata(self, test_data, compare_str=False): """ check test_data in a specific format specified below this routine allows us to check numerous cases in different configurations """ with self.et: for d in test_data: """ format of test_data is a LIST of either: DICT = {"tag": } LIST = [{"tag": }, value to check] only one tag to set, this is all just for testing """ set_tag_dict = None check_tag_value = None set_tag_key = None if isinstance(d, dict): set_tag_dict = d # unpack into key/value # https://stackoverflow.com/questions/58129118/how-to-unpack-dict-with-one-key-value-pair-to-two-variables-more-elegantly set_tag_key, check_tag_value = next(iter(set_tag_dict.items())) else: set_tag_dict = d[0] check_tag_value = d[1] # unpack into key/value, ignore value set_tag_key = next(iter(set_tag_dict.items()))[0] # set the data self.et.set_tags(self.jpg_file, set_tag_dict) # get the data r = self.et.get_tags(self.jpg_file, set_tag_key) #print(r) # check if compare_str: # if compare by str only, a shorthand for the tests which will return str self.assertEqual(str(r[0][set_tag_key]), str(check_tag_value)) else: self.assertEqual(r[0][set_tag_key], check_tag_value) # --------------------------------------------------------------------------------------------------------- def test_baseline_exiftool_behavior(self): """ test baseline exiftool behavior If this test has failed, it means that exiftool returned output that has changed behavior since this test was written. You should investigate what changed before trying to fix any other tests """ # set default self.et.set_json_loads(json.loads) test_data = [ # baseline tests, exiftool returns a str in json ## notice how the default exiftool behavior is different depending on field type # Comment is a string field # FocalLength is a float field {"Comment": "01"}, {"Comment": "0000001"}, {"Comment": "00.1"}, {"Comment": "00.1000"}, {"Comment": "NaN"}, {"Comment": "Infinity"}, {"Comment": "-Infinity"}, {"Comment": "nan"}, {"Comment": "inf"}, [{"Comment": Decimal('935733.817019799357333475932629142801644788893573383506621454627967')}, '935733.817019799357333475932629142801644788893573383506621454627967'], [{"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 [{"Comment": " -1"}, " -1"], # exiftool removes a leading space {"Comment": "1 "}, [{"FocalLength": "00.1000"}, 0.1], [{"FocalLength": "010"}, 10], [{"FocalLength": "01.0"}, 1], [{"FocalLength": "blahblahblah"}, 1], # this is ignored by exiftool, so it uses previous set value # exiftool returns a number here (text field) [{"Comment": " 1"}, 1], [{"Comment": " -1"}, -1], {"Comment": 1}, {"Comment": -1}, {"Comment": 1.1}, {"Comment": -1.1}, [{"Comment": "10"}, 10], [{"Comment": "-10"}, -10], [{"Comment": "1.10"}, 1.1], [{"Comment": "-1.10"}, -1.1], [{"Comment": "0.1000"}, 0.1], [{"Comment": "1.337e+40"}, 1.337e+40], [{"Comment": "1.33700e+40"}, 1.337e+40], [{"Comment": Decimal('935733.81701979935')}, 935733.8170197994], # notice that exiftool rounds here ] self.check_testdata(test_data) # --------------------------------------------------------------------------------------------------------- def test_json_tag_comment_number(self): """ test that covers a numeric tag causing data mismatch with the parameters to get it to pass (default json processor) Addresses: https://github.com/sylikc/pyexiftool/issues/76 """ self.et.set_json_loads(json.loads, parse_float=str) # should return all strings self.check_testdata(self.test_data_str, compare_str=True) # --------------------------------------------------------------------------------------------------------- @unittest.skipIf(has_simplejson is False, "simplejson not installed") def test_simplejson_tag_comment_number(self): """ test that covers a numeric tag causing data mismatch simplejson is the CPython json implementation in pure python (slower) """ self.et.set_json_loads(simplejson.loads, parse_float=str) self.check_testdata(self.test_data_str, compare_str=True) # --------------------------------------------------------------------------------------------------------- @unittest.skipIf(has_ujson is False, "ujson not installed") @unittest.expectedFailure def test_ujson_tag_comment_number(self): """ test that covers a numeric tag causing data mismatch ujson does not support the parse_float, and it's an outstanding bug https://github.com/ultrajson/ultrajson/issues/401 https://github.com/ultrajson/ultrajson/issues/600 """ self.et.set_json_loads(ujson.loads) #ujson.loads('{"test": 1}', parse_float=str) self.check_testdata(self.test_data_str, compare_str=True) # --------------------------------------------------------------------------------------------------------- @unittest.skipIf(has_orjson is False, "orjson not installed") @unittest.expectedFailure def test_orjson_tag_comment_number(self): """ test that covers a numeric tag causing data mismatch orjson does not support this type of processing https://github.com/ijl/orjson/issues/21 """ self.et.set_json_loads(orjson.loads) self.check_testdata(self.test_data_str, compare_str=True) # --------------------------------------------------------------------------------------------------------- def test_json_loads_invalid(self): """ tests that an invalid set is caught (coverage test) """ with self.assertRaises(TypeError): self.et.set_json_loads("hi") # --------------------------------------------------------------------------------------------------------- if __name__ == '__main__': unittest.main()