From a84fc13436e057c3abb1b44f001959b3f8b67ff3 Mon Sep 17 00:00:00 2001 From: ti-oluwa <105179638+ti-oluwa@users.noreply.github.com> Date: Sun, 9 Jun 2024 16:50:07 +0100 Subject: [PATCH] New release: Code refactoring, performance optimizations and bug fixes --- LICENSE | 695 +------------------------- README.md | 104 ++-- dist/tranzlate-0.0.2-py3-none-any.whl | Bin 0 -> 9608 bytes dist/tranzlate-0.0.2.tar.gz | Bin 0 -> 11496 bytes pyproject.toml | 10 +- requirements.txt | 1 - tests/fixtures/text.html | 19 + tests/fixtures/text.txt | 17 + tests/test_translator.py | 33 +- tranzlate/__init__.py | 9 +- tranzlate/translator.py | 493 +++++++++--------- 11 files changed, 355 insertions(+), 1026 deletions(-) create mode 100644 dist/tranzlate-0.0.2-py3-none-any.whl create mode 100644 dist/tranzlate-0.0.2.tar.gz create mode 100644 tests/fixtures/text.html create mode 100644 tests/fixtures/text.txt diff --git a/LICENSE b/LICENSE index f288702..a6c17fa 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,21 @@ - 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 -. +MIT License + +Copyright (c) 2024 Daniwl Toluwalase Afolayan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index da77457..28a0dda 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ ## tranzlate -A wrapper around the translators package by UlionTse that enables multilingual translation of text, files, markup and BeautifulSoup objects. +A wrapper around the [`translators`](https://pypi.org/project/translators/) package, providing a simpler interface for the translation of text, files, markup and BeautifulSoup. ## Installation @@ -12,9 +12,11 @@ pip install tranzlate ## Usage -### Create a Translator +> Ensure you have `beautifulsoup4` installed if you want to translate markup or BeautifulSoup. Run `pip install beautifulsoup4` in your terminal. -The `Translator` class is the main interface for the package. It can be used to translate text, files, markup and BeautifulSoup objects. To create an instance of the `Translator` class, simply import the `tranzlate` package and instantiate the `Translator` class: +### Create a translator + +The `Translator` class is the main interface for the package. It can be used to translate text, bytes, files, markup and BeautifulSoup. To create an instance of the `Translator` class, simply import the `tranzlate` package and instantiate a `Translator`: ```python import tranzlate @@ -22,7 +24,7 @@ import tranzlate translator = tranzlate.Translator() ``` -### Use a Custom Translation Engine +### Use a custom translation engine By default, the `Translator` class uses Bing Translator as its translation engine. Based on test results, Bing is the most reliable translation engine. However, you can use any translation engine that is supported by the translators package by passing the name of the engine to the `Translator` class on instantiation: @@ -31,7 +33,7 @@ In this example, we will use Google Translate as our translation engine: ```python import tranzlate -translator = tranzlate.Translator('google') +google = tranzlate.Translator('google') ``` To get a list of all supported translation engines: @@ -45,148 +47,140 @@ print(tranzlate.Translator.engines()) # ['bing', 'google', 'yandex', 'baidu', 'sogou', 'tencent', 'deepl', 'alibaba', ...] ``` -### Detect Language +### Detect language ```python import tranzlate -translator = tranzlate.Translator() text = 'Good Morning!' -detected_lang = translator.detect_language(text) -print(detected_lang) +language = tranzlate.Translator.detect_language(text) +print(language) # Output: en ``` -### Translate Text, Markup and BeautifulSoup Objects +### Translate text, bytes, markup and BeautifulSoup -To translate text, markup or a soup, you can use the `translate` method of the `Translator` class. The `translate` method is a general purpose method that can be used to translate text, markup and BeautifulSoup objects. +Translate text, markup or a soup using the `translate` method of the `Translator` class. The `translate` method is a general purpose method that can be used to translate text, bytes and markup. -#### Translate Text +#### Translate text/bytes ```python import tranzlate -translator = tranzlate.Translator() - +bing = tranzlate.Translator("bing") text = 'Good Morning!' -translation = translator.translate(text, target_lang='yo') +translation = bing.translate(text, target_lang='yo') print(translation) # Output: Eku ojumo! ``` -#### Translate Markup +#### Translate markup ```python import tranzlate -translator = tranzlate.Translator() +bing = tranzlate.Translator("bing") markup = '

Good Morning!

' -translated_markup = translator.translate(markup, target_lang='yo', is_markup=True) +translated_markup = bing.translate(markup, target_lang='yo', is_markup=True) print(translated_markup) # Output:

Eku ojumo!

``` -#### Translate BeautifulSoup Objects +#### Translate BeautifulSoup ```python import tranzlate from bs4 import BeautifulSoup -translator = tranzlate.Translator() - +baidu = tranzlate.Translator("baidu") markup = '

Good Morning!

