././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728999050.702708 libzim-3.6.0/0000755000175100001770000000000014703467213012422 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/LICENSE0000644000175100001770000010451514703467205013436 0ustar00runnerdocker GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/MANIFEST.in0000644000175100001770000000057214703467205014165 0ustar00runnerdockerinclude LICENSE include README.md include tests/*.py include pyproject.toml include setup.cfg include requirements-dev.txt include tasks.py include libzim/*.cpp include libzim/*.h include libzim/*.py include libzim/*.pxd include libzim/*.pyx global-exclude __pycache__/* exclude *.egg-info/* exclude libzim/*.dylib exclude libzim/*.so exclude libzim/*.so.* exclude libzim/*.dll ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728999050.702708 libzim-3.6.0/PKG-INFO0000644000175100001770000002657014703467213013531 0ustar00runnerdockerMetadata-Version: 2.1 Name: libzim Version: 3.6.0 Summary: A python-facing API for creating and interacting with ZIM files Author-email: openZIM License: GPL-3.0-or-later Project-URL: Homepage, https://github.com/openzim/python-libzim Project-URL: Donate, https://www.kiwix.org/en/support-us/ Classifier: Development Status :: 5 - Production/Stable Classifier: Topic :: Utilities Classifier: Topic :: Software Development :: Libraries Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: System :: Archiving Classifier: Topic :: System :: Archiving :: Compression Classifier: Topic :: System :: Archiving :: Mirroring Classifier: Topic :: System :: Archiving :: Backup Classifier: Intended Audience :: Developers Classifier: Programming Language :: Cython Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Typing :: Stubs Only Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) Classifier: Operating System :: MacOS Classifier: Operating System :: POSIX Requires-Python: <3.14,>=3.9 Description-Content-Type: text/markdown License-File: LICENSE Provides-Extra: scripts Requires-Dist: invoke==2.2.0; extra == "scripts" Provides-Extra: lint Requires-Dist: black==24.10.0; extra == "lint" Requires-Dist: ruff==0.6.9; extra == "lint" Requires-Dist: libzim; extra == "lint" Requires-Dist: libzim[build]; extra == "lint" Provides-Extra: check Requires-Dist: pyright==1.1.384; extra == "check" Requires-Dist: libzim; extra == "check" Requires-Dist: libzim[build]; extra == "check" Requires-Dist: libzim[test]; extra == "check" Requires-Dist: types-setuptools; extra == "check" Provides-Extra: test Requires-Dist: pytest==8.3.3; extra == "test" Requires-Dist: coverage==7.6.2; extra == "test" Requires-Dist: libzim[build]; extra == "test" Provides-Extra: build Requires-Dist: setuptools==75.1.0; extra == "build" Requires-Dist: wheel==0.44.0; extra == "build" Requires-Dist: cython==3.0.11; extra == "build" Requires-Dist: delocate==0.11.0; platform_system == "Windows" and extra == "build" Provides-Extra: dev Requires-Dist: pre-commit==4.0.1; extra == "dev" Requires-Dist: ipython==8.28.0; extra == "dev" Requires-Dist: types-setuptools; extra == "dev" Requires-Dist: libzim[scripts]; extra == "dev" Requires-Dist: libzim[lint]; extra == "dev" Requires-Dist: libzim[test]; extra == "dev" Requires-Dist: libzim[check]; extra == "dev" Requires-Dist: libzim[build]; extra == "dev" # python-libzim `libzim` module allows you to read and write [ZIM files](https://openzim.org) in Python. It provides a shallow python interface on top of the [C++ `libzim` library](https://github.com/openzim/libzim). It is primarily used in [openZIM](https://github.com/openzim/) scrapers like [`sotoki`](https://github.com/openzim/sotoki) or [`youtube2zim`](https://github.com/openzim/youtube). [![Build Status](https://github.com/openzim/python-libzim/workflows/test/badge.svg?query=branch%3Amain)](https://github.com/openzim/python-libzim/actions?query=branch%3Amain) [![CodeFactor](https://www.codefactor.io/repository/github/openzim/python-libzim/badge)](https://www.codefactor.io/repository/github/openzim/python-libzim) [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) [![PyPI version shields.io](https://img.shields.io/pypi/v/libzim.svg)](https://pypi.org/project/libzim/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/libzim.svg)](https://pypi.org/project/libzim) [![codecov](https://codecov.io/gh/openzim/python-libzim/branch/main/graph/badge.svg)](https://codecov.io/gh/openzim/python-libzim) ## Installation ```sh pip install libzim ``` Our [PyPI wheels](https://pypi.org/project/libzim/) bundle a [recent release](https://download.openzim.org/release/libzim/) of the C++ libzim and are available for the following platforms: - macOS for `x86_64` and `arm64` - GNU/Linux for `x86_64`, `armhf` and `aarch64` - Linux+musl for `x86_64` and `aarch64` - Windows for `x64` Wheels are available for CPython only (but can be built for Pypy). Users on other platforms can install the source distribution (see [Building](#Building) below). ## Contributions ```sh git clone git@github.com:openzim/python-libzim.git && cd python-libzim # hatch run test:coverage ``` See [CONTRIBUTING.md](./CONTRIBUTING.md) for additional details then [Open a ticket](https://github.com/openzim/python-libzim/issues/new) or submit a Pull Request on Github 🤗! ## Usage ### Read a ZIM file ```python from libzim.reader import Archive from libzim.search import Query, Searcher from libzim.suggestion import SuggestionSearcher zim = Archive("test.zim") print(f"Main entry is at {zim.main_entry.get_item().path}") entry = zim.get_entry_by_path("home/fr") print(f"Entry {entry.title} at {entry.path} is {entry.get_item().size}b.") print(bytes(entry.get_item().content).decode("UTF-8")) # searching using full-text index search_string = "Welcome" query = Query().set_query(search_string) searcher = Searcher(zim) search = searcher.search(query) search_count = search.getEstimatedMatches() print(f"there are {search_count} matches for {search_string}") print(list(search.getResults(0, search_count))) # accessing suggestions search_string = "kiwix" suggestion_searcher = SuggestionSearcher(zim) suggestion = suggestion_searcher.suggest(search_string) suggestion_count = suggestion.getEstimatedMatches() print(f"there are {suggestion_count} matches for {search_string}") print(list(suggestion.getResults(0, suggestion_count))) ``` ### Write a ZIM file ```py from libzim.writer import Creator, Item, StringProvider, FileProvider, Hint class MyItem(Item): def __init__(self, title, path, content = "", fpath = None): super().__init__() self.path = path self.title = title self.content = content self.fpath = fpath def get_path(self): return self.path def get_title(self): return self.title def get_mimetype(self): return "text/html" def get_contentprovider(self): if self.fpath is not None: return FileProvider(self.fpath) return StringProvider(self.content) def get_hints(self): return {Hint.FRONT_ARTICLE: True} content = """Web Page Title

Welcome to this ZIM

Kiwix

""" item = MyItem("Hello Kiwix", "home", content) item2 = MyItem("Bonjour Kiwix", "home/fr", None, "home-fr.html") with Creator("test.zim").config_indexing(True, "eng") as creator: creator.set_mainpath("home") creator.add_item(item) creator.add_item(item2) illustration = pathlib.Path("icon48x48.png").read_bytes() creator.add_illustration(48, illustration) for name, value in { "creator": "python-libzim", "description": "Created in python", "name": "my-zim", "publisher": "You", "title": "Test ZIM", "language": "eng", "date": "2024-06-30" }.items(): creator.add_metadata(name.title(), value) ``` #### Thread safety > The reading part of the libzim is most of the time thread safe. Searching and creating part are not. [libzim documentation](https://libzim.readthedocs.io/en/latest/usage.html#introduction) `python-libzim` disables the [GIL](https://wiki.python.org/moin/GlobalInterpreterLock) on most of C++ libzim calls. You **must prevent concurrent access** yourself. This is easily done by wrapping all creator calls with a [`threading.Lock()`](https://docs.python.org/3/library/threading.html#lock-objects) ```py lock = threading.Lock() with Creator("test.zim") as creator: # Thread #1 with lock: creator.add_item(item1) # Thread #2 with lock: creator.add_item(item2) ``` #### Type hints `libzim` being a binary extension, there is no Python source to provide types information. We provide them as type stub files. When using `pyright`, you would normally receive a warning when importing from `libzim` as there could be discrepencies between actual sources and the (manually crafted) stub files. You can disable the warning via `reportMissingModuleSource = "none"`. ## Building `libzim` package building offers different behaviors via environment variables | Variable | Example | Use case | | -------------------------------- | ---------------------------------------- | -------- | | `LIBZIM_DL_VERSION` | `8.1.1` or `2023-04-14` | Specify the C++ libzim binary version to download and bundle. Either a release version string or a date, in which case it downloads a nightly | | `USE_SYSTEM_LIBZIM` | `1` | Uses `LDFLAG` and `CFLAGS` to find the libzim to link against. Resulting wheel won't bundle C++ libzim. | | `DONT_DOWNLOAD_LIBZIM` | `1` | Disable downloading of C++ libzim. Place headers in `include/` and libzim dylib/so in `libzim/` if no using system libzim. It will be bundled in wheel. | | `PROFILE` | `0` | Enable profile tracing in Cython extension. Required for Cython code coverage reporting. | | `SIGN_APPLE` | `1` | Set to sign and notarize the extension for macOS. Requires following informations | | `APPLE_SIGNING_IDENTITY` | `Developer ID Application: OrgName (ID)` | Required for signing on macOS | | `APPLE_SIGNING_KEYCHAIN_PATH` | `/tmp/build.keychain` | Path to the Keychain containing the certificate to sign for macOS with | | `APPLE_SIGNING_KEYCHAIN_PROFILE` | `build` | Name of the profile in the specified Keychain | ### Building on Windows On Windows, built wheels needs to be fixed post-build to move the bundled DLLs (libzim and libicu) next to the wrapper (Windows does not support runtime path). After building you wheel, run ```ps python setup.py repair_win_wheel --wheel=dist/xxx.whl --destdir wheels\ ``` Similarily, if you install as editable (`pip install -e .`), you need to place those DLLs at the root of the repo. ```ps Move-Item -Force -Path .\libzim\*.dll -Destination .\ ``` ### Examples ##### Default: downloading and bundling most appropriate libzim release binary ```sh python3 -m build ``` #### Using system libzim (brew, debian or manually installed) - not bundled ```sh # using system-installed C++ libzim brew install libzim # macOS apt-get install libzim-devel # debian dnf install libzim-dev # fedora USE_SYSTEM_LIBZIM=1 python3 -m build --wheel # using a specific C++ libzim USE_SYSTEM_LIBZIM=1 \ CFLAGS="-I/usr/local/include" \ LDFLAGS="-L/usr/local/lib" DYLD_LIBRARY_PATH="/usr/local/lib" \ LD_LIBRARY_PATH="/usr/local/lib" \ python3 -m build --wheel ``` #### Other platforms On platforms for which there is no [official binary](https://download.openzim.org/release/libzim/) available, you'd have to [compile C++ libzim from source](https://github.com/openzim/libzim) first then either use `DONT_DOWNLOAD_LIBZIM` or `USE_SYSTEM_LIBZIM`. ## License [GPLv3](https://www.gnu.org/licenses/gpl-3.0) or later, see [LICENSE](LICENSE) for more details. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/README.md0000644000175100001770000002131614703467205013705 0ustar00runnerdocker# python-libzim `libzim` module allows you to read and write [ZIM files](https://openzim.org) in Python. It provides a shallow python interface on top of the [C++ `libzim` library](https://github.com/openzim/libzim). It is primarily used in [openZIM](https://github.com/openzim/) scrapers like [`sotoki`](https://github.com/openzim/sotoki) or [`youtube2zim`](https://github.com/openzim/youtube). [![Build Status](https://github.com/openzim/python-libzim/workflows/test/badge.svg?query=branch%3Amain)](https://github.com/openzim/python-libzim/actions?query=branch%3Amain) [![CodeFactor](https://www.codefactor.io/repository/github/openzim/python-libzim/badge)](https://www.codefactor.io/repository/github/openzim/python-libzim) [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) [![PyPI version shields.io](https://img.shields.io/pypi/v/libzim.svg)](https://pypi.org/project/libzim/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/libzim.svg)](https://pypi.org/project/libzim) [![codecov](https://codecov.io/gh/openzim/python-libzim/branch/main/graph/badge.svg)](https://codecov.io/gh/openzim/python-libzim) ## Installation ```sh pip install libzim ``` Our [PyPI wheels](https://pypi.org/project/libzim/) bundle a [recent release](https://download.openzim.org/release/libzim/) of the C++ libzim and are available for the following platforms: - macOS for `x86_64` and `arm64` - GNU/Linux for `x86_64`, `armhf` and `aarch64` - Linux+musl for `x86_64` and `aarch64` - Windows for `x64` Wheels are available for CPython only (but can be built for Pypy). Users on other platforms can install the source distribution (see [Building](#Building) below). ## Contributions ```sh git clone git@github.com:openzim/python-libzim.git && cd python-libzim # hatch run test:coverage ``` See [CONTRIBUTING.md](./CONTRIBUTING.md) for additional details then [Open a ticket](https://github.com/openzim/python-libzim/issues/new) or submit a Pull Request on Github 🤗! ## Usage ### Read a ZIM file ```python from libzim.reader import Archive from libzim.search import Query, Searcher from libzim.suggestion import SuggestionSearcher zim = Archive("test.zim") print(f"Main entry is at {zim.main_entry.get_item().path}") entry = zim.get_entry_by_path("home/fr") print(f"Entry {entry.title} at {entry.path} is {entry.get_item().size}b.") print(bytes(entry.get_item().content).decode("UTF-8")) # searching using full-text index search_string = "Welcome" query = Query().set_query(search_string) searcher = Searcher(zim) search = searcher.search(query) search_count = search.getEstimatedMatches() print(f"there are {search_count} matches for {search_string}") print(list(search.getResults(0, search_count))) # accessing suggestions search_string = "kiwix" suggestion_searcher = SuggestionSearcher(zim) suggestion = suggestion_searcher.suggest(search_string) suggestion_count = suggestion.getEstimatedMatches() print(f"there are {suggestion_count} matches for {search_string}") print(list(suggestion.getResults(0, suggestion_count))) ``` ### Write a ZIM file ```py from libzim.writer import Creator, Item, StringProvider, FileProvider, Hint class MyItem(Item): def __init__(self, title, path, content = "", fpath = None): super().__init__() self.path = path self.title = title self.content = content self.fpath = fpath def get_path(self): return self.path def get_title(self): return self.title def get_mimetype(self): return "text/html" def get_contentprovider(self): if self.fpath is not None: return FileProvider(self.fpath) return StringProvider(self.content) def get_hints(self): return {Hint.FRONT_ARTICLE: True} content = """Web Page Title

Welcome to this ZIM

Kiwix

""" item = MyItem("Hello Kiwix", "home", content) item2 = MyItem("Bonjour Kiwix", "home/fr", None, "home-fr.html") with Creator("test.zim").config_indexing(True, "eng") as creator: creator.set_mainpath("home") creator.add_item(item) creator.add_item(item2) illustration = pathlib.Path("icon48x48.png").read_bytes() creator.add_illustration(48, illustration) for name, value in { "creator": "python-libzim", "description": "Created in python", "name": "my-zim", "publisher": "You", "title": "Test ZIM", "language": "eng", "date": "2024-06-30" }.items(): creator.add_metadata(name.title(), value) ``` #### Thread safety > The reading part of the libzim is most of the time thread safe. Searching and creating part are not. [libzim documentation](https://libzim.readthedocs.io/en/latest/usage.html#introduction) `python-libzim` disables the [GIL](https://wiki.python.org/moin/GlobalInterpreterLock) on most of C++ libzim calls. You **must prevent concurrent access** yourself. This is easily done by wrapping all creator calls with a [`threading.Lock()`](https://docs.python.org/3/library/threading.html#lock-objects) ```py lock = threading.Lock() with Creator("test.zim") as creator: # Thread #1 with lock: creator.add_item(item1) # Thread #2 with lock: creator.add_item(item2) ``` #### Type hints `libzim` being a binary extension, there is no Python source to provide types information. We provide them as type stub files. When using `pyright`, you would normally receive a warning when importing from `libzim` as there could be discrepencies between actual sources and the (manually crafted) stub files. You can disable the warning via `reportMissingModuleSource = "none"`. ## Building `libzim` package building offers different behaviors via environment variables | Variable | Example | Use case | | -------------------------------- | ---------------------------------------- | -------- | | `LIBZIM_DL_VERSION` | `8.1.1` or `2023-04-14` | Specify the C++ libzim binary version to download and bundle. Either a release version string or a date, in which case it downloads a nightly | | `USE_SYSTEM_LIBZIM` | `1` | Uses `LDFLAG` and `CFLAGS` to find the libzim to link against. Resulting wheel won't bundle C++ libzim. | | `DONT_DOWNLOAD_LIBZIM` | `1` | Disable downloading of C++ libzim. Place headers in `include/` and libzim dylib/so in `libzim/` if no using system libzim. It will be bundled in wheel. | | `PROFILE` | `0` | Enable profile tracing in Cython extension. Required for Cython code coverage reporting. | | `SIGN_APPLE` | `1` | Set to sign and notarize the extension for macOS. Requires following informations | | `APPLE_SIGNING_IDENTITY` | `Developer ID Application: OrgName (ID)` | Required for signing on macOS | | `APPLE_SIGNING_KEYCHAIN_PATH` | `/tmp/build.keychain` | Path to the Keychain containing the certificate to sign for macOS with | | `APPLE_SIGNING_KEYCHAIN_PROFILE` | `build` | Name of the profile in the specified Keychain | ### Building on Windows On Windows, built wheels needs to be fixed post-build to move the bundled DLLs (libzim and libicu) next to the wrapper (Windows does not support runtime path). After building you wheel, run ```ps python setup.py repair_win_wheel --wheel=dist/xxx.whl --destdir wheels\ ``` Similarily, if you install as editable (`pip install -e .`), you need to place those DLLs at the root of the repo. ```ps Move-Item -Force -Path .\libzim\*.dll -Destination .\ ``` ### Examples ##### Default: downloading and bundling most appropriate libzim release binary ```sh python3 -m build ``` #### Using system libzim (brew, debian or manually installed) - not bundled ```sh # using system-installed C++ libzim brew install libzim # macOS apt-get install libzim-devel # debian dnf install libzim-dev # fedora USE_SYSTEM_LIBZIM=1 python3 -m build --wheel # using a specific C++ libzim USE_SYSTEM_LIBZIM=1 \ CFLAGS="-I/usr/local/include" \ LDFLAGS="-L/usr/local/lib" DYLD_LIBRARY_PATH="/usr/local/lib" \ LD_LIBRARY_PATH="/usr/local/lib" \ python3 -m build --wheel ``` #### Other platforms On platforms for which there is no [official binary](https://download.openzim.org/release/libzim/) available, you'd have to [compile C++ libzim from source](https://github.com/openzim/libzim) first then either use `DONT_DOWNLOAD_LIBZIM` or `USE_SYSTEM_LIBZIM`. ## License [GPLv3](https://www.gnu.org/licenses/gpl-3.0) or later, see [LICENSE](LICENSE) for more details. ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728999050.702708 libzim-3.6.0/libzim/0000755000175100001770000000000014703467213013710 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/libzim/__init__.pyi0000644000175100001770000000053414703467205016175 0ustar00runnerdockerfrom libzim import ( reader, # noqa: F401 # pyright: ignore[reportUnusedImport] search, # noqa: F401 # pyright: ignore[reportUnusedImport] suggestion, # noqa: F401 # pyright: ignore[reportUnusedImport] version, # noqa: F401 # pyright: ignore[reportUnusedImport] writer, # noqa: F401 # pyright: ignore[reportUnusedImport] ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/libzim/libwrapper.cpp0000644000175100001770000001505614703467205016573 0ustar00runnerdocker/* * This file is part of python-libzim * (see https://github.com/libzim/python-libzim) * * Copyright (c) 2020 Juan Diego Caballero * Copyright (c) 2020 Matthieu Gautier * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include "libwrapper.h" #include "libzim_api.h" #include #include #include #include ObjWrapper::ObjWrapper(PyObject* obj) : m_obj(obj) { if (import_libzim()) { std::cerr << "Error executing import_libzim!\n"; throw std::runtime_error("Error executing import_libzim"); } Py_XINCREF(m_obj); } ObjWrapper::ObjWrapper(ObjWrapper&& other) : m_obj(other.m_obj) { other.m_obj = nullptr; } ObjWrapper& ObjWrapper::operator=(ObjWrapper&& other) { m_obj = other.m_obj; other.m_obj = nullptr; return *this; } ObjWrapper::~ObjWrapper() { // We must decrement the ref of the python object. if (m_obj != nullptr) { PyGILState_STATE gstate; gstate = PyGILState_Ensure(); Py_XDECREF(this->m_obj); PyGILState_Release(gstate); } } // Just call the right (regarding the output) method. // No check or error handling. template Output _callMethodOnObj(PyObject *obj, const std::string& methodName, std::string& error); template<> bool _callMethodOnObj(PyObject *obj, const std::string& methodName, std::string& error) { return bool_cy_call_fct(obj, methodName, &error); } template<> std::string _callMethodOnObj(PyObject *obj, const std::string& methodName, std::string& error) { return string_cy_call_fct(obj, methodName, &error); } template<> uint64_t _callMethodOnObj(PyObject *obj, const std::string& methodName, std::string& error) { return uint64_cy_call_fct(obj, methodName, &error); } template<> uint32_t _callMethodOnObj(PyObject *obj, const std::string& methodName, std::string& error) { return uint32_cy_call_fct(obj, methodName, &error); } template<> zim::Blob _callMethodOnObj(PyObject *obj, const std::string& methodName, std::string& error) { return blob_cy_call_fct(obj, methodName, &error); } template<> std::unique_ptr _callMethodOnObj(PyObject *obj, const std::string& methodName, std::string& error) { return std::unique_ptr(contentprovider_cy_call_fct(obj, methodName, &error)); } template<> std::shared_ptr _callMethodOnObj(PyObject *obj, const std::string& methodName, std::string& error) { return std::shared_ptr(indexdata_cy_call_fct(obj, methodName, &error)); } template<> zim::writer::Hints _callMethodOnObj(PyObject *obj, const std::string& methodName, std::string& error) { return hints_cy_call_fct(obj, methodName, &error); } template<> zim::writer::IndexData::GeoPosition _callMethodOnObj(PyObject *obj, const std::string& methodName, std::string& error) { return geoposition_cy_call_fct(obj, methodName, &error); } // This cpp function call a python method on a python object. // It checks that we are in a valid state and handle any potential error coming from python. template Output callMethodOnObj(PyObject* obj, const std::string& methodName) { if (!obj) { throw std::runtime_error("Python object not set"); } std::string error; Output out = _callMethodOnObj(obj, methodName, error); if (!error.empty()) { throw std::runtime_error(error); } return out; } /* ################################ # Content Provider Wrapper # ################################ */ zim::size_type ContentProviderWrapper::getSize() const { return callMethodOnObj(m_obj, "get_size"); } zim::Blob ContentProviderWrapper::feed() { return callMethodOnObj(m_obj, "feed"); } /* ################################ # Index Data Wrapper # ################################ */ bool IndexDataWrapper::hasIndexData() const { return callMethodOnObj(m_obj, "has_indexdata"); } std::string IndexDataWrapper::getTitle() const { return callMethodOnObj(m_obj, "get_title"); } std::string IndexDataWrapper::getContent() const { return callMethodOnObj(m_obj, "get_content"); } std::string IndexDataWrapper::getKeywords() const { return callMethodOnObj(m_obj, "get_keywords"); } uint32_t IndexDataWrapper::getWordCount() const { return callMethodOnObj(m_obj, "get_wordcount"); } zim::writer::IndexData::GeoPosition IndexDataWrapper::getGeoPosition() const { return callMethodOnObj(m_obj, "get_geoposition"); } /* ######################### # WriterItem # ######################### */ std::string WriterItemWrapper::getPath() const { return callMethodOnObj(m_obj, "get_path"); } std::string WriterItemWrapper::getTitle() const { return callMethodOnObj(m_obj, "get_title"); } std::string WriterItemWrapper::getMimeType() const { return callMethodOnObj(m_obj, "get_mimetype"); } std::unique_ptr WriterItemWrapper::getContentProvider() const { return callMethodOnObj>(m_obj, "get_contentprovider"); } std::shared_ptr WriterItemWrapper::getIndexData() const { // Item without method defined (should not happen on proper subclass) if (!obj_has_attribute(m_obj, "get_indexdata")) { return zim::writer::Item::getIndexData(); } if (method_is_none(m_obj, "get_indexdata")) { return zim::writer::Item::getIndexData(); } return callMethodOnObj>(m_obj, "get_indexdata"); } zim::writer::Hints WriterItemWrapper::getHints() const { return callMethodOnObj(m_obj, "get_hints"); } zim::Compression comp_from_int(int compValue) { switch(compValue) { case 0: return zim::Compression::None; case 1: return zim::Compression::Zstd; default: // Should we raise an error ? return zim::Compression::None; } } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/libzim/libwrapper.h0000644000175100001770000002546214703467205016242 0ustar00runnerdocker// -*- c++ -*- /* * This file is part of python-libzim * (see https://github.com/libzim/python-libzim) * * Copyright (c) 2021 Matthieu Gautier . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef LIBZIM_LIBWRAPPER_H #define LIBZIM_LIBWRAPPER_H #include #include #include #include #include #include #include #include struct _object; typedef _object PyObject; // There are two kinds of wrapping : // - Wrapping C++ object to pass it in the Python world. // - Wrapping Python objects to pass it to the C++ world (mainly used by the creator). // // C++ wrapper side. // The main issue here is that libzim classes cannot be "default constructed". // libzim object are build by the libzim itself and are always "valid". // But cython generate code using two instructions : // The cython code `cdef Item item = archive.getItem(...)` is translated to : // ``` // Item item; // item = archive.getItem(...); // ``` // Which is not possible because the Item has not default constructor. // The solution is to manipulate all libzim object through pointers // (pointer can be default constructed to nullptr). // As the libzim functions/methods return directly the instance, we have to wrap all // of them (in pure C++) to make them return a pointer. // (Hopefully, copy constructor is available on libzim classes) // // To help us, we define a Wrapper class which wrap a libzim instance by storing // a internel pointer to a heap allocated instance. // This wrapper provide all constructors/helpers to build it and use the wrapped instance. // (Especially, a default constructor) // // On top of that, we are writing specific wrapper to overwrite some method to return a // Wrapper instead of Foo. // As Wrapper do not inherit from Foo, we must define all the methods we want to wrap in python. // Thoses methods just have to forward the call from the wrapper to the wrapped instance. // As Wrapper can be implicitly constructed from Foo, we can also simply forward the call and the // conversion will be made for us. // The macro FORWARD help us a lot here. /** * A base wrapper for our structures */ template class Wrapper { public: Wrapper() {} ~Wrapper() = default; Wrapper(const Base& base) : mp_base(new Base(base)) {} Wrapper(Base&& base) : mp_base(new Base(std::move(base))) {} Wrapper(Wrapper&& other) = default; Wrapper& operator=(Wrapper&& other) = default; protected: std::unique_ptr mp_base; }; #define FORWARD(OUT, NAME) template OUT NAME(ARGS&&... args) const { return mp_base->NAME(std::forward(args)...); } namespace wrapper { // Wrapping blob is not necessary as we can default construct a zim::Blob. // But it is nice to have for consistancy. class Blob : public Wrapper { public: Blob() = default; Blob(const zim::Blob& o) : Wrapper(o) {} Blob(const char* data, zim::size_type size) : Wrapper(zim::Blob(data, size)) {}; operator zim::Blob() { return *mp_base; } FORWARD(const char*, data) FORWARD(const char*, end) FORWARD(zim::size_type, size) }; class Item : public Wrapper { public: Item() = default; Item(const zim::Item& o) : Wrapper(o) {} FORWARD(std::string, getTitle) FORWARD(std::string, getPath) FORWARD(std::string, getMimetype) FORWARD(wrapper::Blob, getData) FORWARD(zim::size_type, getSize) FORWARD(zim::entry_index_type, getIndex) }; class Entry : public Wrapper { public: Entry() = default; Entry(const zim::Entry& o) : Wrapper(o) {} FORWARD(std::string, getTitle) FORWARD(std::string, getPath) FORWARD(bool, isRedirect) FORWARD(wrapper::Item, getItem) FORWARD(wrapper::Item, getRedirect) FORWARD(wrapper::Entry, getRedirectEntry) FORWARD(zim::entry_index_type, getIndex) }; class Archive : public Wrapper { public: Archive() = default; Archive(const std::string& filename) : Wrapper(zim::Archive(filename)) {}; Archive(const zim::Archive& o) : Wrapper(o) {}; zim::Archive& operator*() const { return *mp_base; } FORWARD(wrapper::Entry, getEntryByPath) FORWARD(wrapper::Entry, getEntryByTitle) FORWARD(wrapper::Entry, getMainEntry) FORWARD(wrapper::Item, getIllustrationItem) FORWARD(std::set, getIllustrationSizes) std::string getUuid() const { auto u = mp_base->getUuid(); std::string uuids(u.data, u.size()); return uuids; } FORWARD(zim::size_type, getFilesize) FORWARD(std::string, getMetadata) FORWARD(wrapper::Item, getMetadataItem) FORWARD(std::vector, getMetadataKeys) FORWARD(zim::size_type, getEntryCount) FORWARD(zim::size_type, getAllEntryCount) FORWARD(zim::size_type, getArticleCount) FORWARD(zim::size_type, getMediaCount) FORWARD(std::string, getChecksum) FORWARD(std::string, getFilename) FORWARD(bool, hasMainEntry) FORWARD(bool, hasIllustration) FORWARD(bool, hasEntryByPath) FORWARD(bool, hasEntryByTitle) FORWARD(bool, isMultiPart) FORWARD(bool, hasNewNamespaceScheme) FORWARD(bool, hasFulltextIndex) FORWARD(bool, hasTitleIndex) FORWARD(bool, hasChecksum) FORWARD(bool, check) }; class SearchResultSet : public Wrapper { public: SearchResultSet() = default; SearchResultSet(const zim::SearchResultSet& o) : Wrapper(o) {}; FORWARD(zim::SearchIterator, begin) FORWARD(zim::SearchIterator, end) FORWARD(int, size) }; class Search : public Wrapper { public: Search() = default; Search(zim::Search&& s) : Wrapper(std::move(s)) {}; FORWARD(int, getEstimatedMatches) FORWARD(wrapper::SearchResultSet, getResults) }; class Searcher : public Wrapper { public: Searcher() = default; Searcher(const wrapper::Archive& a) : Wrapper(zim::Searcher(*a)) {}; Searcher(const zim::Searcher& o) : Wrapper(o) {}; FORWARD(void, setVerbose) FORWARD(wrapper::Search, search) }; class SuggestionItem : public Wrapper { public: SuggestionItem() = default; SuggestionItem(const zim::SuggestionItem& o) : Wrapper(o) {}; FORWARD(std::string, getTitle) FORWARD(std::string, getPath) FORWARD(std::string, getSnippet) FORWARD(bool, hasSnippet) }; class SuggestionIterator : public Wrapper { public: SuggestionIterator() = default; SuggestionIterator(const zim::SuggestionIterator& o) : Wrapper(o) {}; zim::SuggestionIterator& operator*() const { return *mp_base; } FORWARD(bool, operator==) bool operator!=(const wrapper::SuggestionIterator& it) const { return *mp_base != *it; } FORWARD(wrapper::SuggestionIterator, operator++) SuggestionItem getSuggestionItem() const { return mp_base->operator*(); } // FORWARD(wrapper::SuggestionItem, operator*) FORWARD(wrapper::Entry, getEntry) }; class SuggestionResultSet : public Wrapper { public: SuggestionResultSet() = default; SuggestionResultSet(const zim::SuggestionResultSet& o) : Wrapper(o) {}; FORWARD(wrapper::SuggestionIterator, begin) FORWARD(wrapper::SuggestionIterator, end) FORWARD(int, size) }; class SuggestionSearch : public Wrapper { public: SuggestionSearch() = default; SuggestionSearch(zim::SuggestionSearch&& s) : Wrapper(std::move(s)) {}; FORWARD(int, getEstimatedMatches) FORWARD(wrapper::SuggestionResultSet, getResults) }; class SuggestionSearcher : public Wrapper { public: SuggestionSearcher() = default; SuggestionSearcher(const wrapper::Archive& a) : Wrapper(zim::SuggestionSearcher(*a)) {}; SuggestionSearcher(const zim::SuggestionSearcher& o) : Wrapper(o) {}; FORWARD(void, setVerbose) FORWARD(wrapper::SuggestionSearch, suggest) }; } // namespace wrapper #undef FORWARD // Python wrapper // // The main issue is to forward the c++ method call (made by `zim::Creator`) to the // python method. // // To do so, we define a helper wrapper (ObjWrapper) which wrap a PyObject and allow us to call // different kind of methods (signatures). // Then we write specific wrapper to forward the call using helper methods of ObjWrapper. class ObjWrapper { public: ObjWrapper(PyObject* obj); ObjWrapper(const ObjWrapper& other) = delete; ObjWrapper(ObjWrapper&& other); ~ObjWrapper(); ObjWrapper& operator=(ObjWrapper&& other); protected: PyObject* m_obj; }; class WriterItemWrapper : public zim::writer::Item, private ObjWrapper { public: WriterItemWrapper(PyObject *obj) : ObjWrapper(obj) {}; ~WriterItemWrapper() = default; std::string getPath() const override; std::string getTitle() const override; std::string getMimeType() const override; std::unique_ptr getContentProvider() const override; std::shared_ptr getIndexData() const override; zim::writer::Hints getHints() const override; }; class ContentProviderWrapper : public zim::writer::ContentProvider, private ObjWrapper { public: ContentProviderWrapper(PyObject *obj) : ObjWrapper(obj) {}; ~ContentProviderWrapper() = default; zim::size_type getSize() const override; zim::Blob feed() override; }; class IndexDataWrapper: public zim::writer::IndexData, private ObjWrapper { public: IndexDataWrapper(PyObject *obj) : ObjWrapper(obj) {}; ~IndexDataWrapper() = default; bool hasIndexData() const override; std::string getTitle() const override; std::string getContent() const override; std::string getKeywords() const override; uint32_t getWordCount() const override; IndexData::GeoPosition getGeoPosition() const override; }; // Small helpers // The current stable cython version (0.29.24) doesn't support scoped enum (next version >30 will be). // The cython generated __Pyx_PyInt_As_enum__zim_3a__3a_Compression(PyOobject*) // try to do some strange bit shifting of `zim::Compression` which doesn't compile. // Let's provide our own function for this zim::Compression comp_from_int(int compValue); #endif // LIBZIM_LIBWRAPPER_H ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/libzim/libzim.pyx0000644000175100001770000013115414703467205015746 0ustar00runnerdocker# This file is part of python-libzim # (see https://github.com/libzim/python-libzim) # # Copyright (c) 2020 Juan Diego Caballero # Copyright (c) 2020 Matthieu Gautier # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Make our libzim module a package by setting a __path__ # There is no real path here, but it will be passed to our module finder. """openZIM's file format library binding - libzim.writer to create ZIM file with Creator - libzim.reader to open ZIM file as Archive - libzim.search to search on an Archive - libzim.suggestion to retrieve suggestions on an Archive https://openzim.org""" __path__ = [] cimport zim import datetime import enum import importlib import importlib.abc import os import pathlib import sys import traceback from collections import OrderedDict from types import ModuleType from typing import Dict, Generator, Iterator, List, Optional, Set, TextIO, Tuple, Union from uuid import UUID from cpython.buffer cimport PyBUF_WRITABLE from cpython.ref cimport PyObject from cython.operator import preincrement from libc.stdint cimport uint32_t, uint64_t from libcpp cimport bool from libcpp.map cimport map from libcpp.memory cimport shared_ptr from libcpp.string cimport string from libcpp.utility cimport move pybool = type(True) pyint = type(1) def create_module(name, doc, members): """Create/define a module for name and docstring, populated by members""" module = ModuleType(name, doc) _all = [] for obj in members: if isinstance(obj, tuple): name = obj[0] obj = obj[1] else: name = obj.__name__ setattr(module, name, obj) _all.append(name) module.__all__ = _all sys.modules[name] = module return module ############################################################################### #  Public API to be called from C++ side # ############################################################################### # This calls a python method and returns a python object. cdef object call_method(object obj, string method): func = getattr(obj, method.decode('UTF-8')) return func() # Define methods calling a python method and converting the resulting python # object to the correct cpp type. # Will be used by cpp side to call python method. cdef public api: # this tells whether a method/property is none or not bool method_is_none(object obj, string method) with gil: func = getattr(obj, method.decode('UTF-8')) return func is None bool obj_has_attribute(object obj, string attribute) with gil: """Check if a object has a given attribute""" return hasattr(obj, attribute.decode('UTF-8')) string string_cy_call_fct(object obj, string method, string *error) with gil: """Lookup and execute a pure virtual method on object returning a string""" try: ret_str = call_method(obj, method) return ret_str.encode('UTF-8') except Exception as e: error[0] = traceback.format_exc().encode('UTF-8') return b"" zim.Blob blob_cy_call_fct(object obj, string method, string *error) with gil: """Lookup and execute a pure virtual method on object returning a Blob""" cdef WritingBlob blob try: blob = call_method(obj, method) if blob is None: raise RuntimeError("Blob is none") return move(blob.c_blob) except Exception as e: error[0] = traceback.format_exc().encode('UTF-8') return move(zim.Blob()) zim.ContentProvider* contentprovider_cy_call_fct(object obj, string method, string *error) with gil: """Lookup and execute a pure virtual method on object returning a ContentProvider""" try: contentProvider = call_method(obj, method) if not contentProvider: raise RuntimeError("ContentProvider is None") return new zim.ContentProviderWrapper(contentProvider) except Exception as e: error[0] = traceback.format_exc().encode('UTF-8') return NULL zim.IndexData* indexdata_cy_call_fct(object obj, string method, string *error) with gil: """Lookup and execute a pure virtual method on object returning a IndexData""" try: indexData = call_method(obj, method) if not indexData: # indexData is none return NULL; return new zim.IndexDataWrapper(indexData) except Exception as e: error[0] = traceback.format_exc().encode('UTF-8') return NULL bool bool_cy_call_fct(object obj, string method, string *error) with gil: """Lookup and execute a pure virtual method on object returning a bool""" try: return call_method(obj, method) except Exception as e: error[0] = traceback.format_exc().encode('UTF-8') return False uint64_t uint64_cy_call_fct(object obj, string method, string *error) with gil: """Lookup and execute a pure virtual method on object returning an uint64_t""" try: return call_method(obj, method) except Exception as e: error[0] = traceback.format_exc().encode('UTF-8') return 0 uint32_t uint32_cy_call_fct(object obj, string method, string *error) with gil: """Lookup and execute a pure virtual method on object returning an uint_32""" try: return call_method(obj, method) except Exception as e: error[0] = traceback.format_exc().encode('UTF-8') return 0 zim.GeoPosition geoposition_cy_call_fct(object obj, string method, string *error) with gil: """Lookup and execute a pure virtual method on object returning a GeoPosition""" try: geoPosition = call_method(obj, method) if geoPosition: return zim.GeoPosition(True, geoPosition[0], geoPosition[1]); except Exception as e: error[0] = traceback.format_exc().encode('UTF-8') return zim.GeoPosition(False, 0, 0) map[zim.HintKeys, uint64_t] convertToCppHints(dict hintsDict): """C++ Hints from Python dict""" cdef map[zim.HintKeys, uint64_t] ret; for key, value in hintsDict.items(): ret[key.value] = value return ret map[zim.HintKeys, uint64_t] hints_cy_call_fct(object obj, string method, string* error) with gil: """Lookup and execute a pure virtual method on object returning Hints""" cdef map[zim.HintKeys, uint64_t] ret; try: func = getattr(obj, method.decode('UTF-8')) hintsDict = {k: pybool(v) for k, v in func().items() if isinstance(k, Hint)} return convertToCppHints(hintsDict) except Exception as e: error[0] = traceback.format_exc().encode('UTF-8') return ret ############################################################################### #  Creator module # ############################################################################### writer_module_name = f"{__name__}.writer" cdef class WritingBlob: __module__ = writer_module_name cdef zim.Blob c_blob cdef bytes ref_content def __cinit__(self, content: Union[str, bytes]): if isinstance(content, str): self.ref_content = content.encode('UTF-8') else: self.ref_content = content self.c_blob = move(zim.Blob( self.ref_content, len(self.ref_content))) def size(self) -> pyint: return self.c_blob.size() class Compression(enum.Enum): """Compression algorithms available to create ZIM files""" __module__ = writer_module_name # We don't care of the exact value. The function comp_from_int will do the right # conversion to zim::Compression none = 0 zstd = 1 class Hint(enum.Enum): __module__ = writer_module_name COMPRESS = zim.HintKeys.COMPRESS FRONT_ARTICLE = zim.HintKeys.FRONT_ARTICLE cdef class _Creator: """ZIM Creator Attributes ---------- *c_creator : zim.ZimCreator a pointer to the C++ Creator object _filename: pathlib.Path path to create the ZIM file at _started : bool flag if the creator has started""" __module__ = writer_module_name cdef zim.ZimCreator c_creator cdef object _filename cdef object _started def __cinit__(self, object filename: pathlib.Path, *args, **kwargs): self._filename = pathlib.Path(filename) self._started = False # fail early if destination is not writable parent = self._filename.expanduser().resolve().parent if not os.access(parent, mode=os.W_OK, effective_ids=(os.access in os.supports_effective_ids)): raise IOError(f"Unable to write ZIM file at {self._filename}") def __init__(self, filename: pathlib.Path): """Constructs a Creator for a ZIM file at path Parameters ---------- filename : pathlib.Path Full path to a zim file""" pass def config_verbose(self, bool verbose: bool) -> Creator: """Set creator verbosity (inside libzim). Default is off""" if self._started: raise RuntimeError("Creator started") self.c_creator.configVerbose(verbose) return self def config_compression(self, compression: Compression) -> Creator: """Set compression algorithm to use. Check libzim for default Fall 2021 default: zstd""" if self._started: raise RuntimeError("Creator started") self.c_creator.configCompression(zim.comp_from_int(compression.value)) return self def config_clustersize(self, int size: pyint) -> Creator: """Set size of created clusters. Check libzim for default libzim will store at most this value per cluster before creating another one. Fall 2021 default: 2Mib""" if self._started: raise RuntimeError("Creator started") self.c_creator.configClusterSize(size) return self def config_indexing(self, bool indexing: bool, str language: str) -> Creator: """Configure fulltext indexing feature indexing: whether to create a full-text index of the content language: language (ISO-639-3 code) to assume content in during indexation""" if self._started: raise RuntimeError("Creator started") self.c_creator.configIndexing(indexing, language.encode('UTF-8')) return self def config_nbworkers(self, int nbWorkers: pyint) -> Creator: """Number of thread to use for internal worker""" if self._started: raise RuntimeError("Creator started") self.c_creator.configNbWorkers(nbWorkers) return self def set_mainpath(self, str mainPath: str) -> Creator: """Set path of the main entry""" self.c_creator.setMainPath(mainPath.encode('UTF-8')) return self def add_illustration(self, int size: pyint, content: bytes): """Add a PNG illustration to Archive https://wiki.openzim.org/wiki/Metadata Raises ------ RuntimeError If an Illustration exists with the same size""" cdef string _content = content self.c_creator.addIllustration(size, _content) # def set_uuid(self, uuid) -> Creator: # self.c_creator.setUuid(uuid) def add_item(self, writer_item not None: BaseWritingItem): """Add an item to the Creator object. Parameters ---------- item : WriterItem The item to add to the file Raises ------ RuntimeError If an Item exists with the same path RuntimeError If the ZimCreator was already finalized""" if not self._started: raise RuntimeError("Creator not started") # Make a shared pointer to ZimArticleWrapper from the ZimArticle object cdef shared_ptr[zim.WriterItem] item = shared_ptr[zim.WriterItem]( new zim.WriterItemWrapper(writer_item)); with nogil: self.c_creator.addItem(item) def add_metadata(self, str name: str, bytes content: bytes, str mimetype: str): """Add metadata entry to Archive https://wiki.openzim.org/wiki/Metadata Raises ------ RuntimeError If a Metadata exists with the same name""" if not self._started: raise RuntimeError("Creator not started") cdef string _name = name.encode('UTF-8') cdef string _content = content cdef string _mimetype = mimetype.encode('UTF-8') with nogil: self.c_creator.addMetadata(_name, _content, _mimetype) def add_redirection(self, str path: str, str title: str, str targetPath: str, dict hints: Dict[Hint, pyint]): """Add redirection entry to Archive https://wiki.openzim.org/wiki/ZIM_file_format#Redirect_Entry Raises ------ RuntimeError If a Rediction exists with the same path """ if not self._started: raise RuntimeError("Creator not started") cdef string _path = path.encode('UTF-8') cdef string _title = title.encode('UTF-8') cdef string _targetPath = targetPath.encode('UTF-8') cdef map[zim.HintKeys, uint64_t] _hints = convertToCppHints(hints) with nogil: self.c_creator.addRedirection(_path, _title, _targetPath, _hints) def add_alias(self, str path: str, str title: str, str targetPath: str, dict hints: Dict[Hint, pyint]): """Alias the (existing) entry `targetPath` as a new entry `path`. Raises ------ RuntimeError If `targetPath` entry doesn't exist. """ if not self._started: raise RuntimeError("Creator not started") cdef string _path = path.encode('UTF-8') cdef string _title = title.encode('UTF-8') cdef string _targetPath = targetPath.encode('UTF-8') cdef map[zim.HintKeys, uint64_t] _hints = convertToCppHints(hints) with nogil: self.c_creator.addAlias(_path, _title, _targetPath, _hints) def __enter__(self): cdef string _path = str(self._filename).encode('UTF-8') with nogil: self.c_creator.startZimCreation(_path) self._started = True return self def __exit__(self, exc_type, exc_val, exc_tb): if True or exc_type is None: with nogil: self.c_creator.finishZimCreation() self._started = False @property def filename(self) -> pathlib.Path: return self._filename class ContentProvider: __module__ = writer_module_name def __init__(self): self.generator = None def get_size(self) -> pyint: """Size of get_data's result in bytes""" raise NotImplementedError("get_size must be implemented.") def feed(self) -> WritingBlob: """Blob(s) containing the complete content of the article. Must return an empty blob to tell writer no more content has to be written. Sum(size(blobs)) must be equals to `self.get_size()` """ if self.generator is None: self.generator = self.gen_blob() try: # We have to keep a ref to _blob to be sure gc do not del it while cpp is # using it self._blob = next(self.generator) except StopIteration: self._blob = WritingBlob("") return self._blob def gen_blob(self) -> Generator[WritingBlob, None, None]: """Generator yielding blobs for the content of the article""" raise NotImplementedError("gen_blob (ro feed) must be implemented") class StringProvider(ContentProvider): """ContentProvider for a single encoded-or-not UTF-8 string""" __module__ = writer_module_name def __init__(self, content: Union[str, bytes]): super().__init__() self.content = content.encode("UTF-8") if isinstance(content, str) else content def get_size(self) -> pyint: return len(self.content) def gen_blob(self) -> Generator[WritingBlob, None, None]: yield WritingBlob(self.content) class FileProvider(ContentProvider): """ContentProvider for a file using its local path""" __module__ = writer_module_name def __init__(self, filepath: Union[pathlib.Path, str]): super().__init__() self.filepath = filepath self.size = os.path.getsize(self.filepath) def get_size(self) -> pyint: return self.size def gen_blob(self) -> Generator[WritingBlob, None, None]: bsize = 1048576 # 1MiB chunk with open(self.filepath, "rb") as fh: res = fh.read(bsize) while res: yield WritingBlob(res) res = fh.read(bsize) class IndexData: """ IndexData stub to override Return a subclass of it in Item.get_indexdata()""" __module__ = writer_module_name def has_indexdata(self) -> bool: """Return true if the IndexData actually contains data""" return False def get_title(self) -> str: """Title to index. Might be the same as Item.get_title or not""" raise NotImplementedError("get_title must be implemented.") def get_content(self) -> str: """Content to index. Might be the same as Item.get_title or not""" raise NotImplementedError("get_content must be implemented.") def get_keywords(self) -> str: """Keywords used to index the item. Must be a string containing keywords separated by a space""" raise NotImplementedError("get_keywords must be implemented.") def get_wordcount(self) -> int: """Number of word in content""" raise NotImplementedError("get_wordcount must be implemented.") def get_geoposition(self) -> Optional[Tuple[float, float]]: """GeoPosition used to index the item. Must be a tuple (latitude, longitude) or None""" return None class BaseWritingItem: """Item stub to override Pass a subclass of it to Creator.add_item()""" __module__ = writer_module_name def __init__(self): self._blob = None get_indexdata = None def get_path(self) -> str: """Full path of item""" raise NotImplementedError("get_path must be implemented.") def get_title(self) -> str: """Item title. Might be indexed and used in suggestions""" raise NotImplementedError("get_title must be implemented.") def get_mimetype(self) -> str: """MIME-type of the item's content.""" raise NotImplementedError("get_mimetype must be implemented.") def get_contentprovider(self) -> ContentProvider: """ContentProvider containing the complete content of the item""" raise NotImplementedError("get_contentprovider must be implemented.") def get_hints(self) -> Dict[Hint, pyint]: """Dict of Hint: value informing Creator how to handle this item""" raise NotImplementedError("get_hints must be implemented.") def __repr__(self) -> str: return ( f"{self.__class__.__name__}(path={self.get_path()}, " f"title={self.get_title()})" ) class Creator(_Creator): __module__ = writer_module_name def config_compression(self, compression: Union[Compression, str]): if not isinstance(compression, Compression): compression = getattr(Compression, compression.lower()) return super().config_compression(compression) def add_metadata( self, name: str, content: Union[str, bytes, datetime.date, datetime.datetime], mimetype: str = "text/plain;charset=UTF-8" ): if name == "Date" and isinstance(content, (datetime.date, datetime.datetime)): content = content.strftime("%Y-%m-%d").encode("UTF-8") if isinstance(content, str): content = content.encode("UTF-8") super().add_metadata(name=name, content=content, mimetype=mimetype) def __repr__(self) -> str: return f"Creator(filename={self.filename})" writer_module_doc = """libzim writer module - Creator to create ZIM files - Item to store ZIM articles metadata - ContentProvider to store an Item's content - Blob to store actual content - StringProvider to store an Item's content from a string - FileProvider to store an Item's content from a file path - Compression to select the algorithm to compress ZIM archive with Usage: with Creator(pathlib.Path("myfile.zim")) as creator: creator.config_verbose(False) creator.add_metadata("Name", b"my name") # example creator.add_item(MyItemSubclass(path, title, mimetype, content) creator.set_mainpath(path)""" writer_public_objects = [ Creator, Compression, ('Blob', WritingBlob), Hint, ('Item', BaseWritingItem), ContentProvider, FileProvider, StringProvider, IndexData ] writer = create_module(writer_module_name, writer_module_doc, writer_public_objects) ############################################################################### #  Reader module # ############################################################################### reader_module_name = f"{__name__}.reader" cdef Py_ssize_t itemsize = 1 cdef class ReadingBlob: __module__ = reader_module_name cdef zim.Blob c_blob cdef Py_ssize_t size cdef int view_count # Factory functions - Currently Cython can't use classmethods @staticmethod cdef from_blob(zim.Blob blob): """Creates a python Blob from a C++ Blob (zim::) -> Blob Parameters ---------- blob : Blob A C++ Entry Returns ------ Blob Casted blob""" cdef ReadingBlob rblob = ReadingBlob() rblob.c_blob = move(blob) rblob.size = rblob.c_blob.size() rblob.view_count = 0 return rblob def __dealloc__(self): if self.view_count: raise RuntimeError("Blob has views") def __getbuffer__(self, Py_buffer *buffer, int flags): if flags&PyBUF_WRITABLE: raise BufferError("Cannot create writable memoryview on readonly data") buffer.obj = self buffer.buf = self.c_blob.data() buffer.len = self.size buffer.readonly = 1 buffer.format = 'c' buffer.internal = NULL # see References buffer.itemsize = itemsize buffer.ndim = 1 buffer.shape = &self.size buffer.strides = &itemsize buffer.suboffsets = NULL # for pointer arrays only self.view_count += 1 def __releasebuffer__(self, Py_buffer *buffer): self.view_count -= 1 cdef class Entry: """Entry in a ZIM archive Attributes ---------- *c_entry : Entry (zim::) a pointer to the C++ entry object""" __module__ = reader_module_name cdef zim.Entry c_entry # Factory functions - Currently Cython can't use classmethods @staticmethod cdef from_entry(zim.Entry ent): """Creates a python Entry from a C++ Entry (zim::) -> Entry Parameters ---------- ent : Entry A C++ Entry Returns ------ Entry Casted entry""" cdef Entry entry = Entry() entry.c_entry = move(ent) return entry @property def title(self) -> str: return self.c_entry.getTitle().decode('UTF-8') @property def path(self) -> str: return self.c_entry.getPath().decode("UTF-8", "strict") @property def _index(self) -> pyint: """Internal index in Archive""" return self.c_entry.getIndex() @property def is_redirect(self) -> pybool: """Whether entry is a redirect""" return self.c_entry.isRedirect() def get_redirect_entry(self) -> Entry: """Target of this entry, if a redirect""" cdef zim.Entry entry = move(self.c_entry.getRedirectEntry()) return Entry.from_entry(move(entry)) def get_item(self) -> Item: cdef zim.Item item = move(self.c_entry.getItem(True)) return Item.from_item(move(item)) def __repr__(self) -> str: return f"{self.__class__.__name__}(url={self.path}, title={self.title})" cdef class Item: """Item in a ZIM archive Attributes ---------- *c_entry : Entry (zim::) a pointer to the C++ entry object""" __module__ = reader_module_name cdef zim.Item c_item cdef ReadingBlob _blob cdef bool _haveBlob # Factory functions - Currently Cython can't use classmethods @staticmethod cdef from_item(zim.Item _item): """Creates a python ReadArticle from a C++ Article (zim::) -> ReadArticle Parameters ---------- _item : Item A C++ Item Returns ------ Item Casted item""" cdef Item item = Item() item.c_item = move(_item) return item @property def title(self) -> str: return self.c_item.getTitle().decode('UTF-8') @property def path(self) -> str: return self.c_item.getPath().decode("UTF-8", "strict") @property def content(self) -> memoryview: if not self._haveBlob: self._blob = ReadingBlob.from_blob(move(self.c_item.getData( 0))) self._haveBlob = True return memoryview(self._blob) @property def mimetype(self) -> str: return self.c_item.getMimetype().decode('UTF-8') @property def _index(self) -> pyint: """Internal index in Archive""" return self.c_item.getIndex() @property def size(self) -> pyint: return self.c_item.getSize() def __repr__(self) -> str: return f"{self.__class__.__name__}(url={self.path}, title={self.title})" cdef class Archive: """ZIM Archive Reader Attributes ---------- *c_archive : Archive a pointer to a C++ Archive object _filename : pathlib.Path the file name of the Archive Reader object""" __module__ = reader_module_name cdef zim.Archive c_archive cdef object _filename def __cinit__(self, object filename: pathlib.Path): """Constructs an Archive from full zim file path Parameters ---------- filename : pathlib.Path Full path to a zim file""" self.c_archive = move(zim.Archive(str(filename).encode('UTF-8'))) self._filename = pathlib.Path(self.c_archive.getFilename().decode("UTF-8", "strict")) def __eq__(self, other) -> pybool: if Archive not in type(self).mro() or Archive not in type(other).mro(): return False try: return self.filename.expanduser().resolve() == other.filename.expanduser().resolve() except Exception: return False @property def filename(self) -> pathlib.Path: return self._filename @property def filesize(self) -> pyint: """Total size of ZIM file (or files if split""" return self.c_archive.getFilesize() def has_entry_by_path(self, path: str) -> pybool: """Whether Archive has an entry with this path""" return self.c_archive.hasEntryByPath(path.encode('UTF-8')) def get_entry_by_path(self, path: str) -> Entry: """Entry from a path -> Entry Parameters ---------- path : str The path of the article Returns ------- Entry The Entry object Raises ------ KeyError If an entry with the provided path is not found in the archive""" cdef zim.Entry entry try: entry = move(self.c_archive.getEntryByPath(path.encode('UTF-8'))) except RuntimeError as e: raise KeyError(str(e)) return Entry.from_entry(move(entry)) def has_entry_by_title(self, title: str) -> pybool: """Whether Archive has en entry with this title Uses get_entry_by_title() so it's specificities apply as well""" return self.c_archive.hasEntryByTitle(title.encode('UTF-8')) def get_entry_by_title(self, title: str) -> Entry: """Entry from a title -> Entry If ZIM doesn't contain a listing/titleOrdered/v1 entry (most likely because if was created without any FRONT_ARTICLE) then this yields results for matching path if the title was not set at creation time. Otherwise raises KeyError. Parameters ---------- title : str The title of the article Returns ------- Entry The first Entry object matching the title Raises ------ KeyError If an entry with the provided title is not found in the archive""" cdef zim.Entry entry try: entry = move(self.c_archive.getEntryByTitle(title.encode('UTF-8'))) except RuntimeError as e: raise KeyError(str(e)) return Entry.from_entry(move(entry)) @property def metadata_keys(self) -> List[str]: """List of Metadata keys present in this archive""" return [key.decode("UTF-8", "strict") for key in self.c_archive.getMetadataKeys()] def get_metadata_item(self, name: str) -> Item: """A Metadata's Item""" cdef zim.Item item = move(self.c_archive.getMetadataItem(name.encode('UTF-8'))) return Item.from_item(move(item)) def get_metadata(self, name: str) -> bytes: """A Metadata's content -> bytes Parameters ---------- name: str name/path of the Metadata Entry Returns ------- bytes Metadata entry's content. Can be of any type.""" return bytes(self.c_archive.getMetadata(name.encode('UTF-8'))) def _get_entry_by_id(self, entry_id: pyint) -> Entry: """Entry from an entry Id""" cdef zim.Entry entry = move(self.c_archive.getEntryByPath(entry_id)) return Entry.from_entry(move(entry)) @property def has_main_entry(self) -> pybool: """Whether Archive has a Main Entry set""" return self.c_archive.hasMainEntry() @property def main_entry(self) -> Entry: """Main Entry of the Archive""" return Entry.from_entry(move(self.c_archive.getMainEntry())) @property def uuid(self) -> UUID: """Archive UUID""" return UUID(self.c_archive.getUuid().hex()) @property def has_new_namespace_scheme(self) -> pybool: """Whether Archive is using new “namespaceless” namespace scheme""" return self.c_archive.hasNewNamespaceScheme() @property def is_multipart(self) -> pybool: """Whether Archive is multipart (split over multiple files)""" return self.c_archive.isMultiPart() @property def has_fulltext_index(self) -> pybool: """Whether Archive includes a full-text index""" return self.c_archive.hasFulltextIndex() @property def has_title_index(self) -> pybool: """Whether Archive includes a Title index""" return self.c_archive.hasTitleIndex() @property def has_checksum(self) -> str: """Whether Archive includes a checksum of its content""" return self.c_archive.hasChecksum() @property def checksum(self) -> str: """Archive's checksum""" return self.c_archive.getChecksum().decode("UTF-8", "strict") def check(self) -> pybool: """Whether Archive has a checksum and file verifies it""" return self.c_archive.check() @property def entry_count(self) -> pyint: """Number of user entries in Archive If Archive doesn't support “user entries” then this returns `all_entry_count`""" return self.c_archive.getEntryCount() @property def all_entry_count(self) -> pyint: """Number of entries in Archive. Total number of entries in the archive, including internal entries created by libzim itself, metadata, indexes, etc.""" return self.c_archive.getAllEntryCount() @property def article_count(self) -> pyint: """Number of “articles” in the Archive If Archive has_new_namespace_scheme then this is the number of Entry with “FRONT_ARTICLE” Hint. Otherwise, this is the number or entries in “A” namespace. Note: a few ZIM created during transition might have new scheme but no listing, resulting in this returning all entries.""" return self.c_archive.getArticleCount() @property def media_count(self) -> pyint: """Number of media in the Archive This definition of "media" is based on the mimetype.""" return self.c_archive.getMediaCount() def get_illustration_sizes(self) -> Set[pyint]: """Sizes for which an illustration is available (@1 scale only)""" return self.c_archive.getIllustrationSizes() def has_illustration(self, size: pyint = None) -> pybool: """Whether Archive has an illustration metadata for this size""" if size is not None: return self.c_archive.hasIllustration(size) return self.c_archive.hasIllustration() def get_illustration_item(self, size: pyint = None) -> Item: """Illustration Metadata Item for this size""" try: if size is not None: return Item.from_item(move(self.c_archive.getIllustrationItem(size))) return Item.from_item(move(self.c_archive.getIllustrationItem())) except RuntimeError as e: raise KeyError(str(e)) def __repr__(self) -> str: return f"{self.__class__.__name__}(filename={self.filename})" reader_module_doc = """libzim reader module - Archive to open and read ZIM files (gives access to all `Entry`) - Entry knows about redirections, exposes path and title and gives access to `Item` - Item holds the content and metadata Usage: with Archive(fpath) as zim: entry = zim.get_entry_by_path(zim.main_entry.path) print(f"Article {entry.title} at {entry.path} is " f"{entry.get_item().content.nbytes}b")""" reader_public_objects = [ Archive, Entry, Item, ] reader = create_module(reader_module_name, reader_module_doc, reader_public_objects) ############################################################################### #  Search module # ############################################################################### search_module_name = f"{__name__}.search" cdef class Query: """ZIM agnostic Query-builder to use with a Searcher""" __module__ = search_module_name cdef zim.Query c_query def set_query(self, query: str): self.c_query.setQuery(query.encode('UTF-8')) return self cdef class SearchResultSet: """Iterator over a Search result: entry paths""" __module__ = search_module_name cdef zim.SearchResultSet c_resultset @staticmethod cdef from_resultset(zim.SearchResultSet _resultset): cdef SearchResultSet resultset = SearchResultSet() resultset.c_resultset = move(_resultset) return resultset def __iter__(self) -> Iterator[str]: """Entry paths found in Archive for Search""" cdef zim.SearchIterator current = self.c_resultset.begin() cdef zim.SearchIterator end = self.c_resultset.end() while current != end: yield current.getPath().decode('UTF-8') preincrement(current) cdef class Search: """Search request over a ZIM Archive""" __module__ = search_module_name cdef zim.Search c_search # Factory functions - Currently Cython can't use classmethods @staticmethod cdef from_search(zim.Search _search): """Creates a python ReadArticle from a C++ Article (zim::) -> ReadArticle Parameters ---------- _item : Item A C++ Item Returns ------ Item Casted item""" cdef Search search = Search() search.c_search = move(_search) return search def getEstimatedMatches(self) -> pyint: """Estimated number of results in Archive for the search""" return self.c_search.getEstimatedMatches() def getResults(self, start: pyint, count: pyint) -> SearchResultSet: """Iterator over Entry paths found in Archive for the search""" return SearchResultSet.from_resultset(move(self.c_search.getResults(start, count))) cdef class Searcher: """ZIM Archive Searcher Attributes ---------- *c_archive : Searcher a pointer to a C++ Searcher object""" __module__ = search_module_name cdef zim.Searcher c_searcher def __cinit__(self, object archive: Archive): """Constructs an Archive from full zim file path Parameters ---------- filename : pathlib.Path Full path to a zim file""" self.c_searcher = move(zim.Searcher(archive.c_archive)) def search(self, object query: Query) -> Search: """Search object for a query of this Searcher's ZIM Archive""" return Search.from_search(move(self.c_searcher.search(query.c_query))) search_module_doc = """libzim search module - Query to prepare a query from a string - Searcher to perform a search over a libzim.reader.Archive Usage: archive = libzim.reader.Archive(fpath) searcher = Searcher(archive) query = Query().set_query("foo") search = searcher.search(query) for path in search.getResults(10, 10) # get result from 10 to 20 (10 results) print(path, archive.get_entry_by_path(path).title)""" search_public_objects = [ Query, SearchResultSet, Search, Searcher, ] search = create_module(search_module_name, search_module_doc, search_public_objects) ############################################################################### #  Suggestion module # ############################################################################### suggestion_module_name = f"{__name__}.suggestion" cdef class SuggestionResultSet: """Iterator over a SuggestionSearch result: entry paths""" __module__ = suggestion_module_name cdef zim.SuggestionResultSet c_resultset @staticmethod cdef from_resultset(zim.SuggestionResultSet _resultset): cdef SuggestionResultSet resultset = SuggestionResultSet() resultset.c_resultset = move(_resultset) return resultset def __iter__(self) -> Iterator[str]: """Entry paths found in Archive for SuggestionSearch""" cdef zim.SuggestionIterator current = self.c_resultset.begin() cdef zim.SuggestionIterator end = self.c_resultset.end() while current != end: yield current.getSuggestionItem().getPath().decode('UTF-8') preincrement(current) cdef class SuggestionSearch: __module__ = suggestion_module_name cdef zim.SuggestionSearch c_search # Factory functions - Currently Cython can't use classmethods @staticmethod cdef from_search(zim.SuggestionSearch _search): """Creates a python ReadArticle from a C++ Article (zim::) -> ReadArticle Parameters ---------- _item : Item A C++ Item Returns ------ Item Casted item""" cdef SuggestionSearch search = SuggestionSearch() search.c_search = move(_search) return search def getEstimatedMatches(self) -> pyint: """Estimated number of results in Archive for the suggestion search""" return self.c_search.getEstimatedMatches() def getResults(self, start: pyint, count: pyint) -> SuggestionResultSet: """Iterator over Entry paths found in Archive for the suggestion search""" return SuggestionResultSet.from_resultset(move(self.c_search.getResults(start, count))) cdef class SuggestionSearcher: """ZIM Archive SuggestionSearcher Attributes ---------- *c_archive : Searcher a pointer to a C++ Searcher object""" __module__ = suggestion_module_name cdef zim.SuggestionSearcher c_searcher def __cinit__(self, object archive: Archive): """Constructs an Archive from full zim file path Parameters ---------- filename : pathlib.Path Full path to a zim file""" self.c_searcher = move(zim.SuggestionSearcher(archive.c_archive)) def suggest(self, query: str) -> SuggestionSearch: """SuggestionSearch object for a query of this SuggestionSearcher's ZIM Archive""" return SuggestionSearch.from_search(move(self.c_searcher.suggest(query.encode('UTF-8')))) suggestion_module_doc = """libzim suggestion module - SuggestionSearcher to perform a suggestion search over a libzim.reader.Archive Usage: archive = Archive(fpath) suggestion_searcher = SuggestionSearcher(archive) suggestions = suggestion_searcher.suggest("foo") for path in suggestion.getResults(10, 10) # get result from 10 to 20 (10 results) print(path, archive.get_entry_by_path(path).title)""" suggestion_public_objects = [ SuggestionSearcher ] suggestion = create_module(suggestion_module_name, suggestion_module_doc, suggestion_public_objects) version_module_doc = """libzim version module - Get version of libzim and its dependencies - Print version of libzim and its dependencies - Get libzim version Usage: from libzim.version import get_libzim_version, get_versions, print_versions major, minor, patch = get_libzim_version().split(".", 2) for dependency, version in get_versions().items(): print(f"- {dependency}={version}") print_versions()""" def print_versions(out: TextIO = sys.stdout): """print libzim and its dependencies list with their versions""" for library, version in get_versions().items(): prefix = "" if library == "libzim" else "+ " print(f"{prefix}{library} {version}", file=out or sys.stdout) def get_versions() -> OrderedDict[str, str]: """ library: version mapping. Always includes `libzim`""" versions = zim.getVersions() return OrderedDict({ library.decode("UTF-8"): version.decode("UTF-8") for library, version in versions }) def get_libzim_version() -> str: """libzim version string""" return get_versions()["libzim"] version_public_objects = [ get_libzim_version, get_versions, print_versions, ] version_module_name = f"{__name__}.version" version = create_module(version_module_name, version_module_doc, version_public_objects) class ModuleLoader(importlib.abc.Loader): # Create our module. Easy, just return the created module @staticmethod def create_module(spec): return { 'libzim.writer': writer, 'libzim.reader': reader, 'libzim.search': search, 'libzim.suggestion': suggestion, 'libzim.version': version }.get(spec.name, None) @staticmethod def exec_module(module): # Nothing to execute for our already existing module. # But we need to define exec_module to tell python not use the legacy import system. pass class ModuleFinder(importlib.abc.MetaPathFinder): def find_spec(self, fullname, path, target=None): if fullname.startswith("libzim."): return importlib.machinery.ModuleSpec(fullname, ModuleLoader) # This is not our problem, let import mechanism continue return None # register finder for our submodules sys.meta_path.insert(0, ModuleFinder()) __all__ = ["writer", "reader", "search", "suggestion", "version"] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/libzim/reader.pyi0000644000175100001770000000445114703467205015702 0ustar00runnerdockerfrom __future__ import annotations import pathlib from uuid import UUID class Item: @property def title(self) -> str: ... @property def path(self) -> str: ... @property def content(self) -> memoryview: ... @property def mimetype(self) -> str: ... @property def _index(self) -> int: ... @property def size(self) -> int: ... def __repr__(self) -> str: ... class Entry: @property def title(self) -> str: ... @property def path(self) -> str: ... @property def _index(self) -> int: ... @property def is_redirect(self) -> bool: ... def get_redirect_entry(self) -> Entry: ... def get_item(self) -> Item: ... def __repr__(self) -> str: ... class Archive: def __init__(self, filename: pathlib.Path) -> None: ... @property def filename(self) -> pathlib.Path: ... @property def filesize(self) -> int: ... def has_entry_by_path(self, path: str) -> bool: ... def get_entry_by_path(self, path: str) -> Entry: ... def has_entry_by_title(self, title: str) -> bool: ... def get_entry_by_title(self, title: str) -> Entry: ... @property def metadata_keys(self) -> list[str]: ... def get_metadata_item(self, name: str) -> Item: ... def get_metadata(self, name: str) -> bytes: ... def _get_entry_by_id(self, entry_id: int) -> Entry: ... @property def has_main_entry(self) -> bool: ... @property def main_entry(self) -> Entry: ... @property def uuid(self) -> UUID: ... @property def has_new_namespace_scheme(self) -> bool: ... @property def is_multipart(self) -> bool: ... @property def has_fulltext_index(self) -> bool: ... @property def has_title_index(self) -> bool: ... @property def has_checksum(self) -> str: ... @property def checksum(self) -> str: ... def check(self) -> bool: ... @property def entry_count(self) -> int: ... @property def all_entry_count(self) -> int: ... @property def article_count(self) -> int: ... @property def media_count(self) -> int: ... def get_illustration_sizes(self) -> set[int]: ... def has_illustration(self, size: int | None = None) -> bool: ... def get_illustration_item(self, size: int | None = None) -> Item: ... def __repr__(self) -> str: ... ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/libzim/search.pyi0000644000175100001770000000104314703467205015677 0ustar00runnerdockerfrom __future__ import annotations from collections.abc import Iterator from typing import Self from libzim.reader import Archive class Query: def set_query(self, query: str) -> Self: ... class SearchResultSet: def __iter__(self) -> Iterator[str]: ... class Search: def getEstimatedMatches(self) -> int: ... # noqa: N802 def getResults(self, start: int, count: int) -> SearchResultSet: ... # noqa: N802 class Searcher: def __init__(self, archive: Archive) -> None: ... def search(self, query: Query) -> Search: ... ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/libzim/suggestion.pyi0000644000175100001770000000077714703467205016636 0ustar00runnerdockerfrom __future__ import annotations from collections.abc import Iterator from libzim.reader import Archive class SuggestionResultSet: def __iter__(self) -> Iterator[str]: ... class SuggestionSearch: def getEstimatedMatches(self) -> int: ... # noqa: N802 def getResults( # noqa: N802 self, start: int, count: int ) -> SuggestionResultSet: ... class SuggestionSearcher: def __init__(self, archive: Archive) -> None: ... def suggest(self, query: str) -> SuggestionSearch: ... ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/libzim/version.pyi0000644000175100001770000000037614703467205016127 0ustar00runnerdockerfrom __future__ import annotations import sys from collections import OrderedDict from typing import TextIO def print_versions(out: TextIO = sys.stdout) -> None: ... def get_versions() -> OrderedDict[str, str]: ... def get_libzim_version() -> str: ... ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/libzim/writer.pyi0000644000175100001770000000554714703467205015763 0ustar00runnerdockerfrom __future__ import annotations import datetime import enum import pathlib import types from collections.abc import Callable, Generator from typing import Self class Compression(enum.Enum): none: Self zstd: Self class Hint(enum.Enum): COMPRESS: Self FRONT_ARTICLE: Self class Blob: def __init__(self, content: str | bytes) -> None: ... def size(self) -> int: ... ref_content: bytes class ContentProvider: def feed(self) -> Blob: ... def get_size(self) -> int: ... def gen_blob(self) -> Generator[Blob, None, None]: ... generator: Generator[Blob, None, None] class StringProvider(ContentProvider): def __init__(self, content: str | bytes) -> None: ... class FileProvider(ContentProvider): def __init__(self, filepath: pathlib.Path | str) -> None: ... class Item: def get_path(self) -> str: ... def get_title(self) -> str: ... def get_mimetype(self) -> str: ... def get_contentprovider(self) -> ContentProvider: ... def get_hints(self) -> dict[Hint, int]: ... def __repr__(self) -> str: ... get_indexdata: Callable[[], IndexData | None] | None _blob: Blob class IndexData: def has_indexdata(self) -> bool: ... def get_title(self) -> str: ... def get_content(self) -> str: ... def get_keywords(self) -> str: ... def get_wordcount(self) -> int: ... def get_geoposition(self) -> tuple[float, float] | None: ... class Creator: def __init__(self, filename: pathlib.Path) -> None: ... def config_verbose(self, verbose: bool) -> Self: ... def config_compression(self, compression: Compression | str) -> Self: ... def config_clustersize(self, size: int) -> Self: ... def config_indexing(self, indexing: bool, language: str) -> Self: ... def config_nbworkers(self, nbWorkers: int) -> Self: ... # noqa: N803 def set_mainpath(self, mainPath: str) -> Self: ... # noqa: N803 def add_illustration(self, size: int, content: bytes) -> None: ... def add_item(self, writer_item: Item) -> None: ... def add_metadata( self, name: str, content: str | bytes | datetime.date | datetime.datetime, mimetype: str = "text/plain;charset=UTF-8", ) -> None: ... def add_redirection( self, path: str, title: str, targetPath: str, # noqa: N803 hints: dict[Hint, int], ) -> None: ... def add_alias( self, path: str, title: str, targetPath: str, # noqa: N803 hints: dict[Hint, int], ) -> None: ... def __enter__(self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None, ) -> None: ... @property def filename(self) -> pathlib.Path: ... def __repr__(self) -> str: ... _filename: pathlib.Path _started: bool ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/libzim/zim.pxd0000644000175100001770000001726414703467205015237 0ustar00runnerdocker# This file is part of python-libzim # (see https://github.com/libzim/python-libzim) # # Copyright (c) 2020 Juan Diego Caballero # Copyright (c) 2020 Matthieu Gautier # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from cpython.ref cimport PyObject from libc.stdint cimport uint32_t, uint64_t from libcpp cimport bool from libcpp.map cimport map from libcpp.memory cimport shared_ptr from libcpp.pair cimport pair from libcpp.set cimport set from libcpp.string cimport string from libcpp.vector cimport vector cdef extern from "zim/zim.h" namespace "zim": ctypedef uint64_t size_type ctypedef uint64_t offset_type ctypedef uint32_t entry_index_type cdef enum Compression: # We need to declare something here to be syntaxically correct # but we don't use those values (even if they are valid). None "zim::Compression::None" Zstd "zim::Compression::Zstd" cdef extern from "zim/writer/item.h" namespace "zim::writer": cdef cppclass WriterItem "zim::writer::Item": pass ctypedef enum HintKeys: COMPRESS FRONT_ARTICLE cdef cppclass IndexData: pass cdef extern from "zim/writer/item.h" namespace "zim::writer::IndexData": cppclass GeoPosition: GeoPosition() GeoPosition(bool, double, double) cdef extern from "zim/writer/contentProvider.h" namespace "zim::writer": cdef cppclass ContentProvider: pass cdef extern from "zim/writer/creator.h" namespace "zim::writer": cdef cppclass ZimCreator "zim::writer::Creator": void configVerbose(bint verbose) void configCompression(Compression compression) void configClusterSize(int size) void configIndexing(bint indexing, string language) void configNbWorkers(int nbWorkers) void startZimCreation(string filepath) nogil except +; void addItem(shared_ptr[WriterItem] item) nogil except + void addMetadata(string name, string content, string mimetype) nogil except + void addRedirection(string path, string title, string targetpath, map[HintKeys, uint64_t] hints) nogil except + void addAlias(string path, string title, string targetpath, map[HintKeys, uint64_t] hints) except + nogil void finishZimCreation() nogil except + void setMainPath(string mainPath) void addIllustration(unsigned int size, string content) nogil except + cdef extern from "zim/search.h" namespace "zim": cdef cppclass Query: Query() Query& setQuery(string query) Query& setGeorange(float latitude, float longitude, float distance) cdef extern from "zim/search_iterator.h" namespace "zim": cdef cppclass SearchIterator: SearchIterator() SearchIterator operator++() bint operator==(SearchIterator) bint operator!=(SearchIterator) string getPath() string getTitle() # Import the python wrappers (ObjWrapper) from libwrapper. # The only thing we need to know here is how to create the wrappers. # Other (cpp) methods must exists (to be called from cpp side), # but we don't care about them as we will not call them in python side. cdef extern from "libwrapper.h": cdef cppclass ContentProviderWrapper(ContentProvider): ContentProviderWrapper(PyObject* obj) except + cdef cppclass WriterItemWrapper: WriterItemWrapper(PyObject* obj) except + cdef cppclass IndexDataWrapper(IndexData): IndexDataWrapper(PyObject* obj) except + Compression comp_from_int(int) # Import the cpp wrappers. cdef extern from "libwrapper.h" namespace "wrapper": cdef cppclass Blob: Blob() except + Blob(const char* data, uint64_t size) except + const char* data() except + const char* end() except + uint64_t size() except + cdef cppclass Entry: string getTitle() string getPath() except + bint isRedirect() Item getItem(bint follow) except + Item getRedirect() except + Entry getRedirectEntry() except + int getIndex() except + cdef cppclass Item: string getTitle() except + string getPath() except + string getMimetype() except + Blob getData(offset_type offset) except + Blob getData(offset_type offset, size_type size) except + size_type getSize() except + int getIndex() except + cdef cppclass Archive: Archive() except + Archive(string filename) except + uint64_t getFilesize() except + Entry getEntryByPath(string path) except + Entry getEntryByPath(entry_index_type idx) except + Entry getEntryByTitle(string title) except + string getMetadata(string name) except + Item getMetadataItem(string name) except + vector[string] getMetadataKeys() except + Entry getMainEntry() except + Item getIllustrationItem() except + Item getIllustrationItem(int size) except + size_type getEntryCount() except + size_type getAllEntryCount() except + size_type getArticleCount() except + size_type getMediaCount() except + string getChecksum() except + string getFilename() except + string getUuid() except + bool hasMainEntry() except + bool hasIllustration() except + bool hasIllustration(unsigned int size) except + set[unsigned int] getIllustrationSizes() except + bool hasEntryByPath(string path) except + bool hasEntryByTitle(string title) except + bool isMultiPart() except + bool hasNewNamespaceScheme() except + bool hasFulltextIndex() except + bool hasTitleIndex() except + bool hasChecksum() except + bool check() except + cdef cppclass Searcher: Searcher() Searcher(const Archive& archive) except + setVerbose(bool verbose) Search search(Query query) except + cdef cppclass Search: int getEstimatedMatches() except + SearchResultSet getResults(int start, int count) except + cdef cppclass SearchResultSet: SearchIterator begin() SearchIterator end() int size() cdef cppclass SuggestionItem: string getPath() string getTitle() string getSnippet() bool hasSnippet() cdef cppclass SuggestionIterator: SuggestionIterator() SuggestionIterator operator++() bint operator==(SuggestionIterator) bint operator!=(SuggestionIterator) SuggestionItem getSuggestionItem() Entry getEntry() cdef cppclass SuggestionSearcher: SuggestionSearcher() SuggestionSearcher(const Archive& archive) except + setVerbose(bool verbose) SuggestionSearch suggest(string query) except + cdef cppclass SuggestionSearch: int getEstimatedMatches() except + SuggestionResultSet getResults(int start, int count) except + cdef cppclass SuggestionResultSet: SuggestionIterator begin() SuggestionIterator end() int size() cdef extern from "zim/version.h" namespace "zim": cdef vector[pair[string, string]] getVersions() ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728999050.702708 libzim-3.6.0/libzim.egg-info/0000755000175100001770000000000014703467213015402 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999050.0 libzim-3.6.0/libzim.egg-info/SOURCES.txt0000644000175100001770000000052214703467212017264 0ustar00runnerdockerLICENSE MANIFEST.in README.md pyproject.toml setup.py tasks.py libzim/__init__.pyi libzim/libwrapper.cpp libzim/libwrapper.h libzim/libzim.pyx libzim/reader.pyi libzim/search.pyi libzim/suggestion.pyi libzim/version.pyi libzim/writer.pyi libzim/zim.pxd tests/test_libzim_creator.py tests/test_libzim_reader.py tests/test_libzim_version.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/pyproject.toml0000644000175100001770000001747014703467205015350 0ustar00runnerdocker[build-system] requires = [ "setuptools == 74.1.1", "wheel == 0.44.0", "cython == 3.0.11", "delocate == 0.11.0 ; platform_system=='Windows'", ] build-backend = "setuptools.build_meta" [project] name = "libzim" version = "3.6.0" requires-python = ">=3.9,<3.14" description = "A python-facing API for creating and interacting with ZIM files" authors = [ {name = "openZIM", email = "dev@kiwix.org"}, ] readme = "README.md" license = {text = "GPL-3.0-or-later"} classifiers = [ "Development Status :: 5 - Production/Stable", "Topic :: Utilities", "Topic :: Software Development :: Libraries", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Archiving", "Topic :: System :: Archiving :: Compression", "Topic :: System :: Archiving :: Mirroring", "Topic :: System :: Archiving :: Backup", "Intended Audience :: Developers", "Programming Language :: Cython", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Typing :: Stubs Only", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Operating System :: MacOS", "Operating System :: POSIX", ] [project.urls] Homepage = "https://github.com/openzim/python-libzim" Donate = "https://www.kiwix.org/en/support-us/" [project.optional-dependencies] scripts = [ "invoke==2.2.0", ] lint = [ "black==24.10.0", "ruff==0.6.9", "libzim", "libzim[build]", ] check = [ "pyright==1.1.384", "libzim", "libzim[build]", "libzim[test]", "types-setuptools", ] test = [ "pytest==8.3.3", "coverage==7.6.2", # for cython coverage plugin "libzim[build]", ] build = [ "setuptools == 75.1.0", "wheel == 0.44.0", "cython == 3.0.11", "delocate == 0.11.0 ; platform_system=='Windows'", ] dev = [ "pre-commit==4.0.1", "ipython==8.28.0", "types-setuptools", "libzim[scripts]", "libzim[lint]", "libzim[test]", "libzim[check]", "libzim[build]", ] [tool.setuptools] include-package-data = true zip-safe = false packages = [ "libzim" ] [tool.setuptools.package-data] libzim = [ "py.typed", "*.pyi", "libzim.9.dylib", "libzim.so.9", "zim-9.dll", "icuuc74.dll", "icutu74.dll", "icuio74.dll", "icuin74.dll", "icudt74.dll", ] [tool.cibuildwheel] build = "*" # disabling PyPy due to 2 failing tests skip = "pp* *win32*" test-requires = ["pytest"] test-command = "py.test {project}/tests/" manylinux-x86_64-image = "manylinux_2_28" manylinux-aarch64-image = "manylinux_2_28" manylinux-pypy_x86_64-image = "manylinux_2_28" manylinux-pypy_aarch64-image = "manylinux_2_28" [tool.cibuildwheel.windows] before-build = "pip install setuptools cython delocate" repair-wheel-command = "python.exe setup.py repair_win_wheel --destdir={dest_dir} --wheel={wheel}" [tool.cibuildwheel.linux] archs = ["x86_64", "aarch64"] [tool.cibuildwheel.macos] archs = ["x86_64", "arm64"] # macOS arm64 is cross-compiled and can not be tested. # cibuildwheel skips it already. *_arm64 this removes the warning # skipping tests on cp <=3.9 as the wheels we produce are on unexpected combinations # because those python versions were released before our building host version # > requires changing wheel names test-skip = "*_arm64 cp39*" [tool.hatch.build] exclude = [ "/.github", ] [tool.hatch.build.targets.wheel] packages = ["libzim"] [tool.hatch.envs.default] features = ["dev"] [tool.hatch.envs.default.scripts] download-libzim = "inv download-libzim" build-ext = "inv build-ext" clean = "inv clean" [tool.hatch.envs.test] features = ["scripts", "test"] [tool.hatch.envs.test.env-vars] PROFILE = "1" [[tool.hatch.envs.test.matrix]] python = ["3.9", "3.10", "3.11", "3.12", "3.13"] [tool.hatch.envs.test.scripts] run = "inv test --args '{args}'" run-cov = "inv test-cov --args '{args}'" report-cov = "inv report-cov" coverage = "inv coverage --args '{args}'" html = "inv coverage --html --args '{args}'" [tool.hatch.envs.lint] template = "lint" skip-install = false features = ["scripts", "lint"] [tool.hatch.envs.lint.scripts] black = "inv lint-black --args '{args}'" ruff = "inv lint-ruff --args '{args}'" all = "inv lintall --args '{args}'" fix-black = "inv fix-black --args '{args}'" fix-ruff = "inv fix-ruff --args '{args}'" fixall = "inv fixall --args '{args}'" [tool.hatch.envs.check] features = ["scripts", "check"] [tool.hatch.envs.check.scripts] pyright = "inv check-pyright --args '{args}'" all = "inv checkall --args '{args}'" [tool.black] line-length = 88 target-version = ['py312'] [tool.ruff] target-version = "py312" line-length = 88 src = ["src"] [tool.ruff.lint] select = [ "A", # flake8-builtins # "ANN", # flake8-annotations "ARG", # flake8-unused-arguments # "ASYNC", # flake8-async "B", # flake8-bugbear # "BLE", # flake8-blind-except "C4", # flake8-comprehensions "C90", # mccabe # "COM", # flake8-commas # "D", # pydocstyle # "DJ", # flake8-django "DTZ", # flake8-datetimez "E", # pycodestyle (default) "EM", # flake8-errmsg # "ERA", # eradicate # "EXE", # flake8-executable "F", # Pyflakes (default) # "FA", # flake8-future-annotations "FBT", # flake8-boolean-trap # "FLY", # flynt # "G", # flake8-logging-format "I", # isort "ICN", # flake8-import-conventions # "INP", # flake8-no-pep420 # "INT", # flake8-gettext "ISC", # flake8-implicit-str-concat "N", # pep8-naming # "NPY", # NumPy-specific rules # "PD", # pandas-vet # "PGH", # pygrep-hooks # "PIE", # flake8-pie # "PL", # Pylint "PLC", # Pylint: Convention "PLE", # Pylint: Error "PLR", # Pylint: Refactor "PLW", # Pylint: Warning # "PT", # flake8-pytest-style # "PTH", # flake8-use-pathlib # "PYI", # flake8-pyi "Q", # flake8-quotes # "RET", # flake8-return # "RSE", # flake8-raise "RUF", # Ruff-specific rules "S", # flake8-bandit # "SIM", # flake8-simplify # "SLF", # flake8-self "T10", # flake8-debugger "T20", # flake8-print # "TCH", # flake8-type-checking # "TD", # flake8-todos "TID", # flake8-tidy-imports # "TRY", # tryceratops "UP", # pyupgrade "W", # pycodestyle "YTT", # flake8-2020 ] ignore = [ # Allow non-abstract empty methods in abstract base classes "B027", # Remove flake8-errmsg since we consider they bloat the code and provide limited value "EM", # Allow boolean positional values in function calls, like `dict.get(... True)` "FBT003", # Ignore checks for possible passwords "S105", "S106", "S107", # Ignore warnings on subprocess.run / popen "S603", # Ignore complexity "C901", "PLR0911", "PLR0912", "PLR0913", "PLR0915", ] unfixable = [ # Don't touch unused imports "F401", ] [tool.ruff.lint.isort] known-first-party = ["libzim"] [tool.ruff.lint.flake8-bugbear] # add exceptions to B008 for fastapi. extend-immutable-calls = ["fastapi.Depends", "fastapi.Query"] [tool.ruff.lint.flake8-tidy-imports] ban-relative-imports = "all" [tool.ruff.lint.per-file-ignores] # Tests can use magic values, assertions, and relative imports, and print "tests/**/*" = ["PLR2004", "S101", "TID252", "T201", "ARG001", "ARG002", "N803"] "setup.py" = ["T201"] "libzim/*.pyi" = ["FBT001"] [tool.pytest.ini_options] minversion = "7.3" testpaths = ["tests"] pythonpath = ["."] [tool.coverage] plugins = "Cython.Coverage" [tool.coverage.paths] libzim = ["libzim"] tests = ["tests"] [tool.coverage.run] source_pkgs = ["libzim"] branch = true parallel = true omit = [ "libzim/__about__.py", ] [tool.coverage.report] exclude_lines = [ "no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:", ] [tool.pyright] include = ["libzim", "tests", "tasks.py"] exclude = [".env/**", ".venv/**"] pythonVersion = "3.13" typeCheckingMode="basic" disableBytesTypePromotions = true ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728999050.702708 libzim-3.6.0/setup.cfg0000644000175100001770000000004614703467213014243 0ustar00runnerdocker[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/setup.py0000755000175100001770000005134014703467205014143 0ustar00runnerdocker#!/usr/bin/env python3 """python-libzim (openZIM/libzim binding for Python) The project is compiled in two steps: 1. Cython: compile the cython format files (.pyx, .pyd) to C++ (.cpp and .h) 2. Cythonize: compile the generated C++ to a python-importable binary extension .so The Cython and Cythonize compilation is done automatically by the build backend""" from __future__ import annotations import os import pathlib import platform as sysplatform import re import shutil import subprocess import sys import sysconfig import tarfile import urllib.request import zipfile from ctypes.util import find_library from pathlib import Path from Cython.Build import cythonize from Cython.Distutils.build_ext import new_build_ext as build_ext from setuptools import Command, Extension, setup class Config: libzim_dl_version: str = os.getenv("LIBZIM_DL_VERSION", "9.2.3-2") use_system_libzim: bool = bool(os.getenv("USE_SYSTEM_LIBZIM") or False) download_libzim: bool = not bool(os.getenv("DONT_DOWNLOAD_LIBZIM") or False) # toggle profiling for coverage report in Cython profiling: bool = os.getenv("PROFILE", "0") == "1" # macOS signing should_sign_apple: bool = bool(os.getenv("SIGN_APPLE") or False) apple_signing_identity: str = os.getenv("APPLE_SIGNING_IDENTITY") or "" apple_signing_keychain: str = os.getenv("APPLE_SIGNING_KEYCHAIN_PATH") or "" apple_signing_keychain_profile: str = ( os.getenv("APPLE_SIGNING_KEYCHAIN_PROFILE") or "" ) # windows _msvc_debug: bool = bool(os.getenv("MSVC_DEBUG")) supported_platforms = { # noqa: RUF012 "Darwin": ["x86_64", "arm64"], "Linux": ["x86_64", "aarch64"], "Linux-musl": ["x86_64", "aarch64"], "Windows": ["amd64"], } base_dir: pathlib.Path = Path(__file__).parent # Avoid running cythonize on `setup.py clean` and similar buildless_commands: tuple[str, ...] = ( "clean", "repair_win_wheel", "--help", "egg_info", "--version", "download_libzim", "build_sdist", "sdist", ) @property def libzim_major(self) -> str: # assuming nightlies are for version 8.x return "9" if self.is_nightly else self.libzim_dl_version[0] @property def found_libzim(self) -> str: return find_library("zim") or "" @property def is_latest_nightly(self) -> bool: """will use redirect to latest available nightly""" return self.libzim_dl_version == "nightly" @property def is_nightly(self) -> bool: return self.is_latest_nightly or bool( re.match(r"\d{4}-\d{2}-\d{2}", self.libzim_dl_version) ) @property def platform(self) -> str: """Platform building for: Darwin, Linux""" return sysplatform.system() @property def platform_libc(self) -> str: """Platform adjusted for libc variant: Darwin, Linux, Linux-musl""" if self.platform == "Linux" and self.is_musl: return "Linux-musl" return self.platform @property def arch(self) -> str: # macOS x86_64|arm64 - linux x86_64|aarch64 # when using cibuildwheel on macOS to cross-compile, # `_PYTHON_HOST_PLATFORM` contains # a platform string like macosx-11.0-arm64 # we extract the cross-compile arch from it return ( os.getenv("_PYTHON_HOST_PLATFORM", "").rsplit("-", 1)[-1] or sysplatform.machine().lower() ) def check_platform(self): if ( self.platform_libc not in self.supported_platforms or self.arch not in self.supported_platforms[self.platform_libc] ): raise NotImplementedError( f"Platform {self.platform_libc}/{self.arch} is not supported." ) @property def libzim_fname(self): """binary libzim dynamic library fname (platform dependent)""" # assuming we'll always link to same major return { "Darwin": f"libzim.{self.libzim_major}.dylib", "Linux": f"libzim.so.{self.libzim_major}", "Windows": f"zim-{self.libzim_major}.dll", }[self.platform] @property def archive_suffix(self): if self.platform == "Windows": return ".zip" return ".tar.gz" @property def archive_format(self): return {".zip": "zip", ".tar.gz": "gztar"}.get(self.archive_suffix) @property def is_musl(self) -> bool: """whether running on a musl system (Alpine)""" ps = subprocess.run( ["/usr/bin/env", "ldd", "--version"], capture_output=True, text=True, check=False, ) try: return "musl libc" in ps.stderr.splitlines()[0] except Exception: return False @property def wants_universal(self) -> bool: """whether requesting a macOS universal build""" return self.platform == "Darwin" and sysconfig.get_platform().endswith( "universal2" ) @property def use_msvc_debug(self) -> bool: """whether to add _DEBUG define to compilation requires having python debug binaries installed. mandatory for compiling against libzim nighlies""" return self._msvc_debug or self.is_nightly def get_download_filename(self, arch: str | None = None) -> str: """filename to download to get binary libzim for platform/arch""" arch = arch or self.arch # believe this is incorrect naming at openZIM ; will open ticket if self.platform == "Windows" and arch == "amd64": arch = "x86_64" lzplatform = {"Darwin": "macos", "Linux": "linux", "Windows": "win"}.get( self.platform ) variant = "" if self.platform == "Linux": variant = "-musl" if self.is_musl else "-manylinux" if self.is_latest_nightly: version_suffix = "" else: version_suffix = f"-{self.libzim_dl_version}" return pathlib.Path( f"libzim_{lzplatform}-{arch}{variant}{version_suffix}{self.archive_suffix}" ).name def download_to_dest(self): """download expected libzim binary into libzim/ and libzim/include/ folders""" self.check_platform() if self.wants_universal: folders = {} for arch in self.supported_platforms["Darwin"]: folders[arch] = self._download_and_extract( self.get_download_filename(arch) ) try: # duplicate x86_64 tree as placeholder (removing first) folder = folders["x86_64"].with_name( folders["x86_64"].name.replace("x86_64", "universal") ) shutil.rmtree(folder, ignore_errors=True) shutil.copytree( folders["x86_64"], folder, symlinks=True, ignore_dangling_symlinks=True, ) # delete libzim from copied tree dest = folder / "lib" / self.libzim_fname dest.unlink() # create universal from all archs subprocess.run( ["/usr/bin/env", "lipo"] + [ str(folder / "lib" / self.libzim_fname) for folder in folders.values() ] + ["-output", str(dest), "-create"], check=True, ) finally: # clean-up temp folders for _folder in folders.values(): shutil.rmtree(_folder, ignore_errors=True) else: folder = self._download_and_extract(self.get_download_filename()) self._install_from(folder) def _download_and_extract(self, filename: str) -> pathlib.Path: """folder it downloaded and extracted libzim dist to""" fpath = self.base_dir / filename source_url = "http://download.openzim.org/release/libzim" if self.is_latest_nightly: source_url = "http://download.openzim.org/nightly" elif self.is_nightly: source_url = f"http://download.openzim.org/nightly/{self.libzim_dl_version}" url = f"{source_url}/{fpath.name}" # download a local copy if none present if not fpath.exists(): print(f"> from {url}") with ( urllib.request.urlopen(url) as response, # noqa: S310 open(fpath, "wb") as fh, # nosec ): # nosec fh.write(response.read()) else: print(f"> reusing local file {fpath}") print("> extracting archive") # nightly have different download name and extracted folder name as it # uses a redirect if self.is_latest_nightly: if self.archive_format == "zip": zf = zipfile.ZipFile(fpath) folder = pathlib.Path(pathlib.Path(zf.namelist()[0]).parts[0]) else: tf = tarfile.open(fpath) folder = pathlib.Path(pathlib.Path(tf.getmembers()[0].name).parts[0]) else: folder = fpath.with_name(fpath.name.replace(self.archive_suffix, "")) # unless for ZIP, extract to current folder (all files inside an in-tar folder) extract_to = folder if self.archive_format == "zip" else self.base_dir shutil.unpack_archive(fpath, extract_to, self.archive_format) return folder def _install_from(self, folder: pathlib.Path): """move headers and libzim binary from dist folder to expected location""" libzim_dir = self.base_dir / "libzim" # remove existing headers if present self.base_dir.joinpath("include").mkdir(parents=True, exist_ok=True) shutil.rmtree(self.base_dir / "include" / "zim", ignore_errors=True) # copy new zim headers (self.base_dir / "include").mkdir(exist_ok=True, parents=True) shutil.move(folder / "include" / "zim", self.base_dir / "include" / "zim") # copy new libs (from lib/, lib/ or lib64/) for fpath in folder.rglob("lib*/**/libzim.*"): print(f"{fpath} -> {libzim_dir / fpath.name}") os.replace(fpath, libzim_dir / fpath.name) # windows has different folder and name for fpath in ( list(folder.joinpath("bin").rglob("zim-*.dll")) + list(folder.joinpath("bin").rglob("icu*.dll")) + list(folder.joinpath("lib").rglob("zim.lib")) ): print(f"{fpath} -> {libzim_dir / fpath.name}") os.replace(fpath, libzim_dir / fpath.name) # remove temp folder shutil.rmtree(folder, ignore_errors=True) assert self.base_dir.joinpath("include", "zim", "zim.h").exists() # noqa: S101 if config.platform == "Darwin": print("> ensure libzim is notarized") spctl = subprocess.run( [ "/usr/bin/env", "spctl", "-a", "-v", "-t", "install", str(self.base_dir / "libzim" / config.libzim_fname), ], check=False, ) if spctl.returncode != 0: print( "libzim binary is not notarized! Not an official release?", file=sys.stderr, ) def cleanup(self): """removes created files to prevent re-run issues""" # we downloaded libzim, so we must remove it if self.download_libzim: print("removing downloaded libraries") for fpath in self.dylib_file.parent.glob("*.[dylib|so|dll|lib|pc]*"): print(">", fpath) fpath.unlink(missing_ok=True) if self.header_file.parent.exists(): print("removing downloaded headers") shutil.rmtree(self.header_file.parent, ignore_errors=True) def repair_windows_wheel(self, wheel: Path, dest_dir: Path): """opens windows wheels in target folder and moves all DLLs files inside subdirectories of the wheel to the root one (where wrapper is expected)""" from delocate.wheeltools import InWheel # we're only interested in windows wheels if not re.match(r"libzim-.+-win_.+", wheel.stem): return dest_wheel = dest_dir / wheel.name with InWheel(str(wheel), str(dest_wheel)) as wheel_dir_path: print(f"repairing {wheel.name} for Windows (DLLs next to wrapper)") wheel_dir = Path(wheel_dir_path) for dll in wheel_dir.joinpath("libzim").rglob("*.dll"): print(f"> moving {dll} using {dll.relative_to(wheel_dir).parent}") dll.replace(wheel_dir / dll.name) @property def header_file(self) -> pathlib.Path: return self.base_dir / "include" / "zim" / "zim.h" @property def dylib_file(self) -> pathlib.Path: return self.base_dir / "libzim" / self.libzim_fname @property def can_sign_apple(self) -> bool: return all( [ self.platform == "Darwin", self.apple_signing_identity, self.apple_signing_keychain, self.apple_signing_keychain_profile, self.should_sign_apple, ] ) config = Config() def get_cython_extension() -> list[Extension]: define_macros: list[tuple[str, str | None]] = [] compiler_directives = {"language_level": "3"} if config.profiling: define_macros += [("CYTHON_TRACE", "1"), ("CYTHON_TRACE_NOGIL", "1")] compiler_directives.update(linetrace="true") include_dirs: list[str] = [] library_dirs: list[str] = [] runtime_library_dirs: list[str] = [] if config.use_system_libzim: if not config.found_libzim: raise OSError( "[!] The libzim library cannot be found.\n" "Please verify it is correctly installed and can be found." ) print( f"Using found library at {config.found_libzim}. " "Adjust CFLAGS/LDFLAGS if needed" ) else: if config.download_libzim: print("Downloading libzim. Set `DONT_DOWNLOAD_LIBZIM` not to.") config.download_to_dest() # Check for the CPP Libzim library headers in expected directory if not config.header_file.exists() or not config.dylib_file.exists(): raise OSError( "Unable to find a local copy of libzim " f"at {config.header_file} and {config.dylib_file}" ) print("Using local libzim binary. Set `USE_SYSTEM_LIBZIM` otherwise.") include_dirs.append("include") library_dirs = ["libzim"] if config.platform != "Windows": runtime_library_dirs = ( [f"@loader_path/libzim/{config.libzim_fname}"] if config.platform == "Darwin" else ["$ORIGIN/libzim/"] ) extra_compile_args = ["-std=c++11", "-Wall"] if config.platform == "Windows": extra_compile_args.append("/MDd" if config.use_msvc_debug else "/MD") ... else: extra_compile_args.append("-Wextra") wrapper_extension = Extension( name="libzim", sources=["libzim/libzim.pyx", "libzim/libwrapper.cpp"], include_dirs=include_dirs, libraries=["zim"], library_dirs=library_dirs, runtime_library_dirs=runtime_library_dirs, extra_compile_args=extra_compile_args, language="c++", define_macros=define_macros, ) return cythonize([wrapper_extension], compiler_directives=compiler_directives) class LibzimBuildExt(build_ext): def finalize_options(self): """Workaround for rpath bug in distutils for macOS""" super().finalize_options() if config.platform == "Darwin": # Special treatment of rpath in case of OSX, to work around python # distutils bug 36353. This constructs proper rpath arguments for clang. # See https://bugs.python.org/issue36353 for path in self.rpath: for ext in self.extensions: ext.extra_link_args.append("-Wl,-rpath," + path) self.rpath[:] = [] def build_extension(self, ext): """Properly set rpath on macOS and optionaly trigger macOS signing""" super().build_extension(ext) if config.platform == "Darwin" and not config.use_system_libzim: # use install_name_tool to properly set the rpath on the wrapper # so it finds libzim in a subfolder # for ext in self.extensions: fpath = self.get_ext_fullpath(ext.name) subprocess.run( [ "/usr/bin/env", "install_name_tool", "-change", config.libzim_fname, f"@loader_path/libzim/{config.libzim_fname}", str(fpath), ], check=True, ) if config.platform == "Darwin" and config.should_sign_apple: self.sign_extension_macos(ext) def sign_extension_macos(self, ext): """sign and notarize extension on macOS""" print("Signing & Notarization of the extension") if not config.can_sign_apple: raise OSError("Can't sign for apple. Missing information") ext_fpath = pathlib.Path(self.get_ext_fullpath(ext.name)) print("> signing the extension") subprocess.run( [ "/usr/bin/env", "codesign", "--force", "--sign", config.apple_signing_identity, str(ext_fpath), "--deep", "--timestamp", ], check=True, ) print("> create ZIP package for notarization request") ext_zip = ext_fpath.with_name(f"{ext_fpath.name}.zip") subprocess.run( [ "/usr/bin/env", "ditto", "-c", "-k", "--keepParent", str(ext_fpath), str(ext_zip), ], check=True, ) print("> request notarization") # security unlock-keychain -p mysecretpassword $(pwd)/build.keychain subprocess.run( [ "/usr/bin/env", "xcrun", "notarytool", "submit", "--keychain", config.apple_signing_keychain, "--keychain-profile", config.apple_signing_keychain_profile, "--wait", ext_zip, ], check=True, ) print("> removing zip file") ext_zip.unlink() print("> displaying request status (should be rejected)") subprocess.run( [ "/usr/bin/env", "spctl", "--assess", "-vv", "--type", "install", str(ext_fpath), ], check=False, ) class DownloadLibzim(Command): """dedicated command to solely download libzim binary""" user_options = [] # noqa: RUF012 def initialize_options(self): ... def finalize_options(self): ... def run(self): config.download_to_dest() class LibzimClean(Command): user_options = [] # noqa: RUF012 def initialize_options(self): ... def finalize_options(self): ... def run(self): config.cleanup() class RepairWindowsWheel(Command): user_options = [ # noqa: RUF012 ("wheel=", None, "Wheel to repair"), ("destdir=", None, "Destination folder for repaired wheels"), ] def initialize_options(self): self.wheel: str = "" self.destdir: str = "" def finalize_options(self): assert ( # noqa: S101 self.wheel and Path(self.wheel).exists() ), "wheel file does not exists" assert self.destdir and ( # noqa: S101 Path(self.destdir).exists() and Path(self.destdir).is_dir() ), "dest_dir does not exists" def run(self): config.repair_windows_wheel(wheel=Path(self.wheel), dest_dir=Path(self.destdir)) if len(sys.argv) == 1 or ( len(sys.argv) >= 2 and sys.argv[1] in config.buildless_commands # noqa: PLR2004 ): ext_modules = [] else: ext_modules = get_cython_extension() setup( cmdclass={ "build_ext": LibzimBuildExt, "download_libzim": DownloadLibzim, "clean": LibzimClean, "repair_win_wheel": RepairWindowsWheel, }, ext_modules=ext_modules, ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/tasks.py0000644000175100001770000000747514703467205014137 0ustar00runnerdocker# pyright: strict, reportUntypedFunctionDecorator=false import os from invoke.context import Context from invoke.tasks import task # pyright: ignore [reportUnknownVariableType] use_pty = not os.getenv("CI", "") @task def clean(ctx: Context): """download C++ libzim binary""" ctx.run("python setup.py clean") @task def download_libzim(ctx: Context, version: str = ""): """download C++ libzim binary""" env = f"LIBZIM_DL_VERSION={version}" if version else "" ctx.run(f"{env} python setup.py download_libzim") @task def build_ext(ctx: Context): """build extension to use locally (devel, tests)""" ctx.run("PROFILE=1 python setup.py build_ext -i") @task(optional=["args"], help={"args": "pytest additional arguments"}) def test(ctx: Context, args: str = ""): """run tests (without coverage)""" build_ext(ctx) ctx.run(f"pytest {args}", pty=use_pty) @task(optional=["args"], help={"args": "pytest additional arguments"}) def test_cov(ctx: Context, args: str = ""): """run test vith coverage""" ctx.run(f"coverage run -m pytest {args}", pty=use_pty) @task(optional=["html"], help={"html": "flag to export html report"}) def report_cov(ctx: Context, *, html: bool = False): """report coverage""" ctx.run("coverage combine", warn=True, pty=use_pty) ctx.run("coverage report --show-missing", pty=use_pty) ctx.run("coverage xml", pty=use_pty) if html: ctx.run("coverage html", pty=use_pty) @task( optional=["args", "html"], help={ "args": "pytest additional arguments", "html": "flag to export html report", }, ) def coverage(ctx: Context, args: str = "", *, html: bool = False): """run tests and report coverage""" test_cov(ctx, args=args) report_cov(ctx, html=html) @task(optional=["args"], help={"args": "black additional arguments"}) def lint_black(ctx: Context, args: str = "."): args = args or "." # needed for hatch script ctx.run("black --version", pty=use_pty) ctx.run(f"black --check --diff {args}", pty=use_pty) @task(optional=["args"], help={"args": "ruff additional arguments"}) def lint_ruff(ctx: Context, args: str = "."): args = args or "." # needed for hatch script ctx.run("ruff --version", pty=use_pty) ctx.run(f"ruff check {args}", pty=use_pty) @task( optional=["args"], help={ "args": "linting tools (black, ruff) additional arguments, typically a path", }, ) def lintall(ctx: Context, args: str = "."): """Check linting""" args = args or "." # needed for hatch script lint_black(ctx, args) lint_ruff(ctx, args) @task(optional=["args"], help={"args": "check tools (pyright) additional arguments"}) def check_pyright(ctx: Context, args: str = ""): """check static types with pyright""" ctx.run("pyright --version") ctx.run(f"pyright {args}", pty=use_pty) @task(optional=["args"], help={"args": "check tools (pyright) additional arguments"}) def checkall(ctx: Context, args: str = ""): """check static types""" check_pyright(ctx, args) @task(optional=["args"], help={"args": "black additional arguments"}) def fix_black(ctx: Context, args: str = "."): """fix black formatting""" args = args or "." # needed for hatch script ctx.run(f"black {args}", pty=use_pty) @task(optional=["args"], help={"args": "ruff additional arguments"}) def fix_ruff(ctx: Context, args: str = "."): """fix all ruff rules""" args = args or "." # needed for hatch script ctx.run(f"ruff check --fix {args}", pty=use_pty) @task( optional=["args"], help={ "args": "linting tools (black, ruff) additional arguments, typically a path", }, ) def fixall(ctx: Context, args: str = "."): """Fix everything automatically""" args = args or "." # needed for hatch script fix_black(ctx, args) fix_ruff(ctx, args) lintall(ctx, args) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1728999050.702708 libzim-3.6.0/tests/0000755000175100001770000000000014703467213013564 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/tests/test_libzim_creator.py0000644000175100001770000007072714703467205020220 0ustar00runnerdocker#!/usr/bin/env python from __future__ import annotations import base64 import datetime import itertools import os import pathlib import platform import subprocess import sys import pytest import libzim.writer # pyright: ignore [reportMissingModuleSource] from libzim.reader import Archive # pyright: ignore [reportMissingModuleSource] from libzim.search import Query, Searcher # pyright: ignore [reportMissingModuleSource] from libzim.suggestion import ( # pyright: ignore [reportMissingModuleSource] SuggestionSearcher, ) from libzim.writer import ( # pyright: ignore [reportMissingModuleSource] Blob, ContentProvider, Creator, FileProvider, Hint, IndexData, Item, StringProvider, ) HOME_PATH = "lorem_ipsum" class StaticItem(libzim.writer.Item): def __init__(self, **kwargs): super().__init__() for k, v in kwargs.items(): setattr(self, k, v) def get_path(self) -> str: return getattr(self, "path", "") def get_title(self) -> str: return getattr(self, "title", "") def get_mimetype(self) -> str: return getattr(self, "mimetype", "") def get_contentprovider(self) -> libzim.writer.ContentProvider: if getattr(self, "filepath", None): return FileProvider(filepath=getattr(self, "filepath", "")) return StringProvider(content=getattr(self, "content", "")) def get_hints(self) -> dict[Hint, int]: return getattr(self, "hints", {Hint.FRONT_ARTICLE: True}) @pytest.fixture(scope="function") def fpath(tmpdir): return pathlib.Path(tmpdir / "test.zim") @pytest.fixture(scope="module") def favicon_data(): return base64.b64decode( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQ" "ImWO4ISn6HwAE2QIGKsd69QAAAABJRU5ErkJggg==" ) @pytest.fixture(scope="module") def lipsum(): return ( "Lorem Ipsum" "

What is Lorem Ipsum?

Lorem Ipsum is" "simply dummy text of the printing and typesetting industry. Lorem" "Ipsum has been the industry's standard dummy text ever since the" "1500s, when an unknown printer took a galley of type and scrambled it" "to make a type specimen book. It has survived not only five centuries," "but also the leap into electronic typesetting, remaining essentially" "unchanged. It was popularised in the 1960s with the release of" "Letraset sheets containing Lorem Ipsum passages, and more recently" "with desktop publishing software like Aldus PageMaker including" "versions of Lorem Ipsum.

Why do we use it?

" "

It is a long established fact that a reader will be distracted by" "the readable content of a page when looking at its layout. The point" "of using Lorem Ipsum is that it has a more-or-less normal distribution" "of letters, as opposed to using 'Content here, content here', making" "it look like readable English. Many desktop publishing packages and" "web page editors now use Lorem Ipsum as their default model text, and" "a search for 'lorem ipsum' will uncover many web sites still in their" "infancy. Various versions have evolved over the years, sometimes by" "accident, sometimes on purpose (injected humour and the like).

" "

Where does it come from?

Contrary to" "popular belief, Lorem Ipsum is not simply random text. It has roots in" "a piece of classical Latin literature from 45 BC, making it over 2000" "years old. Richard McClintock, a Latin professor at Hampden-Sydney" "College in Virginia, looked up one of the more obscure Latin words," "consectetur, from a Lorem Ipsum passage, and going through the cites" "of the word in classical literature, discovered the undoubtable" 'source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de' 'Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero,' "written in 45 BC. This book is a treatise on the theory of ethics," "very popular during the Renaissance. The first line of Lorem Ipsum," '"Lorem ipsum dolor sit amet..", comes from a line in section' "1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s" "is reproduced below for those interested. Sections 1.10.32 and 1.10.33" 'from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in' "their exact original form, accompanied by English versions from the" "1914 translation by H. Rackham.

Where can I get" "some?

There are many variations of passages of Lorem Ipsum" "available, but the majority have suffered alteration in some form, by" "injected humour, or randomised words which don't look even slightly" "believable. If you are going to use a passage of Lorem Ipsum, you need" "to be sure there isn't anything embarrassing hidden in the middle of" "text. All the Lorem Ipsum generators on the Internet tend to repeat" "predefined chunks as necessary, making this the first true generator" "on the Internet. It uses a dictionary of over 200 Latin words," "combined with a handful of model sentence structures, to generate" "Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is" "therefore always free from repetition, injected humour, or" "non-characteristic words etc.

" ) @pytest.fixture(scope="module") def lipsum_item(lipsum): return StaticItem(path=HOME_PATH, content=lipsum, mimetype="text/html") def test_imports(): assert libzim.writer.Compression assert libzim.writer.Blob assert libzim.writer.Item assert libzim.writer.ContentProvider assert libzim.writer.FileProvider assert libzim.writer.StringProvider assert libzim.writer.Creator def test_creator_filename(fpath): with Creator(fpath) as c: assert c.filename == fpath assert Archive(fpath).filename == fpath def test_creator_repr(fpath): with Creator(fpath) as c: assert str(fpath) in str(c) def get_creator_output(fpath, verbose): """run creator with configVerbose(verbose) and return its stdout as str""" code = """ from libzim.writer import Creator with Creator(r"{fpath}").config_verbose({verbose}) as creator: pass """.replace( "{fpath}", str(fpath) ).replace( "{verbose}", str(verbose) ) ps = subprocess.run( [sys.executable, "-c", code], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False, ) assert ps.returncode == 0 return ps.stdout @pytest.mark.parametrize("verbose", [True, False]) def test_creator_verbose(fpath, verbose): output = get_creator_output(fpath, verbose).strip() lines = output.splitlines() if verbose: assert "T:" in output assert len(lines) >= 5 else: assert len(lines) == 2 def test_creator_compression(fpath, lipsum_item): """make sure we can create ZIM files with various compression algorithms also makes sure we're getting different sizes using diffrent alg. based on a piece of text that should give different results""" filesizes = {} for comp in libzim.writer.Compression.__members__.keys(): fpath_str = fpath.with_name(f"{fpath.name}_{comp}_str.zim") with Creator(fpath_str).config_compression(comp) as c: c.add_item(lipsum_item) fpath_val = fpath.with_name(f"{fpath.name}_{comp}_val.zim") comp_val = getattr(libzim.writer.Compression, comp) with Creator(fpath_val).config_compression(comp_val) as c: c.add_item(lipsum_item) assert Archive(fpath_str).checksum assert Archive(fpath_str).filesize == Archive(fpath_val).filesize filesizes[comp] = Archive(fpath_str).filesize for a, b in itertools.combinations(filesizes.keys(), 2): assert filesizes[a] != filesizes[b] # now don't specify with Creator(fpath) as c: c.add_item(lipsum_item) # default should be zstd assert Archive(fpath).filesize == filesizes["zstd"] @pytest.mark.parametrize("cluster_size", [0, 128, 512, 8196, 10240]) def test_creator_clustersize(fpath, cluster_size, lipsum_item): """ensure we can create ZIM with arbitrary min-cluster-size""" with Creator(fpath).config_clustersize(cluster_size) as c: c.add_item(lipsum_item) @pytest.mark.parametrize( "indexing, language, expected", [ (False, "a", 0), (False, "eng", 0), (True, "eng", 1), (True, "en", 1), (True, "fra", 1), (True, "fr", 1), ], ) def test_creator_indexing(fpath, lipsum_item, indexing, language, expected): with Creator(fpath).config_indexing(indexing, language) as c: c.add_item(lipsum_item) zim = Archive(fpath) assert zim.has_fulltext_index == indexing if indexing: query = Query().set_query("standard") searcher = Searcher(zim) search = searcher.search(query) assert search.getEstimatedMatches() == expected @pytest.mark.parametrize("nb_workers", [1, 2, 3, 5]) def test_creator_nbworkers(fpath, lipsum_item, nb_workers): with Creator(fpath).config_nbworkers(nb_workers) as c: c.add_item(lipsum_item) def test_creator_combine_config(fpath, lipsum_item): with ( Creator(fpath) .config_verbose(True) .config_compression("zstd") .config_clustersize(1024) .config_indexing(True, "eng") .config_nbworkers(2) as c ): c.add_item(lipsum_item) @pytest.mark.parametrize( "name, args", [ ("verbose", (True,)), ("compression", ("zstd",)), ("clustersize", (1024,)), ("indexing", (True, "eng")), ("nbworkers", (2,)), ], ) def test_creator_config_poststart(fpath, name, args): with Creator(fpath) as c: with pytest.raises(RuntimeError, match="started"): getattr(c, f"config_{name}")(*args) def test_creator_nocontext(fpath, lipsum_item): """ensure we can use the creator linearily""" creator = Creator(fpath) exc_type, exc_val, exc_tb = None, None, None creator.__enter__() creator.add_metadata("Name", "name") creator.add_item(lipsum_item) with pytest.raises(RuntimeError): creator.config_verbose(True) creator.__exit__(exc_type, exc_val, exc_tb) # now with an exception creator = Creator(fpath) creator.__enter__() creator.add_item(lipsum_item) try: creator.add_redirection("A", HOME_PATH) # pyright: ignore [reportCallIssue] except Exception: exc_type, exc_val, exc_tb = sys.exc_info() with pytest.raises(TypeError): raise creator.__exit__(exc_type, exc_val, exc_tb) def test_creator_subclass(fpath, lipsum_item): class ACreator(Creator): def __init__(self, fpath, tata): super().__init__(filename=fpath) self.ready = False def __exit__(self, exc_type, exc_val, exc_tb): super().__exit__(exc_type, exc_val, exc_tb) self.ready = True creator = ACreator(fpath, tata=2) assert creator.ready is False with creator: assert creator.ready is False creator.add_item(lipsum_item) assert creator.ready is True def test_creator_mainpath(fpath, lipsum_item): main_path = HOME_PATH with Creator(fpath).set_mainpath(main_path) as c: c.add_item(lipsum_item) zim = Archive(fpath) assert zim.has_main_entry is True assert zim.main_entry.path == "mainPage" assert zim.main_entry.get_item().path == main_path del zim fpath.unlink() with Creator(fpath) as c: c.add_item(lipsum_item) zim = Archive(fpath) assert zim.has_main_entry is False with pytest.raises(RuntimeError): assert zim.main_entry def test_creator_illustration(fpath, favicon_data): with Creator(fpath) as c: c.add_illustration(48, favicon_data) c.add_illustration(96, favicon_data) zim = Archive(fpath) assert zim.has_illustration() is True assert zim.has_illustration(48) is True assert zim.has_illustration(96) is True assert zim.has_illustration(128) is False assert bytes(zim.get_illustration_item().content) == favicon_data assert bytes(zim.get_illustration_item(96).content) == favicon_data assert zim.get_illustration_sizes() == {48, 96} def test_creator_additem(fpath, lipsum_item): # ensure we can't add if not started c = Creator(fpath) with pytest.raises(RuntimeError, match="not started"): c.add_item(lipsum_item) del c with Creator(fpath) as c: c.add_item(lipsum_item) with pytest.raises(TypeError, match="must not be None"): c.add_item(None) # pyright: ignore [reportCallIssue, reportArgumentType] with pytest.raises(RuntimeError): c.add_item("hello") # pyright: ignore [reportCallIssue, reportArgumentType] with pytest.raises(TypeError, match="takes exactly 1 positional argument"): c.add_item(mimetype="text/html") # pyright: ignore [reportCallIssue] def test_creator_metadata(fpath, lipsum_item): metadata = { # kiwix-mandatory "Name": "wikipedia_fr_football", "Title": "English Wikipedia", "Creator": "English speaking Wikipedia contributors", "Publisher": "Wikipedia user Foobar", "Date": "2009-11-21", "Description": "All articles (without images) from the english Wikipedia", "Language": "eng", # optional "Longdescription": ( "This ZIM file contains all articles (without images) " "from the english Wikipedia by 2009-11-10." " The topics are ..." ), "Licence": "CC-BY", "Tags": "wikipedia;_category:wikipedia;_pictures:no;" "_videos:no;_details:yes;_ftindex:yes", "Flavour": "nopic", "Source": "https://en.wikipedia.org/", "Scraper": "sotoki 1.2.3", } # ensure we can't add if not started c = Creator(fpath) with pytest.raises(RuntimeError, match="not started"): key = next(iter(metadata.keys())) c.add_metadata(key, metadata[key]) del c with Creator(fpath) as c: c.add_item(lipsum_item) for name, value in metadata.items(): if name == "Date": continue c.add_metadata(name, value) mdate = datetime.date(*[int(x) for x in metadata.get("Date", "").split("-")]) c.add_metadata("Date", mdate) zim = Archive(fpath) for name, value in metadata.items(): assert zim.get_metadata(name).decode("UTF-8") == value def test_creator_metadata_overwrite(fpath, lipsum_item, favicon_data): """re-adding an Entry (even Metadata) now raises an exception (libzim 7.2+)""" with Creator(fpath) as c: c.add_item(lipsum_item) with pytest.raises(RuntimeError, match="Impossible to add"): c.add_item(lipsum_item) c.add_metadata("Key", "first") with pytest.raises(RuntimeError, match="Impossible to add"): c.add_metadata("Key", "second") c.add_redirection("home", lipsum_item.get_path(), "Home", {}) with pytest.raises(RuntimeError, match="Impossible to add"): c.add_redirection("home", lipsum_item.get_path(), "Home again", {}) c.add_illustration(48, favicon_data) # this currently segfaults but it should not with pytest.raises(RuntimeError, match="Impossible to add"): c.add_illustration(48, favicon_data) zim = Archive(fpath) assert zim.get_metadata("Key").decode("UTF-8") == "first" def test_creator_redirection(fpath, lipsum_item): # ensure we can't add if not started c = Creator(fpath) with pytest.raises(RuntimeError, match="not started"): c.add_redirection("home", "hello", HOME_PATH, {Hint.FRONT_ARTICLE: True}) del c with Creator(fpath) as c: c.add_item(lipsum_item) c.add_redirection("home", "hello", HOME_PATH, {Hint.FRONT_ARTICLE: True}) c.add_redirection("accueil", "bonjour", HOME_PATH, {Hint.FRONT_ARTICLE: True}) zim = Archive(fpath) assert zim.entry_count == 3 assert zim.has_entry_by_path("home") is True assert zim.has_entry_by_path("accueil") is True assert zim.get_entry_by_path("home").is_redirect assert ( zim.get_entry_by_path("home").get_redirect_entry().path == zim.get_entry_by_path(HOME_PATH).path ) assert zim.get_entry_by_path("accueil").get_item().path == HOME_PATH # suggestions sugg_searcher = SuggestionSearcher(zim) sugg_hello = sugg_searcher.suggest("hello") assert "home" in list(sugg_hello.getResults(0, sugg_hello.getEstimatedMatches())) sugg_bonjour = sugg_searcher.suggest("bonjour") assert "accueil" in list( sugg_bonjour.getResults(0, sugg_hello.getEstimatedMatches()) ) def test_creator_alias(fpath, lipsum_item): # ensure we can't add if not started c = Creator(fpath) with pytest.raises(RuntimeError, match="not started"): c.add_redirection("home", "hello", HOME_PATH, {Hint.FRONT_ARTICLE: True}) del c with Creator(fpath) as c: c.add_item(lipsum_item) c.add_alias("home", "hello", HOME_PATH, {Hint.FRONT_ARTICLE: True}) with pytest.raises(RuntimeError, match="doesn't exist"): c.add_alias( "accueil", "bonjour", HOME_PATH + "_non_existent", {Hint.FRONT_ARTICLE: True}, ) zim = Archive(fpath) assert zim.entry_count == 2 assert zim.has_entry_by_path("home") is True assert zim.has_entry_by_path("accueil") is False assert not zim.get_entry_by_path("home").is_redirect assert ( zim.get_entry_by_path("home").get_item().content == zim.get_entry_by_path(HOME_PATH).get_item().content ) def test_item_notimplemented(fpath, lipsum_item): item = Item() for member in ("path", "title", "mimetype", "contentprovider"): with pytest.raises(NotImplementedError): getattr(item, f"get_{member}")() assert HOME_PATH in str(lipsum_item) assert lipsum_item.get_title() in str(lipsum_item) def test_contentprovider(fpath): cp = ContentProvider() for member in ("get_size", "gen_blob"): with pytest.raises(NotImplementedError): getattr(cp, member)() def test_fileprovider(fpath, lipsum): lipsum_fpath = fpath.with_name("lipsum.html") with open(lipsum_fpath, "w") as fh: for _ in range(0, 10): fh.write(lipsum) item = StaticItem(path=HOME_PATH, filepath=lipsum_fpath, mimetype="text/html") assert HOME_PATH in str(item) assert item.get_title() in str(item) with Creator(fpath) as c: c.add_item(item) zim = Archive(fpath) with open(lipsum_fpath, "rb") as fh: assert bytes(zim.get_entry_by_path(HOME_PATH).get_item().content) == fh.read() # test feed streaming cp = item.get_contentprovider() b = cp.feed() while b.size(): assert isinstance(b, Blob) b = cp.feed() def test_stringprovider(fpath, lipsum): item = StaticItem(path=HOME_PATH, content=lipsum, mimetype="text/html") assert HOME_PATH in str(item) assert item.get_title() in str(item) with Creator(fpath) as c: c.add_item(item) zim = Archive(fpath) assert bytes(zim.get_entry_by_path(HOME_PATH).get_item().content) == lipsum.encode( "UTF-8" ) # test feed streaming cp = item.get_contentprovider() b = cp.feed() while b.size(): assert isinstance(b, Blob) b = cp.feed() def test_item_contentprovider_none(fpath): class AnItem: def get_path(self): return "" def get_title(self): return "" def get_mimetype(self): return "" def get_contentprovider(self): return "" def get_hints(self): return {} with Creator(fpath) as c: with pytest.raises(RuntimeError, match="ContentProvider is None"): c.add_item(AnItem()) # pyright: ignore [reportArgumentType] def test_missing_contentprovider(fpath): class AnItem: def get_path(self): return "" def get_title(self): return "" def get_mimetype(self): return "" def get_hints(self): return {} with Creator(fpath) as c: with pytest.raises(RuntimeError, match="has no attribute"): c.add_item(AnItem()) # pyright: ignore [reportArgumentType] def test_missing_hints(fpath): class AnItem: def get_path(self): return "" def get_title(self): return "" def get_mimetype(self): return "" with Creator(fpath) as c: with pytest.raises(RuntimeError, match="has no attribute 'get_hints'"): c.add_item(AnItem()) # pyright: ignore [reportArgumentType] with pytest.raises(RuntimeError, match="must be implemented"): c.add_item(libzim.writer.Item()) def test_nondict_hints(fpath): with Creator(fpath) as c: with pytest.raises(RuntimeError, match="has no attribute 'items'"): c.add_item(StaticItem(path="1", title="", hints=1)) with pytest.raises(TypeError, match="hints"): c.add_redirection( "a", "", "b", hints=1 # pyright: ignore [reportArgumentType] ) def test_hints_values(fpath): with Creator(fpath) as c: # correct values c.add_item(StaticItem(path="0", title="", hints={})) c.add_item( StaticItem( path="1", title="", hints={Hint.FRONT_ARTICLE: True, Hint.COMPRESS: False}, ) ) # non-expected Hints are ignored c.add_item(StaticItem(path="2", title="", hints={"hello": "world"})) # Hint values are casted to bool c.add_item(StaticItem(path="3", title="", hints={Hint.FRONT_ARTICLE: "world"})) c.add_redirection( path="4", title="", targetPath="0", hints={Hint.COMPRESS: True} ) # filtered-out values c.add_item(StaticItem(path="5", title="", hints={5: True})) c.add_item(StaticItem(path="6", title="", hints={"yolo": True})) c.add_item(StaticItem(path="7", title="", hints={"FRONT_ARTICLE": True})) c.add_item(StaticItem(path="8", title="", hints={0: True})) # non-existent Hint with pytest.raises(AttributeError, match="YOLO"): c.add_item( StaticItem( path="0", title="", hints={ Hint.YOLO: True # pyright: ignore [reportAttributeAccessIssue] }, ) ) with pytest.raises(AttributeError, match="YOLO"): c.add_redirection( # pyright: ignore [reportCallIssue] path="5", title="", targetPath="0", hints={Hint.YOLO: True}, # pyright: ignore [reportAttributeAccessIssue] ) @pytest.mark.parametrize( "indexData, customContent, search_expected", [ (None, "", [("standard", 1), ("home", 0), ("computer", 0)]), (False, "", [("standard", 1), ("home", 0), ("computer", 0)]), (True, "home", [("standard", 1), ("home", 1), ("computer", 0)]), (True, "computer", [("standard", 1), ("home", 0), ("computer", 1)]), (True, "standard", [("standard", 2), ("home", 0), ("computer", 0)]), ], ) def test_custom_indexdata( fpath, lipsum_item, lipsum, indexData, customContent, search_expected ): item = StaticItem(path=HOME_PATH + "custom", content=lipsum, mimetype="text/html") if indexData is None: item.get_indexdata = lambda: None else: class CustomIndexData(IndexData): def has_indexdata(self): return indexData def get_title(self): return "" def get_content(self): return customContent def get_keywords(self): return "" def get_wordcount(self): return 1 item.get_indexdata = CustomIndexData with Creator(fpath).config_indexing(True, "eng") as c: c.add_item(lipsum_item) c.add_item(item) zim = Archive(fpath) searcher = Searcher(zim) for search_query, expected in search_expected: query = Query().set_query(search_query) search = searcher.search(query) assert search.getEstimatedMatches() == expected def test_indexdata_interface(): default_id = IndexData() assert default_id.has_indexdata() is False for method in ("title", "content", "keywords", "wordcount"): with pytest.raises(NotImplementedError): getattr(default_id, f"get_{method}")() assert default_id.get_geoposition() is None def test_exc_in_indexdata(fpath, lipsum): item = StaticItem(path=HOME_PATH + "custom", content=lipsum, mimetype="text/html") class CustomIndexData(IndexData): def has_indexdata(self): raise IndexError item.get_indexdata = CustomIndexData with pytest.raises(RuntimeError, match="IndexError"): with Creator(fpath).config_indexing(True, "eng") as c: c.add_item(item) def test_reimpfeed(fpath): class AContentProvider: def __init__(self): self.called = False def get_size(self): return 1 def feed(self): if self.called: return Blob("") self.called = True return Blob("1") class AnItem(Item): def get_path(self): return "-" def get_title(self): return "" def get_mimetype(self): return "" def get_hints(self): return {} def get_contentprovider(self): return AContentProvider() with Creator(fpath) as c: c.add_item(AnItem()) item = AnItem() cp = item.get_contentprovider() assert cp.get_size() == 1 assert cp.feed().size() == 1 def test_virtualmethods_int_exc(fpath): class AContentProvider: def get_size(self): return "" def feed(self): return Blob("") class AnItem(Item): def get_path(self): return "" def get_title(self): return "" def get_mimetype(self): return "" def get_hints(self): return {} def get_contentprovider(self): return AContentProvider() with Creator(fpath) as c: with pytest.raises(RuntimeError, match="TypeError: an integer is required"): c.add_item(AnItem()) def test_creator_badfilename(tmpdir): if platform.system() != "Windows" and os.getuid() != 0: # lack of perm with pytest.raises(IOError): Creator(pathlib.Path("/root/test.zim")) # forward slash points to non-existing folder with pytest.raises(IOError): Creator(tmpdir / "test/test.zim") def test_accented_search_from_libzim(fpath): """copy of libzim accented search test https://github.com/openzim/libzim/blob/main/test/search.cpp#L290 (88543b00)""" with Creator(fpath).config_verbose(True).config_indexing(True, "eng") as creator: creator.add_item( StaticItem( path="path0", title="Test Article0", content="This is a tèst articlé. temp0", mimetype="text/html", ) ) creator.add_item( StaticItem( path="path1", title="Test Article1", content="This is another test article. For article1.", mimetype="text/html", ) ) zim = Archive(fpath) assert zim.entry_count == 2 assert zim.article_count == 2 assert zim.all_entry_count == 7 ascii_query = Query().set_query("test article") ascii_searcher = Searcher(zim) ascii_search = ascii_searcher.search(ascii_query) assert ascii_search.getEstimatedMatches() == zim.article_count assert list(ascii_search.getResults(0, zim.article_count)) == ["path0", "path1"] accented_query = Query().set_query("test àrticlé") accented_searcher = Searcher(zim) accented_search = accented_searcher.search(accented_query) assert accented_search.getEstimatedMatches() == zim.article_count assert list(accented_search.getResults(0, zim.article_count)) == ["path0", "path1"] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1728999045.0 libzim-3.6.0/tests/test_libzim_reader.py0000644000175100001770000004406314703467205020015 0ustar00runnerdocker#!/usr/bin/env python import gc import os import pathlib import uuid from urllib.request import urlretrieve import pytest import libzim.writer # pyright: ignore [reportMissingModuleSource] from libzim.reader import Archive # pyright: ignore [reportMissingModuleSource] from libzim.search import Query, Searcher # pyright: ignore [reportMissingModuleSource] from libzim.suggestion import ( # pyright: ignore [reportMissingModuleSource] SuggestionSearcher, ) # expected data for tests ZIMs (see `all_zims`) ZIMS_DATA = { "blank.zim": { "filename": "blank.zim", "filesize": 2197, "new_ns": True, "mutlipart": False, "zim_uuid": None, "metadata_keys": ["Counter"], "test_metadata": None, "test_metadata_value": None, "has_main_entry": False, "has_favicon_entry": False, "has_fulltext_index": False, "has_title_index": False, "has_checksum": True, "checksum": None, "is_valid": True, "entry_count": 0, "all_entry_count": 2, "article_count": 0, "media_count": 0, "suggestion_string": None, "suggestion_count": 0, "suggestion_result": [], "search_string": None, "search_count": 0, "search_result": [], "test_path": None, "test_title": None, "test_mimetype": None, "test_size": None, "test_content_includes": None, "test_redirect": None, "test_redirect_to": None, }, "zimfile.zim": { "filename": "zimfile.zim", "filesize": 569304, "new_ns": False, "mutlipart": False, "zim_uuid": "6f1d19d0633f087bfb557ac324ff9baf", "metadata_keys": [ "Counter", "Creator", "Date", "Description", "Flavour", "Language", "Name", "Publisher", "Scraper", "Tags", "Title", ], "test_metadata": "Name", "test_metadata_value": "wikipedia_en_ray_charles", "has_main_entry": True, "has_favicon_entry": True, "has_fulltext_index": True, "has_title_index": True, "has_checksum": True, "checksum": None, "is_valid": True, "entry_count": 371, "all_entry_count": 371, "article_count": 129, "media_count": 45, "suggestion_string": "lucky", "suggestion_count": 1, "suggestion_result": ["A/That_Lucky_Old_Sun"], "search_string": "lucky", "search_count": 1, "search_result": ["A/That_Lucky_Old_Sun"], "test_path": "A/A_Song_for_You", "test_title": "A Song for You", "test_mimetype": "text/html", "test_size": 7461, "test_content_includes": "which was released in 1970 on Shelter Records", "test_redirect": "A/What_I_Say", "test_redirect_to": "A/What'd_I_Say", }, "example.zim": { "filename": "example.zim", "filesize": 259145, "new_ns": True, "mutlipart": False, "zim_uuid": "5dc0b3af5df20925f0cad2bf75e78af6", "metadata_keys": [ "Counter", "Creator", "Date", "Description", "Language", "Publisher", "Scraper", "Tags", "Title", ], "test_metadata": "Title", "test_metadata_value": "Wikibooks", "has_main_entry": True, "has_favicon_entry": False, "has_fulltext_index": True, "has_title_index": True, "has_checksum": True, "checksum": "abcd818c87079cb29282282b47ee46ec", "is_valid": True, "entry_count": 60, "all_entry_count": 75, "article_count": 0, "media_count": 22, "suggestion_string": "Free", "suggestion_count": 1, "suggestion_result": [ "FreedomBox for Communities_Offline Wikipedia " "- Wikibooks, open books for an open world.html" ], "search_string": "main", "search_count": 2, "search_result": [ "Wikibooks.html", "FreedomBox for Communities_Offline Wikipedia " "- Wikibooks, open books for an open world.html", ], "test_path": "FreedomBox for Communities_Offline Wikipedia - Wikibooks, " "open books for an open world.html", "test_title": "FreedomBox for Communities/Offline Wikipedia - Wikibooks, " "open books for an open world", "test_mimetype": "text/html", "test_size": 52771, "test_content_includes": "looking forward to your contributions.", "test_redirect": None, }, "corner_cases%23%26.zim": { "filename": "corner_cases%23%26.zim", "filesize": 35991, "new_ns": True, "mutlipart": False, "zim_uuid": "702abcbe6fe926152f5d451af7986437", "metadata_keys": [ "Counter", "Date", "Illustration_48x48@1", "Language", "Scraper", "Tags", "Title", ], "test_metadata": "Title", "test_metadata_value": "ZIM corner cases", "has_main_entry": True, "has_favicon_entry": True, "has_fulltext_index": False, "has_title_index": True, "has_checksum": True, "checksum": None, "is_valid": True, "entry_count": 7, "all_entry_count": 18, "article_count": 2, "media_count": 1, "suggestion_string": "c#", "suggestion_count": 1, "suggestion_result": ["c#.html"], "search_string": None, "search_count": 0, "search_result": [], "test_path": "empty.html", "test_title": "empty.html", "test_mimetype": "text/html", "test_size": 0, "test_content_includes": "", "test_redirect": None, "test_redirect_to": None, }, "small.zim": { "filename": "small.zim", "filesize": 41155, "new_ns": True, "mutlipart": False, "zim_uuid": "3581ae7eedd57e6cd2f1c0cab073643f", "metadata_keys": [ "Counter", "Creator", "Date", "Description", "Illustration_48x48@1", "Language", "Publisher", "Scraper", "Tags", "Title", ], "test_metadata": "Title", "test_metadata_value": "Test ZIM file", "has_main_entry": True, "has_favicon_entry": True, "has_fulltext_index": False, "has_title_index": True, "has_checksum": True, "checksum": None, "is_valid": True, "entry_count": 2, "all_entry_count": 16, "article_count": 1, "media_count": 1, "suggestion_string": None, "suggestion_count": None, "suggestion_result": None, "search_string": None, "search_count": None, "search_result": None, "test_path": "main.html", "test_title": "Test ZIM file", "test_mimetype": "text/html", "test_size": 207, "test_content_includes": "Test ZIM file", "test_redirect": None, "test_redirect_to": None, }, } skip_if_offline = pytest.mark.skipif( bool(os.getenv("OFFLINE")), reason="OFFLINE environ requested offline-only" ) def get_pytest_param(name, *fields): args = [ZIMS_DATA[name].get(field, f"MISSING-VALUE {field}") for field in fields] return pytest.param(*args) def get_pytest_params_list(*fields): return [get_pytest_param(name, *fields) for name in ZIMS_DATA.keys()] def parametrize_for(fields): return ( ", ".join(fields), get_pytest_params_list(*fields), ) @pytest.fixture(scope="module") def all_zims(tmpdir_factory): """creates a temp dir with all ZIM files inside: - downloaded ones from libzim - blank one created with pylibzim""" temp_dir = tmpdir_factory.mktemp("data") libzim_urls = [ f"https://github.com/kiwix/libkiwix/raw/main/test/data/{name}" for name in ("zimfile.zim", "example.zim", "corner_cases%23%26.zim") ] + ["https://github.com/openzim/zim-testing-suite/raw/main/data/nons/small.zim"] # download libzim tests for url in libzim_urls: urlretrieve(url, temp_dir / os.path.basename(url)) # noqa: S310 # nosec # create blank using pylibzim creator = libzim.writer.Creator(temp_dir / "blank.zim") with creator: pass return pathlib.Path(temp_dir) def test_open_badfile(tmpdir): fpath = tmpdir / "not-exist.zim" with pytest.raises(RuntimeError): Archive(fpath) fpath = tmpdir / "not-zim.zim" with open(fpath, "w") as fh: fh.write("text file") with pytest.raises(RuntimeError): Archive(fpath) @skip_if_offline def test_content_ref_keep(all_zims): """Get the memoryview on a content and loose the reference on the article. We try to load a lot of other articles to detect possible use of dandling pointer """ archive = Archive(all_zims / "zimfile.zim") content = None def get_content(): nonlocal content entry = archive.get_entry_by_path("A/That_Lucky_Old_Sun") item = entry.get_item() assert isinstance(item.content, memoryview) content = item.content get_content() # Now we have a content but no reference to the entry/item. gc.collect() # Load a lot of content for i in range(0, archive.entry_count, 2): entry = archive._get_entry_by_id(i) if not entry.is_redirect: _ = entry.get_item().content # Check everything is ok assert content and len(content) == 3559 assert content and ( bytes(content[:100]) == b'\n\n ' b'\n That Lucky Old Sun<' ) @skip_if_offline @pytest.mark.parametrize( *parametrize_for(["filename", "filesize", "new_ns", "mutlipart", "zim_uuid"]) ) def test_reader_archive(all_zims, filename, filesize, new_ns, mutlipart, zim_uuid): fpath = all_zims / filename zim = Archive(fpath) # check externaly verifiable data assert zim.filename == fpath assert zim.filesize == os.path.getsize(fpath) if filesize is not None: assert zim.filesize == filesize assert zim.has_new_namespace_scheme is new_ns assert zim.is_multipart is mutlipart assert str(fpath) in str(zim) # ensure uuid is returned assert isinstance(zim.uuid, uuid.UUID) assert len(zim.uuid.hex) == 32 if zim_uuid: assert zim.uuid.hex == zim_uuid @skip_if_offline @pytest.mark.parametrize( *parametrize_for( ["filename", "metadata_keys", "test_metadata", "test_metadata_value"] ) ) def test_reader_metadata( all_zims, filename, metadata_keys, test_metadata, test_metadata_value ): zim = Archive(all_zims / filename) # make sure metadata_keys is empty assert zim.metadata_keys == metadata_keys if test_metadata: assert zim.get_metadata(test_metadata).decode("UTF-8") == test_metadata_value item = zim.get_metadata_item(test_metadata) assert item.mimetype in ("text/plain", "text/plain;charset=utf-8") # newer assert item.size > 1 @skip_if_offline @pytest.mark.parametrize( *parametrize_for(["filename", "new_ns", "has_main_entry", "has_favicon_entry"]) ) def test_reader_main_favicon_entries( all_zims, filename, new_ns, has_main_entry, has_favicon_entry ): zim = Archive(all_zims / filename) # make sure we have no main entry assert zim.has_main_entry is has_main_entry if has_main_entry is False: with pytest.raises(RuntimeError): assert zim.main_entry else: assert zim.main_entry if new_ns: assert zim.main_entry.path == "mainPage" # make sure we have no favicon entry assert zim.has_illustration(48) is has_favicon_entry if has_favicon_entry: assert 48 in zim.get_illustration_sizes() if has_favicon_entry is False: with pytest.raises(KeyError): assert zim.get_illustration_item(48) else: assert zim.get_illustration_item() if new_ns: assert zim.get_illustration_item().path == "Illustration_48x48@1" assert zim.get_illustration_sizes() == {48} assert zim.get_metadata_item("Illustration_48x48@1").mimetype == "image/png" @skip_if_offline @pytest.mark.parametrize( *parametrize_for(["filename", "has_fulltext_index", "has_title_index"]) ) def test_reader_has_index(all_zims, filename, has_fulltext_index, has_title_index): zim = Archive(all_zims / filename) # we should not get a fulltext index but title should assert zim.has_fulltext_index is has_fulltext_index assert zim.has_title_index is has_title_index @skip_if_offline @pytest.mark.parametrize(*parametrize_for(["filename", "has_checksum", "is_valid"])) def test_reader_checksum(all_zims, filename, has_checksum, is_valid): zim = Archive(all_zims / filename) # verify checksum assert zim.has_checksum is has_checksum assert isinstance(zim.checksum, str) assert len(zim.checksum) == 32 if has_checksum else 0 assert zim.checksum != zim.uuid assert zim.check() is is_valid @skip_if_offline @pytest.mark.parametrize( *parametrize_for( [ "filename", "entry_count", "all_entry_count", "article_count", "media_count", "has_fulltext_index", "suggestion_string", "suggestion_count", "suggestion_result", "search_string", "search_count", "search_result", ] ) ) def test_reader_suggest_search( all_zims, filename, entry_count, all_entry_count, article_count, media_count, has_fulltext_index, suggestion_string, suggestion_count, suggestion_result, search_string, search_count, search_result, ): zim = Archive(all_zims / filename) # suggestion and search results assert zim.entry_count == entry_count assert zim.all_entry_count == all_entry_count assert zim.article_count == article_count assert zim.media_count == media_count if has_fulltext_index and search_string is not None: query = Query().set_query(search_string) searcher = Searcher(zim) search = searcher.search(query) assert search.getEstimatedMatches() == search_count assert list(search.getResults(0, search_count)) == search_result if suggestion_string is not None: suggestion_searcher = SuggestionSearcher(zim) suggestion = suggestion_searcher.suggest(suggestion_string) assert suggestion.getEstimatedMatches() == suggestion_count assert list(suggestion.getResults(0, suggestion_count)) == suggestion_result @skip_if_offline @pytest.mark.parametrize( *parametrize_for( [ "filename", "test_path", "test_title", "test_mimetype", "test_size", "test_content_includes", ] ) ) def test_reader_get_entries( all_zims, filename, test_path, test_title, test_mimetype, test_size, test_content_includes, ): zim = Archive(all_zims / filename) # entries with pytest.raises(KeyError): zim.get_entry_by_path("___missing") if test_path: assert zim.has_entry_by_path(test_path) entry = zim.get_entry_by_path(test_path) assert entry.title == test_title assert entry.path == test_path assert test_path in str(entry) assert test_title in str(entry) item = entry.get_item() assert item.title == test_title assert item.path == test_path assert test_path in str(item) assert test_title in str(item) assert item.mimetype == test_mimetype assert item.size == test_size assert isinstance(item.content, memoryview) assert test_content_includes in bytes(item.content).decode("UTF-8") with pytest.raises(KeyError): zim.get_entry_by_title("___missing") # example.zim cannot be queried by title as all its entries have been created # with empty titles but the ZIM contains a v1 title listing. if test_title and filename != "example.zim": assert zim.has_entry_by_title(test_title) assert zim.get_entry_by_title(test_title).path == entry.path @skip_if_offline @pytest.mark.parametrize( *parametrize_for(["filename", "test_redirect", "test_redirect_to"]) ) def test_reader_redirect(all_zims, filename, test_redirect, test_redirect_to): zim = Archive(all_zims / filename) if test_redirect: assert zim.get_entry_by_path(test_redirect).is_redirect if test_redirect_to: target_entry = zim.get_entry_by_path(test_redirect) assert target_entry.get_redirect_entry().path == test_redirect_to # make sure get_item resolves it assert target_entry.get_item().path == test_redirect_to # should be last redirect assert target_entry.get_redirect_entry().is_redirect is False with pytest.raises(RuntimeError): target_entry.get_redirect_entry().get_redirect_entry() @skip_if_offline @pytest.mark.parametrize(*parametrize_for(["filename"])) def test_reader_by_id(all_zims, filename): zim = Archive(all_zims / filename) # test index access for index in range(0, zim.entry_count - 1): assert zim._get_entry_by_id(index)._index == index assert zim._get_entry_by_id(index).get_item()._index >= 0 @skip_if_offline def test_archive_equality(all_zims): class Different: def __init__(self, filename): self.filename = filename class Sub(Archive): pass class Sub2(Archive): @property def filename(self): return 1 fpath1 = all_zims / "zimfile.zim" fpath2 = all_zims / "example.zim" zim = Archive(fpath1) assert zim != Archive(fpath2) assert zim == Archive(fpath1) assert zim != Different(fpath1) assert zim == Sub(fpath1) assert zim != Sub2(fpath1) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������././@PaxHeader��������������������������������������������������������������������������������������0000000�0000000�0000000�00000000026�00000000000�010213� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������22 mtime=1728999045.0 ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������libzim-3.6.0/tests/test_libzim_version.py�����������������������������������������������������������0000644�0001751�0000177�00000001664�14703467205�020240� 0����������������������������������������������������������������������������������������������������ustar�00runner��������������������������docker�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������import re import sys from libzim.version import ( # pyright: ignore [reportMissingModuleSource] get_libzim_version, get_versions, print_versions, ) def test_version_print_version_with_stdout(capsys): print_versions() print("", file=sys.stdout, flush=True) stdout, stderr = capsys.readouterr() assert len(stdout) != 0 def test_version_print_version_with_stderr(capsys): print_versions(sys.stderr) print("", file=sys.stderr, flush=True) stdout, stderr = capsys.readouterr() assert len(stderr) != 0 def test_get_versions(): versions = get_versions() assert versions assert "libzim" in versions assert len(versions.keys()) > 1 for library, version in versions.items(): assert isinstance(library, str) assert isinstance(version, str) def test_get_libzim_version(): # libzim uses semantic versioning assert re.match(r"\d+\.\d+\.\d+", get_libzim_version()) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������