././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1692346883.7278492
py3exiv2-0.12.0/ 0000775 0001750 0001750 00000000000 14467625004 013233 5 ustar 00vincent vincent ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1422272980.0
py3exiv2-0.12.0/COPYING 0000666 0001750 0001750 00000076405 12461424724 014302 0 ustar 00vincent vincent GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 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
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1423058185.0
py3exiv2-0.12.0/DESCRIPTION.rst 0000666 0001750 0001750 00000001725 12464422411 015547 0 ustar 00vincent vincent python3-exiv2
=============
A Python 3 binding to the library exiv2.
python3-exiv2 is a Python 3 binding to exiv2, the C++ library for manipulation of EXIF, IPTC and XMP image metadata. It is a python 3 module that allows your scripts to read and write metadata (EXIF, IPTC, XMP, thumbnails) embedded in image files (JPEG, TIFF, ...).
It is designed as a high-level interface to the functionalities offered by libexiv2. Using python’s built-in data types and standard modules, it provides easy manipulation of image metadata.
python3-exiv2 is distributed under the GPL version 3 license.
The main content of the code was initially written by Olivier Tilloy for Python 2 under the name pyexiv2.
py3exiv2 depends on the following libraries:
* python (≥ 3.2)
* boost.python3 (http://www.boost.org/libs/python/doc/index.html)
* exiv2 (http://www.exiv2.org/)
Build depends:
* python-all-dev (≥ 3.2)
* libexiv2-dev (≥ 0.20)
* libboost-python-dev (≥ 1.48)
* g++
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1435985747.0
py3exiv2-0.12.0/MANIFEST.in 0000666 0001750 0001750 00000000166 12545663523 015001 0 ustar 00vincent vincent include DESCRIPTION.rst
include src/exiv2wrapper.cpp
include src/exiv2wrapper.hpp
include src/exiv2wrapper_python.cpp
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1692346883.7278492
py3exiv2-0.12.0/PKG-INFO 0000664 0001750 0001750 00000003740 14467625004 014334 0 ustar 00vincent vincent Metadata-Version: 2.1
Name: py3exiv2
Version: 0.12.0
Summary: A Python3 binding to the library exiv2
Home-page: https://launchpad.net/py3exiv2
Author: Vincent Vande Vyvre
Author-email: vincent.vandevyvre@oqapy.eu
License: GPL-3
Keywords: exiv2 pyexiv2 EXIF IPTC XMP image metadata
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
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: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
License-File: COPYING
python3-exiv2
=============
A Python 3 binding to the library exiv2.
python3-exiv2 is a Python 3 binding to exiv2, the C++ library for manipulation of EXIF, IPTC and XMP image metadata. It is a python 3 module that allows your scripts to read and write metadata (EXIF, IPTC, XMP, thumbnails) embedded in image files (JPEG, TIFF, ...).
It is designed as a high-level interface to the functionalities offered by libexiv2. Using python’s built-in data types and standard modules, it provides easy manipulation of image metadata.
python3-exiv2 is distributed under the GPL version 3 license.
The main content of the code was initially written by Olivier Tilloy for Python 2 under the name pyexiv2.
py3exiv2 depends on the following libraries:
* python (≥ 3.2)
* boost.python3 (http://www.boost.org/libs/python/doc/index.html)
* exiv2 (http://www.exiv2.org/)
Build depends:
* python-all-dev (≥ 3.2)
* libexiv2-dev (≥ 0.20)
* libboost-python-dev (≥ 1.48)
* g++
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1629265139.0
py3exiv2-0.12.0/README 0000666 0001750 0001750 00000007116 14107116363 014114 0 ustar 00vincent vincent py3exiv2
*******
Welcome to py3exiv2, a python 3 binding to exiv2 (http://exiv2.org/), the C++
library for manipulation of EXIF, IPTC and XMP image metadata.
It is a python 3 module that allows your python scripts to read and write
metadata (EXIF, IPTC, XMP, thumbnails) embedded in image files
(JPEG, TIFF, ...).
Point your browser to http://exiv2.org/metadata.html for the complete metadata
tag reference.
Build dependencies
==================
py3exiv2 depends on the following libraries:
* python (≥ 3.3)
* boost.python3 (http://www.boost.org/libs/python/doc/index.html)
* exiv2 (http://www.exiv2.org/)
Some examples in src/ use PyGTK (http://www.pygtk.org/) and PyQt
(http://www.riverbankcomputing.co.uk/software/pyqt/) to display image previews,
those are optional dependencies.
This is a typical list of build dependencies for a Debian/Ubuntu system:
* python-all-dev (≥ 3.3)
* libexiv2-dev (≥ 0.20)
* libboost-python-dev (≥ 1.48)
* g++
Building and installing
=======================
To build and install the library, while in the top-level directory
(e.g. '~/dev/p3yexiv2', which should contain a file named 'configure.py'),
run the following commands:
$ python3 configure.py # To chek your environment and write the Makefile
$ ./build.sh # To compile the lib
$ ./build.sh -i # as administrator to install all files
You can run configure.py with the following arguments:
-h show the help message and exit
--libboost=FILE where FILE is the full path of libboost-python3
e.g. `/usr/lib/x86_64-linux-gnu/libboost_python-py34.so`
The result of the build is a dynamic library, libexiv2python.so, in the build/
directory. This is the low-level binding. It is in turn used in a higher level
module, pyexiv2.
The `./build.sh -i` command installs the two modules in your site-specific directory
for Python modules (e.g. '/usr/lib/python3/dist-packages/' on Linux).
To use py3exiv2 in your scripts, simply import the pyexiv2 module.
Note: the lib name is py3exiv2 but, for compatibility, the top-level module
is named pyexiv2
Documentation
=============
You can find the API documentation at:
http://python3-exiv2.readthedocs.org/en/latest
or refer to the internal documentation for a guide on how to use py3exiv2.
In a python interpreter, type:
>>> import pyexiv2
>>> help(pyexiv2)
License
=======
Copyright (C) 2006-2011 Olivier Tilloy
Copyright (C) 2015-2021 Vincent Vande Vyvre
py3exiv2 is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License version 3 as published by the Free
Software Foundation.
py3exiv2 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 py3exiv2; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
Developers
==========
py3exiv2 is Free Software, meaning that you are encouraged to play with it,
modify it to suit your needs and contribute back your changes and bug fixes.
The bug tracking system and the main bazaar branch are hosted at Launchpad:
https://launchpad.net/py3exiv2
To get a working copy of the latest version of the code, you need to have bazaar
(http://bazaar.canonical.com/) installed:
$ bzr branch lp:py3exiv2
Feedback, bug reports and patches are welcome!
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1692346883.7278492
py3exiv2-0.12.0/setup.cfg 0000664 0001750 0001750 00000000046 14467625004 015054 0 ustar 00vincent vincent [egg_info]
tag_build =
tag_date = 0
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1690443008.0
py3exiv2-0.12.0/setup.py 0000666 0001750 0001750 00000005233 14460416400 014741 0 ustar 00vincent vincent #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Replacement setup.py for py3exiv2, that allows building on OSX
# https://gist.github.com/ndevenish/6410cab393bd8dec1b016061ddb5573b
import sys
import os
import glob
import subprocess
import platform
from setuptools import setup, find_packages, Extension
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
long_description = f.read()
def get_libboost_osx():
places = ["/usr/local/lib/libboost_python3*.dylib",
"/opt/homebrew/Cellar/boost-python3/*/lib/libboost_python3*.dylib"]
for place in places:
try:
files = glob.glob(place)
for f in files:
if not "-mt" in f:
return os.path.basename(f).replace("lib", "").split(".")[0]
except:
pass
print("libboost for OSX not found!")
sys.exit()
if platform.system() == "Darwin":
boostlib = get_libboost_osx()
else:
python_version = str(sys.version_info.major) + str(sys.version_info.minor)
boostlib = 'boost_python' + python_version
setup(
name='py3exiv2',
version='0.12.0',
description='A Python3 binding to the library exiv2',
long_description=long_description,
url='https://launchpad.net/py3exiv2',
author='Vincent Vande Vyvre',
author_email='vincent.vandevyvre@oqapy.eu',
license='GPL-3',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Programming Language :: C++',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11'
],
keywords='exiv2 pyexiv2 EXIF IPTC XMP image metadata',
packages = find_packages('src'),
package_dir = {'': 'src'},
package_data={'':['src/*.cpp', 'src/*.hpp',]},
ext_modules=[
Extension('libexiv2python',
['src/exiv2wrapper.cpp', 'src/exiv2wrapper_python.cpp'],
libraries=[boostlib, 'exiv2'],
extra_compile_args=['-g', '-std=c++11']
)
],
)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1692346883.7238493
py3exiv2-0.12.0/src/ 0000775 0001750 0001750 00000000000 14467625004 014022 5 ustar 00vincent vincent ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1691598598.0
py3exiv2-0.12.0/src/exiv2wrapper.cpp 0000664 0001750 0001750 00000171344 14464737406 017205 0 ustar 00vincent vincent // *****************************************************************************
/*
* Copyright (C) 2006-2012 Olivier Tilloy
* Copyright (C) 2015-2023 Vincent Vande Vyvre
*
* This file is part of the pyexiv2 distribution.
*
* py3exiv2 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 2
* of the License, or (at your option) any later version.
*
* py3exiv2 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 py3exiv2; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
*/
/*
Maintainer: Vincent Vande Vyvre
*/
// *****************************************************************************
#include "exiv2wrapper.hpp"
#include "boost/python/stl_iterator.hpp"
#include
// Custom error codes for Exiv2 exceptions
#define METADATA_NOT_READ 101
#define NON_REPEATABLE 102
#define KEY_NOT_FOUND 103
#define INVALID_VALUE 104
#define EXISTING_PREFIX 105
#define BUILTIN_NS 106
#define NOT_REGISTERED 107
#if EXIV2_MAJOR_VERSION >= 1 || (EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION >= 28)
#define HAVE_CLASS_ERROR_CODE
#endif
#if EXIV2_MAJOR_VERSION >= 1 || (EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION == 27)
#define HAVE_EXIV2_ERROR_CODE
#endif
// Custom macros
#ifdef HAVE_CLASS_ERROR_CODE
#define CHECK_METADATA_READ \
if (!_dataRead) throw Exiv2::Error(Exiv2::ErrorCode::kerErrorMessage, "metadata not read");
#else
#ifdef HAVE_EXIV2_ERROR_CODE
#define CHECK_METADATA_READ \
if (!_dataRead) throw Exiv2::Error(Exiv2::kerErrorMessage, "metadata not read");
#else
#define HAVE_OLD_ERROR_CODE
#define CHECK_METADATA_READ \
if (!_dataRead) throw Exiv2::Error(METADATA_NOT_READ);
#endif
#endif
namespace exiv2wrapper
{
void Image::_instantiate_image()
{
_exifThumbnail = 0;
// If an exception is thrown, it has to be done outside of the
// Py_{BEGIN,END}_ALLOW_THREADS block.
#ifdef HAVE_CLASS_ERROR_CODE
Exiv2::Error error = Exiv2::Error(Exiv2::ErrorCode::kerSuccess);
#else
#ifdef HAVE_EXIV2_ERROR_CODE
Exiv2::Error error = Exiv2::Error(Exiv2::kerSuccess);
#else
Exiv2::Error error(0);
#endif
#endif
// Release the GIL to allow other python threads to run
// while opening the file.
Py_BEGIN_ALLOW_THREADS
try
{
if (_data != 0)
{
_image = Exiv2::ImageFactory::open(_data, _size);
}
else
{
_image = Exiv2::ImageFactory::open(_filename);
}
}
catch (Exiv2::Error& err)
{
//std::cout << " Caught Exiv2 exception '" << err.code() << "'\n";
error = err;
}
// Re-acquire the GIL
Py_END_ALLOW_THREADS
if (int(error.code()) == 0)
{
assert(_image.get() != 0);
_dataRead = false;
}
else
{
throw error;
}
}
// Base constructor
Image::Image(const std::string& filename)
{
_filename = filename;
_data = 0;
_instantiate_image();
}
// From buffer constructor
Image::Image(const std::string& buffer, unsigned long size)
{
// Deep copy of the data buffer
_data = new Exiv2::byte[size];
for (unsigned long i = 0; i < size; ++i)
{
_data[i] = buffer[i];
}
_size = size;
_instantiate_image();
}
// Copy constructor
Image::Image(const Image& image)
{
_filename = image._filename;
_instantiate_image();
}
Image::~Image()
{
if (_data != 0)
{
delete[] _data;
}
if (_exifThumbnail != 0)
{
delete _exifThumbnail;
}
}
void Image::readMetadata()
{
// If an exception is thrown, it has to be done outside of the
// Py_{BEGIN,END}_ALLOW_THREADS block.
#ifdef HAVE_CLASS_ERROR_CODE
Exiv2::Error error = Exiv2::Error(Exiv2::ErrorCode::kerSuccess);
#else
#ifdef HAVE_EXIV2_ERROR_CODE
Exiv2::Error error = Exiv2::Error(Exiv2::kerSuccess);
#else
Exiv2::Error error(0);
#endif
#endif
// Release the GIL to allow other python threads to run
// while reading metadata.
Py_BEGIN_ALLOW_THREADS
try
{
_image->readMetadata();
_exifData = &_image->exifData();
_iptcData = &_image->iptcData();
_xmpData = &_image->xmpData();
_dataRead = true;
}
catch (Exiv2::Error& err)
{
//std::cout << " Caught Exiv2 exception '" << err.code() << "'\n";
error = err;
}
// Re-acquire the GIL
Py_END_ALLOW_THREADS
if (int(error.code()) != 0)
{
throw error;
}
}
void Image::writeMetadata()
{
CHECK_METADATA_READ
// If an exception is thrown, it has to be done outside of the
// Py_{BEGIN,END}_ALLOW_THREADS block.
#ifdef HAVE_CLASS_ERROR_CODE
Exiv2::Error error = Exiv2::Error(Exiv2::ErrorCode::kerSuccess);
#else
#ifdef HAVE_EXIV2_ERROR_CODE
Exiv2::Error error = Exiv2::Error(Exiv2::kerSuccess);
#else
Exiv2::Error error(0);
#endif
#endif
// Release the GIL to allow other python threads to run
// while writing metadata.
Py_BEGIN_ALLOW_THREADS
try
{
_image->writeMetadata();
}
catch (Exiv2::Error& err)
{
//std::cout << "Caught Exiv2 exception '" << err.code() << "'\n";
error = err;
}
// Re-acquire the GIL
Py_END_ALLOW_THREADS
if (int(error.code()) != 0)
{
throw error;
}
}
unsigned int Image::pixelWidth() const
{
CHECK_METADATA_READ
return _image->pixelWidth();
}
unsigned int Image::pixelHeight() const
{
CHECK_METADATA_READ
return _image->pixelHeight();
}
std::string Image::mimeType() const
{
CHECK_METADATA_READ
return _image->mimeType();
}
boost::python::list Image::exifKeys()
{
CHECK_METADATA_READ
boost::python::list keys;
for(Exiv2::ExifMetadata::iterator i = _exifData->begin();
i != _exifData->end();
++i)
{
keys.append(i->key());
}
return keys;
}
const ExifTag Image::getExifTag(std::string key)
{
CHECK_METADATA_READ
Exiv2::ExifKey exifKey = Exiv2::ExifKey(key);
if(_exifData->findKey(exifKey) == _exifData->end())
#ifdef HAVE_CLASS_ERROR_CODE
{
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidKey, key);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
throw Exiv2::Error(Exiv2::kerInvalidKey, key);
}
#else
{
throw Exiv2::Error(KEY_NOT_FOUND, key);
}
#endif
#endif
return ExifTag(key, &(*_exifData)[key], _exifData, _image->byteOrder());
}
void Image::deleteExifTag(std::string key)
{
CHECK_METADATA_READ
Exiv2::ExifKey exifKey = Exiv2::ExifKey(key);
Exiv2::ExifMetadata::iterator datum = _exifData->findKey(exifKey);
if(datum == _exifData->end())
#ifdef HAVE_CLASS_ERROR_CODE
{
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidKey, key);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
throw Exiv2::Error(Exiv2::kerInvalidKey, key);
}
#else
{
throw Exiv2::Error(KEY_NOT_FOUND, key);
}
#endif
#endif
_exifData->erase(datum);
}
boost::python::list Image::iptcKeys()
{
CHECK_METADATA_READ
boost::python::list keys;
for(Exiv2::IptcMetadata::iterator i = _iptcData->begin();
i != _iptcData->end();
++i)
{
// The key is appended to the list if and only if it is not already
// present.
if (keys.count(i->key()) == 0)
{
keys.append(i->key());
}
}
return keys;
}
const IptcTag Image::getIptcTag(std::string key)
{
CHECK_METADATA_READ
Exiv2::IptcKey iptcKey = Exiv2::IptcKey(key);
if(_iptcData->findKey(iptcKey) == _iptcData->end())
#ifdef HAVE_CLASS_ERROR_CODE
{
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidKey, key);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
throw Exiv2::Error(Exiv2::kerInvalidKey, key);
}
#else
{
throw Exiv2::Error(KEY_NOT_FOUND, key);
}
#endif
#endif
return IptcTag(key, _iptcData);
}
void Image::deleteIptcTag(std::string key)
{
CHECK_METADATA_READ
Exiv2::IptcKey iptcKey = Exiv2::IptcKey(key);
Exiv2::IptcMetadata::iterator dataIterator = _iptcData->findKey(iptcKey);
if (dataIterator == _iptcData->end())
#ifdef HAVE_CLASS_ERROR_CODE
{
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidKey, key);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
throw Exiv2::Error(Exiv2::kerInvalidKey, key);
}
#else
{
throw Exiv2::Error(KEY_NOT_FOUND, key);
}
#endif
#endif
while (dataIterator != _iptcData->end())
{
if (dataIterator->key() == key)
{
dataIterator = _iptcData->erase(dataIterator);
}
else
{
++dataIterator;
}
}
}
boost::python::list Image::xmpKeys()
{
CHECK_METADATA_READ
boost::python::list keys;
for(Exiv2::XmpMetadata::iterator i = _xmpData->begin();
i != _xmpData->end();
++i)
{
keys.append(i->key());
}
return keys;
}
const XmpTag Image::getXmpTag(std::string key)
{
CHECK_METADATA_READ
Exiv2::XmpKey xmpKey = Exiv2::XmpKey(key);
if(_xmpData->findKey(xmpKey) == _xmpData->end())
#ifdef HAVE_CLASS_ERROR_CODE
{
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidKey, key);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
throw Exiv2::Error(Exiv2::kerInvalidKey, key);
}
#else
{
throw Exiv2::Error(KEY_NOT_FOUND, key);
}
#endif
#endif
return XmpTag(key, &(*_xmpData)[key]);
}
void Image::deleteXmpTag(std::string key)
{
CHECK_METADATA_READ
Exiv2::XmpKey xmpKey = Exiv2::XmpKey(key);
Exiv2::XmpMetadata::iterator i = _xmpData->findKey(xmpKey);
if(i != _xmpData->end())
{
_xmpData->erase(i);
}
else
#ifdef HAVE_CLASS_ERROR_CODE
{
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidKey, key);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
throw Exiv2::Error(Exiv2::kerInvalidKey, key);
}
#else
{
throw Exiv2::Error(KEY_NOT_FOUND, key);
}
#endif
#endif
}
const std::string Image::getComment() const
{
CHECK_METADATA_READ
return _image->comment();
}
void Image::setComment(const std::string& comment)
{
CHECK_METADATA_READ
_image->setComment(comment);
}
void Image::clearComment()
{
CHECK_METADATA_READ
_image->clearComment();
}
boost::python::list Image::previews()
{
CHECK_METADATA_READ
boost::python::list previews;
Exiv2::PreviewManager pm(*_image);
Exiv2::PreviewPropertiesList props = pm.getPreviewProperties();
for (Exiv2::PreviewPropertiesList::const_iterator i = props.begin();
i != props.end();
++i)
{
previews.append(Preview(pm.getPreviewImage(*i)));
}
return previews;
}
void Image::copyMetadata(Image& other, bool exif, bool iptc, bool xmp) const
{
CHECK_METADATA_READ
if (!other._dataRead)
{
#ifdef HAVE_CLASS_ERROR_CODE
{
throw Exiv2::Error(Exiv2::ErrorCode::kerErrorMessage, "metadata not read");
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
throw Exiv2::Error(Exiv2::kerErrorMessage, "metadata not read");
}
#else
{
throw Exiv2::Error(METADATA_NOT_READ);
}
#endif
#endif
}
if (exif)
other._image->setExifData(*_exifData);
if (iptc)
other._image->setIptcData(*_iptcData);
if (xmp)
other._image->setXmpData(*_xmpData);
}
boost::python::object Image::getDataBuffer() const
{
std::string buffer;
// Release the GIL to allow other python threads to run
// while reading the image data.
Py_BEGIN_ALLOW_THREADS
Exiv2::BasicIo& io = _image->io();
unsigned long size = io.size();
long pos = -1;
if (io.isopen())
{
// Remember the current position in the stream
pos = io.tell();
// Go to the beginning of the stream
io.seek(0, Exiv2::BasicIo::beg);
}
else
{
io.open();
}
// Copy the data buffer in a string. Since the data buffer can contain null
// characters ('\x00'), the string cannot be simply constructed like that:
// buffer = std::string((char*) previewImage.pData());
// because it would be truncated after the first occurence of a null
// character. Therefore, it has to be copied character by character.
// First allocate the memory for the whole string...
buffer.resize(size, ' ');
// ... then fill it with the raw data.
for (unsigned long i = 0; i < size; ++i)
{
io.read((Exiv2::byte*) &buffer[i], 1);
}
if (pos == -1)
{
// The stream was initially closed
io.close();
}
else
{
// Reset to the initial position in the stream
io.seek(pos, Exiv2::BasicIo::beg);
}
// Re-acquire the GIL
Py_END_ALLOW_THREADS
return boost::python::object(boost::python::handle<>(
PyBytes_FromStringAndSize(buffer.c_str(), buffer.size())
));
}
Exiv2::ByteOrder Image::getByteOrder() const
{
CHECK_METADATA_READ
return _image->byteOrder();
}
Exiv2::ExifThumb* Image::_getExifThumbnail()
{
CHECK_METADATA_READ
if (_exifThumbnail == 0)
{
_exifThumbnail = new Exiv2::ExifThumb(*_exifData);
}
return _exifThumbnail;
}
const std::string Image::getExifThumbnailMimeType()
{
return std::string(_getExifThumbnail()->mimeType());
}
const std::string Image::getExifThumbnailExtension()
{
return std::string(_getExifThumbnail()->extension());
}
void Image::writeExifThumbnailToFile(const std::string& path)
{
_getExifThumbnail()->writeFile(path);
}
boost::python::list Image::getExifThumbnailData()
{
Exiv2::DataBuf buffer = _getExifThumbnail()->copy();
// Copy the data buffer in a list.
boost::python::list data;
#ifdef HAVE_CLASS_ERROR_CODE
for(unsigned int i = 0; i < buffer.size(); ++i)
{
unsigned char* datum = buffer.data(i);
data.append(datum);
}
return data;
#else
// libexiv2 < 0.28
for(unsigned int i = 0; i < buffer.size_; ++i)
{
unsigned int datum = buffer.pData_[i];
data.append(datum);
}
return data;
#endif
}
void Image::eraseExifThumbnail()
{
_getExifThumbnail()->erase();
}
void Image::setExifThumbnailFromFile(const std::string& path)
{
_getExifThumbnail()->setJpegThumbnail(path);
}
void Image::setExifThumbnailFromData(const std::string& data)
{
const Exiv2::byte* buffer = (const Exiv2::byte*) data.c_str();
_getExifThumbnail()->setJpegThumbnail(buffer, data.size());
}
const std::string Image::getIptcCharset() const
{
CHECK_METADATA_READ
const char* charset = _iptcData->detectCharset();
if (charset != 0)
{
return std::string(charset);
}
else
{
return std::string();
}
}
ExifTag::ExifTag(const std::string& key,
Exiv2::Exifdatum* datum, Exiv2::ExifData* data,
Exiv2::ByteOrder byteOrder):
_key(key), _byteOrder(byteOrder)
{
if (datum != 0 && data != 0)
{
_datum = datum;
_data = data;
}
else
{
_datum = new Exiv2::Exifdatum(_key);
_data = 0;
}
// Conditional code, exiv2 0.21 changed APIs we need
// (see https://bugs.launchpad.net/pyexiv2/+bug/684177).
#if EXIV2_MAJOR_VERSION >= 1 || (EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION >= 21)
Exiv2::ExifKey exifKey(key);
_type = Exiv2::TypeInfo::typeName(exifKey.defaultTypeId());
// Where available, extract the type from the metadata, it is more reliable
// than static type information. The exception is for user comments, for
// which we’d rather keep the 'Comment' type instead of 'Undefined'.
if ((_data != 0) && (_type != "Comment"))
{
const char* typeName = _datum->typeName();
if (typeName != 0)
{
_type = typeName;
}
}
_name = exifKey.tagName();
_label = exifKey.tagLabel();
_description = exifKey.tagDesc();
_sectionName = Exiv2::ExifTags::sectionName(exifKey);
// The section description is not exposed in the API any longer
// (see http://dev.exiv2.org/issues/744). For want of anything better,
// fall back on the section’s name.
_sectionDescription = _sectionName;
#else
const uint16_t tag = _datum->tag();
const Exiv2::IfdId ifd = _datum->ifdId();
_type = Exiv2::TypeInfo::typeName(Exiv2::ExifTags::tagType(tag, ifd));
// Where available, extract the type from the metadata, it is more reliable
// than static type information. The exception is for user comments, for
// which we’d rather keep the 'Comment' type instead of 'Undefined'.
if ((_data != 0) && (_type != "Comment"))
{
const char* typeName = _datum->typeName();
if (typeName != 0)
{
_type = typeName;
}
}
_name = Exiv2::ExifTags::tagName(tag, ifd);
_label = Exiv2::ExifTags::tagLabel(tag, ifd);
_description = Exiv2::ExifTags::tagDesc(tag, ifd);
_sectionName = Exiv2::ExifTags::sectionName(tag, ifd);
_sectionDescription = Exiv2::ExifTags::sectionDesc(tag, ifd);
#endif
}
ExifTag::~ExifTag()
{
if (_data == 0)
{
delete _datum;
}
}
void ExifTag::setRawValue(const std::string& value)
{
int result = _datum->setValue(value);
if (result != 0)
#ifdef HAVE_CLASS_ERROR_CODE
{
std::string message("Invalid value: ");
message += value;
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidDataset, message);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
std::string message("Invalid value: ");
message += value;
throw Exiv2::Error(Exiv2::kerInvalidDataset, message);
}
#else
{
throw Exiv2::Error(INVALID_VALUE);
}
#endif
#endif
}
void ExifTag::setParentImage(Image& image)
{
Exiv2::ExifData* data = image.getExifData();
if (data == _data)
{
// The parent image is already the one passed as a parameter.
// This happens when replacing a tag by itself. In this case, don’t do
// anything (see https://bugs.launchpad.net/pyexiv2/+bug/622739).
return;
}
_data = data;
#if EXIV2_MAJOR_VERSION >= 1 || (EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION >= 28)
Exiv2::Value::UniquePtr value = _datum->getValue();
#else
Exiv2::Value::AutoPtr value = _datum->getValue();
#endif
delete _datum;
_datum = &(*_data)[_key.key()];
_datum->setValue(value.get());
_byteOrder = image.getByteOrder();
}
const std::string ExifTag::getKey()
{
return _key.key();
}
const std::string ExifTag::getType()
{
return _type;
}
const std::string ExifTag::getName()
{
return _name;
}
const std::string ExifTag::getLabel()
{
return _label;
}
const std::string ExifTag::getDescription()
{
return _description;
}
const std::string ExifTag::getSectionName()
{
return _sectionName;
}
const std::string ExifTag::getSectionDescription()
{
return _sectionDescription;
}
const std::string ExifTag::getRawValue()
{
return _datum->toString();
}
const std::string ExifTag::getHumanValue()
{
return _datum->print(_data);
}
int ExifTag::getByteOrder()
{
return _byteOrder;
}
IptcTag::IptcTag(const std::string& key, Exiv2::IptcData* data): _key(key)
{
_from_data = (data != 0);
if (_from_data)
{
_data = data;
}
else
{
_data = new Exiv2::IptcData();
_data->add(Exiv2::Iptcdatum(_key));
}
Exiv2::IptcMetadata::iterator iterator = _data->findKey(_key);
const uint16_t tag = iterator->tag();
const uint16_t record = iterator->record();
_type = Exiv2::TypeInfo::typeName(Exiv2::IptcDataSets::dataSetType(tag, record));
_name = Exiv2::IptcDataSets::dataSetName(tag, record);
_title = Exiv2::IptcDataSets::dataSetTitle(tag, record);
_description = Exiv2::IptcDataSets::dataSetDesc(tag, record);
// What is the photoshop name anyway? Where is it used?
_photoshopName = Exiv2::IptcDataSets::dataSetPsName(tag, record);
_repeatable = Exiv2::IptcDataSets::dataSetRepeatable(tag, record);
_recordName = Exiv2::IptcDataSets::recordName(record);
_recordDescription = Exiv2::IptcDataSets::recordDesc(record);
if (_from_data)
{
// Check that we are not trying to assign multiple values to a tag that
// is not repeatable.
unsigned int nb_values = 0;
for(Exiv2::IptcMetadata::iterator iterator = _data->begin();
iterator != _data->end(); ++iterator)
{
if (iterator->key() == key)
{
++nb_values;
if (!_repeatable && (nb_values > 1))
#ifdef HAVE_CLASS_ERROR_CODE
{
std::string mssg("Tag not repeatable: ");
mssg += key;
throw Exiv2::Error(Exiv2::ErrorCode::kerErrorMessage, mssg);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
std::string mssg("Tag not repeatable: ");
mssg += key;
throw Exiv2::Error(Exiv2::kerErrorMessage, mssg);
}
#else
{
throw Exiv2::Error(NON_REPEATABLE);
}
#endif
#endif
}
}
}
}
IptcTag::~IptcTag()
{
if (!_from_data)
{
delete _data;
}
}
void IptcTag::setRawValues(const boost::python::list& values)
{
if (!_repeatable && (boost::python::len(values) > 1))
{
// The tag is not repeatable but we are trying to assign it more than
// one value.
#ifdef HAVE_CLASS_ERROR_CODE
{
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidDataset, "Tag not repeatable");
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
throw Exiv2::Error(Exiv2::kerInvalidDataset, "Tag not repeatable");
}
#else
{
throw Exiv2::Error(NON_REPEATABLE);
}
#endif
#endif
}
unsigned int index = 0;
unsigned int max = boost::python::len(values);
Exiv2::IptcMetadata::iterator iterator = _data->findKey(_key);
while (index < max)
{
std::string value = boost::python::extract(values[index++]);
if (iterator != _data->end())
{
// Override an existing value
int result = iterator->setValue(value);
if (result != 0)
#ifdef HAVE_CLASS_ERROR_CODE
{
std::string mssg("Invalid value: ");
mssg += value;
// there's no invalid value error in libexiv2, so we use
// kerInvalidDataset wich raise a Python ValueError
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidDataset, mssg);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
std::string mssg("Invalid value: ");
mssg += value;
// there's no invalid value error in libexiv2, so we use
// kerInvalidDataset wich raise a Python ValueError
throw Exiv2::Error(Exiv2::kerInvalidDataset, mssg);
}
#else
{
throw Exiv2::Error(INVALID_VALUE);
}
#endif
#endif
// Jump to the next datum matching the key
++iterator;
while ((iterator != _data->end()) && (iterator->key() != _key.key()))
{
++iterator;
}
}
else
{
// Append a new value
Exiv2::Iptcdatum datum(_key);
int result = datum.setValue(value);
if (result != 0)
#ifdef HAVE_CLASS_ERROR_CODE
{
std::string mssg("Invalid value: ");
mssg += value;
throw Exiv2::Error(Exiv2::ErrorCode::kerErrorMessage, mssg);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
std::string mssg("Invalid value: ");
mssg += value;
throw Exiv2::Error(Exiv2::kerErrorMessage, mssg);
}
#else
{
throw Exiv2::Error(INVALID_VALUE);
}
#endif
#endif
int state = _data->add(datum);
if (state == 6)
#ifdef HAVE_CLASS_ERROR_CODE
{
std::string mssg("Tag not repeatable: ");
mssg += _key.key();
throw Exiv2::Error(Exiv2::ErrorCode::kerErrorMessage, mssg);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
std::string mssg("Tag not repeatable: ");
mssg += _key.key();
throw Exiv2::Error(Exiv2::kerErrorMessage, mssg);
}
#else
{
throw Exiv2::Error(NON_REPEATABLE);
}
#endif
#endif
// Reset iterator that has been invalidated by appending a datum
iterator = _data->end();
}
}
// Erase the remaining values if any
while (iterator != _data->end())
{
if (iterator->key() == _key.key())
{
iterator = _data->erase(iterator);
}
else
{
++iterator;
}
}
}
void IptcTag::setParentImage(Image& image)
{
Exiv2::IptcData* data = image.getIptcData();
if (data == _data)
{
// The parent image is already the one passed as a parameter.
// This happens when replacing a tag by itself. In this case, don’t do
// anything (see https://bugs.launchpad.net/pyexiv2/+bug/622739).
return;
}
const boost::python::list values = getRawValues();
delete _data;
_from_data = true;
_data = data;
setRawValues(values);
}
const std::string IptcTag::getKey()
{
return _key.key();
}
const std::string IptcTag::getType()
{
return _type;
}
const std::string IptcTag::getName()
{
return _name;
}
const std::string IptcTag::getTitle()
{
return _title;
}
const std::string IptcTag::getDescription()
{
return _description;
}
const std::string IptcTag::getPhotoshopName()
{
return _photoshopName;
}
const bool IptcTag::isRepeatable()
{
return _repeatable;
}
const std::string IptcTag::getRecordName()
{
return _recordName;
}
const std::string IptcTag::getRecordDescription()
{
return _recordDescription;
}
const boost::python::list IptcTag::getRawValues()
{
boost::python::list values;
for(Exiv2::IptcMetadata::iterator iterator = _data->begin();
iterator != _data->end(); ++iterator)
{
if (iterator->key() == _key.key())
{
values.append(iterator->toString());
}
}
return values;
}
XmpTag::XmpTag(const std::string& key, Exiv2::Xmpdatum* datum): _key(key)
{
_from_datum = (datum != 0);
if (_from_datum)
{
_datum = datum;
_exiv2_type = datum->typeName();
}
else
{
_datum = new Exiv2::Xmpdatum(_key);
_exiv2_type = Exiv2::TypeInfo::typeName(Exiv2::XmpProperties::propertyType(_key));
}
const char* title = Exiv2::XmpProperties::propertyTitle(_key);
if (title != 0)
{
_title = title;
}
const char* description = Exiv2::XmpProperties::propertyDesc(_key);
if (description != 0)
{
_description = description;
}
const Exiv2::XmpPropertyInfo* info = Exiv2::XmpProperties::propertyInfo(_key);
if (info != 0)
{
_name = info->name_;
_type = info->xmpValueType_;
}
}
XmpTag::~XmpTag()
{
if (!_from_datum)
{
delete _datum;
}
}
void XmpTag::setTextValue(const std::string& value)
{
_datum->setValue(value);
}
void XmpTag::setArrayValue(const boost::python::list& values)
{
// Reset the value
_datum->setValue(0);
for(boost::python::stl_input_iterator iterator(values);
iterator != boost::python::stl_input_iterator();
++iterator)
{
_datum->setValue(*iterator);
}
}
void XmpTag::setLangAltValue(const boost::python::dict& values)
{
// Reset the value
_datum->setValue(0);
for(boost::python::stl_input_iterator iterator(values);
iterator != boost::python::stl_input_iterator();
++iterator)
{
std::string key = *iterator;
std::string value = boost::python::extract(values.get(key));
_datum->setValue("lang=\"" + key + "\" " + value);
}
}
void XmpTag::setParentImage(Image& image)
{
Exiv2::Xmpdatum* datum = &(*image.getXmpData())[_key.key()];
if (datum == _datum)
{
// The parent image is already the one passed as a parameter.
// This happens when replacing a tag by itself. In this case, don’t do
// anything (see https://bugs.launchpad.net/pyexiv2/+bug/622739).
return;
}
#if EXIV2_MAJOR_VERSION >= 1 || (EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION >= 28)
Exiv2::Value::UniquePtr value = _datum->getValue();
#else
Exiv2::Value::AutoPtr value = _datum->getValue();
#endif
delete _datum;
_from_datum = true;
_datum = &(*image.getXmpData())[_key.key()];
_datum->setValue(value.get());
}
const std::string XmpTag::getKey()
{
return _key.key();
}
const std::string XmpTag::getExiv2Type()
{
return _exiv2_type;
}
const std::string XmpTag::getType()
{
return _type;
}
const std::string XmpTag::getName()
{
return _name;
}
const std::string XmpTag::getTitle()
{
return _title;
}
const std::string XmpTag::getDescription()
{
return _description;
}
const std::string XmpTag::getTextValue()
{
return dynamic_cast(&_datum->value())->value_;
}
const boost::python::list XmpTag::getArrayValue()
{
#ifdef HAVE_OLD_ERROR_CODE
std::vector value =
dynamic_cast(&_datum->value())->value_;
boost::python::list rvalue;
for(std::vector::const_iterator i = value.begin();
i != value.end(); ++i)
{
rvalue.append(*i);
}
return rvalue;
#else
// We can't use &_datum->value())->value_ because value_ is private in
// this context (change in libexiv2 0.27)
const Exiv2::XmpArrayValue* xav =
dynamic_cast(&_datum->value());
boost::python::list rvalue;
for(uint i = 0; i < xav->count(); ++i)
{
std::string value = xav->toString(i);
rvalue.append(value);
}
return rvalue;
#endif
}
const boost::python::dict XmpTag::getLangAltValue()
{
Exiv2::LangAltValue::ValueType value =
dynamic_cast(&_datum->value())->value_;
boost::python::dict rvalue;
for (Exiv2::LangAltValue::ValueType::const_iterator i = value.begin();
i != value.end(); ++i)
{
rvalue[i->first] = i->second;
}
return rvalue;
}
Preview::Preview(const Exiv2::PreviewImage& previewImage)
{
_mimeType = previewImage.mimeType();
_extension = previewImage.extension();
_size = previewImage.size();
_dimensions = boost::python::make_tuple(previewImage.width(),
previewImage.height());
// Copy the data buffer in a string. Since the data buffer can contain null
// characters ('\x00'), the string cannot be simply constructed like that:
// _data = std::string((char*) previewImage.pData());
// because it would be truncated after the first occurence of a null
// character. Therefore, it has to be copied character by character.
const Exiv2::byte* pData = previewImage.pData();
// First allocate the memory for the whole string...
_data = std::string(_size, ' ');
// ... then fill it with the raw data.
for(unsigned int i = 0; i < _size; ++i)
{
_data[i] = pData[i];
}
}
boost::python::object Preview::getData() const
{
return boost::python::object(boost::python::handle<>(
PyBytes_FromStringAndSize(_data.c_str(), _size)
));
}
void Preview::writeToFile(const std::string& path) const
{
std::string filename = path + _extension;
std::ofstream fd(filename.c_str(), std::ios::out | std::ios::binary);
fd << _data;
fd.close();
}
#ifdef HAVE_OLD_ERROR_CODE
void translateExiv2Error(Exiv2::Error const& error)
{
// Use the Python 'C' API to set up an exception object
const char* message = error.what();
// The type of the Python exception depends on the error code
// Warning: this piece of code should be updated in case the error codes
// defined by Exiv2 (file 'src/error.cpp') are changed
switch (error.code())
{
// Exiv2 error codes
case 2:
// {path}: Call to `{function}' failed: {strerror}
// May be raised when reading a file
PyErr_SetString(PyExc_RuntimeError, message);
break;
case 3:
// This does not look like a {image type} image
// May be raised by readMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 4:
// Invalid dataset name `{dataset name}'
// May be raised when instantiating an IptcKey from a string
PyErr_SetString(PyExc_KeyError, message);
break;
case 5:
// Invalid record name `{record name}'
// May be raised when instantiating an IptcKey from a string
PyErr_SetString(PyExc_KeyError, message);
break;
case 6:
// Invalid key `{key}'
// May be raised when instantiating an ExifKey, an IptcKey or an
// XmpKey from a string
PyErr_SetString(PyExc_KeyError, message);
break;
case 7:
// Invalid tag name or ifdId `{tag name}', ifdId {ifdId}
// May be raised when instantiating an ExifKey from a string
PyErr_SetString(PyExc_KeyError, message);
break;
case 8:
// Value not set
// May be raised when calling value() on a datum
PyErr_SetString(PyExc_ValueError, message);
break;
case 9:
// {path}: Failed to open the data source: {strerror}
// May be raised by readMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 10:
// {path}: Failed to open file ({mode}): {strerror}
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 11:
// {path}: The file contains data of an unknown image type
// May be raised when opening an image
PyErr_SetString(PyExc_TypeError, message);
break;
case 12:
// The memory contains data of an unknown image type
// May be raised when instantiating an image from a data buffer
PyErr_SetString(PyExc_IOError, message);
break;
case 13:
// Image type {image type} is not supported
// May be raised when creating a new image
PyErr_SetString(PyExc_IOError, message);
break;
case 14:
// Failed to read image data
// May be raised by readMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 15:
// This does not look like a JPEG image
// May be raised by readMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 17:
// {old path}: Failed to rename file to {new path}: {strerror}
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 18:
// {path}: Transfer failed: {strerror}
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 19:
// Memory transfer failed: {strerror}
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 20:
// Failed to read input data
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 21:
// Failed to write image
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 22:
// Input data does not contain a valid image
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 23:
// Invalid ifdId {ifdId}
// May be raised when instantiating an ExifKey from a tag and
// IFD item string
PyErr_SetString(PyExc_KeyError, message);
break;
case 26:
// Offset out of range
// May be raised by writeMetadata() (TIFF)
PyErr_SetString(PyExc_IOError, message);
break;
case 27:
// Unsupported data area offset type
// May be raised by writeMetadata() (TIFF)
PyErr_SetString(PyExc_IOError, message);
break;
case 28:
// Invalid charset: `{charset name}'
// May be raised when instantiating a CommentValue from a string
PyErr_SetString(PyExc_ValueError, message);
break;
case 29:
// Unsupported date format
// May be raised when instantiating a DateValue from a string
PyErr_SetString(PyExc_ValueError, message);
break;
case 30:
// Unsupported time format
// May be raised when instantiating a TimeValue from a string
PyErr_SetString(PyExc_ValueError, message);
break;
case 31:
// Writing to {image format} images is not supported
// May be raised by writeMetadata() for certain image types
PyErr_SetString(PyExc_IOError, message);
break;
case 32:
// Setting {metadata type} in {image format} images is not supported
// May be raised when setting certain types of metadata for certain
// image types that don't support them
PyErr_SetString(PyExc_ValueError, message);
break;
case 33:
// This does not look like a CRW image
// May be raised by readMetadata() (CRW)
PyErr_SetString(PyExc_IOError, message);
break;
case 35:
// No namespace info available for XMP prefix `{prefix}'
// May be raised when retrieving property info for an XmpKey
PyErr_SetString(PyExc_KeyError, message);
break;
case 36:
// No prefix registered for namespace `{namespace}', needed for
// property path `{property path}'
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_KeyError, message);
break;
case 37:
// Size of {type of metadata} JPEG segment is larger than
// 65535 bytes
// May be raised by writeMetadata() (JPEG)
PyErr_SetString(PyExc_ValueError, message);
break;
case 38:
// Unhandled Xmpdatum {key} of type {value type}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_TypeError, message);
break;
case 39:
// Unhandled XMP node {key} with opt={XMP Toolkit option flags}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_TypeError, message);
break;
case 40:
// XMP Toolkit error {error id}: {error message}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_RuntimeError, message);
break;
case 41:
// Failed to decode Lang Alt property {property path}
// with opt={XMP Toolkit option flags}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_ValueError, message);
break;
case 42:
// Failed to decode Lang Alt qualifier {qualifier path}
// with opt={XMP Toolkit option flags}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_ValueError, message);
break;
case 43:
// Failed to encode Lang Alt property {key}
// May be raised by writeMetadata()
PyErr_SetString(PyExc_ValueError, message);
break;
case 44:
// Failed to determine property name from path {property path},
// namespace {namespace}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_KeyError, message);
break;
case 45:
// Schema namespace {namespace} is not registered with
// the XMP Toolkit
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_ValueError, message);
break;
case 46:
// No namespace registered for prefix `{prefix}'
// May be raised when instantiating an XmpKey from a string
PyErr_SetString(PyExc_KeyError, message);
break;
case 47:
// Aliases are not supported. Please send this XMP packet
// to ahuggel@gmx.net `{namespace}', `{property path}', `{value}'
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_ValueError, message);
break;
case 48:
// Invalid XmpText type `{type}'
// May be raised when instantiating an XmpTextValue from a string
PyErr_SetString(PyExc_TypeError, message);
break;
case 49:
// TIFF directory {TIFF directory name} has too many entries
// May be raised by writeMetadata() (TIFF)
PyErr_SetString(PyExc_IOError, message);
break;
// Added in py3exiv2
case 50:
// Multiple TIFF array element tags %1 in one directory")
// May be raised by readMetadata() (TIFF)
PyErr_SetString(PyExc_IOError, message);
break;
case 51:
// TIFF array element tag %1 has wrong type") }, // %1=tag number
// May be raised by readMetadata() (TIFF)
PyErr_SetString(PyExc_TypeError, message);
break;
case 52:
// %1 has invalid XMP value type `%2'
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_ValueError, message);
break;
// Custom error codes
case METADATA_NOT_READ:
PyErr_SetString(PyExc_IOError, "Image metadata has not been read yet");
break;
case NON_REPEATABLE:
PyErr_SetString(PyExc_KeyError, "Tag is not repeatable");
break;
case KEY_NOT_FOUND:
PyErr_SetString(PyExc_KeyError, "Tag not set");
break;
case INVALID_VALUE:
PyErr_SetString(PyExc_ValueError, "Invalid value");
break;
case EXISTING_PREFIX:
PyErr_SetString(PyExc_KeyError, "A namespace with this prefix already exists");
break;
case BUILTIN_NS:
PyErr_SetString(PyExc_KeyError, "Cannot unregister a builtin namespace");
break;
case NOT_REGISTERED:
PyErr_SetString(PyExc_KeyError, "No namespace registered under this name");
break;
// Default handler
default:
PyErr_SetString(PyExc_RuntimeError, message);
}
}
#else
void translateExiv2Error(Exiv2::Error const& error)
{
// Use the Python 'C' API to set up an exception object
const char* message = error.what();
// The type of the Python exception depends on the error code
// Warning: this piece of code should be updated in case the error codes
// defined by Exiv2 (file 'src/error.cpp') are changed
switch (int(error.code()))
{
case 1:
// kerErrorMessage Unidentified error
PyErr_SetString(PyExc_RuntimeError, message);
break;
case 2:
// kerCallFailed {path}: Call to `{function}' failed: {strerror}
// May be raised when reading a file
PyErr_SetString(PyExc_RuntimeError, message);
break;
case 3:
// kerNotAnImage This does not look like a {image type} image
// May be raised by readMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 4:
// kerInvalidDataset Invalid dataset name `{dataset name}'
PyErr_SetString(PyExc_ValueError, message);
break;
case 5:
// kerInvalidRecord Invalid record name `{record name}'
// May be raised when instantiating an IptcKey from a string
PyErr_SetString(PyExc_KeyError, message);
break;
case 6:
// kerInvalidKey Invalid key `{key}'
// May be raised when instantiating an ExifKey, an IptcKey or an
// XmpKey from a string
PyErr_SetString(PyExc_KeyError, message);
break;
case 7:
// kerInvalidTag
// Invalid tag name or ifdId `{tag name}', ifdId {ifdId}
// May be raised when instantiating an ExifKey from a string
PyErr_SetString(PyExc_KeyError, message);
break;
case 8:
// kerValueNotSet Value not set
// May be raised when calling value() on a datum
PyErr_SetString(PyExc_ValueError, message);
break;
case 9:
// kerDataSourceOpenFailed
// {path}: Failed to open the data source: {strerror}
// May be raised by readMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 10:
// kerFileOpenFailed
// {path}: Failed to open file ({mode}): {strerror}
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 11:
// kerFileOpenFailed
// {path}: The file contains data of an unknown image type
// May be raised when opening an image
PyErr_SetString(PyExc_TypeError, message);
break;
case 12:
// kerMemoryContainsUnknownImageType
//The memory contains data of an unknown image type
// May be raised when instantiating an image from a data buffer
PyErr_SetString(PyExc_IOError, message);
break;
case 13:
// kerUnsupportedImageType Image type {image type} is not supported
// May be raised when creating a new image
PyErr_SetString(PyExc_IOError, message);
break;
case 14:
// kerFailedToReadImageData Failed to read image data
// May be raised by readMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 15:
// kerNotAJpeg This does not look like a JPEG image
// May be raised by readMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 17:
// kerFileRenameFailed
// {old path}: Failed to rename file to {new path}: {strerror}
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 18:
// kerTransferFailed {path}: Transfer failed: {strerror}
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 19:
// kerMemoryTransferFailed Memory transfer failed: {strerror}
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 20:
// kerInputDataReadFailed Failed to read input data
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 21:
// kerImageWriteFailed Failed to write image
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 22:
// kerNoImageInInputData Input data does not contain a valid image
// May be raised by writeMetadata()
PyErr_SetString(PyExc_IOError, message);
break;
case 23:
// kerInvalidIfdId Invalid ifdId {ifdId}
// May be raised when instantiating an ExifKey from a tag and
// IFD item string
PyErr_SetString(PyExc_KeyError, message);
break;
case 24:
// kerValueTooLarge
// Entry::setValue: Value too large {tag}, {size}, {requested}
PyErr_SetString(PyExc_ValueError, message);
break;
case 25:
// kerDataAreaValueTooLarge
// Entry::setDataArea: Value too large {tag}, {size}, {requested}
PyErr_SetString(PyExc_ValueError, message);
break;
case 26:
// kerOffsetOutOfRange Offset out of range
// May be raised by writeMetadata() (TIFF)
PyErr_SetString(PyExc_IOError, message);
break;
case 27:
// kerUnsupportedDataAreaOffsetType
// Unsupported data area offset type
// May be raised by writeMetadata() (TIFF)
PyErr_SetString(PyExc_IOError, message);
break;
case 28:
// kerInvalidCharset Invalid charset: `{charset name}'
// May be raised when instantiating a CommentValue from a string
PyErr_SetString(PyExc_ValueError, message);
break;
case 29:
// kerUnsupportedDateFormat Unsupported date format
// May be raised when instantiating a DateValue from a string
PyErr_SetString(PyExc_ValueError, message);
break;
case 30:
// kerUnsupportedTimeFormat Unsupported time format
// May be raised when instantiating a TimeValue from a string
PyErr_SetString(PyExc_ValueError, message);
break;
case 31:
// kerWritingImageFormatUnsupported
// Writing to {image format} images is not supported
// May be raised by writeMetadata() for certain image types
PyErr_SetString(PyExc_IOError, message);
break;
case 32:
// kerInvalidSettingForImage
// Setting {metadata type} in {image format} images is not supported
// May be raised when setting certain types of metadata for certain
// image types that don't support them
PyErr_SetString(PyExc_ValueError, message);
break;
case 33:
// kerNotACrwImage This does not look like a CRW image
// May be raised by readMetadata() (CRW)
PyErr_SetString(PyExc_IOError, message);
break;
case 34:
// kerFunctionNotSupported {function}: Not supported
PyErr_SetString(PyExc_IOError, message);
break;
case 35:
// kerNoNamespaceInfoForXmpPrefix
// No namespace info available for XMP prefix `{prefix}'
// May be raised when retrieving property info for an XmpKey
PyErr_SetString(PyExc_KeyError, message);
break;
case 36:
// kerNoPrefixForNamespace
// No prefix registered for namespace `{namespace}', needed for
// property path `{property path}'
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_KeyError, message);
break;
case 37:
// kerTooLargeJpegSegment
// Size of {type of metadata} JPEG segment is larger than
// 65535 bytes
// May be raised by writeMetadata() (JPEG)
PyErr_SetString(PyExc_ValueError, message);
break;
case 38:
// kerUnhandledXmpdatum
// Unhandled Xmpdatum {key} of type {value type}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_TypeError, message);
break;
case 39:
// kerUnhandledXmpNode
// Unhandled XMP node {key} with opt={XMP Toolkit option flags}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_TypeError, message);
break;
case 40:
// kerXMPToolkitError
// XMP Toolkit error {error id}: {error message}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_RuntimeError, message);
break;
case 41:
// kerDecodeLangAltPropertyFailed
// Failed to decode Lang Alt property {property path}
// with opt={XMP Toolkit option flags}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_ValueError, message);
break;
case 42:
// kerDecodeLangAltQualifierFailed
// Failed to decode Lang Alt qualifier {qualifier path}
// with opt={XMP Toolkit option flags}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_ValueError, message);
break;
case 43:
// kerEncodeLangAltPropertyFailed
// Failed to encode Lang Alt property {key}
// May be raised by writeMetadata()
PyErr_SetString(PyExc_ValueError, message);
break;
case 44:
// kerPropertyNameIdentificationFailed
// Failed to determine property name from path {property path},
// namespace {namespace}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_KeyError, message);
break;
case 45:
// kerSchemaNamespaceNotRegistered
// Schema namespace {namespace} is not registered with
// the XMP Toolkit
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_ValueError, message);
break;
case 46:
// kerNoNamespaceForPrefix
// No namespace registered for prefix `{prefix}'
// May be raised when instantiating an XmpKey from a string
PyErr_SetString(PyExc_KeyError, message);
break;
case 47:
// kerAliasesNotSupported
// Aliases are not supported. Please send this XMP packet
// to ahuggel@gmx.net `{namespace}', `{property path}', `{value}'
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_ValueError, message);
break;
case 48:
// kerInvalidXmpText
// Invalid XmpText type `{type}'
// May be raised when instantiating an XmpTextValue from a string
PyErr_SetString(PyExc_TypeError, message);
break;
case 49:
// kerTooManyTiffDirectoryEntries
// TIFF directory {TIFF directory name} has too many entries
// May be raised by writeMetadata() (TIFF)
PyErr_SetString(PyExc_IOError, message);
break;
// Added in py3exiv2
case 50:
// kerMultipleTiffArrayElementTagsInDirectory
// Multiple TIFF array element tags {number} in one directory")
// May be raised by readMetadata() (TIFF)
PyErr_SetString(PyExc_IOError, message);
break;
case 51:
// kerWrongTiffArrayElementTagType
// TIFF array element tag {number} has wrong type") }, // %1=tag number
// May be raised by readMetadata() (TIFF)
PyErr_SetString(PyExc_TypeError, message);
break;
// Added in libexiv2 0.27
case 52:
// kerInvalidKeyXmpValue {key} has invalid XMP value type {type}
// May be raised by readMetadata() when reading the XMP data
PyErr_SetString(PyExc_ValueError, message);
break;
case 53:
// kerInvalidIccProfile Not a valid ICC Profile
PyErr_SetString(PyExc_ValueError, message);
break;
case 54:
// kerInvalidXMP Not valid XMP
PyErr_SetString(PyExc_TypeError, message);
break;
case 55:
// kerTiffDirectoryTooLarge tiff directory length is too large
PyErr_SetString(PyExc_ValueError, message);
break;
case 56:
// kerInvalidTypeValue
// Invalid type value detected in Image::printIFDStructure
PyErr_SetString(PyExc_TypeError, message);
break;
case 57:
// kerInvalidMalloc
// Invalid memory allocation request
PyErr_SetString(PyExc_MemoryError, message);
break;
case 58:
// kerCorruptedMetadata Corrupted image metadata
PyErr_SetString(PyExc_IOError, message);
break;
case 59:
// kerArithmeticOverflow Arithmetic operation overflow
PyErr_SetString(PyExc_OverflowError, message);
break;
case 60:
// kerMallocFailed Memory allocation failed
PyErr_SetString(PyExc_MemoryError, message);
break;
// Default handler
default:
PyErr_SetString(PyExc_RuntimeError, message);
}
}
#endif
bool initialiseXmpParser()
{
if (!Exiv2::XmpParser::initialize())
return false;
std::string prefix("py3exiv2");
std::string name("www.py3exiv2.tuxfamily.org/");
try
{
const std::string& ns = Exiv2::XmpProperties::ns(prefix);
}
catch (Exiv2::Error& error)
{
// No namespace exists with the requested prefix, it is safe to
// register a new one.
Exiv2::XmpProperties::registerNs(name, prefix);
}
return true;
}
bool closeXmpParser()
{
std::string name("www.py3exiv2.tuxfamily.org/");
const std::string& prefix = Exiv2::XmpProperties::prefix(name);
if (prefix != "")
{
Exiv2::XmpProperties::unregisterNs(name);
}
Exiv2::XmpParser::terminate();
return true;
}
void registerXmpNs(const std::string& name, const std::string& prefix)
{
try
{
const std::string& ns = Exiv2::XmpProperties::ns(prefix);
}
catch (Exiv2::Error& error)
{
// No namespace exists with the requested prefix, it is safe to
// register a new one.
Exiv2::XmpProperties::registerNs(name, prefix);
return;
}
#ifdef HAVE_CLASS_ERROR_CODE
{
std::string mssg("Namespace already exists: ");
mssg += prefix;
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidKey, mssg);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
std::string mssg("Namespace already exists: ");
mssg += prefix;
throw Exiv2::Error(Exiv2::kerInvalidKey, mssg);
}
#else
{
throw Exiv2::Error(EXISTING_PREFIX, prefix);
}
#endif
#endif
}
void unregisterXmpNs(const std::string& name)
{
const std::string& prefix = Exiv2::XmpProperties::prefix(name);
if (prefix != "")
{
Exiv2::XmpProperties::unregisterNs(name);
try
{
const Exiv2::XmpNsInfo* info = Exiv2::XmpProperties::nsInfo(prefix);
}
catch (Exiv2::Error& error)
{
// The namespace has been successfully unregistered.
return;
}
// The namespace hasn’t been unregistered because it’s builtin.
#ifdef HAVE_CLASS_ERROR_CODE
{
std::string mssg("Can't unregister builtin namespace: ");
mssg += name;
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidKey, mssg);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
std::string mssg("Can't unregister builtin namespace: ");
mssg += name;
throw Exiv2::Error(Exiv2::kerInvalidKey, mssg);
}
#else
{
throw Exiv2::Error(BUILTIN_NS, name);
}
#endif
#endif
}
else
#ifdef HAVE_CLASS_ERROR_CODE
{
std::string mssg("Namespace does not exists: ");
mssg += name;
throw Exiv2::Error(Exiv2::ErrorCode::kerInvalidKey, mssg);
}
#else
#ifdef HAVE_EXIV2_ERROR_CODE
{
std::string mssg("Namespace does not exists: ");
mssg += name;
throw Exiv2::Error(Exiv2::kerInvalidKey, mssg);
}
#else
{
throw Exiv2::Error(NOT_REGISTERED, name);
}
#endif
#endif
}
void unregisterAllXmpNs()
{
// Unregister all custom namespaces.
Exiv2::XmpProperties::unregisterNs();
}
// End of namespace exiv2wrapper
}
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1691480919.0
py3exiv2-0.12.0/src/exiv2wrapper.hpp 0000664 0001750 0001750 00000020735 14464371527 017205 0 ustar 00vincent vincent // *****************************************************************************
/*
* Copyright (C) 2006-2010 Olivier Tilloy
* Copyright (C) 2015-2023 Vincent Vande Vyvre
*
* This file is part of the py3exiv2 distribution.
*
* py3exiv2 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 2
* of the License, or (at your option) any later version.
*
* py3exiv2 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 py3exiv2; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
*/
/*
Maintainer: Vincent Vande Vyvre
*/
// *****************************************************************************
#ifndef __exiv2wrapper__
#define __exiv2wrapper__
#endif
#include
#include "exiv2/exiv2.hpp"
#include "boost/python.hpp"
namespace exiv2wrapper
{
class Image;
class ExifTag
{
public:
// Constructor
ExifTag(const std::string& key,
Exiv2::Exifdatum* datum=0, Exiv2::ExifData* data=0,
Exiv2::ByteOrder byteOrder=Exiv2::invalidByteOrder);
~ExifTag();
void setRawValue(const std::string& value);
void setParentImage(Image& image);
const std::string getKey();
const std::string getType();
const std::string getName();
const std::string getLabel();
const std::string getDescription();
const std::string getSectionName();
const std::string getSectionDescription();
const std::string getRawValue();
const std::string getHumanValue();
int getByteOrder();
private:
Exiv2::ExifKey _key;
Exiv2::Exifdatum* _datum;
Exiv2::ExifData* _data;
std::string _type;
std::string _name;
std::string _label;
std::string _description;
std::string _sectionName;
std::string _sectionDescription;
int _byteOrder;
};
class IptcTag
{
public:
// Constructor
IptcTag(const std::string& key, Exiv2::IptcData* data=0);
~IptcTag();
void setRawValues(const boost::python::list& values);
void setParentImage(Image& image);
const std::string getKey();
const std::string getType();
const std::string getName();
const std::string getTitle();
const std::string getDescription();
const std::string getPhotoshopName();
const bool isRepeatable();
const std::string getRecordName();
const std::string getRecordDescription();
const boost::python::list getRawValues();
private:
Exiv2::IptcKey _key;
bool _from_data; // whether the tag is built from an existing IptcData
Exiv2::IptcData* _data;
std::string _type;
std::string _name;
std::string _title;
std::string _description;
std::string _photoshopName;
bool _repeatable;
std::string _recordName;
std::string _recordDescription;
};
class XmpTag
{
public:
// Constructor
XmpTag(const std::string& key, Exiv2::Xmpdatum* datum=0);
~XmpTag();
void setTextValue(const std::string& value);
void setArrayValue(const boost::python::list& values);
void setLangAltValue(const boost::python::dict& values);
void setParentImage(Image& image);
const std::string getKey();
const std::string getExiv2Type();
const std::string getType();
const std::string getName();
const std::string getTitle();
const std::string getDescription();
const std::string getTextValue();
const boost::python::list getArrayValue();
const boost::python::dict getLangAltValue();
private:
Exiv2::XmpKey _key;
bool _from_datum; // whether the tag is built from an existing Xmpdatum
Exiv2::Xmpdatum* _datum;
std::string _exiv2_type;
std::string _type;
std::string _name;
std::string _title;
std::string _description;
};
class Preview
{
public:
Preview(const Exiv2::PreviewImage& previewImage);
boost::python::object getData() const;
void writeToFile(const std::string& path) const;
std::string _mimeType;
std::string _extension;
unsigned int _size;
boost::python::tuple _dimensions;
std::string _data;
const Exiv2::byte* pData;
};
class Image
{
public:
// Constructors
Image(const std::string& filename);
Image(const std::string& buffer, unsigned long size);
Image(const Image& image);
~Image();
void readMetadata();
void writeMetadata();
// Read-only access to the dimensions of the picture.
unsigned int pixelWidth() const;
unsigned int pixelHeight() const;
// Read-only access to the MIME type of the image.
std::string mimeType() const;
// Read and write access to the EXIF tags.
// For a complete list of the available EXIF tags, see
// libexiv2's documentation (http://exiv2.org/tags.html).
// Return a list of all the keys of available EXIF tags set in the
// image.
boost::python::list exifKeys();
// Return the required EXIF tag.
// Throw an exception if the tag is not set.
const ExifTag getExifTag(std::string key);
// Delete the required EXIF tag.
// Throw an exception if the tag was not set.
void deleteExifTag(std::string key);
// Read and write access to the IPTC tags.
// For a complete list of the available IPTC tags, see
// libexiv2's documentation (http://exiv2.org/iptc.html).
// Returns a list of all the keys of available IPTC tags set in the
// image. This list has no duplicates: each of its items is unique,
// even if a tag is present more than once.
boost::python::list iptcKeys();
// Return the required IPTC tag.
// Throw an exception if the tag is not set.
const IptcTag getIptcTag(std::string key);
// Delete (all the repetitions of) the required IPTC tag.
// Throw an exception if the tag was not set.
void deleteIptcTag(std::string key);
boost::python::list xmpKeys();
// Return the required XMP tag.
// Throw an exception if the tag is not set.
const XmpTag getXmpTag(std::string key);
// Delete the required XMP tag.
// Throw an exception if the tag was not set.
void deleteXmpTag(std::string key);
// Comment
const std::string getComment() const;
void setComment(const std::string& comment);
void clearComment();
// Read access to the thumbnail embedded in the image.
boost::python::list previews();
// Manipulate the JPEG/TIFF thumbnail embedded in the EXIF data.
const std::string getExifThumbnailMimeType();
const std::string getExifThumbnailExtension();
void writeExifThumbnailToFile(const std::string& path);
boost::python::list getExifThumbnailData();
void eraseExifThumbnail();
void setExifThumbnailFromFile(const std::string& path);
void setExifThumbnailFromData(const std::string& data);
// Copy the metadata to another image.
void copyMetadata(Image& other, bool exif=true, bool iptc=true, bool xmp=true) const;
// Return the image data buffer.
boost::python::object getDataBuffer() const;
// Accessors
Exiv2::ExifData* getExifData() { return _exifData; };
Exiv2::IptcData* getIptcData() { return _iptcData; };
Exiv2::XmpData* getXmpData() { return _xmpData; };
Exiv2::ByteOrder getByteOrder() const;
const std::string getIptcCharset() const;
private:
std::string _filename;
Exiv2::byte* _data;
long _size;
#if EXIV2_MAJOR_VERSION >= 1 || (EXIV2_MAJOR_VERSION == 0 && EXIV2_MINOR_VERSION >= 28)
Exiv2::Image::UniquePtr _image;
#else
Exiv2::Image::AutoPtr _image;
#endif
Exiv2::ExifData* _exifData;
Exiv2::IptcData* _iptcData;
Exiv2::XmpData* _xmpData;
Exiv2::ExifThumb* _exifThumbnail;
Exiv2::ExifThumb* _getExifThumbnail();
// true if the image's internal metadata has already been read,
// false otherwise
bool _dataRead;
void _instantiate_image();
};
// Translate an Exiv2 generic exception into a Python exception
void translateExiv2Error(Exiv2::Error const& error);
// Functions to manipulate custom XMP namespaces
bool initialiseXmpParser();
bool closeXmpParser();
void registerXmpNs(const std::string& name, const std::string& prefix);
void unregisterXmpNs(const std::string& name);
void unregisterAllXmpNs();
} // End of namespace exiv2wrapper
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1690440594.0
py3exiv2-0.12.0/src/exiv2wrapper_python.cpp 0000664 0001750 0001750 00000014405 14460411622 020561 0 ustar 00vincent vincent // *****************************************************************************
/*
* Copyright (C) 2006-2012 Olivier Tilloy
* Copyright (C) 2015-2023 Vincent Vande Vyvre
*
* This file is part of the py3exiv2 distribution.
*
* py3exiv2 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 2
* of the License, or (at your option) any later version.
*
* py3exiv2 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 py3exiv2; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
*/
/*
Maintainer: Vincent Vande Vyvre
*/
// *****************************************************************************
#include
#include "exiv2wrapper.hpp"
#include "exiv2/exv_conf.h"
#include "exiv2/version.hpp"
#include
using namespace boost::python;
using namespace exiv2wrapper;
BOOST_PYTHON_MODULE(libexiv2python)
{
scope().attr("exiv2_version_info") = \
boost::python::make_tuple(EXIV2_MAJOR_VERSION,
EXIV2_MINOR_VERSION,
EXIV2_PATCH_VERSION);
register_exception_translator(&translateExiv2Error);
// Swallow all warnings and error messages written by libexiv2 to stderr
// (if it was compiled with DEBUG or without SUPPRESS_WARNINGS).
// See https://bugs.launchpad.net/pyexiv2/+bug/507620.
std::cerr.rdbuf(NULL);
class_("_ExifTag", init())
.def("_setRawValue", &ExifTag::setRawValue)
.def("_setParentImage", &ExifTag::setParentImage)
.def("_getKey", &ExifTag::getKey)
.def("_getType", &ExifTag::getType)
.def("_getName", &ExifTag::getName)
.def("_getLabel", &ExifTag::getLabel)
.def("_getDescription", &ExifTag::getDescription)
.def("_getSectionName", &ExifTag::getSectionName)
.def("_getSectionDescription", &ExifTag::getSectionDescription)
.def("_getRawValue", &ExifTag::getRawValue)
.def("_getHumanValue", &ExifTag::getHumanValue)
.def("_getByteOrder", &ExifTag::getByteOrder)
;
class_("_IptcTag", init())
.def("_setRawValues", &IptcTag::setRawValues)
.def("_setParentImage", &IptcTag::setParentImage)
.def("_getKey", &IptcTag::getKey)
.def("_getType", &IptcTag::getType)
.def("_getName", &IptcTag::getName)
.def("_getTitle", &IptcTag::getTitle)
.def("_getDescription", &IptcTag::getDescription)
.def("_getPhotoshopName", &IptcTag::getPhotoshopName)
.def("_isRepeatable", &IptcTag::isRepeatable)
.def("_getRecordName", &IptcTag::getRecordName)
.def("_getRecordDescription", &IptcTag::getRecordDescription)
.def("_getRawValues", &IptcTag::getRawValues)
;
class_("_XmpTag", init())
.def("_setTextValue", &XmpTag::setTextValue)
.def("_setArrayValue", &XmpTag::setArrayValue)
.def("_setLangAltValue", &XmpTag::setLangAltValue)
.def("_setParentImage", &XmpTag::setParentImage)
.def("_getKey", &XmpTag::getKey)
.def("_getExiv2Type", &XmpTag::getExiv2Type)
.def("_getType", &XmpTag::getType)
.def("_getName", &XmpTag::getName)
.def("_getTitle", &XmpTag::getTitle)
.def("_getDescription", &XmpTag::getDescription)
.def("_getTextValue", &XmpTag::getTextValue)
.def("_getArrayValue", &XmpTag::getArrayValue)
.def("_getLangAltValue", &XmpTag::getLangAltValue)
;
class_("_Preview", init())
.def_readonly("mime_type", &Preview::_mimeType)
.def_readonly("extension", &Preview::_extension)
.def_readonly("size", &Preview::_size)
.def_readonly("dimensions", &Preview::_dimensions)
.def_readonly("data", &Preview::_data)
.def("get_data", &Preview::getData)
.def("write_to_file", &Preview::writeToFile)
;
class_("_Image", init())
.def(init())
.def("_readMetadata", &Image::readMetadata)
.def("_writeMetadata", &Image::writeMetadata)
.def("_getPixelWidth", &Image::pixelWidth)
.def("_getPixelHeight", &Image::pixelHeight)
.def("_getMimeType", &Image::mimeType)
.def("_exifKeys", &Image::exifKeys)
.def("_getExifTag", &Image::getExifTag)
.def("_deleteExifTag", &Image::deleteExifTag)
.def("_iptcKeys", &Image::iptcKeys)
.def("_getIptcTag", &Image::getIptcTag)
.def("_deleteIptcTag", &Image::deleteIptcTag)
.def("_xmpKeys", &Image::xmpKeys)
.def("_getXmpTag", &Image::getXmpTag)
.def("_deleteXmpTag", &Image::deleteXmpTag)
.def("_getComment", &Image::getComment)
.def("_setComment", &Image::setComment)
.def("_clearComment", &Image::clearComment)
.def("_previews", &Image::previews)
.def("_copyMetadata", &Image::copyMetadata)
.def("_getDataBuffer", &Image::getDataBuffer)
.def("_getExifThumbnailMimeType", &Image::getExifThumbnailMimeType)
.def("_getExifThumbnailExtension", &Image::getExifThumbnailExtension)
.def("_writeExifThumbnailToFile", &Image::writeExifThumbnailToFile)
.def("_getExifThumbnailData", &Image::getExifThumbnailData)
.def("_eraseExifThumbnail", &Image::eraseExifThumbnail)
.def("_setExifThumbnailFromFile", &Image::setExifThumbnailFromFile)
.def("_setExifThumbnailFromData", &Image::setExifThumbnailFromData)
.def("_getIptcCharset", &Image::getIptcCharset)
;
def("_initialiseXmpParser", initialiseXmpParser);
def("_closeXmpParser", closeXmpParser);
def("_registerXmpNs", registerXmpNs, args("name", "prefix"));
def("_unregisterXmpNs", unregisterXmpNs, args("name"));
def("_unregisterAllXmpNs", unregisterAllXmpNs);
}
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1692346883.7238493
py3exiv2-0.12.0/src/py3exiv2.egg-info/ 0000775 0001750 0001750 00000000000 14467625004 017205 5 ustar 00vincent vincent ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1692346883.0
py3exiv2-0.12.0/src/py3exiv2.egg-info/PKG-INFO 0000664 0001750 0001750 00000003740 14467625003 020305 0 ustar 00vincent vincent Metadata-Version: 2.1
Name: py3exiv2
Version: 0.12.0
Summary: A Python3 binding to the library exiv2
Home-page: https://launchpad.net/py3exiv2
Author: Vincent Vande Vyvre
Author-email: vincent.vandevyvre@oqapy.eu
License: GPL-3
Keywords: exiv2 pyexiv2 EXIF IPTC XMP image metadata
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
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: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
License-File: COPYING
python3-exiv2
=============
A Python 3 binding to the library exiv2.
python3-exiv2 is a Python 3 binding to exiv2, the C++ library for manipulation of EXIF, IPTC and XMP image metadata. It is a python 3 module that allows your scripts to read and write metadata (EXIF, IPTC, XMP, thumbnails) embedded in image files (JPEG, TIFF, ...).
It is designed as a high-level interface to the functionalities offered by libexiv2. Using python’s built-in data types and standard modules, it provides easy manipulation of image metadata.
python3-exiv2 is distributed under the GPL version 3 license.
The main content of the code was initially written by Olivier Tilloy for Python 2 under the name pyexiv2.
py3exiv2 depends on the following libraries:
* python (≥ 3.2)
* boost.python3 (http://www.boost.org/libs/python/doc/index.html)
* exiv2 (http://www.exiv2.org/)
Build depends:
* python-all-dev (≥ 3.2)
* libexiv2-dev (≥ 0.20)
* libboost-python-dev (≥ 1.48)
* g++
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1692346883.0
py3exiv2-0.12.0/src/py3exiv2.egg-info/SOURCES.txt 0000664 0001750 0001750 00000000640 14467625003 021070 0 ustar 00vincent vincent COPYING
DESCRIPTION.rst
MANIFEST.in
README
setup.py
src/exiv2wrapper.cpp
src/exiv2wrapper.hpp
src/exiv2wrapper_python.cpp
src/py3exiv2.egg-info/PKG-INFO
src/py3exiv2.egg-info/SOURCES.txt
src/py3exiv2.egg-info/dependency_links.txt
src/py3exiv2.egg-info/top_level.txt
src/pyexiv2/__init__.py
src/pyexiv2/exif.py
src/pyexiv2/iptc.py
src/pyexiv2/metadata.py
src/pyexiv2/preview.py
src/pyexiv2/utils.py
src/pyexiv2/xmp.py ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1692346883.0
py3exiv2-0.12.0/src/py3exiv2.egg-info/dependency_links.txt 0000664 0001750 0001750 00000000001 14467625003 023252 0 ustar 00vincent vincent
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1692346883.0
py3exiv2-0.12.0/src/py3exiv2.egg-info/top_level.txt 0000664 0001750 0001750 00000000027 14467625003 021735 0 ustar 00vincent vincent libexiv2python
pyexiv2
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1692346883.7278492
py3exiv2-0.12.0/src/pyexiv2/ 0000775 0001750 0001750 00000000000 14467625004 015430 5 ustar 00vincent vincent ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1690440744.0
py3exiv2-0.12.0/src/pyexiv2/__init__.py 0000664 0001750 0001750 00000006625 14460412050 017536 0 ustar 00vincent vincent # -*- coding: utf-8 -*-
# ******************************************************************************
#
# Copyright (C) 2006-2011 Olivier Tilloy
# Copyright (C) 2015-2023 Vincent Vande Vyvre
#
# This file is part of the py3exiv2 distribution.
#
# py3exiv2 is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3 as published by the Free Software Foundation.
#
# py3exiv2 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 py3exiv2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
#
# Maintainer: Vincent Vande Vyvre
#
# ******************************************************************************
"""
Manipulation of EXIF, IPTC and XMP metadata and thumbnails embedded in images.
The ImageMetadata class provides read/write access to all the metadata and
the various thumbnails embedded in an image file such as JPEG and TIFF files.
Metadata is accessed through tag classes (ExifTag, IptcTag, XmpTag)
and the tag values are conveniently wrapped in python objects.
For example, a tag containing a date/time information for the image
(e.g. Exif.Photo.DateTimeOriginal) will be represented by a python
datetime.datetime object.
This module is a python layer on top of the low-level python binding of the
C++ library Exiv2, libexiv2python.
A typical use of this binding would be:
>>> import pyexiv2
>>> metadata = pyexiv2.ImageMetadata('test/smiley.jpg')
>>> metadata.read()
>>> print(metadata.exif_keys)
['Exif.Image.ImageDescription', 'Exif.Image.XResolution',
'Exif.Image.YResolution', 'Exif.Image.ResolutionUnit', 'Exif.Image.Software',
'Exif.Image.DateTime', 'Exif.Image.Artist', 'Exif.Image.Copyright',
'Exif.Image.ExifTag', 'Exif.Photo.Flash', 'Exif.Photo.PixelXDimension',
'Exif.Photo.PixelYDimension']
>>> print(metadata['Exif.Image.DateTime'].value)
2004-07-13 21:23:44
>>> import datetime
>>> metadata['Exif.Image.DateTime'].value = datetime.datetime.today()
>>> metadata.write()
"""
import libexiv2python
from pyexiv2.metadata import ImageMetadata
from pyexiv2.exif import ExifValueError, ExifTag, ExifThumbnail
from pyexiv2.iptc import IptcValueError, IptcTag
from pyexiv2.xmp import (XmpValueError, XmpTag, register_namespace,
unregister_namespace, unregister_namespaces)
from pyexiv2.preview import Preview
from pyexiv2.utils import (FixedOffset, NotifyingList,
undefined_to_string, string_to_undefined,
GPSCoordinate)
def _make_version(version_info):
return '.'.join([str(i) for i in version_info])
#: A tuple containing the three components of the version number: major, minor, micro.
version_info = (0, 12, 0)
#: The version of the module as a string (major.minor.micro).
__version__ = _make_version(version_info)
#: A tuple containing the three components of the version number of libexiv2: major, minor, micro.
exiv2_version_info = libexiv2python.exiv2_version_info
#: The version of libexiv2 as a string (major.minor.micro).
__exiv2_version__ = _make_version(exiv2_version_info)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1690440656.0
py3exiv2-0.12.0/src/pyexiv2/exif.py 0000666 0001750 0001750 00000044057 14460411720 016740 0 ustar 00vincent vincent # -*- coding: utf-8 -*-
# ******************************************************************************
#
# Copyright (C) 2006-2011 Olivier Tilloy
# Copyright (C) 2015-2023 Vincent Vande Vyvre
#
# This file is part of the py3exiv2 distribution.
#
# py3exiv2 is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3 as published by the Free Software Foundation.
#
# py3exiv2 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 py3exiv2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
#
# Maintainer: Vincent Vande Vyvre
#
# ******************************************************************************
"""
EXIF specific code.
"""
import libexiv2python
from pyexiv2.utils import (is_fraction, make_fraction, fraction_to_string,
NotifyingList, ListenerInterface,
undefined_to_string, string_to_undefined,
DateTimeFormatter)
import time
import datetime
import sys
class ExifValueError(ValueError):
"""Exception raised when failing to parse the *value* of an EXIF tag.
"""
def __init__(self, value, type_):
"""Instanciate the ExifValueError.
Args:
value -- the value that fails to be parsed
type_ -- the EXIF type of the tag
"""
self.value = value
self.type = type_
def __str__(self):
return 'Invalid value for EXIF type [%s]: [%s]' %(self.type, self.value)
class ExifTag(ListenerInterface):
"""An EXIF tag.
Here is a correspondance table between the EXIF types and the possible
python types the value of a tag may take:
- Ascii: :class:`datetime.datetime`, :class:`datetime.date`, string
- Byte, SByte: bytes
- Comment: string
- Long, SLong: [list of] int
- Short, SShort: [list of] int
- Rational, SRational: [list of] :class:`fractions.Fraction` if available
(Python ≥ 2.6) or :class:`pyexiv2.utils.Rational`
- Undefined: string
"""
# According to the EXIF specification, the only accepted format for an Ascii
# value representing a datetime is '%Y:%m:%d %H:%M:%S', but it seems that
# others formats can be found in the wild.
_datetime_formats = ('%Y:%m:%d %H:%M:%S',
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%dT%H:%M:%SZ')
_date_formats = ('%Y:%m:%d',)
def __init__(self, key, value=None, _tag=None):
""" The tag can be initialized with an optional value which expected
type depends on the EXIF type of the tag.
Args:
key -- the key of the tag
value -- the value of the tag
"""
super().__init__()
if _tag is not None:
self._tag = _tag
else:
self._tag = libexiv2python._ExifTag(key)
self._raw_value = None
self._value = None
self._value_cookie = False
if value is not None:
self._set_value(value)
def _set_owner(self, metadata):
self._tag._setParentImage(metadata._image)
@staticmethod
def _from_existing_tag(_tag):
"""Build a tag from an already existing libexiv2python._ExifTag.
"""
tag = ExifTag(_tag._getKey(), _tag=_tag)
# Do not set the raw_value property, as it would call _tag._setRawValue
# (see https://bugs.launchpad.net/pyexiv2/+bug/582445).
tag._raw_value = _tag._getRawValue()
tag._value_cookie = True
return tag
@property
def key(self):
"""The key of the tag in the dotted form
``familyName.groupName.tagName`` where ``familyName`` = ``exif``.
"""
return self._tag._getKey()
@property
def type(self):
"""The EXIF type of the tag (one of Ascii, Byte, SByte, Comment, Short,
SShort, Long, SLong, Rational, SRational, Undefined).
"""
return self._tag._getType()
@property
def name(self):
"""The name of the tag (this is also the third part of the key).
"""
return self._tag._getName()
@property
def label(self):
"""The title (label) of the tag.
"""
return self._tag._getLabel()
@property
def description(self):
"""The description of the tag.
"""
return self._tag._getDescription()
@property
def section_name(self):
"""The name of the tag's section.
"""
return self._tag._getSectionName()
@property
def section_description(self):
"""The description of the tag's section.
"""
return self._tag._getSectionDescription()
def _get_raw_value(self):
return self._raw_value
def _set_raw_value(self, value):
self._tag._setRawValue(value)
self._raw_value = value
self._value_cookie = True
raw_value = property(fget=_get_raw_value, fset=_set_raw_value,
doc='The raw value of the tag as a string.')
def _compute_value(self):
"""Lazy computation of the value from the raw value.
"""
if self.type in ('Short', 'SShort', 'Long', 'SLong',
'Rational', 'SRational'):
# May contain multiple values
values = self._raw_value.split()
if len(values) > 1:
# Make values a notifying list
values = [self._convert_to_python(v) for v in values]
self._value = NotifyingList(values)
self._value.register_listener(self)
self._value_cookie = False
return
self._value = self._convert_to_python(self._raw_value)
self._value_cookie = False
def _get_value(self):
if self._value_cookie:
self._compute_value()
return self._value
def _set_value(self, value):
if isinstance(value, (list, tuple)):
raw_values = [self._convert_to_string(v) for v in value]
self.raw_value = ' '.join(raw_values)
else:
self.raw_value = self._convert_to_string(value)
if isinstance(self._value, NotifyingList):
self._value.unregister_listener(self)
if isinstance(value, NotifyingList):
# Already a notifying list
self._value = value
self._value.register_listener(self)
elif isinstance(value, (list, tuple)):
# Make the values a notifying list
self._value = NotifyingList(value)
self._value.register_listener(self)
else:
# Single value
self._value = value
self._value_cookie = False
value = property(fget=_get_value, fset=_set_value,
doc='The value of the tag as a python object.')
@property
def human_value(self):
"""A (read-only) human-readable representation
of the value of the tag.
"""
return self._tag._getHumanValue() or None
def contents_changed(self):
# Implementation of the ListenerInterface.
# React on changes to the list of values of the tag.
# self._value is a list of values and its contents changed.
self._set_value(self._value)
def _match_encoding(self, charset):
# charset see:
# http://www.exiv2.org/doc/classExiv2_1_1CommentValue.html
# enum CharsetId {
# ascii, jis, unicode, undefined,
# invalidCharsetId, lastCharsetId }
encoding = sys.getdefaultencoding()
if charset in ('Ascii', 'ascii'):
encoding = 'ascii'
elif charset in ('Jis', 'jis'):
encoding = 'shift_jis'
elif charset in ('Unicode', 'unicode'):
encoding = 'utf-8'
return encoding
def _convert_to_python(self, value):
"""
Convert one raw value to its corresponding python type.
:param value: the raw value to be converted
:type value: string
:return: the value converted to its corresponding python type
:raise ExifValueError: if the conversion fails
"""
if self.type == 'Ascii':
# The value may contain a Datetime
for format in self._datetime_formats:
try:
t = time.strptime(value, format)
except ValueError:
continue
else:
return datetime.datetime(*t[:6])
# Or a Date (e.g. Exif.GPSInfo.GPSDateStamp)
for format in self._date_formats:
try:
t = time.strptime(value, format)
except ValueError:
continue
else:
return datetime.date(*t[:3])
# Default to string.
# There is currently no charset conversion.
# TODO: guess the encoding and decode accordingly into unicode
# where relevant.
return value
elif self.type in ('Byte', 'SByte'):
if isinstance(value, bytes):
return value.decode('utf-8')
return value
elif self.type == 'Comment':
if isinstance(value, str):
if value.startswith('charset='):
charset, val = value.split(' ', 1)
return val
return value
if value.startswith(b'charset='):
charset = charset.split('=')[1].strip('"')
encoding = self._match_encoding(charset)
return val.decode(encoding, 'replace')
else:
# No encoding defined.
try:
return value.decode('utf-8')
except UnicodeError:
pass
return value
elif self.type in ('Short', 'SShort'):
try:
return int(value)
except ValueError:
raise ExifValueError(value, self.type)
elif self.type in ('Long', 'SLong'):
try:
return int(value)
except ValueError:
raise ExifValueError(value, self.type)
elif self.type in ('Rational', 'SRational'):
try:
r = make_fraction(value)
except (ValueError, ZeroDivisionError):
raise ExifValueError(value, self.type)
else:
if self.type == 'Rational' and r.numerator < 0:
raise ExifValueError(value, self.type)
return r
elif self.type == 'Undefined':
# There is currently no charset conversion.
# TODO: guess the encoding and decode accordingly into unicode
# where relevant.
return undefined_to_string(value)
raise ExifValueError(value, self.type)
def _convert_to_string(self, value):
"""
Convert one value to its corresponding string representation, suitable
to pass to libexiv2.
:param value: the value to be converted
:return: the value converted to its corresponding string representation
:rtype: string
:raise ExifValueError: if the conversion fails
"""
if self.type == 'Ascii':
if isinstance(value, datetime.datetime):
return DateTimeFormatter.exif(value)
elif isinstance(value, datetime.date):
if self.key == 'Exif.GPSInfo.GPSDateStamp':
# Special case
return DateTimeFormatter.exif(value)
else:
return '%s 00:00:00' % DateTimeFormatter.exif(value)
else:
return value
elif self.type in ('Byte', 'SByte'):
if isinstance(value, str):
try:
return value.encode('utf-8')
except UnicodeEncodeError:
raise ExifValueError(value, self.type)
elif isinstance(value, bytes):
return value
else:
raise ExifValueError(value, self.type)
elif self.type == 'Comment':
return self._convert_to_bytes(value)
elif self.type == 'Short':
if isinstance(value, int) and value >= 0:
return str(value)
else:
raise ExifValueError(value, self.type)
elif self.type == 'SShort':
if isinstance(value, int):
return str(value)
else:
raise ExifValueError(value, self.type)
elif self.type == 'Long':
if isinstance(value, int) and value >= 0:
return str(value)
else:
raise ExifValueError(value, self.type)
elif self.type == 'SLong':
if isinstance(value, int):
return str(value)
else:
raise ExifValueError(value, self.type)
elif self.type == 'Rational':
if is_fraction(value) and value.numerator >= 0:
return fraction_to_string(value)
else:
raise ExifValueError(value, self.type)
elif self.type == 'SRational':
if is_fraction(value):
return fraction_to_string(value)
else:
raise ExifValueError(value, self.type)
elif self.type == 'Undefined':
if isinstance(value, str):
try:
return string_to_undefined(value)
except UnicodeEncodeError:
raise ExifValueError(value, self.type)
elif isinstance(value, bytes):
return string_to_undefined(value)
else:
raise ExifValueError(value, self.type)
raise ExifValueError(value, self.type)
def _convert_to_bytes(self, value):
if value is None:
return
if isinstance(value, str):
if value.startswith('charset='):
charset, val = value.split(' ', 1)
charset = charset.split('=')[1].strip('"')
encoding = self._match_encoding(charset)
else:
encoding = 'utf-8'
charset = 'Unicode'
try:
val = value.encode(encoding)
except UnicodeError:
pass
else:
#self._set_raw_value('charset=%s %s' % (charset, val))
return val
elif isinstance(value, bytes):
return value
else:
raise ExifValueError(value, self.type)
def __str__(self):
"""
:return: a string representation of the EXIF tag for debugging purposes
:rtype: string
"""
left = '%s [%s]' % (self.key, self.type)
if self._raw_value is None:
right = '(No value)'
elif self.type == 'Undefined' and len(self._raw_value) > 100:
right = '(Binary value suppressed)'
else:
right = self._raw_value
return '<%s = %s>' % (left, right)
# Support for pickling.
def __getstate__(self):
return (self.key, self.raw_value)
def __setstate__(self, state):
key, raw_value = state
self._tag = libexiv2python._ExifTag(key)
self.raw_value = raw_value
class ExifThumbnail(object):
"""
A thumbnail image optionally embedded in the IFD1 segment of the EXIF data.
The image is either a TIFF or a JPEG image.
"""
def __init__(self, _metadata):
self._metadata = _metadata
@property
def mime_type(self):
"""The mime type of the preview image (e.g. ``image/jpeg``)."""
return self._metadata._image._getExifThumbnailMimeType()
@property
def extension(self):
"""The file extension of the preview image with a leading dot
(e.g. ``.jpg``)."""
return self._metadata._image._getExifThumbnailExtension()
def write_to_file(self, path):
"""
Write the thumbnail image to a file on disk.
The file extension will be automatically appended to the path.
:param path: path to write the thumbnail to (without an extension)
:type path: string
"""
self._metadata._image._writeExifThumbnailToFile(path)
def _update_exif_tags_cache(self):
# Update the cache of EXIF tags
keys = self._metadata._image._exifKeys()
self._metadata._keys['exif'] = keys
#cached = self._metadata._tags['exif'].keys()
for key in self._metadata._tags['exif'].keys():
if key not in keys:
del self._metadata._tags['exif'][key]
def erase(self):
"""
Delete the thumbnail from the EXIF data.
Removes all Exif.Thumbnail.*, i.e. Exif IFD1 tags.
"""
self._metadata._image._eraseExifThumbnail()
self._update_exif_tags_cache()
def set_from_file(self, path):
"""
Set the EXIF thumbnail to the JPEG image path.
This sets only the ``Compression``, ``JPEGInterchangeFormat`` and
``JPEGInterchangeFormatLength`` tags, which is not all the thumbnail
EXIF information mandatory according to the EXIF standard
(but it is enough to work with the thumbnail).
:param path: path to a JPEG file to set the thumbnail to
:type path: string
"""
self._metadata._image._setExifThumbnailFromFile(path)
self._update_exif_tags_cache()
def _get_data(self):
buf_ = self._metadata._image._getExifThumbnailData()
return buf_
def _set_data(self, data):
self._metadata._image._setExifThumbnailFromData(data)
self._update_exif_tags_cache()
data = property(fget=_get_data, fset=_set_data,
doc='The raw thumbnail data. Setting it is restricted to ' +
'a buffer in the JPEG format.')
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1690440763.0
py3exiv2-0.12.0/src/pyexiv2/iptc.py 0000666 0001750 0001750 00000027073 14460412073 016745 0 ustar 00vincent vincent # -*- coding: utf-8 -*-
# ******************************************************************************
#
# Copyright (C) 2006-2011 Olivier Tilloy
# Copyright (C) 2015-2023 Vincent Vande Vyvre
#
# This file is part of the py3exiv2 distribution.
#
# py3exiv2 is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3 as published by the Free Software Foundation.
#
# py3exiv2 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 py3exiv2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
#
# Maintainer: Vincent Vande Vyvre
#
# ******************************************************************************
"""
IPTC specific code.
"""
import libexiv2python
from pyexiv2.utils import ListenerInterface, NotifyingList, \
FixedOffset, DateTimeFormatter
import time
import datetime
import re
import warnings
class IptcValueError(ValueError):
"""
Exception raised when failing to parse the *value* of an IPTC tag.
:attribute value: the value that fails to be parsed
:type value: string
:attribute type: the IPTC type of the tag
:type type: string
"""
def __init__(self, value, type):
self.value = value
self.type = type
def __str__(self):
return 'Invalid value for IPTC type [%s]: [%s]' % \
(self.type, self.value)
class IptcTag(ListenerInterface):
"""An IPTC tag.
This tag can have several values (tags that have the *repeatable* property).
Here is a correspondance table between the IPTC types and the possible
python types the value of a tag may take:
- Short: int
- String: string
- Date: :class:`datetime.date`
- Time: :class:`datetime.time`
- Undefined: string
"""
# strptime is not flexible enough to handle all valid Time formats, we use a
# custom regular expression
_time_zone_re = r'(?P\+|-)(?P\d{2}):(?P\d{2})'
_time_re = re.compile(r'(?P\d{2}):(?P\d{2}):(?P\d{2})(?P%s)' % _time_zone_re)
def __init__(self, key, values=None, _tag=None):
"""The tag can be initialized with an optional list of values which
expected type depends on the IPTC type of the tag.
Args:
key -- the key of the tag
values -- the values of the tag
"""
super(IptcTag, self).__init__()
if _tag is not None:
self._tag = _tag
else:
self._tag = libexiv2python._IptcTag(key)
self._raw_values = None
self._values = None
self._values_cookie = False
if values is not None:
self._set_values(values)
def _set_owner(self, metadata):
self._tag._setParentImage(metadata._image)
@staticmethod
def _from_existing_tag(_tag):
# Build a tag from an already existing libexiv2python._IptcTag
tag = IptcTag(_tag._getKey(), _tag=_tag)
# Do not set the raw_value property, as it would call
# _tag._setRawValues
# (see https://bugs.launchpad.net/pyexiv2/+bug/582445).
tag._raw_values = _tag._getRawValues()
tag._values_cookie = True
return tag
@property
def key(self):
"""The key of the tag in the dotted form
``familyName.groupName.tagName`` where ``familyName`` = ``iptc``.
"""
return self._tag._getKey()
@property
def type(self):
"""The IPTC type of the tag (one of Short, String, Date, Time,
Undefined).
"""
return self._tag._getType()
@property
def name(self):
"""The name of the tag (this is also the third part of the key).
"""
return self._tag._getName()
@property
def title(self):
"""The title (label) of the tag.
"""
return self._tag._getTitle()
@property
def description(self):
"""The description of the tag.
"""
return self._tag._getDescription()
@property
def photoshop_name(self):
"""The Photoshop name of the tag.
"""
return self._tag._getPhotoshopName()
@property
def repeatable(self):
"""Whether the tag is repeatable (accepts several values).
"""
return self._tag._isRepeatable()
@property
def record_name(self):
"""The name of the tag's record.
"""
return self._tag._getRecordName()
@property
def record_description(self):
"""The description of the tag's record.
"""
return self._tag._getRecordDescription()
def _get_raw_values(self):
return self._raw_values
def _set_raw_values(self, values):
if not isinstance(values, (list, tuple)):
raise TypeError('Expecting a list of values')
self._tag._setRawValues(values)
self._raw_values = values
self._values_cookie = True
raw_value = property(fget=_get_raw_values, fset=_set_raw_values,
doc='The raw values of the tag as a list of strings.')
def _compute_values(self):
# Lazy computation of the values from the raw values
self._values = NotifyingList([self._convert_to_python(v)
for v in self._raw_values])
self._values.register_listener(self)
self._values_cookie = False
def _get_values(self):
if self._values_cookie:
self._compute_values()
return self._values
def _set_values(self, values):
if not isinstance(values, (list, tuple)):
raise TypeError('Expecting a list of values')
self.raw_value = [self._convert_to_string(v) for v in values]
if isinstance(self._values, NotifyingList):
self._values.unregister_listener(self)
if isinstance(values, NotifyingList):
# Already a notifying list
self._values = values
else:
# Make the values a notifying list
self._values = NotifyingList(values)
self._values.register_listener(self)
self._values_cookie = False
value = property(fget=_get_values, fset=_set_values,
doc='The values of the tag as a list of python objects.')
def contents_changed(self):
# Implementation of the ListenerInterface.
# React on changes to the list of values of the tag.
# The contents of self._values was changed.
# The following is a quick, non optimal solution.
self._set_values(self._values)
def _convert_to_python(self, value):
"""Convert one raw value to its corresponding python type.
Args:
value -- the raw value to be converted
Return: the value converted to its corresponding python type
Raise IptcValueError: if the conversion fails
"""
if self.type == 'Short':
try:
return int(value)
except ValueError:
raise IptcValueError(value, self.type)
elif self.type == 'String':
# There is currently no charset conversion.
# TODO: guess the encoding and decode accordingly into unicode
# where relevant.
if isinstance(value, bytes):
try:
value = value.decode('utf-8')
except UnicodeDecodeError:
# Unknow encoding, return the raw value
pass
return value
elif self.type == 'Date':
# According to the IPTC specification, the format for a string field
# representing a date is '%Y%m%d'. However, the string returned by
# exiv2 using method DateValue::toString() is formatted using
# pattern '%Y-%m-%d'.
format = '%Y-%m-%d'
try:
t = time.strptime(value, format)
return datetime.date(*t[:3])
except ValueError:
raise IptcValueError(value, self.type)
elif self.type == 'Time':
# According to the IPTC specification, the format for a string field
# representing a time is '%H%M%S±%H%M'. However, the string returned
# by exiv2 using method TimeValue::toString() is formatted using
# pattern '%H:%M:%S±%H:%M'.
match = IptcTag._time_re.match(value)
if match is None:
raise IptcValueError(value, self.type)
gd = match.groupdict()
try:
tzinfo = FixedOffset(gd['sign'], int(gd['ohours']),
int(gd['ominutes']))
except TypeError:
raise IptcValueError(value, self.type)
try:
return datetime.time(int(gd['hours']), int(gd['minutes']),
int(gd['seconds']), tzinfo=tzinfo)
except (TypeError, ValueError):
raise IptcValueError(value, self.type)
elif self.type == 'Undefined':
# Binary data, return it unmodified
return value
raise IptcValueError(value, self.type)
def _convert_to_string(self, value):
"""Convert one value to its corresponding string representation,
suitable to pass to libexiv2.
Args:
value -- the value to be converted
Return: the value converted to its corresponding string representation
Raise IptcValueError: if the conversion fails
"""
if self.type == 'Short':
if isinstance(value, int):
return str(value)
else:
raise IptcValueError(value, self.type)
elif self.type == 'String':
if isinstance(value, str):
try:
return value.encode('utf-8')
except UnicodeEncodeError:
raise IptcValueError(value, self.type)
elif isinstance(value, bytes):
return value
else:
raise IptcValueError(value, self.type)
elif self.type == 'Date':
if isinstance(value, (datetime.date, datetime.datetime)):
return DateTimeFormatter.iptc_date(value)
else:
raise IptcValueError(value, self.type)
elif self.type == 'Time':
if isinstance(value, (datetime.time, datetime.datetime)):
return DateTimeFormatter.iptc_time(value)
else:
raise IptcValueError(value, self.type)
elif self.type == 'Undefined':
if isinstance(value, str):
return value
else:
raise IptcValueError(value, self.type)
raise IptcValueError(value, self.type)
def __str__(self):
"""Return a string representation of the IPTC tag for debugging purposes
"""
left = '%s [%s]' % (self.key, self.type)
if self._raw_values is None:
right = '(No values)'
else:
right = self._raw_values
return '<%s = %s>' % (left, right)
# Support for pickling.
def __getstate__(self):
return (self.key, self.raw_value)
def __setstate__(self, state):
key, raw_value = state
self._tag = libexiv2python._IptcTag(key)
self.raw_value = raw_value
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1690440799.0
py3exiv2-0.12.0/src/pyexiv2/metadata.py 0000666 0001750 0001750 00000047022 14460412137 017563 0 ustar 00vincent vincent # -*- coding: utf-8 -*-
# ******************************************************************************
#
# Copyright (C) 2006-2011 Olivier Tilloy
# Copyright (C) 2015-2023 Vincent Vande Vyvre
#
# This file is part of the py3exiv2 distribution.
#
# py3exiv2 is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3 as published by the Free Software Foundation.
#
# py3exiv2 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 py3exiv2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
#
# Maintainer: Vincent Vande Vyvre
#
# ******************************************************************************
"""
Provide the ImageMetadata class.
"""
import os
import sys
import codecs
from errno import ENOENT
from itertools import chain
if sys.version_info < (3, 3):
from collections import MutableMapping
else:
from collections.abc import MutableMapping
import libexiv2python
from pyexiv2.exif import ExifTag, ExifThumbnail
from pyexiv2.iptc import IptcTag
from pyexiv2.xmp import XmpTag
from pyexiv2.preview import Preview
class ImageMetadata(MutableMapping):
"""A container for all the metadata embedded in an image.
It provides convenient methods for the manipulation of EXIF, IPTC and XMP
metadata embedded in image files such as JPEG and TIFF files, using Python
types.
It also provides access to the previews embedded in an image.
"""
def __init__(self, filename):
"""Instanciate the ImageMeatadata class.
Args:
filename: str(path to an image file)
"""
self.filename = filename
self.__image = None
self._keys = {'exif': None, 'iptc': None, 'xmp': None}
self._tags = {'exif': {}, 'iptc': {}, 'xmp': {}}
self._exif_thumbnail = None
def _instantiate_image(self, filename):
"""Instanciate the exiv2 image.
Args:
filename -- str(path to an image file)
"""
# This method is meant to be overridden in unit tests to easily replace
# the internal image reference by a mock.
if not os.path.exists(filename) or not os.path.isfile(filename):
raise IOError(ENOENT, os.strerror(ENOENT), filename)
# Remember the reference timestamps before doing any access to the file
stat = os.stat(filename)
self._atime = stat.st_atime
self._mtime = stat.st_mtime
return libexiv2python._Image(filename)
@classmethod
def from_buffer(cls, buffer_):
"""Instantiate an image container from an image memoryview.
Args:
buffer_ -- a memoryview containing image data as bytes
"""
obj = cls(None)
obj.__image = libexiv2python._Image(buffer_, len(buffer_))
return obj
@property
def _image(self):
if self.__image is None:
raise IOError('Image metadata has not been read yet')
return self.__image
def read(self):
"""Read the metadata embedded in the associated image.
It is necessary to call this method once before attempting to access
the metadata (an exception will be raised if trying to access metadata
before calling this method).
"""
if self.__image is None:
self.__image = self._instantiate_image(self.filename)
self.__image._readMetadata()
def write(self, preserve_timestamps=False):
"""Write the metadata back to the image.
Args:
preserve_timestamps -- whether to preserve the file's original
timestamps (access time and modification time)
Type: boolean
"""
self._image._writeMetadata()
if self.filename is None:
return
if preserve_timestamps:
# Revert to the original timestamps
os.utime(self.filename, (self._atime, self._mtime))
else:
# Reset the reference timestamps
stat = os.stat(self.filename)
self._atime = stat.st_atime
self._mtime = stat.st_mtime
@property
def dimensions(self):
"""A tuple containing the width and height of the image, expressed in
pixels.
"""
return (self._image._getPixelWidth(), self._image._getPixelHeight())
@property
def mime_type(self):
"""The mime type of the image, as a string.
"""
return self._image._getMimeType()
@property
def exif_keys(self):
"""Return the list of the keys of the available EXIF tags.
"""
if self._keys['exif'] is None:
self._keys['exif'] = self._image._exifKeys()
return self._keys['exif']
@property
def iptc_keys(self):
"""Return the list of the keys of the available IPTC tags.
"""
if self._keys['iptc'] is None:
self._keys['iptc'] = self._image._iptcKeys()
return self._keys['iptc']
@property
def xmp_keys(self):
"""Return the list of the keys of the available XMP tags.
"""
if self._keys['xmp'] is None:
self._keys['xmp'] = self._image._xmpKeys()
return self._keys['xmp']
def _get_exif_tag(self, key):
"""Return the EXIF tag for the given key.
Throw a KeyError if the tag doesn't exist.
Args:
key -- the exif key
"""
try:
return self._tags['exif'][key]
except KeyError:
_tag = self._image._getExifTag(key)
tag = ExifTag._from_existing_tag(_tag)
self._tags['exif'][key] = tag
return tag
def _get_iptc_tag(self, key):
"""Return the IPTC tag for the given key.
Throw a KeyError if the tag doesn't exist.
Args:
key -- the iptc key
"""
try:
return self._tags['iptc'][key]
except KeyError:
_tag = self._image._getIptcTag(key)
tag = IptcTag._from_existing_tag(_tag)
self._tags['iptc'][key] = tag
return tag
def _get_xmp_tag(self, key):
"""Return the XMP tag for the given key.
Throw a KeyError if the tag doesn't exist.
Args:
key -- the xmp key
"""
try:
return self._tags['xmp'][key]
except KeyError:
_tag = self._image._getXmpTag(key)
tag = XmpTag._from_existing_tag(_tag)
self._tags['xmp'][key] = tag
return tag
def __getitem__(self, key):
"""Return a metadata tag for a given key.
Raise KeyError if the tag doesn't exist
Args:
key -- metadata key in the dotted form
``familyName.groupName.tagName`` where ``familyName`` may
be one of ``exif``, ``iptc`` or ``xmp``.
"""
family = key.split('.')[0].lower()
if family in ('exif', 'iptc', 'xmp'):
return getattr(self, '_get_%s_tag' % family)(key)
else:
raise KeyError(key)
def _set_exif_tag(self, key, tag_or_value):
"""Set an EXIF tag. If the tag already exists, its value is overwritten.
Args:
key -- the EXIF key
tag_or_value -- an ExifTag instance or the value of the data
"""
if isinstance(tag_or_value, ExifTag):
tag = tag_or_value
else:
# As a handy shortcut, accept direct value assignment.
tag = ExifTag(key, tag_or_value)
tag._set_owner(self)
self._tags['exif'][tag.key] = tag
if tag.key not in self.exif_keys:
self._keys['exif'].append(tag.key)
def _set_iptc_tag(self, key, tag_or_values):
"""Set an IPTC tag. If the tag already exists, its value is overwritten.
Args:
key -- the IPTC key
tag_or_value -- an IptcTag instance or the value of the data
"""
if isinstance(tag_or_values, IptcTag):
tag = tag_or_values
else:
# As a handy shortcut, accept direct value assignment.
tag = IptcTag(key, tag_or_values)
tag._set_owner(self)
self._tags['iptc'][tag.key] = tag
if tag.key not in self.iptc_keys:
self._keys['iptc'].append(tag.key)
def _set_xmp_tag(self, key, tag_or_value):
"""Set an XMP tag. If the tag already exists, its value is overwritten.
Args:
key -- the XMP key
tag_or_value -- an XmpTag instance or the value of the data
"""
if isinstance(tag_or_value, XmpTag):
tag = tag_or_value
else:
# As a handy shortcut, accept direct value assignment.
tag = XmpTag(key, tag_or_value)
tag._set_owner(self)
self._tags['xmp'][tag.key] = tag
if tag.key not in self.xmp_keys:
self._keys['xmp'].append(tag.key)
def __setitem__(self, key, tag_or_value):
"""Set a metadata tag for a given key.
If the tag was previously set, it is overwritten.
As a handy shortcut, a value may be passed instead of a fully formed
tag. The corresponding tag object will be instantiated.
Raise KeyError if the key is invalid
Args:
key -- metadata key in the dotted form
``familyName.groupName.tagName`` where ``familyName`` may
be one of ``exif``, ``iptc`` or ``xmp``.
tag_or_value -- an instance of the corresponding family of metadata
tag or a value
Type: pyexiv2.exif.ExifTag instance or
pyexiv2.iptc.IptcTag instance or
pyexiv2.xmp.XmpTag instance or
any valid value type
"""
family = key.split('.')[0].lower()
if family in ('exif', 'iptc', 'xmp'):
return getattr(self, '_set_%s_tag' % family)(key, tag_or_value)
else:
raise KeyError(key)
def _delete_exif_tag(self, key):
"""Delete an EXIF tag.
Throw a KeyError if the tag doesn't exist.
Args:
key -- the EXIF key
"""
if key not in self.exif_keys:
raise KeyError('Cannot delete an inexistent tag')
self._image._deleteExifTag(key)
try:
del self._tags['exif'][key]
except KeyError:
# The tag was not cached.
pass
if self._keys['exif'] is not None:
self._keys['exif'].remove(key)
def _delete_iptc_tag(self, key):
"""Delete an IPTC tag.
Throw a KeyError if the tag doesn't exist.
Args:
key -- the IPTC key
"""
if key not in self.iptc_keys:
raise KeyError('Cannot delete an inexistent tag')
self._image._deleteIptcTag(key)
try:
del self._tags['iptc'][key]
except KeyError:
# The tag was not cached.
pass
if self._keys['iptc'] is not None:
self._keys['iptc'].remove(key)
def _delete_xmp_tag(self, key):
"""Delete an XMP tag.
Throw a KeyError if the tag doesn't exist.
Args:
key -- the XMP key
"""
if key not in self.xmp_keys:
raise KeyError('Cannot delete an inexistent tag')
self._image._deleteXmpTag(key)
try:
del self._tags['xmp'][key]
except KeyError:
# The tag was not cached.
pass
if self._keys['xmp'] is not None:
self._keys['xmp'].remove(key)
def __delitem__(self, key):
"""Delete a metadata tag for a given key.
Raise KeyError if the tag with the given key doesn't exist
Args:
key -- the metadata key in the dotted form
``familyName.groupName.tagName`` where ``familyName`` may
be one of ``exif``, ``iptc`` or ``xmp``.
"""
family = key.split('.')[0].lower()
if family in ('exif', 'iptc', 'xmp'):
return getattr(self, '_delete_%s_tag' % family)(key)
else:
raise KeyError(key)
def __iter__(self):
return chain(self.exif_keys, self.iptc_keys, self.xmp_keys)
def __len__(self):
return len([x for x in self])
def _get_comment(self):
return self._image._getComment()
def _set_comment(self, comment):
if comment is not None:
self._image._setComment(comment)
else:
self._del_comment()
def _del_comment(self):
self._image._clearComment()
comment = property(fget=_get_comment, fset=_set_comment, fdel=_del_comment,
doc='The image comment.')
@property
def previews(self):
"""List of the previews available in the image, sorted by increasing
size.
"""
return [Preview(preview) for preview in self._image._previews()]
def copy(self, other, exif=True, iptc=True, xmp=True, comment=True):
"""Copy the metadata to another image.
The metadata in the destination is overridden. In particular, if the
destination contains e.g. EXIF data and the source doesn't, it will be
erased in the destination, unless explicitly omitted.
Args:
other -- the destination metadata to copy to (it must have been
read beforehand)
Type: pyexiv2.metadata.ImageMetadata instance
exif -- whether to copy the EXIF metadata, default True
iptc -- whether to copy the IPTC metadata, default True
xmp -- whether to copy the XMP metadata, default True
comment -- whether to copy the image comment, default True
"""
self._image._copyMetadata(other._image, exif, iptc, xmp)
# Empty the cache where needed
if exif:
other._keys['exif'] = None
other._tags['exif'] = {}
if iptc:
other._keys['iptc'] = None
other._tags['iptc'] = {}
if xmp:
other._keys['xmp'] = None
other._tags['xmp'] = {}
if comment:
other.comment = self.comment
@property
def buffer(self):
"""
The image buffer as a string.
If metadata has been modified, the data won't be up-to-date until
:meth:`.write` has been called.
"""
return self._image._getDataBuffer()
@property
def exif_thumbnail(self):
"""A thumbnail image optionally embedded in the EXIF data.
"""
if self._exif_thumbnail is None:
self._exif_thumbnail = ExifThumbnail(self)
return self._exif_thumbnail
def _get_iptc_charset(self):
value = self._image._getIptcCharset()
if value != '':
return value.lower()
else:
return None
def _set_iptc_charset(self, charset):
if charset is None:
self._del_iptc_charset()
return
try:
name = codecs.lookup(charset).name
except LookupError as error:
raise ValueError(error)
else:
charsets = {'utf-8': '\x1b%G'}
try:
self['Iptc.Envelope.CharacterSet'] = (charsets[name],)
except KeyError:
raise ValueError('Unhandled charset: %s' % name)
def _del_iptc_charset(self):
try:
del self['Iptc.Envelope.CharacterSet']
except KeyError:
pass
iptc_charset = property(fget=_get_iptc_charset,
fset=_set_iptc_charset,
fdel=_del_iptc_charset,
doc='An optional character set the IPTC data'\
' is encoded in.')
# Some convenient functions -------------------------------------------
def get_iso(self):
"""Returns the ISO value as integer.
"""
try:
return self["Exif.Photo.ISOSpeedRatings"].value
except KeyError:
return
def get_shutter_speed(self, float_=False):
"""Returns the exposure time as rational or float.
Args:
float_ -- if False, default, the value is returned as rational
otherwise as float
"""
try:
speed = self['Exif.Photo.ExposureTime'].value
except KeyError:
return
if float_:
if speed.denominator:
return speed.numerator / speed.denominator
return float(numerator)
return speed
def get_focal_length(self):
"""Returns the focal length as float.
"""
try:
focal = self['Exif.Photo.FocalLength'].value
if focal.denominator:
return round(focal.numerator / focal.denominator, 2)
else:
return float(focal.numerator)
except KeyError:
return
def get_aperture(self):
"""Returns the fNumber as float.
"""
try:
fnumber = self["Exif.Photo.FNumber"].value
if fnumber.denominator:
return round(fnumber.numerator / fnumber.denominator, 2)
else:
return float(fnumber.numerator)
except KeyError:
return
def get_orientation(self):
"""Returns the orientation of the image as integer.
If the tag is not set, the value 1 is returned.
"""
try:
return self["Exif.Image.Orientation"].value
except KeyError:
return 1
def get_exposure_data(self, float_=False):
"""Returns the exposure parameters of the image.
The values are returned as a dict which contains:
"iso": the ISO value
"speed": the exposure time
"focal": the focal length
"aperture": the fNumber
"orientation": the orientation of the image
When a tag is not set, the value will be None
Args:
float_ -- if False, default, the value of the exposure time is returned
as rational otherwise as float
"""
data = {"iso": self.get_iso(),
"speed": self.get_shutter_speed(float_),
"focal": self.get_focal_length(),
"aperture": self.get_aperture(),
"orientation": self.get_orientation()}
return data
def get_rights_data(self):
"""Returns the author and copyright info.
The values are returned as a dict which contains:
"creator": the value of Xmp.dc.creator
"artist": the value of Exif.Image.Artist
"rights": the value of Xmp.dc.rights
"copyright": the value of Exif.Image.Copyright
"marked": the value of Xmp.xmpRights.Marked
"usage": the value of Xmp.xmpRights.UsageTerms
When a tag is not set, the value will be None
"""
tags = [('creator', 'Xmp.dc.creator'),
('artist', 'Exif.Image.Artist'),
('rights', 'Xmp.dc.rights'),
('copyright', 'Exif.Image.Copyright'),
('marked', 'Xmp.xmpRights.Marked'),
('usage', 'Xmp.xmpRights.UsageTerms')]
rights = {}
for tag in tags:
try:
rights[tag[0]] = self[tag[1]].value
except KeyError:
rights[tag[0]] = None
return rights
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1690440811.0
py3exiv2-0.12.0/src/pyexiv2/preview.py 0000666 0001750 0001750 00000004520 14460412153 017456 0 ustar 00vincent vincent # -*- coding: utf-8 -*-
# ******************************************************************************
#
# Copyright (C) 2010 Olivier Tilloy
# Copyright (C) 2015-2023 Vincent Vande Vyvre
#
# This file is part of the py3exiv2 distribution.
#
# py3exiv2 is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3 as published by the Free Software Foundation.
#
# py3exiv2 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 py3exiv2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
#
# Maintainer: Vincent Vande Vyvre
#
# ******************************************************************************
"""
Provide the Preview class.
"""
import sys
class Preview(object):
"""A preview image (properties and data buffer) embedded in image metadata.
"""
def __init__(self, preview):
self.__preview = preview
@property
def mime_type(self):
"""The mime type of the preview image (e.g. ``image/jpeg``).
"""
return self.__preview.mime_type
@property
def extension(self):
"""The file extension of the preview image with a leading dot.
"""
return self.__preview.extension
@property
def size(self):
"""The size of the preview image in bytes.
"""
return self.__preview.size
@property
def dimensions(self):
"""A tuple containing the width and height of the preview image
in pixels.
"""
return self.__preview.dimensions
@property
def data(self):
"""The preview image data buffer.
"""
return self.__preview.get_data()
def write_to_file(self, path):
"""Write the preview image to a file on disk.
The file extension will be automatically appended to the path.
Args:
path -- path to write the preview to (without an extension)
"""
return self.__preview.write_to_file(path)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1690440836.0
py3exiv2-0.12.0/src/pyexiv2/utils.py 0000666 0001750 0001750 00000046560 14460412204 017144 0 ustar 00vincent vincent # -*- coding: utf-8 -*-
# ******************************************************************************
#
# Copyright (C) 2006-2012 Olivier Tilloy
# Copyright (C) 2015-2023 Vincent Vande Vyvre
#
# This file is part of the py3exiv2 distribution.
#
# py3exiv2 is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3 as published by the Free Software Foundation.
#
# py3exiv2 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 py3exiv2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
#
# Maintainer: Vincent Vande Vyvre
#
# ******************************************************************************
"""
Utilitary classes and functions.
"""
import datetime
import re
from fractions import Fraction
class FixedOffset(datetime.tzinfo):
"""Define a fixed positive or negative offset of a local time from UTC.
"""
def __init__(self, sign='+', hours=0, minutes=0):
"""Initialize an offset from a sign ('+' or '-') and an absolute value
expressed in hours and minutes.
No check on the validity of those values is performed, it is the
responsibility of the caller to pass valid values.
Args:
sign -- the sign of the offset ('+' or '-')
hours -- an absolute number of hours
minutes -- an absolute number of minutes
"""
self.sign = sign
self.hours = hours
self.minutes = minutes
def utcoffset(self, dt):
"""Return offset of local time from UTC, in minutes east of UTC.
If local time is west of UTC, this value will be negative.
Args:
dt -- the local datetime.time instance
Return: a whole number of minutes in the range -1439 to 1439 inclusive
"""
total = self.hours * 60 + self.minutes
if self.sign == '-':
total = -total
return datetime.timedelta(minutes = total)
def dst(self, dt):
"""Return the daylight saving time (DST) adjustment.
In this implementation, it is always nil.
Args:
dt -- the local datetime.time instance
Return: the DST adjustment (always nil)
"""
return datetime.timedelta(0)
def tzname(self, dt):
"""Return a string representation of the offset in the format '±%H:%M'.
If the offset is nil, the representation is, by convention, 'Z'.
Args:
dt -- the local datetime.time instance
Return: a human-readable representation of the offset
"""
if self.hours == 0 and self.minutes == 0:
return 'Z'
else:
return '%s%02d:%02d' % (self.sign, self.hours, self.minutes)
def __equal__(self, other):
"""Test equality between this offset and another offset.
Args:
other -- another FixedOffset instance
Return: True if the offset are equal, False otherwise
"""
return (self.sign == other.sign) and (self.hours == other.hours) and \
(self.minutes == other.minutes)
def undefined_to_string(undefined):
"""Convert an undefined string into its corresponding sequence of bytes.
The undefined string must contain the ascii codes of a sequence of bytes,
separated by white spaces (e.g. "48 50 50 49" will be converted into
"0221").
The Undefined type is part of the EXIF specification.
Args:
undefined -- an undefined string
Return: the corresponding decoded string
"""
if not undefined:
return ''
return ''.join([chr(int(x)) for x in undefined.rstrip().split(' ')])
def string_to_undefined(sequence):
"""Convert a string into its undefined form.
The undefined form contains a sequence of ascii codes separated by white
spaces (e.g. "0221" will be converted into "48 50 50 49").
The Undefined type is part of the EXIF specification.
Args:
sequence -- a sequence of bytes
Return: the corresponding undefined string
"""
return " ".join([str(ord(s)) for s in sequence])
def is_fraction(obj):
"""Test whether the object is a valid fraction.
"""
return isinstance(obj, Fraction)
def match_string(string):
"""Match a string against the expected format for a :class:`Fraction`
(``[-]numerator/denominator``) and return the numerator and denominator
as a tuple.
Args:
string -- a string representation of a rational number
Return: a tuple (numerator, denominator)
Raise ValueError: if the format of the string is invalid
"""
format_re = re.compile(r'(?P-?\d+)/(?P\d+)')
match = format_re.match(string)
if match is None:
raise ValueError('Invalid format for a rational: %s' % string)
gd = match.groupdict()
return (int(gd['numerator']), int(gd['denominator']))
def make_fraction(*args):
"""Make a fraction.
Raise TypeError: if the arguments do not match the expected format for a
fraction
"""
if len(args) == 1:
numerator, denominator = match_string(args[0])
elif len(args) == 2:
numerator = args[0]
denominator = args[1]
else:
raise TypeError('Invalid format for a fraction: %s' % str(args))
if denominator == 0 and numerator == 0:
# Null rationals are often stored as '0/0'.
# We want to be fault-tolerant in this specific case
# (see https://bugs.launchpad.net/pyexiv2/+bug/786253).
denominator = 1
return Fraction(numerator, denominator)
def fraction_to_string(fraction):
"""Return a string representation of a fraction.
The returned string is always in the form '[numerator]/[denominator]'.
Raise TypeError: if the argument is not a valid fraction
"""
if isinstance(fraction, Fraction):
# fractions.Fraction.__str__ returns '0' for a null numerator.
return '%s/%s' % (fraction.numerator, fraction.denominator)
else:
raise TypeError('Not a fraction')
class ListenerInterface(object):
"""
Interface that an object that wants to listen to changes on another object
should implement.
"""
def contents_changed(self):
"""
React on changes on the object observed.
Override to implement specific behaviours.
"""
raise NotImplementedError()
class NotifyingList(list):
"""A simplistic implementation of a notifying list.
Any changes to the list are notified in a synchronous way to all previously
registered listeners.
A listener must implement the class ListenerInterface.
"""
# Useful documentation:
# file:///usr/share/doc/python2.5/html/lib/typesseq-mutable.html
# http://docs.python.org/reference/datamodel.html#additional-methods-for-emulation-of-sequence-types
def __init__(self, items=[]):
super(NotifyingList, self).__init__(items)
self._listeners = set()
def register_listener(self, listener):
"""Register a new listener to be notified of changes.
Args:
listener -- any ListenerInterface instance that listens for changes
"""
self._listeners.add(listener)
def unregister_listener(self, listener):
"""Unregister a previously registered listener.
Args:
listener -- a previously registered listener
Raise KeyError: if the listener was not previously registered
"""
self._listeners.remove(listener)
def _notify_listeners(self, *args):
for listener in self._listeners:
listener.contents_changed(*args)
def __setitem__(self, index, item):
# FIXME: support slice arguments for extended slicing
super(NotifyingList, self).__setitem__(index, item)
self._notify_listeners()
def __delitem__(self, index):
# FIXME: support slice arguments for extended slicing
super(NotifyingList, self).__delitem__(index)
self._notify_listeners()
def append(self, item):
super(NotifyingList, self).append(item)
self._notify_listeners()
def extend(self, items):
super(NotifyingList, self).extend(items)
self._notify_listeners()
def insert(self, index, item):
super(NotifyingList, self).insert(index, item)
self._notify_listeners()
def pop(self, index=None):
if index is None:
item = super(NotifyingList, self).pop()
else:
item = super(NotifyingList, self).pop(index)
self._notify_listeners()
return item
def remove(self, item):
super(NotifyingList, self).remove(item)
self._notify_listeners()
def reverse(self):
super(NotifyingList, self).reverse()
self._notify_listeners()
def sort(self, key=None, reverse=False):
super(NotifyingList, self).sort(key=key, reverse=reverse)
self._notify_listeners()
def __iadd__(self, other):
self = super(NotifyingList, self).__iadd__(other)
self._notify_listeners()
return self
def __imul__(self, coefficient):
self = super(NotifyingList, self).__imul__(coefficient)
self._notify_listeners()
return self
def setslice__(self, i, j, items):
# __setslice__ is deprecated but needs to be overridden for completeness
super(NotifyingList, self).__setslice__(i, j, items)
self._notify_listeners()
def delslice__(self, i, j):
# __delslice__ is deprecated but needs to be overridden for completeness
deleted = self[i:j]
super(NotifyingList, self).__delslice__(i, j)
if deleted:
self._notify_listeners()
class GPSCoordinate(object):
"""A class representing GPS coordinates (e.g. a latitude or a longitude).
Its attributes (degrees, minutes, seconds, direction) are read-only
properties.
"""
_format_re = re.compile(r'(?P-?\d+),'
'(?P\d+)(,(?P\d+)|\.(?P\d+))'
'(?P[NSEW])')
def __init__(self, degrees, minutes, seconds, direction):
"""Instanciate a GPSCoordinate object.
Args:
degrees -- int(degrees)
minutes -- int(minutes)
seconds -- int(seconds)
direction -- str('N', 'S', 'E' or 'W')
Raise ValueError: if any of the parameter is not in the expected range
of values
"""
if direction not in ('N', 'S', 'E', 'W'):
raise ValueError('Invalid direction: %s' % direction)
self._direction = direction
if (direction in ('N', 'S') and (degrees < 0 or degrees > 90)) or \
(direction in ('E', 'W') and (degrees < 0 or degrees > 180)):
raise ValueError('Invalid value for degrees: %d' % degrees)
self._degrees = degrees
if minutes < 0 or minutes > 60:
raise ValueError('Invalid value for minutes: %d' % minutes)
self._minutes = minutes
if seconds < 0 or seconds > 60:
raise ValueError('Invalid value for seconds: %d' % seconds)
self._seconds = seconds
@property
def degrees(self):
"""The degrees component of the coordinate.
"""
return self._degrees
@property
def minutes(self):
"""The minutes component of the coordinate.
"""
return self._minutes
@property
def seconds(self):
"""The seconds component of the coordinate.
"""
return self._seconds
@property
def direction(self):
"""The direction component of the coordinate.
"""
return self._direction
@staticmethod
def from_string(string):
"""Instantiate a :class:`GPSCoordinate` from a string formatted as
``DDD,MM,SSk`` or ``DDD,MM.mmk`` where ``DDD`` is a number of degrees,
``MM`` is a number of minutes, ``SS`` is a number of seconds, ``mm`` is
a fraction of minutes, and ``k`` is a single character N, S, E, W
indicating a direction (north, south, east, west).
Args:
string -- a string representation of a GPS coordinate
Return: the GPSCoordinate parsed
Raise ValueError: if the format of the string is invalid
"""
match = GPSCoordinate._format_re.match(string)
if match is None:
raise ValueError('Invalid format for a GPS coordinate: %s' % string)
gd = match.groupdict()
fraction = gd['fraction']
if fraction is not None:
seconds = int(round(int(fraction[:2]) * 0.6))
else:
seconds = int(gd['seconds'])
return GPSCoordinate(int(gd['degrees']), int(gd['minutes']), seconds,
gd['direction'])
def __eq__(self, other):
"""Compare two GPS coordinates for equality.
Two coordinates are equal if and only if all their components are equal.
Args:
other -- the GPSCoordinate instance to compare to self for equality
Return: True if equal, False otherwise
"""
return (self._degrees == other._degrees) and \
(self._minutes == other._minutes) and \
(self._seconds == other._seconds) and \
(self._direction == other._direction)
def __str__(self):
"""Return a string representation of the GPS coordinate conforming
to the XMP specification
"""
return '%d,%d,%d%s' % (self._degrees, self._minutes, self._seconds,
self._direction)
class DateTimeFormatter(object):
"""Convenience object that exposes static methods to convert a date, time or
datetime object to a string representation suitable for various metadata
standards.
This is needed because python’s
`strftime() `_
doesn’t work for years before 1900.
This class mostly exists for internal usage only. Clients should never need
to use it.
"""
@staticmethod
def timedelta_to_offset(t):
"""Convert a time delta to a string..
Args:
t -- a datetime.timedelta instance
Return: a string representation of the time delta in the form `±%H:%M`
"""
# timedelta.total_seconds() is only available starting with Python 3.2
seconds = t.total_seconds()
hours = int(seconds / 3600)
minutes = abs(int((seconds - hours * 3600) / 60))
return '%+03d:%02d' % (hours, minutes)
@staticmethod
def exif(d):
"""Convert a date/time object to a string representation conforming to
libexiv2’s internal representation for the EXIF standard.
Args:
d -- a datetime.datetime or datetime.date instance
Return: a string representation conforming to the EXIF standard
Raise TypeError: if the parameter is not a datetime or a date object
"""
if isinstance(d, datetime.datetime):
return '%04d:%02d:%02d %02d:%02d:%02d' % \
(d.year, d.month, d.day, d.hour, d.minute, d.second)
elif isinstance(d, datetime.date):
return '%04d:%02d:%02d' % (d.year, d.month, d.day)
else:
raise TypeError('expecting an object of type '
'datetime.datetime or datetime.date')
@staticmethod
def iptc_date(d):
"""Convert a date object to a string representation conforming to
libexiv2’s internal representation for the IPTC standard.
Args:
d -- a datetime.datetime or datetime.date instance
Return: a string representation conforming to the IPTC standard
Raise TypeError: if the parameter is not a datetime or a date object
"""
if isinstance(d, (datetime.date, datetime.datetime)):
# ISO 8601 date format.
# According to the IPTC specification, the format for a string
# field representing a date is '%Y%m%d'. However, the string
# expected by exiv2's DateValue::read(string) should be
# formatted using pattern '%Y-%m-%d'.
return '%04d-%02d-%02d' % (d.year, d.month, d.day)
else:
raise TypeError('expecting an object of type '
'datetime.datetime or datetime.date')
@staticmethod
def iptc_time(d):
"""Convert a time object to a string representation conforming to
libexiv2’s internal representation for the IPTC standard.
Args:
d -- a datetime.datetime or time instance
Return: a string representation conforming to the IPTC standard
Raise TypeError: if the parameter is not a datetime or a time object
"""
if isinstance(d, (datetime.time, datetime.datetime)):
# According to the IPTC specification, the format for a string
# field representing a time is '%H%M%S±%H%M'. However, the
# string expected by exiv2's TimeValue::read(string) should be
# formatted using pattern '%H:%M:%S±%H:%M'.
r = '%02d:%02d:%02d' % (d.hour, d.minute, d.second)
if d.tzinfo is not None:
t = d.utcoffset()
if t is not None:
r += DateTimeFormatter.timedelta_to_offset(t)
else:
r += '+00:00'
return r
else:
raise TypeError('expecting an object of type '
'datetime.datetime or datetime.time')
@staticmethod
def xmp(d):
"""Convert a date/time object to a string representation conforming to
libexiv2’s internal representation for the XMP standard.
Args:
d -- a datetime.datetime or datetime.date instance
Return: a string representation conforming to the XMP standard
Raise TypeError: if the parameter is not a datetime or a date object
"""
if isinstance(d, datetime.datetime):
t = d.utcoffset()
if d.tzinfo is None or t is None or t == datetime.timedelta(0):
tz = 'Z'
else:
tz = DateTimeFormatter.timedelta_to_offset(t)
if d.hour == 0 and d.minute == 0 and \
d.second == 0 and d.microsecond == 0 and \
(d.tzinfo is None or d.utcoffset() == datetime.timedelta(0)):
return '%04d-%02d-%02d' % (d.year, d.month, d.day)
elif d.second == 0 and d.microsecond == 0:
return '%04d-%02d-%02dT%02d:%02d%s' % \
(d.year, d.month, d.day, d.hour, d.minute, tz)
elif d.microsecond == 0:
return '%04d-%02d-%02dT%02d:%02d:%02d%s' % \
(d.year, d.month, d.day, d.hour, d.minute, d.second, tz)
else:
r = '%04d-%02d-%02dT%02d:%02d:%02d.' % \
(d.year, d.month, d.day, d.hour, d.minute, d.second)
r += str(int(d.microsecond) / 1E6)[2:]
r += tz
return r
elif isinstance(d, datetime.date):
return '%04d-%02d-%02d' % (d.year, d.month, d.day)
else:
raise TypeError('expecting an object of type '
'datetime.datetime or datetime.date')
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1690440918.0
py3exiv2-0.12.0/src/pyexiv2/xmp.py 0000664 0001750 0001750 00000051221 14460412326 016601 0 ustar 00vincent vincent # -*- coding: utf-8 -*-
# ******************************************************************************
#
# Copyright (C) 2006-2011 Olivier Tilloy
# Copyright (C) 2015-2023 Vincent Vande Vyvre
#
# This file is part of the py3exiv2 distribution.
#
# py3exiv2 is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3 as published by the Free Software Foundation.
#
# py3exiv2 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 py3exiv2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
#
# Maintainer: Vincent Vande Vyvre
#
# ******************************************************************************
"""
XMP specific code.
"""
import libexiv2python
from pyexiv2.utils import (FixedOffset, is_fraction, make_fraction,
GPSCoordinate, DateTimeFormatter)
import datetime
import re
class XmpValueError(ValueError):
"""
Exception raised when failing to parse the *value* of an XMP tag.
:attribute value: the value that fails to be parsed
:type value: string
:attribute type: the XMP type of the tag
:type type: string
"""
def __init__(self, value, type_):
self.value = value
self.type = type_
def __str__(self):
return 'Invalid value for XMP type [%s]: [%s]' % \
(self.type, self.value)
class XmpTag(object):
"""Define an XMP tag.
Here is a correspondance table between the XMP types and the possible
python types the value of a tag may take:
- alt, bag, seq: list of the contained simple type
- lang alt: dict of (language-code: value)
- Boolean: boolean
- Colorant: *[not implemented yet]*
- Date: :class:`datetime.date`, :class:`datetime.datetime`
- Dimensions: *[not implemented yet]*
- Font: *[not implemented yet]*
- GPSCoordinate: :class:`pyexiv2.utils.GPSCoordinate`
- Integer: int
- Locale: *[not implemented yet]*
- MIMEType: 2-tuple of strings
- Rational: :class:`fractions.Fraction`
- Real: *[not implemented yet]*
- AgentName, ProperName, Text: unicode string
- Thumbnail: *[not implemented yet]*
- URI, URL: string
- XPath: *[not implemented yet]*
"""
# strptime is not flexible enough to handle all valid Date formats, we use a
# custom regular expression
_time_zone_re = r'$|Z|((?P\+|-)(?P\d{2}):(?P\d{2}))'
_time_re = r'(?P\d{2})(:(?P\d{2})(:(?P\d{2})(.(?P\d+))?)?(?P%s))?' % _time_zone_re
_date_re = re.compile(r'(?P\d{4})(-(?P\d{2})(-(?P\d{2})(T(?P