' soup = BeautifulSoup(markup, 'html.parser') -translated_soup = translator.translate(soup, target_lang='yo') +translated_soup = baidu.translate_soup(soup, target_lang='fr') ``` However, there are specialized methods for translating text, markup and BeautifulSoup objects. These methods are `translate_text`, `translate_markup` and `translate_soup` respectively. -### Translate Files +### Translate files -To translate files, we use the `translate_file` method of the `Translator` class. +To translate files, we use the `translate_file` method. ```python import tranzlate -translator = tranzlate.Translator() -translated_file = translator.translate_file('path/to/file.txt', src_lang="en", target_lang='yo') +bing = tranzlate.Translator() # Bing is used by default +translated_file = bing.translate_file('path/to/file.txt', src_lang="en", target_lang='yo') ``` It is advisable to specify the source language when performing translations as it helps the translation engine to provide more accurate translations. -### Use a Proxy +### Use a proxy -To use a proxy, simply pass the proxy to the `Translator` class on instantiation: +To use a proxy, simply pass your proxies on translation: ```python import tranzlate -translator = tranzlate.Translator() +deepl = tranzlate.Translator("deepl") text = 'Good Morning!' -translation = translator.translate(text, target_lang='yo', proxies={'https': 'https://:'}) +translation = deepl.translate(text, target_lang='yo', proxies={'https': 'https://:'}) print(translation) ``` -### Other Methods - -#### Get Supported Languages - -To get a list of all supported (source) languages by the translator's engine: +### Other methods ```python import tranzlate -translator = tranzlate.Translator() -print(translator.supported_languages) +google = tranzlate.Translator("google") +bing = tranzlate.Translator("bing") ``` -#### Check if a Language is Supported +#### Get supported languages -To check if a (source) language is supported by the translator's engine: +Get a list of all supported (source) languages by the translator's engine: ```python -import tranzlate +print(google.supported_languages) +``` -translator = tranzlate.Translator() -is_supported = translator.is_supported_language('yo') +#### Check if a language is supported + +Check if a (source) language is supported by the translator's engine: + +```python +is_supported = google.supports_language('yo') print(is_supported) # Output: True ``` -#### Check if a Language Pair is Supported +#### Check if a language pair is supported -To check if a language pair is supported by the translator's engine: +Check if a language pair is supported by the translator's engine: ```python -import tranzlate - -translator = tranzlate.Translator() -is_supported = translator.is_supported_pair(src_lang='en', target_lang='yo') +is_supported = bing.supports_pair(src_lang='en', target_lang='yo') print(is_supported) # Output: True ``` -#### Get a List of Supported Target Languages for a Source Language +#### Get a list of supported target languages for a source language -To get a list of supported target languages for a source language: +Get a list of supported target languages for a source language: ```python -import tranzlate - -translator = tranzlate.Translator() -supported_target_languages = translator.get_supported_target_languages('en') +supported_target_languages = bing.get_supported_target_languages('en') print(supported_target_languages) ``` ### Testing -To run the tests, simply run the following command in the root directory of your cloned repository: +To run tests, simply run the following command in the root directory of your cloned repository: ```bash python -m unittest discover tests "test_*.py" diff --git a/dist/tranzlate-0.0.2-py3-none-any.whl b/dist/tranzlate-0.0.2-py3-none-any.whl new file mode 100644 index 0000000000000000000000000000000000000000..73a5704d100b558e6299b002c7e6d9ae5209ef12 GIT binary patch literal 9608 zcmaKyb8u(Nw#R?5?POxxPA0Z(+s?!j+n(6Y#F*H&ZQI71`(C|w?wPvp?5?h^{$qct z*Y34;uU_?)mjVGr1pok$fYrbubvz@#llI>;6d(Wq?f2;HXkhDMZQyJ|ucv2WYvHV? zM`!Qu58=xS-Oz~R`t=!(`Nii=7%qpa zfatTNiF?1tzBAsoE~HOFYrv)9lWL9CkW=Da)Xqxf`YqEDjQs!EJ6@fv=2Tr4HU8Vy zWiS8$<8StwxEYz)J6qVy=aK)2t=lJ z05qMafxH2bNR_36U)VJI!8NVrI8`77q(l6zt~Zi1&r=StR8Bp5L+)Kc4dtb27L0j5 z&2j{4YVZ5*9g?I|IUR;EkMn3vh7sfKB3J%CJk%|TcJ6VKI`a}wIWHUbJ5*uNULx0y zk^H^NQO9WklR6Kx!aZA8xhM5Eq8nJyiNIL!4SR(V%g2Yf6Vvt*OF!;3v+p^>t~yI) z?hvPSxFNQL+UTdR_YISua9#aMx6`zkc_vjH@sLtcTA&Wpj6i7`XwGGm?=3FJsfIRZ z{gc*9w)!2}B{l08hJxd2uQ0V4(OY{`5K?xjWm9|UQyMX+1H_0G{q)#2F8djiI}*j! z2`yPWm8OO9v<@h3iQotdl6)h5;_)ZQQ(eN0DK5Joi47zcl|u1uf!6l0M&J$L?BUb! z+`$3lxCvjYB@$XfKgHW_BW)$^2|G{U2M3d#e>^p`EyTkbFlQN5SL_-mWS8=d*$fq& z6Zh=?I!2=1Y)#$vx|a{;sr`l9L#7d99YLRh_A%IJQkO*JU3<>7V)SD|sij6gDv=@Z zOhV#mOe8WP`Wru6$b~l3uVojRTG2TVM;3yV)e7`z z#Z+M4mfpj$>#g3JHH)9(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vCD*J~B zbLC2VIR@XXM@KQor!2BEaR!Mrw}ST%V4#n19UiAw5fW8dZV$EcGpdW4(m|hi?yy*a zn4RP`n}j7Su;d<$kCc6*aZd@7I z@K2#M6LoL~j5#Ch`NacIvyzpKSzVXhJ*T^haUI1+%NV!S53IhBg8-1Z6rTgMOccg5zY7w6|;5Z!%R3Dp>+VN{23&?z`wlvZ@FU>toL3m;Rvz+wWJ z0tA;5tCfp;+c8pE+uYi$U?)xMptiWk1CBGnCFzj0&97fH1z)(9V&F;r5U6ce_OcS* zCbp0|U4Q0?EikCKiwezg5>|!{QMu}|GQ8AiTg8+{|je>`A@k2P3r&T{rQvli>F8MPrU#B zW&8>IGqC@HJ^dr>Z(;r?^v~e_UueCb#P1vV|NjC1C)DMoz`+0Y2ITLi{d?EYiT^eG EFWYCiw*UYD literal 0 HcmV?d00001 diff --git a/dist/tranzlate-0.0.2.tar.gz b/dist/tranzlate-0.0.2.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..baf08948ec6b2904b0a44d36d9e92e7708446fb4 GIT binary patch literal 11496 zcma*tV{j!*_$c^T6XV3TZB1-vV%z4#nV558PIBU8Vsm2Kwr%6wckljh)qdEj-49*W zUG-Fd>8c0SKhjtP1oJ6ND=4sso2k=J2U8DAW;PZ!77i8d?tJ1JEW!yJjj+mjnkBdP`sa!n~uN;DyN4yQoCdt^bnOPwu8!?Q9#M# z7CDWY*^q0WTzck?_|o)4&lD0Dp#oS`d~r^FqRcKqs# zBp2zuW7BN*3-2OqpBm{?hV|ofIlh@AYQ5%rl!)TJO|24O#j$UJZL=UgLswVEKTuYuCb>+ayA^w&J)lAt-Oib~)GF$r<~TQB}c zb<3(s*S$4u%@lqLpD>>YI5Sts6nngUkiNCDCtKMH!S?h$}OE49E3tdSy28=2xz; zpwAc4x?VYPXDDh8Ma;$R=y;xrpGsbCgEj3mTH?-bA!X0y&g?zqEa2h%_WsvaERUd& zkL%4tlwB?a-U&$>7D9dAAL3n3hg*m*@Jpw+T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@k0T#v%RP}i(J)O>A<dA|SrR^5UkRt)nh!fs#>V6nKIWc5=Z}t^mmQx) zH5c6#pWSQVztf~aU{gPE=`H=)O>C0&D+Yf6?0S;G9om zQKo>jd+^(n^3zAR;cC$K_DiXfg#BSjK8|tO6W9)1^8`M-r@jQ|RU#X literal 0 HcmV?d00001 diff --git a/pyproject.toml b/pyproject.toml index 6751326..ee00813 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,37 +14,33 @@ authors = [ maintainers = [ { name="ti-oluwa", email="tioluwa.dev@gmail.com" }, ] -description = "Multilingual translation of text, files, markup and BeautifulSoup objects." +description = "Translate text, files, markup and BeautifulSoup." keywords = [ "translate", "translation", "google translate", "bing translate", - "yandex translate", "translate text", "translate files", "translate markup", "translate html", "translate xml", - "translate BeautifulSoup", + "beautifulsoup4", "detect language", ] readme = "README.md" requires-python = ">=3.7" classifiers = [ "Programming Language :: Python :: 3", - "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", + "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Development Status :: 4 - Beta", "Intended Audience :: Developers", - "Topic :: Software Development :: Libraries :: Python Modules", - "Topic :: Utilities", "Natural Language :: English", "Typing :: Typed", ] dependencies = [ "translators==5.8.9", - "beautifulsoup4==4.12.2", "simple_file_handler>=0.0.1", ] diff --git a/requirements.txt b/requirements.txt index 0b01b27..859314e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,2 @@ translators==5.8.9 -beautifulsoup4==4.12.2 simple_file_handler>=0.0.1 diff --git a/tests/fixtures/text.html b/tests/fixtures/text.html new file mode 100644 index 0000000..927636a --- /dev/null +++ b/tests/fixtures/text.html @@ -0,0 +1,19 @@ + + + + + + Test Translation + + +

Once upon a time, in a land far, far away, there was a small village nestled among the rolling hills and verdant valleys. The villagers were known for their hard work, kindness, and the vibrant tapestry of stories that wove through their daily lives. One such story was about a wise old woman named Elara who lived on the edge of the village in a quaint little cottage.

+

Elara was known throughout the land for her vast knowledge and gentle wisdom. People from neighboring villages would travel great distances to seek her counsel. She had a gift for understanding the language of nature and could often be found tending to her garden, where the flowers bloomed more brightly and the herbs grew more fragrant under her care.

+

One day, a young girl named Mira, who lived in the village, found herself in need of guidance. She had come to a crossroads in her life and felt lost and uncertain about which path to take. Her parents suggested she visit Elara, and so, with a hopeful heart, Mira set off towards the old woman's cottage.

+

As Mira approached the cottage, she was greeted by the sight of Elara gently coaxing a song from a flute carved from a piece of willow. The music seemed to weave itself into the very air, carrying with it a sense of peace and clarity. Elara looked up and smiled warmly at Mira, inviting her to sit on a bench beneath the shade of an ancient oak tree.

+

"Tell me, child, what troubles you?" Elara asked, her voice as soothing as the melody she had just played.

+

Mira took a deep breath and poured out her heart to Elara, explaining her fears and doubts about the future. Elara listened patiently, her eyes never leaving Mira's face. When Mira had finished, Elara nodded thoughtfully.

+

"Life is much like a garden," Elara began. "It requires patience, care, and the willingness to embrace both the sunshine and the storms. Each path you consider is a seed, full of potential. It is up to you to nurture it, to provide it with the light of your dreams and the water of your efforts. Some seeds will grow into magnificent trees, others into delicate flowers, and some may not grow at all. But each has its place and purpose."

+

Mira felt a sense of calm wash over her as she listened to Elara's words. She realized that there was no single right path, but rather, a journey of growth and discovery. With newfound resolve, she thanked Elara and made her way back to the village, ready to plant the seeds of her future with hope and determination.

+

Years passed, and Mira grew into a strong, confident woman. She often thought of Elara and the wisdom she had shared. The village continued to thrive, each generation carrying forward the stories and lessons of those who came before. And so, the tapestry of life in that small village remained vibrant and ever-changing, a testament to the enduring power of wisdom, kindness, and the human spirit.

+ + diff --git a/tests/fixtures/text.txt b/tests/fixtures/text.txt new file mode 100644 index 0000000..93fa989 --- /dev/null +++ b/tests/fixtures/text.txt @@ -0,0 +1,17 @@ +Once upon a time, in a land far, far away, there was a small village nestled among the rolling hills and verdant valleys. The villagers were known for their hard work, kindness, and the vibrant tapestry of stories that wove through their daily lives. One such story was about a wise old woman named Elara who lived on the edge of the village in a quaint little cottage. + +Elara was known throughout the land for her vast knowledge and gentle wisdom. People from neighboring villages would travel great distances to seek her counsel. She had a gift for understanding the language of nature and could often be found tending to her garden, where the flowers bloomed more brightly and the herbs grew more fragrant under her care. + +One day, a young girl named Mira, who lived in the village, found herself in need of guidance. She had come to a crossroads in her life and felt lost and uncertain about which path to take. Her parents suggested she visit Elara, and so, with a hopeful heart, Mira set off towards the old woman's cottage. + +As Mira approached the cottage, she was greeted by the sight of Elara gently coaxing a song from a flute carved from a piece of willow. The music seemed to weave itself into the very air, carrying with it a sense of peace and clarity. Elara looked up and smiled warmly at Mira, inviting her to sit on a bench beneath the shade of an ancient oak tree. + +"Tell me, child, what troubles you?" Elara asked, her voice as soothing as the melody she had just played. + +Mira took a deep breath and poured out her heart to Elara, explaining her fears and doubts about the future. Elara listened patiently, her eyes never leaving Mira's face. When Mira had finished, Elara nodded thoughtfully. + +"Life is much like a garden," Elara began. "It requires patience, care, and the willingness to embrace both the sunshine and the storms. Each path you consider is a seed, full of potential. It is up to you to nurture it, to provide it with the light of your dreams and the water of your efforts. Some seeds will grow into magnificent trees, others into delicate flowers, and some may not grow at all. But each has its place and purpose." + +Mira felt a sense of calm wash over her as she listened to Elara's words. She realized that there was no single right path, but rather, a journey of growth and discovery. With newfound resolve, she thanked Elara and made her way back to the village, ready to plant the seeds of her future with hope and determination. + +Years passed, and Mira grew into a strong, confident woman. She often thought of Elara and the wisdom she had shared. The village continued to thrive, each generation carrying forward the stories and lessons of those who came before. And so, the tapestry of life in that small village remained vibrant and ever-changing, a testament to the enduring power of wisdom, kindness, and the human spirit. diff --git a/tests/test_translator.py b/tests/test_translator.py index dfd33fc..2e64b6e 100644 --- a/tests/test_translator.py +++ b/tests/test_translator.py @@ -7,6 +7,7 @@ from tranzlate.exceptions import TranslationError, UnsupportedLanguageError + class TestTranslator(unittest.TestCase): """Test case for the Translator class.""" example_text = "Yoruba is a language spoken in West Africa, most prominently Southwestern Nigeria." @@ -43,8 +44,6 @@ def test_detect_language_with_empty_text(self): def test_translate_on_auto(self): with self.assertRaises(TypeError): self.translator.translate(None) - with self.assertRaises(ValueError): - self.translator.translate("") translation = self.translator.translate(self.example_text, target_lang="yo") self.assertIsInstance(translation, str) self.assertNotEqual(translation, self.example_text) @@ -68,37 +67,33 @@ def test_translate_with_empty_target_language(self): def test_translate_with_unsupported_source_language(self): with self.assertRaises(UnsupportedLanguageError): - self.translator.translate(self.example_text, "en-xy", "yo") + self.translator.translate(self.example_text, "xyz", "yo") def test_translate_with_unsupported_target_language(self): with self.assertRaises(UnsupportedLanguageError): - self.translator.translate(self.example_text, "en", "yo-xy") + self.translator.translate(self.example_text, "en", "xyz") def test_translate_with_the_same_source_and_target_language(self): - with self.assertRaises(TranslationError): + with self.assertRaises(ValueError): self.translator.translate(self.example_text, "en", "en") - def test_is_supported_language(self): - self.assertTrue(self.translator.is_supported_language("en")) - self.assertFalse(self.translator.is_supported_language("en-xy")) + def test_supports_language(self): + self.assertTrue(self.translator.supports_language("en")) + self.assertFalse(self.translator.supports_language("xyz")) with self.assertRaises(TypeError): - self.translator.is_supported_language(None) - with self.assertRaises(ValueError): - self.translator.is_supported_language("") + self.translator.supports_language(None) def test_get_supported_target_languages(self): self.assertIsInstance(self.translator.get_supported_target_languages("en"), list) self.assertTrue(len(self.translator.get_supported_target_languages("en")) > 0) - self.assertIsInstance(self.translator.get_supported_target_languages("en-xy"), list) - self.assertTrue(len(self.translator.get_supported_target_languages("en-xy")) == 0) + self.assertIsInstance(self.translator.get_supported_target_languages("xyz"), list) + self.assertTrue(len(self.translator.get_supported_target_languages("xyz")) == 0) with self.assertRaises(TypeError): self.translator.get_supported_target_languages(None) - with self.assertRaises(ValueError): - self.translator.get_supported_target_languages("") - def test_is_supported_pair(self): - self.assertFalse(self.translator.is_supported_pair("en", "en")) - self.assertTrue(self.translator.is_supported_pair("en", "yo")) + def test_supports_pair(self): + self.assertFalse(self.translator.supports_pair("en", "en")) + self.assertTrue(self.translator.supports_pair("en", "yo")) def test_properties(self): self.assertIsInstance(self.translator.server, TranslatorsServer) @@ -136,4 +131,4 @@ def test_translate_soup(self): if "__name__" == "__main__": unittest.main() -# RUN WITH 'python -m unittest discover tests "test_*.py"' from project's root directory +# Run with 'python -m unittest discover tests "test_*.py"' from project's root directory diff --git a/tranzlate/__init__.py b/tranzlate/__init__.py index 403eea6..9b5a5b2 100644 --- a/tranzlate/__init__.py +++ b/tranzlate/__init__.py @@ -1,13 +1,12 @@ """ #### tranzlate -Simple python package for multi-lingual translation of text, files, markup and BeautifulSoup objects. +Translate text, files, markup and BeautifulSoup. @Author: Daniel T. Afolayan (ti-oluwa.github.io) """ -from .translator import Translator +from .translator import Translator, add_translatable_html_tag -__all__ = ["Translator"] -__version__ = "0.0.1" -__author__ = "Daniel T. Afolayan" +__all__ = ["Translator", "add_translatable_html_tag"] +__version__ = "0.0.2" diff --git a/tranzlate/translator.py b/tranzlate/translator.py index 83e73f7..18282c8 100644 --- a/tranzlate/translator.py +++ b/tranzlate/translator.py @@ -3,21 +3,22 @@ """ import functools import sys -from typing import Callable, Dict, List, Tuple, IO -from array import array +from typing import Callable, Dict, Generator, List, Tuple, IO, Any import time -import copy import random -from bs4 import BeautifulSoup -from bs4.element import Tag -from concurrent.futures import ThreadPoolExecutor from translators.server import TranslatorsServer, tss, Tse import simple_file_handler as sfh +import itertools +from asgiref.sync import sync_to_async +import asyncio +import textwrap from .exceptions import TranslationError, UnsupportedLanguageError +__all__ = ["Translator", "add_translatable_html_tag"] + _translatable_tags = ( 'h1', 'u', 's', 'abbr', 'del', 'pre', 'h5', 'sub', 'kbd', 'li', 'dd', 'textarea', 'dt', 'input', 'em', 'sup', 'label', 'button', 'h6', @@ -26,45 +27,23 @@ 'small', 'b', 'q', 'option', 'code', 'h2', 'a', 'strong', 'span', ) - -def _slice_iterable(iter: List | str | Tuple | array, slice_size: int): - ''' - Slices an iterable into smaller iterables of size `slice_size` - - Args: - iter (Iterable): The iterable to slice. - slice_size (int): The size of each slice - ''' - if not isinstance(iter, (list, tuple, str, array)): - raise TypeError('Invalid argument type for `iter`') - if not isinstance(slice_size, int): - raise TypeError('Invalid argument type for `slice_size`') - if slice_size < 1: - raise ValueError('`slice_size` should be greater than 0') - - return [ iter[ i : i + slice_size ] for i in range(0, len(iter), slice_size) ] +def add_translatable_html_tag(tag: str) -> None: + """Add a new HTML tag name to the global list of translatable HTML elements""" + global _translatable_tags + if tag in _translatable_tags: + return + _translatable_tags = (tag, *_translatable_tags) + return None -class Translator: +class Translator(object): """ - A Wrapper around the `TranslatorServer` class from the `translators` package by UlionTse. + Wraps around the `TranslatorServer` class from the `translators` package by UlionTse, + providing a simpler interface for translation. Read more about the `translators` package here: https://pypi.org/project/translators/ - - Usage Example: - - ```python - import tranzlate - - translator = tranzlate.Translator() - text = "Yoruba is a language spoken in West Africa, most prominently Southwestern Nigeria." - translation = translator.translate(text, "en", "yo") - print(translation) - - # Output: "Yorùbá jẹ́ èdè tí ó ń ṣe àwọn èdè ní ìlà oòrùn Áfríkà, tí ó wà ní orílẹ̀-èdè Gúúsù Áfríkà." - ``` """ _server = tss @@ -73,14 +52,13 @@ def __init__(self, engine: str = "bing"): Create a Translator instance. :param engine (str): Name of translation engine to be used. Defaults to "bing" - as it is proven to be the most reliable. + as it has been tested to be the most reliable. #### Call `Translator.engines` to get a list of supported translation engines. """ - if not engine in self.engines(): + if engine not in type(self).engines(): raise ValueError(f"Invalid translation engine: {engine}") self.engine_name = engine - self._cache = {} return None @@ -98,16 +76,19 @@ def engine(self) -> Tse: @property def engine_api(self) -> Callable: - """Method used by the translation engine to make translation requests""" + """API used by the translation engine to carryout translations""" return getattr(self.server, f"{self.engine_name}") @property - def input_limit(self) -> int: + def input_limit(self) -> int | None: """ The maximum number of characters that can be translated at once. This is dependent on the translation engine being used. """ - return self.engine.input_limit + try: + return self.engine.input_limit + except Exception: + return None @functools.cached_property def language_map(self) -> Dict: @@ -117,9 +98,10 @@ def language_map(self) -> Dict: """ try: return self.server.get_languages(self.engine_name) - except: + except BaseException: return {} + @property def supported_languages(self) -> List: """ @@ -135,7 +117,45 @@ def engines(cls) -> List[str]: return cls._server.translators_pool - def is_supported_language(self, lang_code: str) -> bool: + @classmethod + def detect_language(cls, text: str) -> Dict: + """ + Detects the language of the specified text. + + :param text (str): The text to detect the language of. + :return: A dictionary containing the language code and confidence score. + + Bing is the preferred translation engine for this method as it works well for + this purpose. However, it is not guaranteed to work always. + + Usage Example: + ```python + import tranzlate + + text = "Yoruba is a language spoken in West Africa, most prominently Southwestern Nigeria." + language = tranzlate.Translator.detect_language(text) + print(language) + + # Output: {'language': 'en', 'score': 1.0} + ``` + """ + if not isinstance(text, str): + raise TypeError("Invalid type for `text`") + if not text: + raise ValueError("`text` cannot be empty") + try: + result: Dict[str, Any] = cls._server.translate_text( + query_text=text, + translator="bing", + is_detail_result=True + ) + return result.get('detectedLanguage', {}) + except Exception as exc: + sys.stderr.write(f"Error detecting language: {exc}\n") + return {} + + + def supports_language(self, lang_code: str) -> bool: ''' Check if the source language with the specified language code is supported by the translator's engine. @@ -145,10 +165,8 @@ def is_supported_language(self, lang_code: str) -> bool: ''' if not isinstance(lang_code, str): raise TypeError("Invalid type for `lang_code`") - lang_code = lang_code.strip().lower() - if not lang_code: - raise ValueError("`lang_code` cannot be empty") + lang_code = lang_code.strip().lower() return lang_code in self.supported_languages @@ -161,12 +179,11 @@ def get_supported_target_languages(self, src_lang: str) -> List: """ if not isinstance(src_lang, str): raise TypeError("Invalid type for `src_lang`") - if not src_lang: - raise ValueError("Invalid value for `src_lang`") + return self.language_map.get(src_lang, []) - def is_supported_pair(self, src_lang: str, target_lang: str) -> bool: + def supports_pair(self, src_lang: str, target_lang: str) -> bool: """ Check if the source language and target language pair is supported by the translation engine. @@ -178,45 +195,11 @@ def is_supported_pair(self, src_lang: str, target_lang: str) -> bool: return src_lang != target_lang and target_lang in self.get_supported_target_languages(src_lang) - def detect_language(self, _s: str) -> Dict: + def check_languages(self, src_lang: str, target_lang: str) -> Tuple[str, str]: """ - Detects the language of the specified text. - - :param _s (str): The text to detect the language of. - :return: A dictionary containing the language code and confidence score. - - bing is the preferred translation engine for this method as it works well for - this purpose. However, it is not guaranteed to work well always. - - Usage Example: - ```python - import tranzlate - - translator = tranzlate.Translator() - text = "Yoruba is a language spoken in West Africa, most prominently Southwestern Nigeria." - detected_lang = translator.detect_language(text) - print(detected_lang) - - # Output: {'language': 'en', 'score': 1.0} - ``` + Performs necessary 'compatibility' checks on the source and target language. + Raises any of `TypeError`, `ValueError` or `UnsupportedLanguageError`, if there is any issue """ - if not isinstance(_s, str): - raise TypeError("Invalid type for `_s`") - if not _s: - raise ValueError("`_s` cannot be empty") - try: - result = self.server.translate_text( - query_text=_s, - translator="bing", - is_detail_result=True - ) - return result.get('detectedLanguage', {}) if result else {} - except Exception as exc: - sys.stderr.write(f"Error detecting language: {exc}\n") - return {} - - - def _check_lang_codes(self, src_lang: str, target_lang: str) -> None: if not isinstance(src_lang, str): raise TypeError("Invalid type for `src_lang`") if not isinstance(target_lang, str): @@ -227,52 +210,56 @@ def _check_lang_codes(self, src_lang: str, target_lang: str) -> None: raise ValueError("A target language must be provided") if src_lang == target_lang: - raise TranslationError("Source language and target language cannot be the same.") + raise ValueError("Source language and target language cannot be the same.") - if src_lang != 'auto' and not self.is_supported_language(src_lang): + if src_lang != 'auto' and not self.supports_language(src_lang): raise UnsupportedLanguageError( - message=f"Unsupported source language using translation engine, '{self.engine}'", + message=f"Unsupported source language using translation engine, '{self.engine_name}'", code=src_lang, engine=self.engine_name, code_type="source" ) if src_lang != "auto" and target_lang not in self.get_supported_target_languages(src_lang): raise UnsupportedLanguageError( - message=f"Unsupported target language for source language, '{src_lang}', using translation engine, '{self.engine}'", + message=f"Unsupported target language for source language, '{src_lang}', using translation engine, '{self.engine_name}'", code=target_lang, engine=self.engine_name, code_type="target" ) + return src_lang, target_lang def translate( - self, - content: str | bytes | BeautifulSoup, - src_lang: str = "auto", - target_lang: str = "en", - is_markup: bool = False, - encoding: str = "utf-8", - **kwargs - ) -> str | bytes | BeautifulSoup: + self, + content: str | bytes, + src_lang: str = "auto", + target_lang: str = "en", + *, + is_markup: bool = False, + encoding: str = "utf-8", + **kwargs + ) -> str | bytes: ''' Translate content from source language to target language. - :param content (str | bytes | BeatifulSoup): Content to be translated + :param content (str | bytes): Content to be translated :param src_lang (str, optional): Source language. Defaults to "auto". It is advisable to provide a source language to get more accurate translations. :param target_lang (str, optional): Target language. Defaults to "en". :param is_markup (bool, optional): Whether `content` is markup. Defaults to False. :param encoding (str, optional): The encoding of the content (for bytes content only). Defaults to "utf-8". - :param **kwargs: Keyword arguments to be passed to required translation method. + :param **kwargs: Keyword arguments to be passed to the translation server. + :kwarg timeout: float, default None. + :kwarg proxies: dict, default None. :return: Translated content. Usage Example: ```python import tranzlate - translator = tranzlate.Translator() + bing = tranzlate.Translator("bing") text = "Yoruba is a language spoken in West Africa, most prominently Southwestern Nigeria." - translation = translator.translate(text, "en", "yo") + translation = bing.translate(text, "en", "yo") print(translation) # Output: "Yorùbá jẹ́ èdè tí ó ń ṣe àwọn èdè ní ìlà oòrùn Áfríkà, tí ó wà ní orílẹ̀-èdè Gúúsù Áfríkà." @@ -286,13 +273,6 @@ def translate( encoding=encoding, **kwargs ) - elif isinstance(content, BeautifulSoup): - return self.translate_soup( - soup=content, - src_lang=src_lang, - target_lang=target_lang, - **kwargs - ) translation = self.translate_text( text=content.decode(encoding) if is_bytes else content, @@ -303,14 +283,13 @@ def translate( return translation.encode(encoding) if is_bytes else translation - # @functools.cache def translate_text( - self, - text: str, - src_lang: str="auto", - target_lang: str="en", - **kwargs - ) -> str: + self, + text: str, + src_lang: str="auto", + target_lang: str="en", + **kwargs + ) -> str: ''' Translate text from `src_lang` to `target_lang`. @@ -318,60 +297,59 @@ def translate_text( :param src_lang (str, optional): Source language. Defaults to "auto". It is advisable to provide a source language to get more accurate translations. :param target_lang (str, optional): Target language. Defaults to "en". - :param **kwargs: Keyword arguments to be passed to `server.translate_text`. - :kwarg is_detail_result: boolean, default False. - :kwarg professional_field: str, support baidu(), caiyun(), alibaba() only. + :param **kwargs: Keyword arguments to be passed to the translation server. :kwarg timeout: float, default None. :kwarg proxies: dict, default None. - :kwarg sleep_seconds: float, default random.random(). - :kwarg update_session_after_seconds: float, default 1500. - :kwarg if_use_cn_host: bool, default False. - :kwarg reset_host_url: str, default None. - :kwarg if_ignore_empty_query: boolean, default False. - :kwarg if_ignore_limit_of_length: boolean, default False. - :kwarg limit_of_length: int, default 5000. - :kwarg if_show_time_stat: boolean, default False. - :kwarg show_time_stat_precision: int, default 4. - :kwarg lingvanex_model: str, default 'B2C'. :return: Translated text. ''' if not isinstance(text, str): raise TypeError("Invalid type for `text`") if not text: - raise ValueError("`text` cannot be empty") + return text - self._check_lang_codes(src_lang, target_lang) - kwargs_ = {'if_ignore_empty_query': True} + src_lang, target_lang = self.check_languages(src_lang, target_lang) kwargs.pop('is_detail_result', None) - kwargs_.update(kwargs) + kwds = {**kwargs, 'if_ignore_empty_query': True} - def _translate(text: str): + def translate(text: str) -> str: + """Translate text using translation engine""" return self.engine_api( query_text=text, to_language=target_lang, from_language=src_lang, - **kwargs_ + **kwds ) + async_translate = sync_to_async(translate) + + def translate_in_chunks(text: str, chunksize: int) -> str: + tasks = list(map(async_translate, chunks(text, chunksize))) + async def execute_tasks() -> List[str]: + return await asyncio.gather(*tasks) + + translated_chunks = asyncio.run(execute_tasks()) + return "".join(translated_chunks) try: - chunks = _slice_iterable(text, self.input_limit - 1) - translated_chunks = list(map(_translate, chunks)) - translated_text = "".join(translated_chunks) - return translated_text - + input_limit = self.input_limit or 1000 + if len(text) > input_limit: + return translate_in_chunks(text, input_limit) + return translate(text) except Exception as exc: - raise TranslationError(exc.__str__()) + raise TranslationError(str(exc)) from exc def translate_file( - self, - filepath: str, - src_lang: str="auto", - target_lang: str="en", - **kwargs - ) -> IO: + self, + filepath: str, + src_lang: str="auto", + target_lang: str="en", + **kwargs + ) -> IO: ''' - Translates file from `src_lang` to `target_lang`. + Translates file from `src_lang` to `target_lang`. + This method replaces the file content the translation. + You may need to translate a duplicate if you do not want to modify + the original file. Supported file types include: .txt, .csv, .doc, .docx, .pdf, .md..., mostly files with text content. @@ -379,26 +357,15 @@ def translate_file( :param src_lang (str, optional): Source language. Defaults to "auto". It is advisable to provide a source language to get more accurate translations. :param target_lang (str, optional): Target language. Defaults to "en". - :param **kwargs: Keyword arguments to be passed to the `translate_text` method. - :kwarg professional_field: str, support baidu(), caiyun(), alibaba() only. + :param **kwargs: Keyword arguments to be passed to the translation server. :kwarg timeout: float, default None. :kwarg proxies: dict, default None. - :kwarg sleep_seconds: float, default random.random(). - :kwarg update_session_after_seconds: float, default 1500. - :kwarg if_use_cn_host: bool, default False. - :kwarg reset_host_url: str, default None. - :kwarg if_ignore_empty_query: boolean, default False. - :kwarg if_ignore_limit_of_length: boolean, default False. - :kwarg limit_of_length: int, default 5000. - :kwarg if_show_time_stat: boolean, default False. - :kwarg show_time_stat_precision: int, default 4. - :kwarg lingvanex_model: str, default 'B2C'. :return: Translated file. ''' - self._check_lang_codes(src_lang, target_lang) - kwargs_ = {'if_ignore_empty_query': True} + src_lang, target_lang = self.check_languages(src_lang, target_lang) + kwds = {'if_ignore_empty_query': True} kwargs.pop('is_detail_result', None) - kwargs_.update(kwargs) + kwds.update(kwargs) try: with sfh.FileHandler(filepath, exists_ok=True, not_found_ok=False) as file_handler: @@ -406,10 +373,10 @@ def translate_file( if not content: return file_handler.file - if file_handler.filetype in ['xhtml', 'htm', 'shtml', 'html', 'xml']: - translation = self.translate_markup(content, src_lang, target_lang, **kwargs_) + if file_handler.filetype in ('xhtml', 'htm', 'shtml', 'html', 'xml'): + translation = self.translate_markup(content, src_lang, target_lang, **kwds) else: - translation = self.translate_text(content, src_lang, target_lang, **kwargs_) + translation = self.translate_text(content, src_lang, target_lang, **kwds) file_handler.write_to_file(translation, write_mode='w+') return file_handler.file @@ -419,109 +386,100 @@ def translate_file( ) from exc - def _translate_soup_tag( - self, - tag: Tag, - src_lang: str = "auto", - target_lang: str = "en", - _ct: int = 0, - **kwargs - ): + def translate_tag( + self, + tag, + src_lang: str = "auto", + target_lang: str = "en", + **kwargs + ): ''' - Translates the text of a bs4.element.Tag object 'in place'. + Translates the text of a `bs4.element.Tag` object 'in place'. - NOTE: - * This function is not meant to be called directly. Use `translate_soup` instead. - * This function is recursive. - * This function modifies the element in place. - * Translations are cached by default to avoid repeated translations which can be costly. - - :param element (bs4.element.Tag): The tag whose text content is to be translated. + :param element (`bs4.element.Tag`): The tag whose text content is to be translated. :param src_lang (str, optional): Source language. Defaults to "auto". :param target_lang (str, optional): Target language. Defaults to "en". - :param _ct (int, optional): The number of times the function has been called recursively. Defaults to 0. - Do not pass this argument manually. + :return: The translated `bs4.element.Tag` ''' + from bs4.element import Tag + if not isinstance(tag, Tag): raise TypeError("Invalid type for `tag`") - if not isinstance(_ct, int): - raise TypeError("Invalid type for `_ct`") - - if tag.string and tag.string.strip(): - initial_string = copy.copy(tag.string) - cached_translation = self._cache.get(tag.string, None) - if cached_translation: - tag.string.replace_with(cached_translation) - else: - try: - translation = self.translate_text( - text=tag.string, - src_lang=src_lang, - target_lang=target_lang, - **kwargs - ) - tag.string.replace_with(translation) - - except Exception as exc: - error_ = TranslationError(f"Error translating tag: {exc}") - sys.stderr.write(f"{error_}\n") - # try again - _ct += 1 - # prevents the translation engine from blocking our IP address - time.sleep(random.random(2, 4) * _ct) - if _ct <= 3: - return self._translate_soup_tag(tag, src_lang, target_lang, _ct, **kwargs) - finally: - self._cache[initial_string] = translation - return None + + if not (tag.string and tag.string.strip()): + return tag + + translation = self.translate_text( + text=tag.string, + src_lang=src_lang, + target_lang=target_lang, + **kwargs + ) + tag.string.replace_with(translation) + return tag def translate_soup( - self, - soup: BeautifulSoup, - src_lang: str = "auto", - target_lang: str = "en", - thread: bool = True, - **kwargs - ) -> BeautifulSoup: + self, + soup, + src_lang: str = "auto", + target_lang: str = "en", + **kwargs + ): ''' - Translates the text of a BeautifulSoup object. + Translates the text of a `BeautifulSoup` object. - :param soup (BeautifulSoup): The BeautifulSoup object whose text is to be translated. + :param soup (`BeautifulSoup`): The `BeautifulSoup` object whose text is to be translated. :param src_lang (str, optional): Source language. Defaults to "auto". It is advisable to provide a source language to get more accurate translations. :param target_lang (str, optional): The target language for translation. Defaults to "en". - :param thread (bool, optional): Whether to use multi-threading to translate the text. Defaults to True. - :return: The translated BeautifulSoup object. + :return: The translated `BeautifulSoup` object. ''' + try: + from bs4 import BeautifulSoup + except ImportError: + raise ImportError( + '"bs4" is required to translate soup. Run `pip install beautifulsoup4` in your terminal to install it' + ) + if not isinstance(soup, BeautifulSoup): raise TypeError("Invalid type for `soup`") - self._check_lang_codes(src_lang, target_lang) - translatables = soup.find_all(_translatable_tags) - translatables = list(filter(lambda el: bool(el.string), translatables)) - if thread: - with ThreadPoolExecutor() as executor: - for tag_list in _slice_iterable(translatables, 50): - _ = executor.map( - lambda tag: self._translate_soup_tag(tag, src_lang, target_lang, **kwargs), - tag_list - ) - time.sleep(random.randint(3, 5)) - else: - for tag in translatables: - self._translate_soup_tag(tag, src_lang, target_lang, **kwargs) + + src_lang, target_lang = self.check_languages(src_lang, target_lang) + tags = soup.find_all(_translatable_tags) + tags = [tag for tag in tags if tag.string] + + def safe_translate_tag(*args, **kwargs): + """Ignores any exception that occurs during translation""" + try: + return self.translate_tag(*args, **kwargs) + except BaseException: + pass + + kwds = {**kwargs, "src_lang": src_lang, "target_lang": target_lang} + translate_tag = functools.partial(safe_translate_tag, **kwds) + async_translate_tag = sync_to_async(translate_tag) + # Translate tags in batches to avoid making excessive requests to translation server at once + for batch in itertools.batched(tags, 50): + tasks = list(map(async_translate_tag, batch)) + async def execute_tasks() -> List[str]: + return await asyncio.gather(*tasks) + + asyncio.run(execute_tasks()) + time.sleep(random.randint(1, 3)) return soup def translate_markup( - self, - markup: str | bytes, - src_lang: str = "auto", - target_lang: str = "en", - markup_parser: str = "lxml", - encoding: str = "utf-8", - **kwargs - ) -> str | bytes: + self, + markup: str | bytes, + src_lang: str = "auto", + target_lang: str = "en", + *, + markup_parser: str = "lxml", + encoding: str = "utf-8", + **kwargs + ) -> str | bytes: ''' Translates markup (html, xml, etc.) @@ -531,28 +489,33 @@ def translate_markup( :param target_lang (str, optional): Target language. Defaults to "en". :param markup_parser (str, optional): The (beautifulsoup) markup parser to use. Defaults to "lxml". :param encoding (str, optional): The encoding of the markup (for bytes markup only). Defaults to "utf-8". - :param **kwargs: Keyword arguments to be passed to the `translate_soup` method. - :kwarg thread: bool, default True. - :kwarg professional_field: str, support baidu(), caiyun(), alibaba() only. + :param kwargs: Keyword arguments to be passed to the translation server. :kwarg timeout: float, default None. :kwarg proxies: dict, default None. - :kwarg sleep_seconds: float, default random.random(). - :kwarg update_session_after_seconds: float, default 1500. - :kwarg if_use_cn_host: bool, default False. - :kwarg reset_host_url: str, default None. - :kwarg if_ignore_empty_query: boolean, default False. - :kwarg if_ignore_limit_of_length: boolean, default False. - :kwarg limit_of_length: int, default 5000. - :kwarg if_show_time_stat: boolean, default False. - :kwarg show_time_stat_precision: int, default 4. - :kwarg lingvanex_model: str, default 'B2C'. :return: Translated markup. ''' + try: + from bs4 import BeautifulSoup + except ImportError: + raise ImportError( + '"bs4" is required to translate soup. Run `pip install beautifulsoup4` in your terminal to install it' + ) + if not isinstance(markup, (str, bytes)): raise TypeError("Invalid type for `markup`") - + if not markup: + return markup + is_bytes = isinstance(markup, bytes) kwargs.pop('is_detail_result', None) soup = BeautifulSoup(markup, markup_parser, from_encoding=encoding if is_bytes else None) translated_markup = self.translate_soup(soup, src_lang, target_lang, **kwargs).prettify() - return translated_markup.encode('utf-8') if is_bytes else translated_markup + return translated_markup.encode(encoding) if is_bytes else translated_markup + + + +def chunks(text: str, size: int) -> Generator[str, Any, None]: + """Yields a chunk of the text on each iteration, respecting word boundaries.""" + wrapper = textwrap.TextWrapper(width=size, break_long_words=False, replace_whitespace=False) + for chunk in wrapper.wrap(text): + yield chunk