From b98b4fea5b7f1812c15ccae56876428247949aae Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Fri, 1 Mar 2019 21:11:13 +0100 Subject: [PATCH 001/120] Create LICENSE --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + 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 +. From 8e867400e49748f99cf42c11f80d84a484a22e93 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Fri, 1 Mar 2019 21:11:40 +0100 Subject: [PATCH 002/120] added dependencies and requirements --- dependencies.md | 3 +++ requirements.txt | 7 +++++++ 2 files changed, 10 insertions(+) create mode 100644 dependencies.md create mode 100644 requirements.txt diff --git a/dependencies.md b/dependencies.md new file mode 100644 index 0000000..f0980b7 --- /dev/null +++ b/dependencies.md @@ -0,0 +1,3 @@ +## Debian/Ubuntu + + tesseract-ocr libtesseract-dev libleptonica-dev libpython3-dev libzbar-dev diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..eb560f8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +python-telegram-bot +coloredlogs +pillow +watchdog +tesserocr +pydub +zbarlight \ No newline at end of file From c94ec8d5e5abb423dd1740aa53ab59754b9a3ac7 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Fri, 1 Mar 2019 21:12:03 +0100 Subject: [PATCH 003/120] added src --- src/antiflood/__init__.py | 5 + src/antiflood/antiflood.py | 93 +++ src/audiotools/__init__.py | 1 + src/audiotools/speech.py | 70 ++ src/config/__init__.py | 40 + src/database/__init__.py | 37 + src/database/db.py | 141 ++++ src/functional/__init__.py | 3 + src/main.py | 25 + src/metaclass/__init__.py | 1 + src/metaclass/singleton.py | 8 + src/phototools/__init__.py | 2 + src/phototools/ocr.py | 14 + src/phototools/qr.py | 18 + src/resources/__init__.py | 1 + src/resources/loader.py | 76 ++ src/tests/test_db.py | 35 + src/transcriberbot/__init__.py | 3 + src/transcriberbot/bot.py | 779 ++++++++++++++++++ src/transcriberbot/channel_command_handler.py | 16 + src/transcriberbot/tbfilters.py | 20 + src/translator/__init__.py | 1 + .../__pycache__/__init__.cpython-36.pyc | Bin 0 -> 234 bytes .../__pycache__/translator.cpython-36.pyc | Bin 0 -> 1130 bytes src/translator/translator.py | 43 + 25 files changed, 1432 insertions(+) create mode 100644 src/antiflood/__init__.py create mode 100644 src/antiflood/antiflood.py create mode 100644 src/audiotools/__init__.py create mode 100644 src/audiotools/speech.py create mode 100644 src/config/__init__.py create mode 100644 src/database/__init__.py create mode 100644 src/database/db.py create mode 100644 src/functional/__init__.py create mode 100644 src/main.py create mode 100644 src/metaclass/__init__.py create mode 100644 src/metaclass/singleton.py create mode 100644 src/phototools/__init__.py create mode 100644 src/phototools/ocr.py create mode 100644 src/phototools/qr.py create mode 100644 src/resources/__init__.py create mode 100644 src/resources/loader.py create mode 100644 src/tests/test_db.py create mode 100644 src/transcriberbot/__init__.py create mode 100644 src/transcriberbot/bot.py create mode 100644 src/transcriberbot/channel_command_handler.py create mode 100644 src/transcriberbot/tbfilters.py create mode 100644 src/translator/__init__.py create mode 100644 src/translator/__pycache__/__init__.cpython-36.pyc create mode 100644 src/translator/__pycache__/translator.cpython-36.pyc create mode 100644 src/translator/translator.py diff --git a/src/antiflood/__init__.py b/src/antiflood/__init__.py new file mode 100644 index 0000000..f5065ae --- /dev/null +++ b/src/antiflood/__init__.py @@ -0,0 +1,5 @@ +from antiflood.antiflood import on_chat_msg_received +from antiflood.antiflood import register_flood_warning_callback +from antiflood.antiflood import register_flood_started_callback +from antiflood.antiflood import register_flood_ended_callback +from antiflood.antiflood import init \ No newline at end of file diff --git a/src/antiflood/antiflood.py b/src/antiflood/antiflood.py new file mode 100644 index 0000000..16604ef --- /dev/null +++ b/src/antiflood/antiflood.py @@ -0,0 +1,93 @@ +import config +import time +import logging + +logger = logging.getLogger(__name__) + +flood_ratio = 2 # messages/seconds +max_flood_ratio = 10 +time_threshold_warning = 5 # ratio > flood_ratio for {time_threshold_warning} seconds +time_threshold_flood = 10 # ratio > flood_ratio for {time_threshold_flood} seconds +timeout = 4 # flood ends after ratio < flood_ratio for {timeout} seconds + +callback_flood_warning = None +callback_flood_started = None +callback_flood_ended = None + +LEVEL_NORMAL = 0 +LEVEL_WARNING = 1 +LEVEL_FLOOD = 2 +# chat_id -> (level, ratio, msg_num, duration, last_update) +stats = {} + +def register_flood_warning_callback(callback): + global callback_flood_warning + callback_flood_warning = callback + +def register_flood_started_callback(callback): + global callback_flood_started + callback_flood_started = callback + +def register_flood_ended_callback(callback): + global callback_flood_ended + callback_flood_ended = callback + +def init(): + global flood_ratio, max_flood_ratio, time_threshold_warning, time_threshold_flood, timeout + flood_ratio = config.get_config_prop("app")["antiflood"]["flood_ratio"] + max_flood_ratio = config.get_config_prop("app")["antiflood"]["max_flood_ratio"] + time_threshold_warning = config.get_config_prop("app")["antiflood"]["time_threshold_warning"] + time_threshold_flood = config.get_config_prop("app")["antiflood"]["time_threshold_flood"] + timeout = config.get_config_prop("app")["antiflood"]["timeout"] + + logger.info("Ratio: %d", flood_ratio) + logger.info("Max flood ratio: %d", max_flood_ratio) + logger.info("Thr warning: %d", time_threshold_warning) + logger.info("Thr flood: %d", time_threshold_flood) + logger.info("Timeout: %d", timeout) + +def on_chat_msg_received(chat_id): + global flood_ratio, time_threshold_warning, time_threshold_flood, timeout + global callback_flood_warning, callback_flood_started, callback_flood_ended + + curr_time = time.time() + + if chat_id not in stats: + stats[chat_id] = [LEVEL_NORMAL, 1.0, 1, 0.0, curr_time] + + else: + level, ratio, msg_num, duration, last_update = stats[chat_id] + updated_duration = duration + curr_time - last_update + msg_num += 1 + curr_ratio = msg_num / updated_duration + + if curr_ratio < flood_ratio and updated_duration > timeout: + curr_ratio, updated_duration, msg_num = 0, 0, 0 + level = LEVEL_NORMAL + if callback_flood_ended: + callback_flood_ended(chat_id) + + elif updated_duration > 1 and curr_ratio > max_flood_ratio and level < LEVEL_FLOOD: + level = LEVEL_FLOOD + logger.warning("Flood ratio for chat %d is over the top", chat_id) + if callback_flood_started: + callback_flood_started(chat_id) + + elif curr_ratio > flood_ratio: + if updated_duration >= time_threshold_flood and level < LEVEL_FLOOD: + logger.warning("Flood detected for chat %d", chat_id) + level = LEVEL_FLOOD + if callback_flood_started: + callback_flood_started(chat_id) + + elif updated_duration >= time_threshold_warning and level < LEVEL_WARNING: + logger.info("Potential flood for chat %d", chat_id) + level = LEVEL_WARNING + if callback_flood_warning is not None: + callback_flood_warning(chat_id) + + stats[chat_id] = (level, curr_ratio, msg_num, updated_duration, curr_time) + + logger.info("stats[{}]: {}".format(chat_id, stats[chat_id])) + + diff --git a/src/audiotools/__init__.py b/src/audiotools/__init__.py new file mode 100644 index 0000000..b63ff77 --- /dev/null +++ b/src/audiotools/__init__.py @@ -0,0 +1 @@ +from audiotools.speech import transcribe \ No newline at end of file diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py new file mode 100644 index 0000000..65a026a --- /dev/null +++ b/src/audiotools/speech.py @@ -0,0 +1,70 @@ +import functional +import requests +import config +import logging +import traceback +import pydub +import io + +from pydub import AudioSegment + +logger = logging.getLogger("speech") + +def __transcribe_chunk(chunk, lang): + if lang not in config.get_config_prop("wit"): + logger.error("Language not found in wit.json %s", lang) + return None + + logging.debug("Using key %s %s", lang, config.get_config_prop("wit")[lang]) + + headers = { + 'authorization': 'Bearer ' + config.get_config_prop("wit")[lang], + 'accept': 'application/vnd.wit.20180705+json', + 'content-type': 'audio/raw;encoding=signed-integer;bits=16;rate=8000;endian=little', + } + + text = None + try: + request = requests.request( + "POST", + "https://api.wit.ai/speech", + headers=headers, + params = {'verbose': True}, + data=io.BufferedReader(io.BytesIO(chunk.raw_data)) + ) + + logger.debug("Request response %s", request.text) + res = request.json() + + if '_text' in res: + text = res['_text'] + + except Exception as e: + logger.error("Could not transcribe chunk: %s", traceback.format_exc()) + + return text + +def __generate_chunks(segment, length=20, split_on_silence=False): + chunks = list() + if split_on_silence is False: + for i in range(0, len(segment), length*1000): + chunks.append(segment[i:i+length*1000]) + return chunks + +def __preprocess_audio(audio): + return audio.set_sample_width(2).set_channels(1).set_frame_rate(8000) + +def transcribe(path, lang): + logging.info("Transcribing file %s", path) + audio = AudioSegment.from_file(path) + + chunks = __generate_chunks(__preprocess_audio(audio)) + logging.debug("Got %d chunks", len(chunks)) + + for i, chunk in enumerate(chunks): + logging.debug("Transcribing chunk %d", i) + r = __transcribe_chunk(chunk, lang) + logging.debug(r) + + if r is not None: + yield r \ No newline at end of file diff --git a/src/config/__init__.py b/src/config/__init__.py new file mode 100644 index 0000000..b54173a --- /dev/null +++ b/src/config/__init__.py @@ -0,0 +1,40 @@ +import os, glob +import json +import functional +import logging + +import pprint + +logger = logging.getLogger(__name__) + +__configs = {} + +def parse_file(file): + logger.info("Loading config file %s", file) + + with open(file) as f: + data = json.load(f) + return data + +def init(config_folder): + global __configs + files = glob.glob(os.path.join(config_folder, "*.json")) + + keys = [x.replace(config_folder, "").replace(".json", "").replace("/", "") for x in files] + configs = map(parse_file, files) + __configs = dict(zip(keys, configs)) + + base = os.path.join(os.path.dirname(__file__), "../../") + + if not os.path.isabs(__configs['app']['database']): + __configs['app']['database'] = os.path.join(base, __configs['app']['database']) + + if not os.path.isabs(__configs['app']['media_path']): + __configs['app']['media_path'] = os.path.join(base, __configs['app']['media_path']) + + if not os.path.isdir(__configs['app']['media_path']): + os.mkdir(__configs['app']['media_path']) + +def get_config_prop(key): + global __configs + return __configs[key] \ No newline at end of file diff --git a/src/database/__init__.py b/src/database/__init__.py new file mode 100644 index 0000000..526f15f --- /dev/null +++ b/src/database/__init__.py @@ -0,0 +1,37 @@ +from database.db import Database +from database.db import TBDB + +""" +SCHEMA + +TABLE CHATS +| chat_id (int) | lang (str) | + voice_enabled (int) | photos_enabled (bool) | + qr_enabled (bool) | active(bool) | ban (bool) | + +TABLE STATS +| month_year (str) | audio_num (int) | + min_tot_audio (int) | min_transcribed_audio (int) | + num_pictures (int) | + +""" + +def init_schema(database): + with Database(database) as db: + db.execute("""CREATE TABLE IF NOT EXISTS chats ( + chat_id INTEGER PRIMARY KEY, + lang VARCHAR(5) NOT NULL, + voice_enabled INTEGER, + photos_enabled INTEGER, + qr_enabled INTEGER, + active INTEGER, + ban INTEGER) + """) + + db.execute("""CREATE TABLE IF NOT EXISTS stats ( + month_year INTEGER PRIMARY KEY, + audio_num INTEGER, + min_tot_audio INTEGER, + min_transcribed_audio INTEGER, + num_pictures INTEGER) + """) \ No newline at end of file diff --git a/src/database/db.py b/src/database/db.py new file mode 100644 index 0000000..e0b7c41 --- /dev/null +++ b/src/database/db.py @@ -0,0 +1,141 @@ +import sqlite3 +import metaclass +import logging +import config +import traceback + +logger = logging.getLogger(__name__) + +class Database(metaclass=metaclass.Singleton): + __instance = None + + def __init__(self, database): + self.database = database + + def __connect(self): + self.__connection = sqlite3.connect(self.database) + self.__cursor = self.__connection.cursor() + + def __close(self): + self.__connection.commit() + self.__connection.close() + + def __enter__(self): + logger.debug("__enter__") + self.__connect() + return self + + def assoc(self): + self.__connection.row_factory = sqlite3.Row + self.__cursor = self.__connection.cursor() + + + def __exit__(self, exc_type, exc_value, exc_traceback): + logger.debug("__exit__") + self.__close() + + if exc_type: + logger.error("exc_type: {}".format(exc_type)) + logger.error("exc_value: {}".format(exc_value)) + logger.error("exc_traceback: {}".format(exc_traceback)) + logger.error(traceback.format_exc()) + + return True + + def execute(self, query, *args): + res = self.__cursor.execute(query, *args) + return self.__cursor + +class TBDB(): + @staticmethod + def _get_db(): + return Database(config.get_config_prop("app")["database"]) + + + @staticmethod + def create_default_chat_entry(chat_id, lang): + with TBDB._get_db() as db: + db.execute("INSERT INTO chats VALUES(?, ?, ?, ?, ?, ?, ?)", (chat_id, lang, 1, 1, 1, 1, 0)) + + @staticmethod + def get_chat_entry(chat_id): + with TBDB._get_db() as db: + db.assoc() + cursor = db.execute("SELECT * FROM chats WHERE chat_id='{0}'".format(chat_id)) + return cursor.fetchone() + + + @staticmethod + def get_chat_lang(chat_id): + chat_record = TBDB.get_chat_entry(chat_id) + if not chat_record: + logger.debug("Record for chat {} not found, creating one.".format(chat_id)) + TBDB.create_default_chat_entry(chat_id, "en-US") + + with TBDB._get_db() as db: + cursor = db.execute("SELECT lang FROM chats WHERE chat_id='{0}'".format(chat_id)) + return cursor.fetchone()[0] + + @staticmethod + def set_chat_lang(chat_id, lang): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET lang='{0}' WHERE chat_id='{1}'".format(lang, chat_id)) + + + @staticmethod + def get_chat_voice_enabled(chat_id): + with TBDB._get_db() as db: + c = db.execute("SELECT voice_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + + @staticmethod + def set_chat_voice_enabled(chat_id, voice_enabled): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET voice_enabled='{0}' WHERE chat_id='{1}'".format(voice_enabled, chat_id)) + + + @staticmethod + def get_chat_photos_enabled(chat_id): + with TBDB._get_db() as db: + c = db.execute("SELECT photos_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + + @staticmethod + def set_chat_photos_enabled(chat_id, photos_enabled): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET photos_enabled='{0}' WHERE chat_id='{1}'".format(photos_enabled, chat_id)) + + + @staticmethod + def get_chat_qr_enabled(chat_id): + with TBDB._get_db() as db: + c = db.execute("SELECT qr_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + + @staticmethod + def set_chat_qr_enabled(chat_id, qr_enabled): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET qr_enabled='{0}' WHERE chat_id='{1}'".format(qr_enabled, chat_id)) + + @staticmethod + def get_chat_active(chat_id): + with TBDB._get_db() as db: + c = db.execute("SELECT active FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + + @staticmethod + def set_chat_active(chat_id, active): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET active='{0}' WHERE chat_id='{1}'".format(active, chat_id)) + + @staticmethod + def get_chat_ban(chat_id): + with TBDB._get_db() as db: + c = db.execute("SELECT ban FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + + @staticmethod + def set_chat_ban(chat_id, ban): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET ban='{0}' WHERE chat_id='{1}'".format(ban, chat_id)) + diff --git a/src/functional/__init__.py b/src/functional/__init__.py new file mode 100644 index 0000000..e1a5fde --- /dev/null +++ b/src/functional/__init__.py @@ -0,0 +1,3 @@ +def apply_fn(list, fn): + for item in list: + fn(item) \ No newline at end of file diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..7bb992b --- /dev/null +++ b/src/main.py @@ -0,0 +1,25 @@ +import coloredlogs,logging +import config +import resources +import database +import antiflood + +from telegram.ext import Filters + +import transcriberbot +from transcriberbot import TranscriberBot + +coloredlogs.install( + level='DEBUG', + fmt='%(asctime)s - %(name)s - %(levelname)s - %(filename)s [%(funcName)s:%(lineno)d] - %(message)s' +) +logger = logging.getLogger(__name__) + +if __name__ == '__main__': + config.init('../config') + resources.init("../values") + antiflood.init() + transcriberbot.init() + database.init_schema(config.get_config_prop("app")["database"]) + + TranscriberBot.get().start(config.get_config_prop("telegram")["token"]) \ No newline at end of file diff --git a/src/metaclass/__init__.py b/src/metaclass/__init__.py new file mode 100644 index 0000000..81c9a72 --- /dev/null +++ b/src/metaclass/__init__.py @@ -0,0 +1 @@ +from metaclass.singleton import Singleton \ No newline at end of file diff --git a/src/metaclass/singleton.py b/src/metaclass/singleton.py new file mode 100644 index 0000000..d199fb8 --- /dev/null +++ b/src/metaclass/singleton.py @@ -0,0 +1,8 @@ +class Singleton(type): + _instances = {} + + def __call__(cls, *args, **kwargs): + k = (cls, args) + if k not in cls._instances: + cls._instances[k] = super(Singleton, cls).__call__(*args, **kwargs) + return cls._instances[k] \ No newline at end of file diff --git a/src/phototools/__init__.py b/src/phototools/__init__.py new file mode 100644 index 0000000..3fe0f0d --- /dev/null +++ b/src/phototools/__init__.py @@ -0,0 +1,2 @@ +from phototools.ocr import image_ocr +from phototools.qr import read_qr \ No newline at end of file diff --git a/src/phototools/ocr.py b/src/phototools/ocr.py new file mode 100644 index 0000000..c682ac7 --- /dev/null +++ b/src/phototools/ocr.py @@ -0,0 +1,14 @@ +import logging + +from tesserocr import PyTessBaseAPI + +logger = logging.getLogger(__name__) + +def image_ocr(path, lang): + logger.info("opening %s", path) + + with PyTessBaseAPI() as api: + api.SetImageFile(path) + text = api.GetUTF8Text().strip() + + return text \ No newline at end of file diff --git a/src/phototools/qr.py b/src/phototools/qr.py new file mode 100644 index 0000000..5c1e8a3 --- /dev/null +++ b/src/phototools/qr.py @@ -0,0 +1,18 @@ +import zbarlight +import logging +from PIL import Image + +logger = logging.getLogger(__name__) + +def read_qr(path, lang): + logger.info("opening %s", path) + + with open(path, 'rb') as f: + image = Image.open(f) + image.load() + qr = zbarlight.scan_codes('qrcode', image) + if qr is not None: + qr = qr[0].decode("utf-8") + + return qr + diff --git a/src/resources/__init__.py b/src/resources/__init__.py new file mode 100644 index 0000000..98505c5 --- /dev/null +++ b/src/resources/__init__.py @@ -0,0 +1 @@ +from resources.loader import init, get_string_resource, iso639_2_to_639_1 \ No newline at end of file diff --git a/src/resources/loader.py b/src/resources/loader.py new file mode 100644 index 0000000..c330e40 --- /dev/null +++ b/src/resources/loader.py @@ -0,0 +1,76 @@ +import os, glob +import xml.etree.ElementTree as ElementTree +import functools +import functional +import logging + +from watchdog.observers import Observer +from watchdog.events import FileSystemEventHandler + +logger = logging.getLogger(__name__) +strings_r = {} +__resources_directory = None + +class EventHandler(FileSystemEventHandler): + @staticmethod + def on_any_event(event): + if event.event_type == "modified" or event.event_type == "created": + logger.info("Reloading resource folder") + load_config() + +def install_observer(): + handler = EventHandler() + observer = Observer() + observer.schedule(handler, __resources_directory) + observer.start() + +def _load_xml_resouce(path): + logger.info("Loading resource %s", path) + + e = ElementTree.parse(path).getroot() + lang = e.get('lang') + if lang not in strings_r: + strings_r[lang] = {} + + replacements = ('{b}', ''), ('{/b}', ''), + ('{i}', ''), ('{/i}', ''), + ('{code}', ''), ('{/code}', '') + + for string in e.findall('string'): + if string.text is None: + continue + + value = functools.reduce(lambda s, kv: s.replace(*kv), replacements, string.text) + value = value.strip() + strings_r[lang][string.get('name')] = value + logger.debug("Loaded string resource [%s] (%s): %s", string.get('name'), lang, value) + +def load_config(): + files = glob.glob(os.path.join(__resources_directory, "strings*.xml")) + functional.apply_fn(files, _load_xml_resouce) + +def init(values_folder): + global __resources_directory + __resources_directory = values_folder + + load_config() + install_observer() + +def iso639_2_to_639_1(lang): + # Convert ISO 639-2 to 639-1 based on available translations (i.e it -> it-IT) + return next(iter(list(filter(lambda s: s.startswith(lang), strings_r.keys()))), "en-US") + +def get_string_resource(id, lang=None): + global strings_r + + if lang is not None and len(lang) < 5: + lang = iso639_2_to_639_1(lang) + + rr = None + if lang in strings_r and id in strings_r[lang]: + rr = strings_r[lang][id] + elif id in strings_r['default']: + rr = strings_r['default'][id] + + return rr + diff --git a/src/tests/test_db.py b/src/tests/test_db.py new file mode 100644 index 0000000..fcf2bb4 --- /dev/null +++ b/src/tests/test_db.py @@ -0,0 +1,35 @@ +import sys, os +sys.path.append(os.path.abspath(os.path.join('.', 'src'))) + +import config +import database +from database import TBDB + +def setup_function(function): + config.init(os.path.abspath('config')) + config.get_config_prop("app")["database"] = "tmp.db" + database.init_schema(config.get_config_prop("app")["database"]) + +def teardown_function(function): + os.remove(config.get_config_prop("app")["database"]) + +def test_db(): + id = 1234 + + TBDB.create_default_chat_entry(id, 'en-US') + assert TBDB.get_chat_lang(id) == 'en-US' + assert TBDB.get_chat_active(id) == 1 + + TBDB.set_chat_lang(id, 'lang') + TBDB.set_chat_voice_enabled(id, 2) + TBDB.set_chat_photos_enabled(id, 1) + TBDB.set_chat_qr_enabled(id, 1) + TBDB.set_chat_active(id, 0) + TBDB.set_chat_ban(id, 1) + + assert TBDB.get_chat_lang(id) == 'lang' + assert TBDB.get_chat_voice_enabled(id) == 2 + assert TBDB.get_chat_photos_enabled(id) == 1 + assert TBDB.get_chat_qr_enabled(id) == 1 + assert TBDB.get_chat_active(id) == 0 + assert TBDB.get_chat_ban(id) == 1 \ No newline at end of file diff --git a/src/transcriberbot/__init__.py b/src/transcriberbot/__init__.py new file mode 100644 index 0000000..c935b87 --- /dev/null +++ b/src/transcriberbot/__init__.py @@ -0,0 +1,3 @@ +from transcriberbot.bot import TranscriberBot +from transcriberbot.bot import message +from transcriberbot.bot import init \ No newline at end of file diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py new file mode 100644 index 0000000..60c423e --- /dev/null +++ b/src/transcriberbot/bot.py @@ -0,0 +1,779 @@ +import config +import database +import resources as R +import metaclass +import functional +import audiotools +import phototools +import pprint +import logging +import os +import traceback +import telegram +import time +import antiflood +import translator + +from datetime import datetime + +from database import TBDB +from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackQueryHandler, Filters +from telegram.ext import messagequeue as mq +from telegram.utils.request import Request +from telegram import InlineKeyboardButton, InlineKeyboardMarkup +from telegram.error import Unauthorized + +from concurrent.futures import ThreadPoolExecutor + +from transcriberbot import tbfilters +from transcriberbot.channel_command_handler import ChannelCommandHandler + +logger = logging.getLogger(__name__) + +# Utils +def get_language_list(): + return config.get_config_prop("app")["languages"].keys() + +def get_chat_id(update): + chat_id = None + if update.message is not None: + chat_id = update.message.chat.id + elif update.channel_post is not None: + chat_id = update.channel_post.chat.id + return chat_id + +def get_message_id(update): + if update.message is not None: + return update.message.message_id + elif update.channel_post is not None: + return update.channel_post.message_id + + return None + +class TranscriberBot(metaclass=metaclass.Singleton): + class MQBot(telegram.bot.Bot): + def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs): + super().__init__(*args, **kwargs) + self._is_messages_queued_default = is_queued_def + self._msg_queue = mqueue or mq.MessageQueue() + + self.active_chats_cache = {} + + def __del__(self): + try: + self._msg_queue.stop() + except: + pass + super().__del__() + + def active_check(self, fn, *args, **kwargs): + err = None + res = None + + try: + res = fn(*args, **kwargs) + except Unauthorized as e: + pprint.pprint(e) + logger.error(e) + err = e + + if err is not None: + chat_id = kwargs['chat_id'] + if chat_id not in self.active_chats_cache or self.active_chats_cache[chat_id] == 1: + logger.debug("Marking chat {} as inactive".format(chat_id)) + self.active_chats_cache[chat_id] = 0 + TBDB.set_chat_active(chat_id, self.active_chats_cache[chat_id]) + raise err + + return res + + @mq.queuedmessage + def send_message(self, *args, **kwargs): + return self.active_check(super().send_message, *args, **kwargs) + + @mq.queuedmessage + def edit_message_text(self, *args, **kwargs): + return self.active_check(super().edit_message_text, *args, **kwargs) + + def __init__(self): + self.error_handler = None + self.message_handlers = {} + self.command_handlers = {} + self.callback_handlers = {} + self.floods = {} + self.workers = {} + + antiflood.register_flood_warning_callback( + lambda chat_id: TranscriberBot.get().bot().send_message( + chat_id=chat_id, + text=R.get_string_resource("flood_warning", TBDB.get_chat_lang(chat_id)), + parse_mode = "html", + is_group = chat_id < 0 + ) + ) + + def flood_started(chat_id): + logger.info("Flood detected in %d, ignoring messages", chat_id) + self.floods[chat_id] = True + + def flood_ended(chat_id): + logger.info("Flood ended for %d", chat_id) + self.floods[chat_id] = False + + antiflood.register_flood_started_callback(flood_started) + antiflood.register_flood_ended_callback(flood_ended) + + @staticmethod + def get(): + return TranscriberBot() + + def bot(self): + return self.mqbot + + def start(self, token): + self.voice_thread_pool = ThreadPoolExecutor( + max_workers=config.get_config_prop("app")["voice_max_threads"] + ) + self.photos_thread_pool = ThreadPoolExecutor( + max_workers=config.get_config_prop("app")["photos_max_threads"] + ) + + self.queue = mq.MessageQueue() + self.request = Request(con_pool_size=10) + self.mqbot = self.MQBot(token, request=self.request, mqueue=self.queue) + self.updater = Updater(bot=self.mqbot) + self.dispatcher = self.updater.dispatcher + self.__register_handlers() + self.updater.start_polling(clean=True) + self.updater.idle() + + def register_message_handler(self, filter, fn): + self.message_handlers[filter] = fn + + def register_command_handler(self, fn, bypass_admin_check=False): + self.command_handlers[fn.__name__] = (fn, bypass_admin_check) + + def register_callback_handler(self, fn): + self.callback_handlers[fn.__name__] = fn + + def start_thread(self, id): + self.workers[str(id)] = True + + def stop_thread(self, id): + self.workers[str(id)] = False + + def thread_running(self, id): + return self.workers[str(id)] + + def del_thread(self, id): + del self.workers[str(id)] + + def __add_handler(self, handler): + self.dispatcher.add_handler(handler) + + def __add_error_handler(self, handler): + self.dispatcher.add_error_handler(handler) + + def __pre__hook(self, fn, b, u, **kwargs): + m = u.message or u.channel_post + if not m: + return + + age = (datetime.now() - m.date).total_seconds() + if age > config.get_config_prop("app")["antiflood"]["age_threshold"]: + return + + chat_id = get_chat_id(u) + antiflood.on_chat_msg_received(chat_id) + + if chat_id in self.floods and self.floods[chat_id] is True: + return + + if chat_id in self.mqbot.active_chats_cache and self.mqbot.active_chats_cache[chat_id] == 0: + logger.debug("Marking chat {} as active".format(chat_id)) + self.mqbot.active_chats_cache[chat_id] = 1 + TBDB.set_chat_active(chat_id, self.mqbot.active_chats_cache[chat_id]) + + return fn(b, u, **kwargs) + + def __register_handlers(self): + functional.apply_fn( + self.message_handlers.items(), + lambda h: self.__add_handler(MessageHandler( + h[0], + lambda b, u, **kwargs: self.__pre__hook(h[1], b, u, **kwargs))) + ) + + admin_filter = tbfilters.FilterIsAdmin(self.mqbot) + + functional.apply_fn( + self.command_handlers.items(), + lambda h: self.__add_handler(ChannelCommandHandler( + h[0], + lambda b, u, **kwargs: self.__pre__hook(h[1][0], b, u, **kwargs), + filters=admin_filter if h[1][1] is False else None)) + ) + + functional.apply_fn( + self.callback_handlers.items(), + lambda h: self.__add_handler(CallbackQueryHandler(h[1])) + ) + +# Decorators for adding callbacks +def message(filter): + def decor(fn): + TranscriberBot.get().register_message_handler(filter, fn) + return decor + +def command(bypass_admin_check=False): + def decor(fn): + TranscriberBot.get().register_command_handler(fn, bypass_admin_check) + return decor + +def callback_query(fn): + TranscriberBot.get().register_callback_handler(fn) + +# Install language command callbacks +def language_handler(bot, update, language): + chat_id = get_chat_id(update) + lang = config.get_config_prop("app")["languages"][language] #ISO 639-1 code for language + TBDB.set_chat_lang(chat_id, lang) + message = R.get_string_resource("language_set", lang).replace("{lang}", language) + reply = update.message or update.channel_post + reply.reply_text(message) + +def install_language_handlers(language): + handler = lambda b, u: language_handler(b, u, language) + handler.__name__ = language + TranscriberBot.get().register_command_handler(handler) + +# Init +def init(): + functional.apply_fn(get_language_list(), install_language_handlers) + +# Message callbacks +@message(Filters.text & Filters.private) +def private_message(bot, update): + chat_id = get_chat_id(update) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("message_private", TBDB.get_chat_lang(chat_id)) + ) + +@callback_query +def stop(bot, update): + query = update.callback_query + + TranscriberBot.get().stop_thread(query.data) + logger.debug("Stopping thread %s", query.data) + logger.debug("Thread %s running: %r", query.data, TranscriberBot.get().thread_running(query.data)) + + string_stopped = R.get_string_resource( + "transcription_stopped", + TBDB.get_chat_lang(query.message.chat_id) + ) + + bot.edit_message_text( + text=query.message.text + " " + string_stopped, + chat_id=query.message.chat_id, + message_id=query.message.message_id, + parse_mode="html", + is_group=query.message.chat_id < 0 + ) + +def transcribe_audio_file(bot, update, path): + chat_id = get_chat_id(update) + lang = TBDB.get_chat_lang(chat_id) + message_id = get_message_id(update) + is_group = chat_id < 0 + + message = bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("transcribing", lang) + "\n", + reply_to_message_id=message_id, + parse_mode="html", + is_group=is_group + ).result() + + TranscriberBot.get().start_thread(message_id) + logger.debug("Starting thread %d", message_id) + + keyboard = InlineKeyboardMarkup( + [[InlineKeyboardButton("Stop", callback_data=message_id)]] + ) + + text = R.get_string_resource("transcription_text", lang) + "\n" + success = False + for speech in audiotools.transcribe(path, lang): + logger.debug("Thread %d running: %r", message_id, TranscriberBot.get().thread_running(message_id)) + if TranscriberBot.get().thread_running(message_id) is False: + TranscriberBot.get().del_thread(message_id) + return + + retry = True + retry_num = 0 + + while retry and TranscriberBot.get().thread_running(message_id): + try: + if len(text + speech) >= 4080: + text = R.get_string_resource("transcription_continues", lang) + "\n" + message = bot.send_message( + chat_id=chat_id, + text=text + speech + " [..]", + reply_to_message_id=message.message_id, + parse_mode="html", + is_group=is_group, + reply_markup=keyboard + ).result() + else: + message = bot.edit_message_text( + text=text + speech + " [..]", + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group, + reply_markup=keyboard + ).result() + + text += speech + retry = False + success = True + + except telegram.error.TimedOut as t: + logger.error("Timeout error %s", traceback.format_exc()) + retry_num += 1 + if retry_num >= 3: + retry = False + + except telegram.error.RetryAfter as r: + logger.warning("Retrying after %d", r.retry_after) + time.sleep(r.retry_after) + + except telegram.error.TelegramError as te: + logger.error("Telegram error %s", traceback.format_exc()) + retry = False + + except Exception as e: + logger.error("Exception %s", traceback.format_exc()) + retry = False + + retry = True + retry_num = 0 + while retry and TranscriberBot.get().thread_running(message_id): + try: + if success: + bot.edit_message_text( + text=text, + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + ) + else: + bot.edit_message_text( + R.get_string_resource("transcription_failed", lang), + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + ) + retry = False + except telegram.error.TimedOut as t: + logger.error("Timeout error %s", traceback.format_exc()) + retry_num += 1 + if retry_num >= 3: + retry = False + + except telegram.error.RetryAfter as r: + logger.warning("Retrying after %d", r.retry_after) + time.sleep(r.retry_after) + + except telegram.error.TelegramError as te: + logger.error("Telegram error %s", traceback.format_exc()) + retry = False + + except Exception as e: + logger.error("Exception %s", traceback.format_exc()) + retry = False + + TranscriberBot.get().del_thread(message_id) + +def process_media_voice(bot, update, media, name): + chat_id = get_chat_id(update) + file_id = media.file_id + file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) + file = bot.get_file(file_id) + file.download(file_path) + + try: + transcribe_audio_file(bot, update, file_path) + except Exception as e: + logger.error("Exception handling %s from %d: %s", name, chat_id, traceback.format_exc()) + + finally: + os.remove(file_path) + +@message(Filters.voice) +def voice(bot, update): + chat_id = get_chat_id(update) + voice_enabled = TBDB.get_chat_voice_enabled(chat_id) + if voice_enabled == 0: + return + + v = None + if update.message is not None: + v = update.message.voice + elif update.channel_post is not None: + v = update.channel_post.voice + file_id = v.file_id + + if voice_enabled == 2: + pass + else: + TranscriberBot.get().voice_thread_pool.submit( + process_media_voice, bot, update, v, "voice" + ) + +@message(Filters.audio) +def audio(bot, update): + chat_id = get_chat_id(update) + voice_enabled = TBDB.get_chat_voice_enabled(chat_id) + + if voice_enabled == 0: + return + + a = None + if update.message is not None: + a = update.message.audio + elif update.channel_post is not None: + a = update.channel_post.audio + + if voice_enabled == 2: + pass + else: + TranscriberBot.get().voice_thread_pool.submit( + process_media_voice, bot, update, a, "audio" + ) + +@message(Filters.video_note) +def video_note(bot, update): + chat_id = get_chat_id(update) + voice_enabled = TBDB.get_chat_voice_enabled(chat_id) + + if voice_enabled == 0: + return + + vn = None + if update.message is not None: + vn = update.message.video_note + elif update.channel_post is not None: + vn = update.channel_post.video_note + + if voice_enabled == 2: + pass + else: + TranscriberBot.get().voice_thread_pool.submit( + process_media_voice, bot, update, vn, "video_note" + ) + +def process_media_photo(bot, update, photo, chat): + chat_id = get_chat_id(update) + message_id = get_message_id(update) + is_group = chat_id < 0 + + message = None + + if chat["photos_enabled"] == 1: + message = bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("photo_recognizing", chat["lang"]), + reply_to_message_id=message_id, + parse_mode="html", + is_group=is_group + ).result() + + file_id = photo[-1].file_id + file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) + bot.get_file(file_id).download(file_path) + + def process(message): + if chat["qr_enabled"] == 1: + qr = phototools.read_qr(file_path, chat["lang"]) + if qr is not None: + qr = R.get_string_resource("qr_result", chat["lang"]) + "\n" + qr + + if message is not None: + bot.edit_message_text( + text=qr, + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + ) + return + else: + message = bot.send_message( + chat_id=chat_id, + text=qr, + reply_to_message_id=message_id, + parse_mode="html", + is_group=is_group + ).result() + """bot.edit_message_text( + R.get_string_resource("qr_no_text", lang), + chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + )""" + + if chat["photos_enabled"] == 1: + text = phototools.image_ocr(file_path, chat["lang"]) + if text is not None: + text = R.get_string_resource("ocr_result", chat["lang"]) + "\n" + text + bot.edit_message_text( + text=text, + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + ) + return + + bot.edit_message_text( + text=R.get_string_resource("photo_no_text", lang), + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + ) + + retry = True + retry_num = 0 + try: + while retry: + process(message) + retry = False + + except telegram.error.TimedOut as t: + logger.error("Timeout error %s", traceback.format_exc()) + retry_num += 1 + if retry_num >= 3: + retry = False + + except telegram.error.RetryAfter as r: + logger.warning("Retrying after %d", r.retry_after) + time.sleep(r.retry_after) + + except telegram.error.TelegramError as te: + logger.error("Telegram error %s", traceback.format_exc()) + retry = False + + except Exception as e: + logger.error("Exception %s", traceback.format_exc()) + retry = False + + finally: + os.remove(file_path) + +@message(Filters.photo) +def photo(bot, update): + chat_id = get_chat_id(update) + chat = TBDB.get_chat_entry(chat_id) + if chat["qr_enabled"] == 0 and chat["photos_enabled"] == 0: + return + + p = None + if update.message is not None: + p = update.message.photo + elif update.channel_post is not None: + p = update.channel_post.photo + + if p: + TranscriberBot.get().photos_thread_pool.submit( + process_media_photo, bot, update, p, chat + ) + +# Command callbacks +def welcome_message(bot, update): + chat_id = get_chat_id(update) + message_id = get_message_id(update) + chat_record = TBDB.get_chat_entry(chat_id) + + language = None + if chat_record is not None: + language = chat_record["lang"] + elif update.message is not None and update.message.from_user.language_code is not None: + # Channel posts do not have a language_code attribute + logger.debug("Language_code: %s", update.message.from_user.language_code) + language = update.message.from_user.language_code + + message = R.get_string_resource("message_welcome", language) + message = message.replace("{languages}", "/" + "\n/".join(get_language_list())) #Format them to be a list of commands + bot.send_message( + chat_id=chat_id, + text=message, + reply_to_message_id = message_id, + parse_mode = "html", + is_group = chat_id < 0 + ) + + if chat_record is None: + if language is None: + language = "en-US" + + if len(language) < 5: + language = R.iso639_2_to_639_1(language) + + logger.debug("No record found for chat {}, creating one with lang {}".format(chat_id, language)) + TBDB.create_default_chat_entry(chat_id, language) + +@command(bypass_admin_check=False) +def start(bot, update): + welcome_message(bot, update) + +@command(bypass_admin_check=False) +def help(bot, update): + welcome_message(bot, update) + +@command(bypass_admin_check=False) +def lang(bot, update): + chat_id = get_chat_id(update) + bot.send_message(chat_id=chat_id, text=TBDB.get_chat_lang(chat_id)) + +@command(bypass_admin_check=False) +def rate(bot, update): + chat_id = get_chat_id(update) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("message_rate", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(bypass_admin_check=False) +def disable_voice(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_voice_enabled(chat_id, 0) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("voice_disabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(bypass_admin_check=False) +def enable_voice(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_voice_enabled(chat_id, 1) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("voice_enabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(bypass_admin_check=False) +def voice_ask(bot, update): + pass + +@command(bypass_admin_check=False) +def disable_photos(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_photos_enabled(chat_id, 0) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("photos_disabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(bypass_admin_check=False) +def enable_photos(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_photos_enabled(chat_id, 1) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("photos_enabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(bypass_admin_check=False) +def disable_qr(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_qr_enabled(chat_id, 0) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("qr_disabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(bypass_admin_check=False) +def enable_qr(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_qr_enabled(chat_id, 1) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("qr_enabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(bypass_admin_check=True) +def translate(bot, update): + chat_id = get_chat_id(update) + message = update.message + if not message: + message = update.channel_post + + if not message: + return + + lang = message.text + lang = lang.replace("/translate", "").strip() + logger.debug("Language %s", lang) + + if lang not in config.get_config_prop("app")["languages"]: + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("translate_language_not_found", TBDB.get_chat_lang(chat_id)).format(lang), + is_group = chat_id < 0 + ) + return + + lang = config.get_config_prop("app")["languages"][lang].split('-')[0] + + if not message.reply_to_message: + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("translate_reply_to_message", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + return + + translation = translator.translate( + source=TBDB.get_chat_lang(chat_id), + target=lang, + text=message.reply_to_message.text + ) + + message.reply_text(translation) + +@command(bypass_admin_check=False) +def stats(bot, update): + pass + +@command(bypass_admin_check=False) +def donate(bot, update): + chat_id = get_chat_id(update) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("message_donate", TBDB.get_chat_lang(chat_id)), + parse_mode="html", + is_group = chat_id < 0 + ) + +@command(bypass_admin_check=True) +def privacy(bot, update): + chat_id = get_chat_id(update) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("privacy_policy", TBDB.get_chat_lang(chat_id)), + parse_mode='html', + is_group = chat_id < 0 + ) diff --git a/src/transcriberbot/channel_command_handler.py b/src/transcriberbot/channel_command_handler.py new file mode 100644 index 0000000..760f2a7 --- /dev/null +++ b/src/transcriberbot/channel_command_handler.py @@ -0,0 +1,16 @@ +import telegram + +class ChannelCommandHandler(telegram.ext.CommandHandler): + def check_update(self, update): + is_channel = False + + if update.channel_post: + update.message = update.channel_post + is_channel = True + + res = super().check_update(update) + + if is_channel: + update.message = None + + return res \ No newline at end of file diff --git a/src/transcriberbot/tbfilters.py b/src/transcriberbot/tbfilters.py new file mode 100644 index 0000000..835c6c7 --- /dev/null +++ b/src/transcriberbot/tbfilters.py @@ -0,0 +1,20 @@ +from telegram.ext import BaseFilter + +class FilterIsAdmin(BaseFilter): + def __init__(self, bot): + self.bot = bot + + def filter(self, message): + if message.chat.id >= 0: + return True + + if message.chat.type == 'channel': + return True + + sender = message.from_user + admins = message.chat.get_administrators() + + is_admin = list(filter(lambda cm: cm.user.id == sender.id, admins)) + is_admin = len(is_admin) > 0 + + return is_admin \ No newline at end of file diff --git a/src/translator/__init__.py b/src/translator/__init__.py new file mode 100644 index 0000000..114bcb2 --- /dev/null +++ b/src/translator/__init__.py @@ -0,0 +1 @@ +from translator.translator import detect_language, translate \ No newline at end of file diff --git a/src/translator/__pycache__/__init__.cpython-36.pyc b/src/translator/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76c1ee6a37e0c32fc0b23f04d0872f55f36cf07e GIT binary patch literal 234 zcmYL?u?hk)5JWdQ3l+phYwK%FVJjjc78W*IokfUA(1YY6n_S^1`AgSYh`(UvUZF0` zFuMzHW`jY0vV9)s0PrCFhErOS;)u+EVGcYinCAs&VE7*L>_s2Qc{4ONS)HU))wxz@ z+w>BuDmsin)5WYXjvPoi+f$=z%hfXtK!7vmA2oNZ!GR%YqQ+O2J;aIUPvpPeZ$dws7 z-XJeP$?IH8l~+i`t`tlP8cuVoy`R0^@7wR;`g-I1=fwx582iPp4T1g(ocUcenrS{_ zz3R_j`4tkkzDnH3!kx0_ z#D?4{9oyKcQ9K!hH5Y*SG&8x)otkF3b(>Xize3!f!N~a^GZ@F#`AIhUI2^dv5eo3hCw4;)gr@X?WOVwt(RiDEF@R4T&O7fb4VSc%s5_+8f2lml#$ltR%6U^5 zPAoL&U7`z!Sa<762Y)q$Qh*zDzD8!9F3H>iYRJ#C86?K}HU`v2SzWIYui#bnQ>&m! zhJ;a>O?sui%F)7QzKw=SYNp~FVhvkL?cI>rT>PMor=ed}T9#AC4Y*B)I$xe&%TVSj X(*#e)nVyZzF7cKVT#}38N(Rl}*MJ>U literal 0 HcmV?d00001 diff --git a/src/translator/translator.py b/src/translator/translator.py new file mode 100644 index 0000000..305e46b --- /dev/null +++ b/src/translator/translator.py @@ -0,0 +1,43 @@ +import requests +import config + +yandex_detect_url = "https://translate.yandex.net/api/v1.5/tr.json/detect?key={}" +yandex_translate_url = "https://translate.yandex.net/api/v1.5/tr.json/translate?key={}" + + +def detect_language(text): + global yandex_detect_url + + r = requests.post( + yandex_detect_url.format(config.get_config_prop("yandex")["translate_key"]), + data={'text': text} + ) + res = r.json() + + if 'lang' in res: + return res['lang'] + else: + return None + + +def translate(source, target, text): + global yandex_translate_url + + autodetect = detect_language(text) + + if autodetect is not None: + source = autodetect + print("Autodetected language: {0}".format(autodetect)) + + lang = source + "-" + target + print(lang) + + r = requests.post( + yandex_translate_url.format(config.get_config_prop("yandex")["translate_key"]), + data={'lang': lang, 'text': text} + ) + + print(r) + res = r.json() + print(res) + return str(res['text'][0]) + "\n\nPowered by Yandex.Translate http://translate.yandex.com" From 35506c55e0a42ae4c310a99edb1f6324a8572b48 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 5 Mar 2019 14:41:19 +0100 Subject: [PATCH 004/120] added travis.yml --- .coverage | 1 + .travis.yml | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 .coverage create mode 100644 .travis.yml diff --git a/.coverage b/.coverage new file mode 100644 index 0000000..88867c7 --- /dev/null +++ b/.coverage @@ -0,0 +1 @@ +!coverage.py: This is a private format, don't read it directly!{"lines":{"/home/carloalberto/Documents/TranscriberBot/src/functional/__init__.py":[1],"/home/carloalberto/Documents/TranscriberBot/src/metaclass/__init__.py":[1],"/home/carloalberto/Documents/TranscriberBot/src/resources/__init__.py":[1],"/home/carloalberto/Documents/TranscriberBot/src/antiflood/antiflood.py":[1,2,3,5,7,8,9,10,11,13,14,15,17,18,19,21,23,25,27,29,31,33,35,49],"/home/carloalberto/Documents/TranscriberBot/src/database/__init__.py":[1,2,15],"/home/carloalberto/Documents/TranscriberBot/src/main.py":[1,2,3,4,5,7,9,10,12,13,14,16,18],"/home/carloalberto/Documents/TranscriberBot/src/tests/test_sample.py":[1,2,4,5,6],"/home/carloalberto/Documents/TranscriberBot/src/audiotools/__init__.py":[1],"/home/carloalberto/Documents/TranscriberBot/src/antiflood/__init__.py":[1,2,3,4,5],"/home/carloalberto/Documents/TranscriberBot/src/transcriberbot/bot.py":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,22,24,132,27,30,38,46,47,48,563,53,567,571,60,64,68,69,70,71,72,73,74,76,77,653,595,85,89,93,94,96,353,98,100,103,619,530,367,629,609,120,121,123,124,126,127,129,388,135,649,138,141,144,657,147,576,409,156,585,430,177,178,179,180,182,183,185,186,189,196,202,206,214,236,639,605,511],"/home/carloalberto/Documents/TranscriberBot/src/config/__init__.py":[19,1,2,3,4,6,8,10,12,30],"/home/carloalberto/Documents/TranscriberBot/src/phototools/qr.py":[1,2,3,5,7],"/home/carloalberto/Documents/TranscriberBot/src/phototools/__init__.py":[1,2],"/home/carloalberto/Documents/TranscriberBot/src/database/db.py":[1,2,3,4,5,7,9,10,12,15,80,19,86,23,68,28,33,98,104,92,45,110,49,50,116,55,122,60,74],"/home/carloalberto/Documents/TranscriberBot/src/phototools/ocr.py":[1,3,5,7],"/home/carloalberto/Documents/TranscriberBot/src/resources/loader.py":[1,2,3,4,5,7,8,10,11,12,14,15,48,59,52,21,27,63],"/home/carloalberto/Documents/TranscriberBot/src/audiotools/speech.py":[1,2,3,4,5,6,7,9,11,13,47,54,57],"/home/carloalberto/Documents/TranscriberBot/src/metaclass/singleton.py":[1,2,4,5,6,7,8],"/home/carloalberto/Documents/TranscriberBot/src/transcriberbot/__init__.py":[1,2,3]}} \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..1d90459 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,35 @@ +os: linux +dist: bionic +sudo: required +language: python + +python: + - "3.4" + +env: + matrix: + - TESSERACT=3.05.02-3 + +before_install: + - export TESSERACT_INSTALL=$HOME/.tesseract + - export TESSERACT_PKG=$TESSERACT_INSTALL/lib/pkgconfig + - export LD_LIBRARY_PATH=$TESSERACT_INSTALL/lib:$LD_LIBRARY_PATH + - export PKG_CONFIG_PATH=$TESSERACT_PKG:$PKG_CONFIG_PATH + - wget -O - https://github.com/nijel/tesseract-ocr-build/releases/download/$TESSERACT/tesseract.tar.xz | tar -C $HOME -xJf - + +install: + - sudo apt update + - sudo apt install -y tesseract-ocr libtesseract-dev libleptonica-dev libpython3-dev libzbar-dev + - pip install pytest-cov coveralls + - pip install Cython + - pip install Pillow + - pip install -r requirements.txt + +script: + - py.test --cov-report term-missing --cov=src + +branches: + only: + - master +after_success: + - coveralls From f38cfa0509a84e9d2bddebd2320cc4f9ac3f2b0a Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 5 Mar 2019 15:44:50 +0100 Subject: [PATCH 005/120] support for document audio --- config/app.json | 9 +++++++++ src/transcriberbot/bot.py | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/config/app.json b/config/app.json index 9e59b95..0bf13df 100644 --- a/config/app.json +++ b/config/app.json @@ -31,6 +31,15 @@ "voice_max_threads": 30, "photos_max_threads": 10, + "audio_ext": [ + "wav", + "opus", + "3gpp", + "m4a", + "mp4", + "ogg" + ], + "antiflood": { "age_threshold": 10, "flood_ratio": 2, diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index 60c423e..c119613 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -455,6 +455,29 @@ def audio(bot, update): process_media_voice, bot, update, a, "audio" ) +@message(Filters.document) +def document(bot, update): + chat_id = get_chat_id(update) + voice_enabled = TBDB.get_chat_voice_enabled(chat_id) + + m = update.message or update.channel_post + file_name = m.document.file_name + _, file_ext = os.path.splitext(file_name) + + if file_ext[1:] not in config.get_config_prop("app")["audio_ext"]: + logger.info('extension %s not recognized', file_ext) + return + + if voice_enabled == 0: + return + + if voice_enabled == 2: + pass + else: + TranscriberBot.get().voice_thread_pool.submit( + process_media_voice, bot, update, m.document, 'audio_document' + ) + @message(Filters.video_note) def video_note(bot, update): chat_id = get_chat_id(update) From 4730aa6b47d44e5a52881be576a1188c46778cb7 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 5 Mar 2019 16:02:29 +0100 Subject: [PATCH 006/120] updated gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 43c677c..708e75c 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ src/phototools/__pycache__/ src/resources/__pycache__/ src/tests/__pycache__/ src/transcriberbot/__pycache__/ +src/translator/__pycache__/ src/__pycache__/ .pytest_cache/ data/database.db From c2220052d808b3b8fddecc1fca4cdce6b1d85900 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 5 Mar 2019 16:04:02 +0100 Subject: [PATCH 007/120] removed traslator/__pycache__ --- .../__pycache__/__init__.cpython-36.pyc | Bin 234 -> 0 bytes .../__pycache__/translator.cpython-36.pyc | Bin 1130 -> 0 bytes 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/translator/__pycache__/__init__.cpython-36.pyc delete mode 100644 src/translator/__pycache__/translator.cpython-36.pyc diff --git a/src/translator/__pycache__/__init__.cpython-36.pyc b/src/translator/__pycache__/__init__.cpython-36.pyc deleted file mode 100644 index 76c1ee6a37e0c32fc0b23f04d0872f55f36cf07e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 234 zcmYL?u?hk)5JWdQ3l+phYwK%FVJjjc78W*IokfUA(1YY6n_S^1`AgSYh`(UvUZF0` zFuMzHW`jY0vV9)s0PrCFhErOS;)u+EVGcYinCAs&VE7*L>_s2Qc{4ONS)HU))wxz@ z+w>BuDmsin)5WYXjvPoi+f$=z%hfXtK!7vmA2oNZ!GR%YqQ+O2J;aIUPvpPeZ$dws7 z-XJeP$?IH8l~+i`t`tlP8cuVoy`R0^@7wR;`g-I1=fwx582iPp4T1g(ocUcenrS{_ zz3R_j`4tkkzDnH3!kx0_ z#D?4{9oyKcQ9K!hH5Y*SG&8x)otkF3b(>Xize3!f!N~a^GZ@F#`AIhUI2^dv5eo3hCw4;)gr@X?WOVwt(RiDEF@R4T&O7fb4VSc%s5_+8f2lml#$ltR%6U^5 zPAoL&U7`z!Sa<762Y)q$Qh*zDzD8!9F3H>iYRJ#C86?K}HU`v2SzWIYui#bnQ>&m! zhJ;a>O?sui%F)7QzKw=SYNp~FVhvkL?cI>rT>PMor=ed}T9#AC4Y*B)I$xe&%TVSj X(*#e)nVyZzF7cKVT#}38N(Rl}*MJ>U From 077b1037668602320d686c330c524174724b083c Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 6 Mar 2019 11:45:25 +0100 Subject: [PATCH 008/120] fixed indentation --- src/transcriberbot/tbfilters.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/transcriberbot/tbfilters.py b/src/transcriberbot/tbfilters.py index 835c6c7..a6b2d9d 100644 --- a/src/transcriberbot/tbfilters.py +++ b/src/transcriberbot/tbfilters.py @@ -1,20 +1,20 @@ from telegram.ext import BaseFilter class FilterIsAdmin(BaseFilter): - def __init__(self, bot): - self.bot = bot + def __init__(self, bot): + self.bot = bot - def filter(self, message): - if message.chat.id >= 0: - return True + def filter(self, message): + if message.chat.id >= 0: + return True - if message.chat.type == 'channel': - return True + if message.chat.type == 'channel': + return True - sender = message.from_user - admins = message.chat.get_administrators() + sender = message.from_user + admins = message.chat.get_administrators() - is_admin = list(filter(lambda cm: cm.user.id == sender.id, admins)) - is_admin = len(is_admin) > 0 + is_admin = list(filter(lambda cm: cm.user.id == sender.id, admins)) + is_admin = len(is_admin) > 0 - return is_admin \ No newline at end of file + return is_admin \ No newline at end of file From f4e60960e3547e8658037c22e7ff2edc63c89258 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 6 Mar 2019 12:00:25 +0100 Subject: [PATCH 009/120] added filesize limit error --- src/transcriberbot/bot.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index c119613..e0f26f5 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -400,11 +400,24 @@ def transcribe_audio_file(bot, update, path): def process_media_voice(bot, update, media, name): chat_id = get_chat_id(update) + file_size = media.file_size + + if file_size >= 20*(1024**2): + message_id = get_message_id(update) + message = bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("file_too_big", lang) + "\n", + reply_to_message_id=message_id, + parse_mode="html", + is_group=chat_id < 0 + ).result() + return + file_id = media.file_id file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) - file = bot.get_file(file_id) + file = bot.get_file(file_id) file.download(file_path) - + try: transcribe_audio_file(bot, update, file_path) except Exception as e: From ed3376c48d321f4296f754876d441f631b2eb8bb Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 6 Mar 2019 12:08:59 +0100 Subject: [PATCH 010/120] added filter for owner commands --- src/transcriberbot/tbfilters.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/transcriberbot/tbfilters.py b/src/transcriberbot/tbfilters.py index a6b2d9d..3946b4a 100644 --- a/src/transcriberbot/tbfilters.py +++ b/src/transcriberbot/tbfilters.py @@ -1,3 +1,4 @@ +import config from telegram.ext import BaseFilter class FilterIsAdmin(BaseFilter): @@ -17,4 +18,13 @@ def filter(self, message): is_admin = list(filter(lambda cm: cm.user.id == sender.id, admins)) is_admin = len(is_admin) > 0 - return is_admin \ No newline at end of file + return is_admin + +class FilterIsOwner(BaseFilter): + def __init__(self, bot): + self.bot = bot + self.owners = config.get_config_prop('telegram')['admins'] + + def filter(self, message): + is_owner = list(filter(lambda admin: owner == message.chat.id, self.owners)) + return len(is_owner) > 0 \ No newline at end of file From 2587323448dc6a94234f53d3ee3b84f93e774ad4 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 6 Mar 2019 14:51:08 +0100 Subject: [PATCH 011/120] refactored filters for commands --- src/transcriberbot/bot.py | 44 ++++++++++++++++----------------- src/transcriberbot/tbfilters.py | 17 +++++++------ 2 files changed, 30 insertions(+), 31 deletions(-) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index e0f26f5..fb96c1d 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -150,8 +150,8 @@ def start(self, token): def register_message_handler(self, filter, fn): self.message_handlers[filter] = fn - def register_command_handler(self, fn, bypass_admin_check=False): - self.command_handlers[fn.__name__] = (fn, bypass_admin_check) + def register_command_handler(self, fn, filters=None): + self.command_handlers[fn.__name__] = (fn, filters) def register_callback_handler(self, fn): self.callback_handlers[fn.__name__] = fn @@ -203,15 +203,13 @@ def __register_handlers(self): h[0], lambda b, u, **kwargs: self.__pre__hook(h[1], b, u, **kwargs))) ) - - admin_filter = tbfilters.FilterIsAdmin(self.mqbot) functional.apply_fn( self.command_handlers.items(), lambda h: self.__add_handler(ChannelCommandHandler( h[0], lambda b, u, **kwargs: self.__pre__hook(h[1][0], b, u, **kwargs), - filters=admin_filter if h[1][1] is False else None)) + filters=h[1][1])) ) functional.apply_fn( @@ -225,9 +223,9 @@ def decor(fn): TranscriberBot.get().register_message_handler(filter, fn) return decor -def command(bypass_admin_check=False): +def command(filters=None): def decor(fn): - TranscriberBot.get().register_command_handler(fn, bypass_admin_check) + TranscriberBot.get().register_command_handler(fn, filters) return decor def callback_query(fn): @@ -245,7 +243,7 @@ def language_handler(bot, update, language): def install_language_handlers(language): handler = lambda b, u: language_handler(b, u, language) handler.__name__ = language - TranscriberBot.get().register_command_handler(handler) + TranscriberBot.get().register_command_handler(handler, filters=tbfilters.chat_admin) # Init def init(): @@ -664,20 +662,20 @@ def welcome_message(bot, update): logger.debug("No record found for chat {}, creating one with lang {}".format(chat_id, language)) TBDB.create_default_chat_entry(chat_id, language) -@command(bypass_admin_check=False) +@command(filters=tbfilters.chat_admin) def start(bot, update): welcome_message(bot, update) -@command(bypass_admin_check=False) +@command(filters=tbfilters.chat_admin) def help(bot, update): welcome_message(bot, update) -@command(bypass_admin_check=False) +@command(filters=tbfilters.chat_admin) def lang(bot, update): chat_id = get_chat_id(update) bot.send_message(chat_id=chat_id, text=TBDB.get_chat_lang(chat_id)) -@command(bypass_admin_check=False) +@command(filters=tbfilters.chat_admin) def rate(bot, update): chat_id = get_chat_id(update) bot.send_message( @@ -686,7 +684,7 @@ def rate(bot, update): is_group = chat_id < 0 ) -@command(bypass_admin_check=False) +@command(tbfilters.chat_admin) def disable_voice(bot, update): chat_id = get_chat_id(update) TBDB.set_chat_voice_enabled(chat_id, 0) @@ -696,7 +694,7 @@ def disable_voice(bot, update): is_group = chat_id < 0 ) -@command(bypass_admin_check=False) +@command(tbfilters.chat_admin) def enable_voice(bot, update): chat_id = get_chat_id(update) TBDB.set_chat_voice_enabled(chat_id, 1) @@ -706,11 +704,11 @@ def enable_voice(bot, update): is_group = chat_id < 0 ) -@command(bypass_admin_check=False) +@command(tbfilters.chat_admin) def voice_ask(bot, update): pass -@command(bypass_admin_check=False) +@command(tbfilters.chat_admin) def disable_photos(bot, update): chat_id = get_chat_id(update) TBDB.set_chat_photos_enabled(chat_id, 0) @@ -720,7 +718,7 @@ def disable_photos(bot, update): is_group = chat_id < 0 ) -@command(bypass_admin_check=False) +@command(tbfilters.chat_admin) def enable_photos(bot, update): chat_id = get_chat_id(update) TBDB.set_chat_photos_enabled(chat_id, 1) @@ -730,7 +728,7 @@ def enable_photos(bot, update): is_group = chat_id < 0 ) -@command(bypass_admin_check=False) +@command(tbfilters.chat_admin) def disable_qr(bot, update): chat_id = get_chat_id(update) TBDB.set_chat_qr_enabled(chat_id, 0) @@ -740,7 +738,7 @@ def disable_qr(bot, update): is_group = chat_id < 0 ) -@command(bypass_admin_check=False) +@command(tbfilters.chat_admin) def enable_qr(bot, update): chat_id = get_chat_id(update) TBDB.set_chat_qr_enabled(chat_id, 1) @@ -750,7 +748,7 @@ def enable_qr(bot, update): is_group = chat_id < 0 ) -@command(bypass_admin_check=True) +@command def translate(bot, update): chat_id = get_chat_id(update) message = update.message @@ -790,11 +788,11 @@ def translate(bot, update): message.reply_text(translation) -@command(bypass_admin_check=False) +@command(tbfilters.chat_admin) def stats(bot, update): pass -@command(bypass_admin_check=False) +@command(tbfilters.chat_admin) def donate(bot, update): chat_id = get_chat_id(update) bot.send_message( @@ -804,7 +802,7 @@ def donate(bot, update): is_group = chat_id < 0 ) -@command(bypass_admin_check=True) +@command def privacy(bot, update): chat_id = get_chat_id(update) bot.send_message( diff --git a/src/transcriberbot/tbfilters.py b/src/transcriberbot/tbfilters.py index 3946b4a..41b0c69 100644 --- a/src/transcriberbot/tbfilters.py +++ b/src/transcriberbot/tbfilters.py @@ -2,9 +2,6 @@ from telegram.ext import BaseFilter class FilterIsAdmin(BaseFilter): - def __init__(self, bot): - self.bot = bot - def filter(self, message): if message.chat.id >= 0: return True @@ -20,11 +17,15 @@ def filter(self, message): return is_admin +chat_admin = FilterIsAdmin() + class FilterIsOwner(BaseFilter): - def __init__(self, bot): - self.bot = bot - self.owners = config.get_config_prop('telegram')['admins'] + #def __init__(self): + #self.owners = config.get_config_prop('telegram')['admins'] def filter(self, message): - is_owner = list(filter(lambda admin: owner == message.chat.id, self.owners)) - return len(is_owner) > 0 \ No newline at end of file + owners = config.get_config_prop('telegram')['admins'] + is_owner = list(filter(lambda admin: owner == message.chat.id, owners)) + return len(is_owner) > 0 + +bot_admin = FilterIsOwner() \ No newline at end of file From 8e1ccf4b8d44c2c7ac2ca920b707e278b2698eab Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 6 Mar 2019 15:22:46 +0100 Subject: [PATCH 012/120] added users command for admins --- src/database/db.py | 13 +++++++++++++ src/transcriberbot/bot.py | 13 +++++++++++++ src/transcriberbot/tbfilters.py | 6 +++--- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/database/db.py b/src/database/db.py index e0b7c41..a7a2266 100644 --- a/src/database/db.py +++ b/src/database/db.py @@ -138,4 +138,17 @@ def get_chat_ban(chat_id): def set_chat_ban(chat_id, ban): with TBDB._get_db() as db: db.execute("UPDATE chats SET ban='{0}' WHERE chat_id='{1}'".format(ban, chat_id)) + + + @staticmethod + def get_chats_num(): + with TBDB._get_db() as db: + c = db.execute("SELECT count(*) FROM chats") + return int(c.fetchone()[0]) + + @staticmethod + def get_active_chats_num(): + with TBDB._get_db() as db: + c = db.execute("SELECT count(*) FROM chats where active=1") + return int(c.fetchone()[0]) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index fb96c1d..6008396 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -811,3 +811,16 @@ def privacy(bot, update): parse_mode='html', is_group = chat_id < 0 ) + +# Admins commands +@command(tbfilters.bot_admin) +def users(bot, update): + chat_id = get_chat_id(update) + tot_chats = TBDB.get_chats_num() + active_chats = TBDB.get_active_chats_num() + bot.send_message( + chat_id=chat_id, + text='Total users: {}\nActive users: {}'.format(tot_chats, active_chats), + parse_mode='html', + is_group=chat_id < 0 + ) \ No newline at end of file diff --git a/src/transcriberbot/tbfilters.py b/src/transcriberbot/tbfilters.py index 41b0c69..70d12ca 100644 --- a/src/transcriberbot/tbfilters.py +++ b/src/transcriberbot/tbfilters.py @@ -21,11 +21,11 @@ def filter(self, message): class FilterIsOwner(BaseFilter): #def __init__(self): - #self.owners = config.get_config_prop('telegram')['admins'] + #self.admins = config.get_config_prop('telegram')['admins'] def filter(self, message): - owners = config.get_config_prop('telegram')['admins'] - is_owner = list(filter(lambda admin: owner == message.chat.id, owners)) + admins = config.get_config_prop('telegram')['admins'] + is_owner = list(filter(lambda admin: admin == str(message.chat.id), admins)) return len(is_owner) > 0 bot_admin = FilterIsOwner() \ No newline at end of file From a96fd83fa6dfe9d530c8797bbaf1419293069e55 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 6 Mar 2019 15:41:39 +0100 Subject: [PATCH 013/120] active cache initialized from db --- src/database/db.py | 8 +++++++- src/transcriberbot/bot.py | 7 ++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/database/db.py b/src/database/db.py index a7a2266..36156ec 100644 --- a/src/database/db.py +++ b/src/database/db.py @@ -64,7 +64,13 @@ def get_chat_entry(chat_id): cursor = db.execute("SELECT * FROM chats WHERE chat_id='{0}'".format(chat_id)) return cursor.fetchone() - + @staticmethod + def get_chats(): + with TBDB._get_db() as db: + db.assoc() + cursor = db.execute("SELECT * FROM chats") + return [dict(x) for x in cursor.fetchall()] + @staticmethod def get_chat_lang(chat_id): chat_record = TBDB.get_chat_entry(chat_id) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index 6008396..183f26d 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -57,7 +57,12 @@ def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs): self._is_messages_queued_default = is_queued_def self._msg_queue = mqueue or mq.MessageQueue() - self.active_chats_cache = {} + chats = TBDB.get_chats() + print(chats) + self.active_chats_cache = dict(zip( + [c['chat_id'] for c in chats], + [c['active'] for c in chats] + )) def __del__(self): try: From 481212977d628e3fbce365d345a0f6a45820fcf7 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 6 Mar 2019 15:58:37 +0100 Subject: [PATCH 014/120] added handlers for new/left chat member --- src/transcriberbot/bot.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index 183f26d..4c041db 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -633,6 +633,25 @@ def photo(bot, update): process_media_photo, bot, update, p, chat ) +@message(Filters.status_update.new_chat_members) +def new_chat_member(bot, update): + chat_id = get_chat_id(update) + message = update.message or channel_post + + if bot.get_me() in message.new_chat_members: + welcome_message(bot, update) + +@message(Filters.status_update.left_chat_member) +def left_chat_member(bot, update): + chat_id = get_chat_id(update) + message = update.message or channel_post + + if message.left_chat_member.id == bot.get_me().id: + logger.info('Marking chat {} as inactive'.format(chat_id)) + bot.active_chats_cache[chat_id] = 0 + TBDB.set_chat_active(chat_id, bot.active_chats_cache[chat_id]) + + # Command callbacks def welcome_message(bot, update): chat_id = get_chat_id(update) From a402ddb7223039213db0fa97cb2c94e5bf3b2bd6 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 6 Mar 2019 18:42:39 +0100 Subject: [PATCH 015/120] typo --- .gitignore | 1 + src/transcriberbot/bot.py | 5 ++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 708e75c..137e598 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ src/__pycache__/ .pytest_cache/ data/database.db media/ +.vscode/ diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index 4c041db..ad81a5d 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -635,8 +635,7 @@ def photo(bot, update): @message(Filters.status_update.new_chat_members) def new_chat_member(bot, update): - chat_id = get_chat_id(update) - message = update.message or channel_post + message = update.message or update.channel_post if bot.get_me() in message.new_chat_members: welcome_message(bot, update) @@ -644,7 +643,7 @@ def new_chat_member(bot, update): @message(Filters.status_update.left_chat_member) def left_chat_member(bot, update): chat_id = get_chat_id(update) - message = update.message or channel_post + message = update.message or update.channel_post if message.left_chat_member.id == bot.get_me().id: logger.info('Marking chat {} as inactive'.format(chat_id)) From 34a2eddeb85eeb1baf108ed8d0d23b9cb7e43e33 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 6 Mar 2019 19:23:12 +0100 Subject: [PATCH 016/120] moved handlers to separate files --- src/transcriberbot/__init__.py | 3 +- src/transcriberbot/bot.py | 564 +----------------------- src/transcriberbot/handlers_commands.py | 178 ++++++++ src/transcriberbot/handlers_messages.py | 389 ++++++++++++++++ src/transcriberbot/handlers_query.py | 34 ++ 5 files changed, 604 insertions(+), 564 deletions(-) create mode 100644 src/transcriberbot/handlers_commands.py create mode 100644 src/transcriberbot/handlers_messages.py create mode 100644 src/transcriberbot/handlers_query.py diff --git a/src/transcriberbot/__init__.py b/src/transcriberbot/__init__.py index c935b87..f88bbe9 100644 --- a/src/transcriberbot/__init__.py +++ b/src/transcriberbot/__init__.py @@ -1,3 +1,4 @@ from transcriberbot.bot import TranscriberBot from transcriberbot.bot import message -from transcriberbot.bot import init \ No newline at end of file +from transcriberbot.bot import init +from transcriberbot import handlers_commands, handlers_messages, handlers_query \ No newline at end of file diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index ad81a5d..a0d25bb 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -20,7 +20,6 @@ from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackQueryHandler, Filters from telegram.ext import messagequeue as mq from telegram.utils.request import Request -from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.error import Unauthorized from concurrent.futures import ThreadPoolExecutor @@ -254,404 +253,6 @@ def install_language_handlers(language): def init(): functional.apply_fn(get_language_list(), install_language_handlers) -# Message callbacks -@message(Filters.text & Filters.private) -def private_message(bot, update): - chat_id = get_chat_id(update) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("message_private", TBDB.get_chat_lang(chat_id)) - ) - -@callback_query -def stop(bot, update): - query = update.callback_query - - TranscriberBot.get().stop_thread(query.data) - logger.debug("Stopping thread %s", query.data) - logger.debug("Thread %s running: %r", query.data, TranscriberBot.get().thread_running(query.data)) - - string_stopped = R.get_string_resource( - "transcription_stopped", - TBDB.get_chat_lang(query.message.chat_id) - ) - - bot.edit_message_text( - text=query.message.text + " " + string_stopped, - chat_id=query.message.chat_id, - message_id=query.message.message_id, - parse_mode="html", - is_group=query.message.chat_id < 0 - ) - -def transcribe_audio_file(bot, update, path): - chat_id = get_chat_id(update) - lang = TBDB.get_chat_lang(chat_id) - message_id = get_message_id(update) - is_group = chat_id < 0 - - message = bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("transcribing", lang) + "\n", - reply_to_message_id=message_id, - parse_mode="html", - is_group=is_group - ).result() - - TranscriberBot.get().start_thread(message_id) - logger.debug("Starting thread %d", message_id) - - keyboard = InlineKeyboardMarkup( - [[InlineKeyboardButton("Stop", callback_data=message_id)]] - ) - - text = R.get_string_resource("transcription_text", lang) + "\n" - success = False - for speech in audiotools.transcribe(path, lang): - logger.debug("Thread %d running: %r", message_id, TranscriberBot.get().thread_running(message_id)) - if TranscriberBot.get().thread_running(message_id) is False: - TranscriberBot.get().del_thread(message_id) - return - - retry = True - retry_num = 0 - - while retry and TranscriberBot.get().thread_running(message_id): - try: - if len(text + speech) >= 4080: - text = R.get_string_resource("transcription_continues", lang) + "\n" - message = bot.send_message( - chat_id=chat_id, - text=text + speech + " [..]", - reply_to_message_id=message.message_id, - parse_mode="html", - is_group=is_group, - reply_markup=keyboard - ).result() - else: - message = bot.edit_message_text( - text=text + speech + " [..]", - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group, - reply_markup=keyboard - ).result() - - text += speech - retry = False - success = True - - except telegram.error.TimedOut as t: - logger.error("Timeout error %s", traceback.format_exc()) - retry_num += 1 - if retry_num >= 3: - retry = False - - except telegram.error.RetryAfter as r: - logger.warning("Retrying after %d", r.retry_after) - time.sleep(r.retry_after) - - except telegram.error.TelegramError as te: - logger.error("Telegram error %s", traceback.format_exc()) - retry = False - - except Exception as e: - logger.error("Exception %s", traceback.format_exc()) - retry = False - - retry = True - retry_num = 0 - while retry and TranscriberBot.get().thread_running(message_id): - try: - if success: - bot.edit_message_text( - text=text, - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - ) - else: - bot.edit_message_text( - R.get_string_resource("transcription_failed", lang), - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - ) - retry = False - except telegram.error.TimedOut as t: - logger.error("Timeout error %s", traceback.format_exc()) - retry_num += 1 - if retry_num >= 3: - retry = False - - except telegram.error.RetryAfter as r: - logger.warning("Retrying after %d", r.retry_after) - time.sleep(r.retry_after) - - except telegram.error.TelegramError as te: - logger.error("Telegram error %s", traceback.format_exc()) - retry = False - - except Exception as e: - logger.error("Exception %s", traceback.format_exc()) - retry = False - - TranscriberBot.get().del_thread(message_id) - -def process_media_voice(bot, update, media, name): - chat_id = get_chat_id(update) - file_size = media.file_size - - if file_size >= 20*(1024**2): - message_id = get_message_id(update) - message = bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("file_too_big", lang) + "\n", - reply_to_message_id=message_id, - parse_mode="html", - is_group=chat_id < 0 - ).result() - return - - file_id = media.file_id - file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) - file = bot.get_file(file_id) - file.download(file_path) - - try: - transcribe_audio_file(bot, update, file_path) - except Exception as e: - logger.error("Exception handling %s from %d: %s", name, chat_id, traceback.format_exc()) - - finally: - os.remove(file_path) - -@message(Filters.voice) -def voice(bot, update): - chat_id = get_chat_id(update) - voice_enabled = TBDB.get_chat_voice_enabled(chat_id) - if voice_enabled == 0: - return - - v = None - if update.message is not None: - v = update.message.voice - elif update.channel_post is not None: - v = update.channel_post.voice - file_id = v.file_id - - if voice_enabled == 2: - pass - else: - TranscriberBot.get().voice_thread_pool.submit( - process_media_voice, bot, update, v, "voice" - ) - -@message(Filters.audio) -def audio(bot, update): - chat_id = get_chat_id(update) - voice_enabled = TBDB.get_chat_voice_enabled(chat_id) - - if voice_enabled == 0: - return - - a = None - if update.message is not None: - a = update.message.audio - elif update.channel_post is not None: - a = update.channel_post.audio - - if voice_enabled == 2: - pass - else: - TranscriberBot.get().voice_thread_pool.submit( - process_media_voice, bot, update, a, "audio" - ) - -@message(Filters.document) -def document(bot, update): - chat_id = get_chat_id(update) - voice_enabled = TBDB.get_chat_voice_enabled(chat_id) - - m = update.message or update.channel_post - file_name = m.document.file_name - _, file_ext = os.path.splitext(file_name) - - if file_ext[1:] not in config.get_config_prop("app")["audio_ext"]: - logger.info('extension %s not recognized', file_ext) - return - - if voice_enabled == 0: - return - - if voice_enabled == 2: - pass - else: - TranscriberBot.get().voice_thread_pool.submit( - process_media_voice, bot, update, m.document, 'audio_document' - ) - -@message(Filters.video_note) -def video_note(bot, update): - chat_id = get_chat_id(update) - voice_enabled = TBDB.get_chat_voice_enabled(chat_id) - - if voice_enabled == 0: - return - - vn = None - if update.message is not None: - vn = update.message.video_note - elif update.channel_post is not None: - vn = update.channel_post.video_note - - if voice_enabled == 2: - pass - else: - TranscriberBot.get().voice_thread_pool.submit( - process_media_voice, bot, update, vn, "video_note" - ) - -def process_media_photo(bot, update, photo, chat): - chat_id = get_chat_id(update) - message_id = get_message_id(update) - is_group = chat_id < 0 - - message = None - - if chat["photos_enabled"] == 1: - message = bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("photo_recognizing", chat["lang"]), - reply_to_message_id=message_id, - parse_mode="html", - is_group=is_group - ).result() - - file_id = photo[-1].file_id - file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) - bot.get_file(file_id).download(file_path) - - def process(message): - if chat["qr_enabled"] == 1: - qr = phototools.read_qr(file_path, chat["lang"]) - if qr is not None: - qr = R.get_string_resource("qr_result", chat["lang"]) + "\n" + qr - - if message is not None: - bot.edit_message_text( - text=qr, - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - ) - return - else: - message = bot.send_message( - chat_id=chat_id, - text=qr, - reply_to_message_id=message_id, - parse_mode="html", - is_group=is_group - ).result() - """bot.edit_message_text( - R.get_string_resource("qr_no_text", lang), - chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - )""" - - if chat["photos_enabled"] == 1: - text = phototools.image_ocr(file_path, chat["lang"]) - if text is not None: - text = R.get_string_resource("ocr_result", chat["lang"]) + "\n" + text - bot.edit_message_text( - text=text, - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - ) - return - - bot.edit_message_text( - text=R.get_string_resource("photo_no_text", lang), - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - ) - - retry = True - retry_num = 0 - try: - while retry: - process(message) - retry = False - - except telegram.error.TimedOut as t: - logger.error("Timeout error %s", traceback.format_exc()) - retry_num += 1 - if retry_num >= 3: - retry = False - - except telegram.error.RetryAfter as r: - logger.warning("Retrying after %d", r.retry_after) - time.sleep(r.retry_after) - - except telegram.error.TelegramError as te: - logger.error("Telegram error %s", traceback.format_exc()) - retry = False - - except Exception as e: - logger.error("Exception %s", traceback.format_exc()) - retry = False - - finally: - os.remove(file_path) - -@message(Filters.photo) -def photo(bot, update): - chat_id = get_chat_id(update) - chat = TBDB.get_chat_entry(chat_id) - if chat["qr_enabled"] == 0 and chat["photos_enabled"] == 0: - return - - p = None - if update.message is not None: - p = update.message.photo - elif update.channel_post is not None: - p = update.channel_post.photo - - if p: - TranscriberBot.get().photos_thread_pool.submit( - process_media_photo, bot, update, p, chat - ) - -@message(Filters.status_update.new_chat_members) -def new_chat_member(bot, update): - message = update.message or update.channel_post - - if bot.get_me() in message.new_chat_members: - welcome_message(bot, update) - -@message(Filters.status_update.left_chat_member) -def left_chat_member(bot, update): - chat_id = get_chat_id(update) - message = update.message or update.channel_post - - if message.left_chat_member.id == bot.get_me().id: - logger.info('Marking chat {} as inactive'.format(chat_id)) - bot.active_chats_cache[chat_id] = 0 - TBDB.set_chat_active(chat_id, bot.active_chats_cache[chat_id]) - - -# Command callbacks def welcome_message(bot, update): chat_id = get_chat_id(update) message_id = get_message_id(update) @@ -683,167 +284,4 @@ def welcome_message(bot, update): language = R.iso639_2_to_639_1(language) logger.debug("No record found for chat {}, creating one with lang {}".format(chat_id, language)) - TBDB.create_default_chat_entry(chat_id, language) - -@command(filters=tbfilters.chat_admin) -def start(bot, update): - welcome_message(bot, update) - -@command(filters=tbfilters.chat_admin) -def help(bot, update): - welcome_message(bot, update) - -@command(filters=tbfilters.chat_admin) -def lang(bot, update): - chat_id = get_chat_id(update) - bot.send_message(chat_id=chat_id, text=TBDB.get_chat_lang(chat_id)) - -@command(filters=tbfilters.chat_admin) -def rate(bot, update): - chat_id = get_chat_id(update) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("message_rate", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def disable_voice(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_voice_enabled(chat_id, 0) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("voice_disabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def enable_voice(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_voice_enabled(chat_id, 1) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("voice_enabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def voice_ask(bot, update): - pass - -@command(tbfilters.chat_admin) -def disable_photos(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_photos_enabled(chat_id, 0) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("photos_disabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def enable_photos(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_photos_enabled(chat_id, 1) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("photos_enabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def disable_qr(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_qr_enabled(chat_id, 0) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("qr_disabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def enable_qr(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_qr_enabled(chat_id, 1) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("qr_enabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command -def translate(bot, update): - chat_id = get_chat_id(update) - message = update.message - if not message: - message = update.channel_post - - if not message: - return - - lang = message.text - lang = lang.replace("/translate", "").strip() - logger.debug("Language %s", lang) - - if lang not in config.get_config_prop("app")["languages"]: - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("translate_language_not_found", TBDB.get_chat_lang(chat_id)).format(lang), - is_group = chat_id < 0 - ) - return - - lang = config.get_config_prop("app")["languages"][lang].split('-')[0] - - if not message.reply_to_message: - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("translate_reply_to_message", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - return - - translation = translator.translate( - source=TBDB.get_chat_lang(chat_id), - target=lang, - text=message.reply_to_message.text - ) - - message.reply_text(translation) - -@command(tbfilters.chat_admin) -def stats(bot, update): - pass - -@command(tbfilters.chat_admin) -def donate(bot, update): - chat_id = get_chat_id(update) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("message_donate", TBDB.get_chat_lang(chat_id)), - parse_mode="html", - is_group = chat_id < 0 - ) - -@command -def privacy(bot, update): - chat_id = get_chat_id(update) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("privacy_policy", TBDB.get_chat_lang(chat_id)), - parse_mode='html', - is_group = chat_id < 0 - ) - -# Admins commands -@command(tbfilters.bot_admin) -def users(bot, update): - chat_id = get_chat_id(update) - tot_chats = TBDB.get_chats_num() - active_chats = TBDB.get_active_chats_num() - bot.send_message( - chat_id=chat_id, - text='Total users: {}\nActive users: {}'.format(tot_chats, active_chats), - parse_mode='html', - is_group=chat_id < 0 - ) \ No newline at end of file + TBDB.create_default_chat_entry(chat_id, language) \ No newline at end of file diff --git a/src/transcriberbot/handlers_commands.py b/src/transcriberbot/handlers_commands.py new file mode 100644 index 0000000..8ffefff --- /dev/null +++ b/src/transcriberbot/handlers_commands.py @@ -0,0 +1,178 @@ +import config +from database import TBDB +import resources as R + +from transcriberbot import tbfilters +from transcriberbot.bot import TranscriberBot +from transcriberbot.bot import get_chat_id, get_message_id, get_language_list, welcome_message, command + +from telegram.ext import Filters +from transcriberbot import tbfilters + +import translator + +import logging +logger = logging.getLogger(__name__) + +@command(filters=tbfilters.chat_admin) +def start(bot, update): + welcome_message(bot, update) + +@command(filters=tbfilters.chat_admin) +def help(bot, update): + welcome_message(bot, update) + +@command(filters=tbfilters.chat_admin) +def lang(bot, update): + chat_id = get_chat_id(update) + bot.send_message(chat_id=chat_id, text=TBDB.get_chat_lang(chat_id)) + +@command(filters=tbfilters.chat_admin) +def rate(bot, update): + chat_id = get_chat_id(update) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("message_rate", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(tbfilters.chat_admin) +def disable_voice(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_voice_enabled(chat_id, 0) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("voice_disabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(tbfilters.chat_admin) +def enable_voice(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_voice_enabled(chat_id, 1) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("voice_enabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(tbfilters.chat_admin) +def voice_ask(bot, update): + pass + +@command(tbfilters.chat_admin) +def disable_photos(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_photos_enabled(chat_id, 0) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("photos_disabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(tbfilters.chat_admin) +def enable_photos(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_photos_enabled(chat_id, 1) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("photos_enabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(tbfilters.chat_admin) +def disable_qr(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_qr_enabled(chat_id, 0) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("qr_disabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command(tbfilters.chat_admin) +def enable_qr(bot, update): + chat_id = get_chat_id(update) + TBDB.set_chat_qr_enabled(chat_id, 1) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("qr_enabled", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + +@command +def translate(bot, update): + chat_id = get_chat_id(update) + message = update.message + if not message: + message = update.channel_post + + if not message: + return + + lang = message.text + lang = lang.replace("/translate", "").strip() + logger.debug("Language %s", lang) + + if lang not in config.get_config_prop("app")["languages"]: + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("translate_language_not_found", TBDB.get_chat_lang(chat_id)).format(lang), + is_group = chat_id < 0 + ) + return + + lang = config.get_config_prop("app")["languages"][lang].split('-')[0] + + if not message.reply_to_message: + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("translate_reply_to_message", TBDB.get_chat_lang(chat_id)), + is_group = chat_id < 0 + ) + return + + translation = translator.translate( + source=TBDB.get_chat_lang(chat_id), + target=lang, + text=message.reply_to_message.text + ) + + message.reply_text(translation) + +@command(tbfilters.chat_admin) +def stats(bot, update): + pass + +@command(tbfilters.chat_admin) +def donate(bot, update): + chat_id = get_chat_id(update) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("message_donate", TBDB.get_chat_lang(chat_id)), + parse_mode="html", + is_group = chat_id < 0 + ) + +@command +def privacy(bot, update): + chat_id = get_chat_id(update) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("privacy_policy", TBDB.get_chat_lang(chat_id)), + parse_mode='html', + is_group = chat_id < 0 + ) + +# Admins commands +@command(tbfilters.bot_admin) +def users(bot, update): + chat_id = get_chat_id(update) + tot_chats = TBDB.get_chats_num() + active_chats = TBDB.get_active_chats_num() + bot.send_message( + chat_id=chat_id, + text='Total users: {}\nActive users: {}'.format(tot_chats, active_chats), + parse_mode='html', + is_group=chat_id < 0 + ) \ No newline at end of file diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py new file mode 100644 index 0000000..f4283e2 --- /dev/null +++ b/src/transcriberbot/handlers_messages.py @@ -0,0 +1,389 @@ +import config +from database import TBDB +import resources as R + +from transcriberbot import tbfilters +from transcriberbot.bot import TranscriberBot +from transcriberbot.bot import get_chat_id, get_message_id, get_language_list, welcome_message, message + +import telegram +from telegram.ext import Filters +from transcriberbot import tbfilters +from telegram import InlineKeyboardButton, InlineKeyboardMarkup + +import audiotools +import phototools +import logging +import traceback +import time +import os + +logger = logging.getLogger(__name__) + +# Message callbacks +@message(Filters.text & Filters.private) +def private_message(bot, update): + chat_id = get_chat_id(update) + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("message_private", TBDB.get_chat_lang(chat_id)) + ) + +def transcribe_audio_file(bot, update, path): + chat_id = get_chat_id(update) + lang = TBDB.get_chat_lang(chat_id) + message_id = get_message_id(update) + is_group = chat_id < 0 + + message = bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("transcribing", lang) + "\n", + reply_to_message_id=message_id, + parse_mode="html", + is_group=is_group + ).result() + + TranscriberBot.get().start_thread(message_id) + logger.debug("Starting thread %d", message_id) + + keyboard = InlineKeyboardMarkup( + [[InlineKeyboardButton("Stop", callback_data=message_id)]] + ) + + text = R.get_string_resource("transcription_text", lang) + "\n" + success = False + for speech in audiotools.transcribe(path, lang): + logger.debug("Thread %d running: %r", message_id, TranscriberBot.get().thread_running(message_id)) + if TranscriberBot.get().thread_running(message_id) is False: + TranscriberBot.get().del_thread(message_id) + return + + retry = True + retry_num = 0 + + while retry and TranscriberBot.get().thread_running(message_id): + try: + if len(text + speech) >= 4080: + text = R.get_string_resource("transcription_continues", lang) + "\n" + message = bot.send_message( + chat_id=chat_id, + text=text + speech + " [..]", + reply_to_message_id=message.message_id, + parse_mode="html", + is_group=is_group, + reply_markup=keyboard + ).result() + else: + message = bot.edit_message_text( + text=text + speech + " [..]", + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group, + reply_markup=keyboard + ).result() + + text += speech + retry = False + success = True + + except telegram.error.TimedOut as t: + logger.error("Timeout error %s", traceback.format_exc()) + retry_num += 1 + if retry_num >= 3: + retry = False + + except telegram.error.RetryAfter as r: + logger.warning("Retrying after %d", r.retry_after) + time.sleep(r.retry_after) + + except telegram.error.TelegramError as te: + logger.error("Telegram error %s", traceback.format_exc()) + retry = False + + except Exception as e: + logger.error("Exception %s", traceback.format_exc()) + retry = False + + retry = True + retry_num = 0 + while retry and TranscriberBot.get().thread_running(message_id): + try: + if success: + bot.edit_message_text( + text=text, + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + ) + else: + bot.edit_message_text( + R.get_string_resource("transcription_failed", lang), + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + ) + retry = False + except telegram.error.TimedOut as t: + logger.error("Timeout error %s", traceback.format_exc()) + retry_num += 1 + if retry_num >= 3: + retry = False + + except telegram.error.RetryAfter as r: + logger.warning("Retrying after %d", r.retry_after) + time.sleep(r.retry_after) + + except telegram.error.TelegramError as te: + logger.error("Telegram error %s", traceback.format_exc()) + retry = False + + except Exception as e: + logger.error("Exception %s", traceback.format_exc()) + retry = False + + TranscriberBot.get().del_thread(message_id) + +def process_media_voice(bot, update, media, name): + chat_id = get_chat_id(update) + file_size = media.file_size + + if file_size >= 20*(1024**2): + message_id = get_message_id(update) + message = bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("file_too_big", TBDB.get_chat_lang(chat_id)) + "\n", + reply_to_message_id=message_id, + parse_mode="html", + is_group=chat_id < 0 + ).result() + return + + file_id = media.file_id + file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) + file = bot.get_file(file_id) + file.download(file_path) + + try: + transcribe_audio_file(bot, update, file_path) + except Exception as e: + logger.error("Exception handling %s from %d: %s", name, chat_id, traceback.format_exc()) + + finally: + os.remove(file_path) + +@message(Filters.voice) +def voice(bot, update): + chat_id = get_chat_id(update) + voice_enabled = TBDB.get_chat_voice_enabled(chat_id) + if voice_enabled == 0: + return + + v = None + if update.message is not None: + v = update.message.voice + elif update.channel_post is not None: + v = update.channel_post.voice + file_id = v.file_id + + if voice_enabled == 2: + pass + else: + TranscriberBot.get().voice_thread_pool.submit( + process_media_voice, bot, update, v, "voice" + ) + +@message(Filters.audio) +def audio(bot, update): + chat_id = get_chat_id(update) + voice_enabled = TBDB.get_chat_voice_enabled(chat_id) + + if voice_enabled == 0: + return + + a = None + if update.message is not None: + a = update.message.audio + elif update.channel_post is not None: + a = update.channel_post.audio + + if voice_enabled == 2: + pass + else: + TranscriberBot.get().voice_thread_pool.submit( + process_media_voice, bot, update, a, "audio" + ) + +@message(Filters.document) +def document(bot, update): + chat_id = get_chat_id(update) + voice_enabled = TBDB.get_chat_voice_enabled(chat_id) + + m = update.message or update.channel_post + file_name = m.document.file_name + _, file_ext = os.path.splitext(file_name) + + if file_ext[1:] not in config.get_config_prop("app")["audio_ext"]: + logger.info('extension %s not recognized', file_ext) + return + + if voice_enabled == 0: + return + + if voice_enabled == 2: + pass + else: + TranscriberBot.get().voice_thread_pool.submit( + process_media_voice, bot, update, m.document, 'audio_document' + ) + +@message(Filters.video_note) +def video_note(bot, update): + chat_id = get_chat_id(update) + voice_enabled = TBDB.get_chat_voice_enabled(chat_id) + + if voice_enabled == 0: + return + + vn = None + if update.message is not None: + vn = update.message.video_note + elif update.channel_post is not None: + vn = update.channel_post.video_note + + if voice_enabled == 2: + pass + else: + TranscriberBot.get().voice_thread_pool.submit( + process_media_voice, bot, update, vn, "video_note" + ) + +def process_media_photo(bot, update, photo, chat): + chat_id = get_chat_id(update) + message_id = get_message_id(update) + is_group = chat_id < 0 + + message = None + + if chat["photos_enabled"] == 1: + message = bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("photo_recognizing", chat["lang"]), + reply_to_message_id=message_id, + parse_mode="html", + is_group=is_group + ).result() + + file_id = photo[-1].file_id + file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) + bot.get_file(file_id).download(file_path) + + def process(message): + if chat["qr_enabled"] == 1: + qr = phototools.read_qr(file_path, chat["lang"]) + if qr is not None: + qr = R.get_string_resource("qr_result", chat["lang"]) + "\n" + qr + + if message is not None: + bot.edit_message_text( + text=qr, + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + ) + return + else: + message = bot.send_message( + chat_id=chat_id, + text=qr, + reply_to_message_id=message_id, + parse_mode="html", + is_group=is_group + ).result() + + if chat["photos_enabled"] == 1: + text = phototools.image_ocr(file_path, chat["lang"]) + if text is not None: + text = R.get_string_resource("ocr_result", chat["lang"]) + "\n" + text + bot.edit_message_text( + text=text, + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + ) + return + + bot.edit_message_text( + text=R.get_string_resource("photo_no_text", chat["lang"]), + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", + is_group=is_group + ) + + retry = True + retry_num = 0 + try: + while retry: + process(message) + retry = False + + except telegram.error.TimedOut as t: + logger.error("Timeout error %s", traceback.format_exc()) + retry_num += 1 + if retry_num >= 3: + retry = False + + except telegram.error.RetryAfter as r: + logger.warning("Retrying after %d", r.retry_after) + time.sleep(r.retry_after) + + except telegram.error.TelegramError as te: + logger.error("Telegram error %s", traceback.format_exc()) + retry = False + + except Exception as e: + logger.error("Exception %s", traceback.format_exc()) + retry = False + + finally: + os.remove(file_path) + +@message(Filters.photo) +def photo(bot, update): + chat_id = get_chat_id(update) + chat = TBDB.get_chat_entry(chat_id) + if chat["qr_enabled"] == 0 and chat["photos_enabled"] == 0: + return + + p = None + if update.message is not None: + p = update.message.photo + elif update.channel_post is not None: + p = update.channel_post.photo + + if p: + TranscriberBot.get().photos_thread_pool.submit( + process_media_photo, bot, update, p, chat + ) + +@message(Filters.status_update.new_chat_members) +def new_chat_member(bot, update): + message = update.message or update.channel_post + + if bot.get_me() in message.new_chat_members: + welcome_message(bot, update) + +@message(Filters.status_update.left_chat_member) +def left_chat_member(bot, update): + chat_id = get_chat_id(update) + message = update.message or update.channel_post + + if message.left_chat_member.id == bot.get_me().id: + logger.info('Marking chat {} as inactive'.format(chat_id)) + bot.active_chats_cache[chat_id] = 0 + TBDB.set_chat_active(chat_id, bot.active_chats_cache[chat_id]) \ No newline at end of file diff --git a/src/transcriberbot/handlers_query.py b/src/transcriberbot/handlers_query.py new file mode 100644 index 0000000..849ab94 --- /dev/null +++ b/src/transcriberbot/handlers_query.py @@ -0,0 +1,34 @@ +import config +from database import TBDB +import resources as R + +from transcriberbot import tbfilters +from transcriberbot.bot import TranscriberBot +from transcriberbot.bot import get_chat_id, get_message_id, get_language_list, callback_query + +from telegram.ext import Filters +from transcriberbot import tbfilters + +import logging +logger = logging.getLogger(__name__) + +@callback_query +def stop(bot, update): + query = update.callback_query + + TranscriberBot.get().stop_thread(query.data) + logger.debug("Stopping thread %s", query.data) + logger.debug("Thread %s running: %r", query.data, TranscriberBot.get().thread_running(query.data)) + + string_stopped = R.get_string_resource( + "transcription_stopped", + TBDB.get_chat_lang(query.message.chat_id) + ) + + bot.edit_message_text( + text=query.message.text + " " + string_stopped, + chat_id=query.message.chat_id, + message_id=query.message.message_id, + parse_mode="html", + is_group=query.message.chat_id < 0 + ) \ No newline at end of file From 1fec2dfec5a4b5bcbbe00b5b360d8098e7db7b4e Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Thu, 7 Mar 2019 11:08:10 +0100 Subject: [PATCH 017/120] removed unused vars --- src/transcriberbot/handlers_messages.py | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index f4283e2..a7f91dd 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -152,13 +152,13 @@ def process_media_voice(bot, update, media, name): if file_size >= 20*(1024**2): message_id = get_message_id(update) - message = bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("file_too_big", TBDB.get_chat_lang(chat_id)) + "\n", - reply_to_message_id=message_id, - parse_mode="html", - is_group=chat_id < 0 - ).result() + bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("file_too_big", TBDB.get_chat_lang(chat_id)) + "\n", + reply_to_message_id=message_id, + parse_mode="html", + is_group=chat_id < 0 + ) return file_id = media.file_id @@ -170,7 +170,6 @@ def process_media_voice(bot, update, media, name): transcribe_audio_file(bot, update, file_path) except Exception as e: logger.error("Exception handling %s from %d: %s", name, chat_id, traceback.format_exc()) - finally: os.remove(file_path) @@ -185,8 +184,7 @@ def voice(bot, update): if update.message is not None: v = update.message.voice elif update.channel_post is not None: - v = update.channel_post.voice - file_id = v.file_id + v = update.channel_post.voice if voice_enabled == 2: pass From a33c90899daa5fb423ac4e4804edc503e73d19a1 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Thu, 7 Mar 2019 14:03:22 +0100 Subject: [PATCH 018/120] added basic split on silence --- src/audiotools/speech.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index 65a026a..bd43138 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -44,11 +44,18 @@ def __transcribe_chunk(chunk, lang): return text -def __generate_chunks(segment, length=20, split_on_silence=False): +def __generate_chunks(segment, length=20, split_on_silence=False, noise_threshold=-16): chunks = list() if split_on_silence is False: for i in range(0, len(segment), length*1000): chunks.append(segment[i:i+length*1000]) + else: + chunks = pydub.silence.split_on_silence(segment, noise_threshold) + for i, chunk in enumerate(chunks): + if len(chunk) > length*1000: + subchunks = __generate_chunks(chunk, length, split_on_silence, noise_threshold+4) + chunks = chunks[:i-1] + subchunks + chunks[i+1:] + return chunks def __preprocess_audio(audio): From 7a04f99c9f41ba7772c800e3bf425d632ae41280 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Thu, 7 Mar 2019 17:24:46 +0100 Subject: [PATCH 019/120] added IT localization --- src/transcriberbot/handlers_commands.py | 2 +- values/strings.xml | 4 +- values/strings_it-IT.xml | 72 ++++++++++++++++++++++++- 3 files changed, 73 insertions(+), 5 deletions(-) diff --git a/src/transcriberbot/handlers_commands.py b/src/transcriberbot/handlers_commands.py index 8ffefff..7c98c78 100644 --- a/src/transcriberbot/handlers_commands.py +++ b/src/transcriberbot/handlers_commands.py @@ -154,7 +154,7 @@ def donate(bot, update): is_group = chat_id < 0 ) -@command +@command(filters=None) def privacy(bot, update): chat_id = get_chat_id(update) bot.send_message( diff --git a/values/strings.xml b/values/strings.xml index 774bf64..080fb59 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -19,7 +19,7 @@ You can /donate if you like this bot. This will help us maintain the service and https://telegram.me/storebot?start=transcriber_bot -You can make a donation for transcriber_bot on PayPal. This will really help us, thanks for your support! +You can make a donation for TranscriberBot on PayPal. This will really help us, thanks for your support! Money from donations will be used for paying the server and backend costs and let the devs make new features! @@ -59,7 +59,7 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} {b}WARNING:{/b} flood detected. Stop spamming please -Unknown language: {} +Unknown language: {language} You must reply to a message in order to translate it We do not store any personal data or media content (such as audio or pictures). The only user data we store is the telegram chat id along with the chosen settings. Voice/audio messages are sent to (wit.ai https://wit.ai/terms) for transcription, and are immediately deleted after the transcription is completed. Pictures are immediately deleted from our server after OCR or QR recognition is perfomed (offline). diff --git a/values/strings_it-IT.xml b/values/strings_it-IT.xml index 5fa2b34..3965407 100644 --- a/values/strings_it-IT.xml +++ b/values/strings_it-IT.xml @@ -1,6 +1,74 @@ - Lingua impostata in Italiano - Messaggio benvenuto italiano +Lingua impostata in Italiano + + +Questo bot trascrive messaggi vocali e immagini in testo. +Aggiungimi ad un gruppo o inoltrami i messaggi vocali ricevuti. + +Scegli una lingua (per i messaggi vocali): +{languages} + +Per qualsiasi problema, o per metterti in contatto con gli sviluppatori, usa @transcribersupport_bot. +Puoi effettuare una donazione con il comando /donate, ci aiuterà a sostenere i costi del servizio e a migliorarlo. + +{b}Nota{/b}: nei gruppi, il bot risponderà solo ai comandi dati {b}dagli admin{/b} + + + +Puoi fare una donazione per TranscriberBot su PayPal. +Le donazioni ci sono di grande aiuto, grazie! +I ricavi verranno utilizzati per pagare il costo dei server e consentire lo sviluppo di nuove features. + + + +Puoi anche effettuare una donazione in BTC, ETH o LTC + +BTC: {code}1DTrCfoNb9RLJnR5dfJvo9zwRjBZj8j1PY{/code} + +ETH: {code}0x0b784efc808527c75a8ef12a80622c41c28d45bd{/code} + +LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} + + + +Mandami un messaggio vocale o un'immagine con del testo + + +Voce abilitata +Voce disabilitata +Foto abilitate +Foto disabilitate +QR abilitato +QR disabilitato + +Spiacente, il file è troppo grande! (20MB max) + +Trascrivendo.. +L'audio è molto lungo ({0}s), ci vorrà un po' +{b}Testo:{/b} +{b}[continua]:{/b} +Non sono riuscito a trascrivere l'audio +{b}[Fermato]{/b} + +Riconoscimento.. +{b}Testo riconosciuto:{/b} +Nessun testo riconosciuto +{b}Codice QR rilevato:{/b} +Nessun codice QR rilevato + +{b}ATTENZIONE:{/b} flood rilevato. Stop allo spam, perfavore + +Lingua sconosciuta: {language} +Devi rispondere a un messaggio, per poterlo tradurre + + +Non memorizziamo nessun dato personale o contenuto multimediale (come audio o immagini). +Gli unici dati che conserviamo sono l'id della chat di telegram, insieme alle impostazioni scelte. +I messaggi vocali/file audio sono inoltrati a wit.ai (https://wit.ai/terms) per la trascrizione,e vengono immediatamente cancellati al termine. +Le immagini vengono rimosse dai nostri server dopo che l'OCR o il rilevamento di QR sono stati effettuati (offline). + +NON memorizziamo nessun CONTENUTO dei messaggi (testo, multimedia o altro). + \ No newline at end of file From db7ca0cdeb7ceea207b7c62758e68cba9e91ebc9 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Fri, 8 Mar 2019 15:13:52 +0100 Subject: [PATCH 020/120] added space between chunks --- src/transcriberbot/handlers_messages.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index a7f91dd..d09d42e 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -83,7 +83,7 @@ def transcribe_audio_file(bot, update, path): reply_markup=keyboard ).result() - text += speech + text += ' ' + speech retry = False success = True From e957a50fdf81b5a2ab7bd289fa58793538dbc5e2 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Fri, 8 Mar 2019 15:36:56 +0100 Subject: [PATCH 021/120] dropped mp4 support (gifs) --- config/app.json | 1 - src/audiotools/speech.py | 8 ++++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/config/app.json b/config/app.json index 0bf13df..6619c7c 100644 --- a/config/app.json +++ b/config/app.json @@ -36,7 +36,6 @@ "opus", "3gpp", "m4a", - "mp4", "ogg" ], diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index bd43138..9a22d9a 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -44,13 +44,17 @@ def __transcribe_chunk(chunk, lang): return text -def __generate_chunks(segment, length=20, split_on_silence=False, noise_threshold=-16): +def __generate_chunks(segment, length=20, split_on_silence=False, noise_threshold=-36): chunks = list() if split_on_silence is False: for i in range(0, len(segment), length*1000): chunks.append(segment[i:i+length*1000]) else: - chunks = pydub.silence.split_on_silence(segment, noise_threshold) + while len(chunks) < 1: + logger.debug('split_on_silence (threshold %d)', noise_threshold) + chunks = pydub.silence.split_on_silence(segment, noise_threshold) + noise_threshold += 4 + for i, chunk in enumerate(chunks): if len(chunk) > length*1000: subchunks = __generate_chunks(chunk, length, split_on_silence, noise_threshold+4) From 982207916734d31510b5e60ede992e03c99bf58c Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Fri, 8 Mar 2019 15:38:57 +0100 Subject: [PATCH 022/120] updated strings-IT --- values/strings_it-IT.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/values/strings_it-IT.xml b/values/strings_it-IT.xml index 3965407..2b65ac7 100644 --- a/values/strings_it-IT.xml +++ b/values/strings_it-IT.xml @@ -45,7 +45,7 @@ Mandami un messaggio vocale o un'immagine con del testo Spiacente, il file è troppo grande! (20MB max) -Trascrivendo.. +Trascrizione.. L'audio è molto lungo ({0}s), ci vorrà un po' {b}Testo:{/b} {b}[continua]:{/b} From 5c783603a0b0d9fe07e71bf02bb6b5777ccd936c Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sat, 9 Mar 2019 17:25:10 +0100 Subject: [PATCH 023/120] fixed string placeholder substitution --- src/resources/loader.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/resources/loader.py b/src/resources/loader.py index c330e40..a78cf99 100644 --- a/src/resources/loader.py +++ b/src/resources/loader.py @@ -32,9 +32,9 @@ def _load_xml_resouce(path): if lang not in strings_r: strings_r[lang] = {} - replacements = ('{b}', ''), ('{/b}', ''), + replacements = (('{b}', ''), ('{/b}', ''), ('{i}', ''), ('{/i}', ''), - ('{code}', ''), ('{/code}', '') + ('{code}', ''), ('{/code}', '')) for string in e.findall('string'): if string.text is None: From 8e3efdcf693366fe67df857e60d0456a26e11a31 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 12 Mar 2019 14:34:26 +0100 Subject: [PATCH 024/120] updated strings --- values/strings.xml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/values/strings.xml b/values/strings.xml index 080fb59..4f63eb8 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -62,7 +62,12 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} Unknown language: {language} You must reply to a message in order to translate it -We do not store any personal data or media content (such as audio or pictures). The only user data we store is the telegram chat id along with the chosen settings. Voice/audio messages are sent to (wit.ai https://wit.ai/terms) for transcription, and are immediately deleted after the transcription is completed. Pictures are immediately deleted from our server after OCR or QR recognition is perfomed (offline). -We do NOT store ANY message content (text, multimedia or anything else). + +We do not store any personal data or media content (such as audio or pictures). +The only user data we store is the telegram chat id along with the chosen settings. +Voice/audio messages are sent to (wit.ai https://wit.ai/terms) for transcription, and are immediately deleted after the transcription is completed. +Pictures are immediately deleted from our server after OCR or QR recognition is perfomed (offline). +We do NOT store ANY message content (text, multimedia or anything else). + \ No newline at end of file From bfb7c4189368fd2359293655b6e51b14056ea158 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 12 Mar 2019 15:24:42 +0100 Subject: [PATCH 025/120] added broadcast message --- src/transcriberbot/bot.py | 4 +++ src/transcriberbot/handlers_commands.py | 38 +++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index a0d25bb..a75e4d6 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -142,6 +142,10 @@ def start(self, token): max_workers=config.get_config_prop("app")["photos_max_threads"] ) + self.misc_thread_pool = ThreadPoolExecutor( + max_workers=2 + ) + self.queue = mq.MessageQueue() self.request = Request(con_pool_size=10) self.mqbot = self.MQBot(token, request=self.request, mqueue=self.queue) diff --git a/src/transcriberbot/handlers_commands.py b/src/transcriberbot/handlers_commands.py index 7c98c78..801a2fd 100644 --- a/src/transcriberbot/handlers_commands.py +++ b/src/transcriberbot/handlers_commands.py @@ -10,7 +10,8 @@ from transcriberbot import tbfilters import translator - +import time +import traceback import logging logger = logging.getLogger(__name__) @@ -175,4 +176,37 @@ def users(bot, update): text='Total users: {}\nActive users: {}'.format(tot_chats, active_chats), parse_mode='html', is_group=chat_id < 0 - ) \ No newline at end of file + ) + +@command(tbfilters.bot_admin) +def post(bot, update): + chat_id = get_chat_id(update) + text = update.message.text[6:] + + def __post(): + chats = TBDB.get_chats() + sent = 0 + + for chat in chats: + try: + bot.send_message( + chat_id=chat['chat_id'], + text=text, + parse_mode='html', + is_group=int(chat['chat_id']) < 0 + ) + sent += 1 + time.sleep(0.1) + except Exception as e: + logger.error( + "Exception sending broadcast to %d: (%s) %s", + chat['chat_id'], e, traceback.format_exc()) + + bot.send_message( + chat_id=chat_id, + text='Broadcast sent to {}/{} chats'.format(sent, len(chats)), + is_group = chat_id < 0 + ) + TranscriberBot.get().command_handlers['users'](bot, update) + + TranscriberBot.get().misc_thread_pool.submit(__post) \ No newline at end of file From 694276e5c157b1724cecbbe3abac7a39062e1e6e Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 12 Mar 2019 16:29:13 +0100 Subject: [PATCH 026/120] removed unnecessary if-else --- src/transcriberbot/handlers_messages.py | 35 ++++++++----------------- 1 file changed, 11 insertions(+), 24 deletions(-) diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index d09d42e..eb38514 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -180,12 +180,9 @@ def voice(bot, update): if voice_enabled == 0: return - v = None - if update.message is not None: - v = update.message.voice - elif update.channel_post is not None: - v = update.channel_post.voice - + message = update.message or update.channel_post + v = message.voice + if voice_enabled == 2: pass else: @@ -200,13 +197,10 @@ def audio(bot, update): if voice_enabled == 0: return - - a = None - if update.message is not None: - a = update.message.audio - elif update.channel_post is not None: - a = update.channel_post.audio + message = update.message or update.channel_post + a = message.audio + if voice_enabled == 2: pass else: @@ -245,11 +239,8 @@ def video_note(bot, update): if voice_enabled == 0: return - vn = None - if update.message is not None: - vn = update.message.video_note - elif update.channel_post is not None: - vn = update.channel_post.video_note + message = update.message or update.channel_post + vn = message.video_note if voice_enabled == 2: pass @@ -358,15 +349,11 @@ def photo(bot, update): if chat["qr_enabled"] == 0 and chat["photos_enabled"] == 0: return - p = None - if update.message is not None: - p = update.message.photo - elif update.channel_post is not None: - p = update.channel_post.photo + message = update.message or update.channel_post - if p: + if message.photo: TranscriberBot.get().photos_thread_pool.submit( - process_media_photo, bot, update, p, chat + process_media_photo, bot, update, message.photo, chat ) @message(Filters.status_update.new_chat_members) From 1dff50fe9235643efdee35eff19504fe5ad6f79c Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 26 Mar 2019 16:53:24 +0100 Subject: [PATCH 027/120] updated requirements --- requirements.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index eb560f8..2b950df 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,4 +4,5 @@ pillow watchdog tesserocr pydub -zbarlight \ No newline at end of file +zbarlight +requests \ No newline at end of file From 07736e62fd7a89689057f546fd1d20c3aedd0637 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 26 Mar 2019 16:56:53 +0100 Subject: [PATCH 028/120] removed print --- src/transcriberbot/bot.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index a75e4d6..0b68964 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -57,7 +57,6 @@ def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs): self._msg_queue = mqueue or mq.MessageQueue() chats = TBDB.get_chats() - print(chats) self.active_chats_cache = dict(zip( [c['chat_id'] for c in chats], [c['active'] for c in chats] From 7abd244845974332a0ea16bdf54fa0107754a4fe Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 26 Mar 2019 17:09:35 +0100 Subject: [PATCH 029/120] dropped singleton db (test) --- src/database/db.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/database/db.py b/src/database/db.py index 36156ec..31c3b39 100644 --- a/src/database/db.py +++ b/src/database/db.py @@ -6,7 +6,7 @@ logger = logging.getLogger(__name__) -class Database(metaclass=metaclass.Singleton): +class Database(): __instance = None def __init__(self, database): From b188c5b843290d96757516b54a79da3e3c4c0c0c Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Thu, 23 May 2019 17:00:53 +0200 Subject: [PATCH 030/120] Fix default chat entry missing --- src/transcriberbot/bot.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index 0b68964..4e76ee1 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -196,6 +196,10 @@ def __pre__hook(self, fn, b, u, **kwargs): if chat_id in self.floods and self.floods[chat_id] is True: return + if not TBDB.get_chat_entry(chat_id): + # happens when welcome/joined message is not received + TBDB.create_default_chat_entry(chat_id, 'en-US') + if chat_id in self.mqbot.active_chats_cache and self.mqbot.active_chats_cache[chat_id] == 0: logger.debug("Marking chat {} as active".format(chat_id)) self.mqbot.active_chats_cache[chat_id] = 1 From c004873c693c90f8935c2c3fd973efea842a482c Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Fri, 24 May 2019 10:01:19 +0200 Subject: [PATCH 031/120] default photos_enabled=0 --- src/database/db.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/database/db.py b/src/database/db.py index 31c3b39..621cf0f 100644 --- a/src/database/db.py +++ b/src/database/db.py @@ -55,7 +55,10 @@ def _get_db(): @staticmethod def create_default_chat_entry(chat_id, lang): with TBDB._get_db() as db: - db.execute("INSERT INTO chats VALUES(?, ?, ?, ?, ?, ?, ?)", (chat_id, lang, 1, 1, 1, 1, 0)) + db.execute( + "INSERT INTO chats VALUES(chat_id, lang, voice_enabled, photos_enabled, qr_enabled, active, ban)", + (chat_id, lang, 1, 0, 0, 1, 0) + ) @staticmethod def get_chat_entry(chat_id): From 7c3c452eaa57ddd6d9e5d3c880d14514486f7620 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Fri, 24 May 2019 10:26:23 +0200 Subject: [PATCH 032/120] fix query --- src/database/db.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/database/db.py b/src/database/db.py index 621cf0f..4a92579 100644 --- a/src/database/db.py +++ b/src/database/db.py @@ -56,7 +56,7 @@ def _get_db(): def create_default_chat_entry(chat_id, lang): with TBDB._get_db() as db: db.execute( - "INSERT INTO chats VALUES(chat_id, lang, voice_enabled, photos_enabled, qr_enabled, active, ban)", + "INSERT INTO chats(chat_id, lang, voice_enabled, photos_enabled, qr_enabled, active, ban) VALUES(?,?,?,?,?,?,?)", (chat_id, lang, 1, 0, 0, 1, 0) ) From 8116b3713010f42deaba316f5664756bf676f4e6 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 26 May 2019 17:32:56 +0200 Subject: [PATCH 033/120] fix translate command handler --- src/transcriberbot/handlers_commands.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/transcriberbot/handlers_commands.py b/src/transcriberbot/handlers_commands.py index 801a2fd..5efea9d 100644 --- a/src/transcriberbot/handlers_commands.py +++ b/src/transcriberbot/handlers_commands.py @@ -101,13 +101,10 @@ def enable_qr(bot, update): is_group = chat_id < 0 ) -@command +@command() def translate(bot, update): chat_id = get_chat_id(update) - message = update.message - if not message: - message = update.channel_post - + message = update.message or update.channel_post if not message: return From 8d5fe6bf67c32912d5effda2d8b48253fe8890af Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 7 Jul 2019 12:17:10 +0200 Subject: [PATCH 034/120] update version --- config/app.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/app.json b/config/app.json index 6619c7c..982ca4e 100644 --- a/config/app.json +++ b/config/app.json @@ -1,5 +1,5 @@ { - "version": "2.5.0", + "version": "3.0.0", "database": "data/database.db", "media_path": "media", "languages" : { @@ -47,4 +47,4 @@ "time_threshold_flood": 5, "timeout": 10 } -} \ No newline at end of file +} From 75d8f514a015ea458c9a63b9d0151b2be9698976 Mon Sep 17 00:00:00 2001 From: ThigSchuch Date: Sun, 7 Jul 2019 09:11:02 -0300 Subject: [PATCH 035/120] Added PTBR Translation --- values/strings_pt-BR.xml | 74 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 values/strings_pt-BR.xml diff --git a/values/strings_pt-BR.xml b/values/strings_pt-BR.xml new file mode 100644 index 0000000..a48f3d6 --- /dev/null +++ b/values/strings_pt-BR.xml @@ -0,0 +1,74 @@ + + + +Linguagem definida para Português do Brasil + + +Este bot transcreve áudio e imagens em texto. +Adicione-me a um grupo ou encaminhe mensagens e imagens para mim! + +Escolha uma linguagem (para mensagens de voz): +{languages} + +/rate avalie este bot ou deixe seu comentário aqui (https://telegram.me/storebot?start=transcriber_bot) + +Se estiver tendo problemas, ou quer entrar em contato com os desenvolvedores, contate @transcribersupport_bot +Você pode /donate (doar) se gostar do bot. Isso nos ajudará a manter o serviço e continuar melhorando-o. +{b}Observação{/b}: em grupos, o bot responderá {b}apenas comandos de administradores{/b} + + +https://telegram.me/storebot?start=transcriber_bot + +Você pode doar para o TranscriberBot no Paypal. Nos ajudará muito, obrigado pelo seu apoio! +Dinheiro das doações será usado para pagar o servidor, custos de desenvolvimento, e deixar os desenvolvedores fazerem novos recursos! + + + +Você também pode doar em BTC, ETH ou LTC + +BTC: {code}1DTrCfoNb9RLJnR5dfJvo9zwRjBZj8j1PY{/code} + +ETH: {code}0x0b784efc808527c75a8ef12a80622c41c28d45bd{/code} + +LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} + + +Envie-me uma mensagem de voz ou uma imagem com texto + +Voz ativada +Voz desativada +Imagens ativadas +Imagens desativadas +QR ativado +QR desativado + +Desculpe, arquivo muito grande! (limite de 20MB) + +Transcrevendo.. +Áudio muito longo ({0}s), isso demorará um pouco +{b}Texto:{/b} +{b}[continua]:{/b} +Não pude transcrever o áudio +{b}[Parado]{/b} + +Reconhecendo.. +{b}Texto reconhecido:{/b} +Texto não reconhecido +{b}Código QR encontrado:{/b} +Código QR não encontrado + +{b}ATENÇÃO:{/b} flood detectado. Pare de fazer spam, por favor + +Linguagem desconhecida: {language} +Você deve responder a uma mensagem para traduzí-la + + +Nós não armazenamos nenhuma informação ou mídia pessoal (como audios ou imagens). +Os únicos dados que armazenamos é o ID da conversa, juntamente com as configurações escolhidas. +Mensagens de Voz/Áudio são enviadas para (wit.ai https://wit.ai/terms) para transcrição, e são imediatamente apagadas após a transcrição é finalizada. +Imagens são imediatamente apagadas do nosso servidor após o reconhecimento de OCR ou QR é realizado (offline). + +Nós NÃO armazenamos NENHUM conteúdo de mensagens (texto, multimídia ou qualquer outra coisa). + + + \ No newline at end of file From 764cdbc12944241e808889249b72c71fbe09f9dd Mon Sep 17 00:00:00 2001 From: vetu11 Date: Mon, 8 Jul 2019 02:09:34 +0200 Subject: [PATCH 036/120] Translation to Spanish(es-ES) --- values/strings_es-ES.xml | 73 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 values/strings_es-ES.xml diff --git a/values/strings_es-ES.xml b/values/strings_es-ES.xml new file mode 100644 index 0000000..b75f187 --- /dev/null +++ b/values/strings_es-ES.xml @@ -0,0 +1,73 @@ + + + +Idioma establecido como Español + + +Este bot transcribe audio e imágenes a texto. +Añádeme a un grupo o reenvíame mensajes de audio o imagenes! + +Selecciona el idioma (para los mensajes de audio): +{languages} + +Si tienes algún problema o quieres ponerte en contacto con los desarrolladores usa @transcribersupport_bot. +Puedes donar usando /donate si te gusta el bot, ayudará a mantener el servidor y a mejorar el servicio! + +{b}Nota{/b}: en los grupos el bot sólo responderá a {b}comandos de administradores.{/b} + + + +Puedes hacer donaciones a TranscriberBot a través de PayPal. +Las donaciones son de gran ayuda, gracias por el apoyo! +El dinero de las donaciones se usará para cubrir los costes del servidor y apoyar a los desarrolladores. + + + +También puedes donar en Bitcoin, Ethereum o Litecoin + +BTC: {code}1DTrCfoNb9RLJnR5dfJvo9zwRjBZj8j1PY{/code} + +ETH: {code}0x0b784efc808527c75a8ef12a80622c41c28d45bd{/code} + +LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} + + + +Mandame un mensaje de voz o una imagen con texto. + + +Mensajes de voz activados +Mensajes de voz desactivados +Imágenes activadas +Imágenes desactivadas +QR activado +QR desactivado + +¡Lo siento, el archivo es demasiado grande! (20MB max) + +Transcribiendo... +El audio es muy largo ({0}s), esto llevará un tiempo... +{b}Texto:{/b} +{b}[continúa]:{/b} +No se ha podido transcribir el audio +{b}[Interrumpido]{/b} + +Escaneando... +{b}Texto reconocido:{/b} +No se ha encontrado ningún texto +{b}Restulado del QR:{/b} +No se ha encontrado QR + +{b}Atención:{/b} flood detectado. Deja de espamear, por favor. + +Lenguaje desconocido: {language} +Tienes que responder a un mensaje para traducirlo + + +No guardamos ningún dato personal o de multimedia (como audio o mensajes) +Los únicos datos de usuarios que guardamos son la id de chat y las preferencias del mismo. +Los mensajes de audio se envían a (wit.ai https://wit.ai/terms) para la transcripción, y son inmediatamente borrados cuando la transcripción se ha completado. +Las fotos se borran inmediatamente de nuestro servidor una vez se ha escandado en busca de texto o QR (offline). +NO guardamos el contenido de NINGÚN mensaje (textp, multimedia o cualquier otra cosa) + + \ No newline at end of file From 978e88323b7493d96c2c26657150d93eb96564a5 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Tue, 9 Jul 2019 23:39:14 +0200 Subject: [PATCH 037/120] Fix strings_pt-BR --- values/strings_pt-BR.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/values/strings_pt-BR.xml b/values/strings_pt-BR.xml index a48f3d6..f14a432 100644 --- a/values/strings_pt-BR.xml +++ b/values/strings_pt-BR.xml @@ -1,6 +1,6 @@ - + Linguagem definida para Português do Brasil @@ -71,4 +71,4 @@ Imagens são imediatamente apagadas do nosso servidor após o reconhecimento de Nós NÃO armazenamos NENHUM conteúdo de mensagens (texto, multimídia ou qualquer outra coisa). - \ No newline at end of file + From 93549b2fe85da2ac59dc0ab1734c0688618396fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20Mart=C3=ADn=20Malag=C3=B3n?= <45206520+MaanuelMM@users.noreply.github.com> Date: Fri, 13 Mar 2020 20:24:37 +0100 Subject: [PATCH 038/120] Fix None wit.ai response due to segments length I discovered transcription functionality isn't working correctly since 14th February, and after doing some research, I discovered audio segments length are approximately 20.16 sec each one, so I applied a reduction factor of 1.001 to avoid that and, for the moment, it seems to be working great. --- src/audiotools/speech.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index 9a22d9a..e43da93 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -44,11 +44,11 @@ def __transcribe_chunk(chunk, lang): return text -def __generate_chunks(segment, length=20, split_on_silence=False, noise_threshold=-36): +def __generate_chunks(segment, length=20000/1001, split_on_silence=False, noise_threshold=-36): chunks = list() if split_on_silence is False: - for i in range(0, len(segment), length*1000): - chunks.append(segment[i:i+length*1000]) + for i in range(0, len(segment), int(length*1000)): + chunks.append(segment[i:i+int(length*1000)]) else: while len(chunks) < 1: logger.debug('split_on_silence (threshold %d)', noise_threshold) @@ -56,7 +56,7 @@ def __generate_chunks(segment, length=20, split_on_silence=False, noise_threshol noise_threshold += 4 for i, chunk in enumerate(chunks): - if len(chunk) > length*1000: + if len(chunk) > int(length*1000): subchunks = __generate_chunks(chunk, length, split_on_silence, noise_threshold+4) chunks = chunks[:i-1] + subchunks + chunks[i+1:] @@ -78,4 +78,4 @@ def transcribe(path, lang): logging.debug(r) if r is not None: - yield r \ No newline at end of file + yield r From 2bbaa0f1cc172ae838684bf0d77dc2b25c0f3724 Mon Sep 17 00:00:00 2001 From: Davte Date: Sat, 23 May 2020 14:45:28 +0200 Subject: [PATCH 039/120] Fixed python-telegram-bot transition to v12 issues Bot now receives and replies to /start command. Voice message transcribing still fails. --- src/transcriberbot/bot.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index 4e76ee1..71f5efa 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -148,7 +148,7 @@ def start(self, token): self.queue = mq.MessageQueue() self.request = Request(con_pool_size=10) self.mqbot = self.MQBot(token, request=self.request, mqueue=self.queue) - self.updater = Updater(bot=self.mqbot) + self.updater = Updater(bot=self.mqbot, use_context=True) self.dispatcher = self.updater.dispatcher self.__register_handlers() self.updater.start_polling(clean=True) @@ -181,12 +181,14 @@ def __add_handler(self, handler): def __add_error_handler(self, handler): self.dispatcher.add_error_handler(handler) - def __pre__hook(self, fn, b, u, **kwargs): + def __pre__hook(self, fn, u, c, **kwargs): + b = c.bot + m = u.message or u.channel_post if not m: return - age = (datetime.now() - m.date).total_seconds() + age = (datetime.utcnow() - m.date.replace(tzinfo=None)).total_seconds() if age > config.get_config_prop("app")["antiflood"]["age_threshold"]: return From 0cd3eaff82a371d0468c7fd8a3aab1c632cdfb3b Mon Sep 17 00:00:00 2001 From: Davte Date: Sat, 23 May 2020 15:21:43 +0200 Subject: [PATCH 040/120] Fixed wit.ai-related issue API response json key renamed (`_text` > `text`) --- src/audiotools/speech.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index e43da93..cbeff1b 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -38,6 +38,8 @@ def __transcribe_chunk(chunk, lang): if '_text' in res: text = res['_text'] + elif 'text' in res: # Changed in may 2020 + text = res['text'] except Exception as e: logger.error("Could not transcribe chunk: %s", traceback.format_exc()) @@ -78,4 +80,5 @@ def transcribe(path, lang): logging.debug(r) if r is not None: + print(f"Trascritto: {r}") yield r From 8bb19f874e8d35cd402dd72238a782e045033daa Mon Sep 17 00:00:00 2001 From: Davte Date: Sat, 23 May 2020 15:24:38 +0200 Subject: [PATCH 041/120] Print statement removed --- src/audiotools/speech.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index cbeff1b..9505fc8 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -80,5 +80,4 @@ def transcribe(path, lang): logging.debug(r) if r is not None: - print(f"Trascritto: {r}") yield r From c54d4b4d07f38879a7f7179ae8fa253c75fb0ad9 Mon Sep 17 00:00:00 2001 From: stefanodelbosco Date: Wed, 29 Jul 2020 20:31:21 +0200 Subject: [PATCH 042/120] Added Dockerfile and updated the version of python-telegram-bot in the requirements file --- Dockerfile | 13 +++++++++++++ dockerBuild.sh | 1 + dockerRun.sh | 7 +++++++ requirements.txt | 4 ++-- 4 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 Dockerfile create mode 100755 dockerBuild.sh create mode 100755 dockerRun.sh diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4ad9ca1 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM python:3.8.5-buster +RUN apt-get update +RUN apt-get install libzbar-dev libleptonica-dev libtesseract-dev ffmpeg -y +RUN rm -rf /var/lib/apt/lists/* +COPY requirements.txt . +RUN export LC_ALL=C +RUN export LC_CTYPE=C +RUN export LC_NUMERIC=C +RUN pip3 install -r requirements.txt +RUN pip cache purge +COPY src/ src/ +CMD [ "python3.8", "src/main.py" ] + diff --git a/dockerBuild.sh b/dockerBuild.sh new file mode 100755 index 0000000..6230571 --- /dev/null +++ b/dockerBuild.sh @@ -0,0 +1 @@ +docker build --tag transcriberbot . diff --git a/dockerRun.sh b/dockerRun.sh new file mode 100755 index 0000000..5b1933d --- /dev/null +++ b/dockerRun.sh @@ -0,0 +1,7 @@ +docker run \ + -e LC_ALL=C \ + -d --restart unless-stopped \ + -v "$(pwd)"/data:/data \ + -v "$(pwd)"/config:/config \ + -v "$(pwd)"/values:/values \ + transcriberbot diff --git a/requirements.txt b/requirements.txt index 2b950df..b29f863 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,8 +1,8 @@ -python-telegram-bot +python-telegram-bot==12.3.0 coloredlogs pillow watchdog tesserocr pydub zbarlight -requests \ No newline at end of file +requests From f0766a8a79211310a0416abe667d630b9ab0aa1a Mon Sep 17 00:00:00 2001 From: stefanodelbosco Date: Wed, 29 Jul 2020 20:33:43 +0200 Subject: [PATCH 043/120] Added name of container in dockerRun --- dockerRun.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/dockerRun.sh b/dockerRun.sh index 5b1933d..3826e74 100755 --- a/dockerRun.sh +++ b/dockerRun.sh @@ -1,6 +1,7 @@ docker run \ -e LC_ALL=C \ -d --restart unless-stopped \ + --name "transcriberbot" \ -v "$(pwd)"/data:/data \ -v "$(pwd)"/config:/config \ -v "$(pwd)"/values:/values \ From 8946c7027182665f01abe898fb5b297cce82501e Mon Sep 17 00:00:00 2001 From: stefanodelbosco Date: Wed, 29 Jul 2020 23:00:14 +0200 Subject: [PATCH 044/120] Added instructions for installation in README file --- README.md | 50 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 37c45b2..cd6b587 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,53 @@ # Transcriber Bot +[![Bot](https://img.shields.io/badge/Telegram Bot-@Transcriber_bot-0d86d7.svg?style=flat)][https://t.me/Transcriber_bot] [![News channel](https://img.shields.io/badge/News channel-@Transcriber_botNewsChannel-0d86d7.svg?style=flat)][https://t.me/Transcriber_botNewsChannel] + +## Installation + +1. Create your own Telegram bot from @BotFather and take the bot token + +2. Edit the file **config/telegram.json** + + `{ + "username": "BOT USERNAME", + "token": "BOT TOKEN", + "admins": [ "YOUR TELEGRAM ID" ] + }` + +3. Create your own Wit token on [Wit website](https://wit.ai/docs/quickstart) + +4. Edit the file **config/wit.json** (for example with italian token) + + `{ + "it-IT": "WIT TOKEN FOR Italian" + }` + + You can repeat the points 3 and 4 for support multiple languages. + +5. Create your own Yandex translate token on [Yandex website](https://tech.yandex.com/translate/) + +6. Edit the file **config/yandex.json** + + `{ + "translate_key": "YOUR YANDEX TOKEN" + }` + +## Installation with virtualenv + +**Todo...** + +## Installation with Docker + +You can install easily with Docker. + +1. Run the script **dockerBuild.sh** to generate the docker image from the Dockerfile. + +2. Run the script **dockerRun.sh** to create and start the docker container. + + In the run script, the docker directories **config**, **data** and **values** are binding with the repository directory. + If you want to edit the files in the configuration directories you can do this simply by stopping the container. + As soon as you finish editing the files, just restart the container to make them active. + ## TODO - [x] Voice Messages @@ -13,4 +61,4 @@ - [x] Antiflood - [x] Translations - [ ] Voice ask -- [x] Channels support \ No newline at end of file +- [x] Channels support From cf293e9db3131c1156905e778ed132699623e381 Mon Sep 17 00:00:00 2001 From: Stefano Delbosco Date: Wed, 29 Jul 2020 23:08:36 +0200 Subject: [PATCH 045/120] Update README.md fixed badge --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cd6b587..ac7caa5 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Transcriber Bot - -[![Bot](https://img.shields.io/badge/Telegram Bot-@Transcriber_bot-0d86d7.svg?style=flat)][https://t.me/Transcriber_bot] [![News channel](https://img.shields.io/badge/News channel-@Transcriber_botNewsChannel-0d86d7.svg?style=flat)][https://t.me/Transcriber_botNewsChannel] +[![Generic badge](https://img.shields.io/badge/Bot-@Transcriber_bot-0d86d7.svg)](https://shields.io) +[![Generic badge](https://img.shields.io/badge/News-@Transcriber_botNewsChannel-0d86d7.svg)](https://t.me/Transcriber_botNewsChannel) ## Installation From 47ba6efbbb417535b781283721a691a041646507 Mon Sep 17 00:00:00 2001 From: stefanodelbosco Date: Wed, 29 Jul 2020 23:18:33 +0200 Subject: [PATCH 046/120] Updated .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 137e598..e84709d 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ src/__pycache__/ data/database.db media/ .vscode/ +config/ From f75a9b5bd81d8a93329a1a41ecfa009b6ea381b8 Mon Sep 17 00:00:00 2001 From: stefanodelbosco Date: Wed, 29 Jul 2020 23:47:22 +0200 Subject: [PATCH 047/120] Update README.md fixed badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ac7caa5..0518c2a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Transcriber Bot -[![Generic badge](https://img.shields.io/badge/Bot-@Transcriber_bot-0d86d7.svg)](https://shields.io) +[![Generic badge](https://img.shields.io/badge/Bot-@Transcriber_bot-0d86d7.svg)](https://t.me/Transcriber_bot) [![Generic badge](https://img.shields.io/badge/News-@Transcriber_botNewsChannel-0d86d7.svg)](https://t.me/Transcriber_botNewsChannel) ## Installation From 3e21136fe2c99597482e49442a22e957163be17d Mon Sep 17 00:00:00 2001 From: Stefano Delbosco Date: Tue, 4 Aug 2020 18:01:55 +0200 Subject: [PATCH 048/120] Added virtualenv --- README.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0518c2a..7c97641 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Transcriber Bot + [![Generic badge](https://img.shields.io/badge/Bot-@Transcriber_bot-0d86d7.svg)](https://t.me/Transcriber_bot) [![Generic badge](https://img.shields.io/badge/News-@Transcriber_botNewsChannel-0d86d7.svg)](https://t.me/Transcriber_botNewsChannel) @@ -32,9 +33,34 @@ "translate_key": "YOUR YANDEX TOKEN" }` + + ## Installation with virtualenv -**Todo...** +1. Install virtualenv and setuptools package + + `$ python3 -m pip install --upgrade pip` + `$ pip3 install virtualenv setuptools` + +2. Make a note of the full file path to the custom version of Python you just installed + + `$ which python3 ` + +3. Create the virtual environment while you specify the version of Python you wish to use + + `$ virtualenv -p /usr/bin/python3 venv` + +4. Activate the new virtual environment + + `$ source venv/bin/activate` + +5. Install the requirement packages + + `(venv) $ pip3 install -r requirements.txt` + +6. Run the bot + + `(venv) $ python3 src/main.py` ## Installation with Docker From 36a1c249395d03747fe2c9d46a0f7cffb23f532f Mon Sep 17 00:00:00 2001 From: Stefano Delbosco Date: Tue, 4 Aug 2020 18:03:03 +0200 Subject: [PATCH 049/120] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7c97641..995cd39 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![Generic badge](https://img.shields.io/badge/Bot-@Transcriber_bot-0d86d7.svg)](https://t.me/Transcriber_bot) [![Generic badge](https://img.shields.io/badge/News-@Transcriber_botNewsChannel-0d86d7.svg)](https://t.me/Transcriber_botNewsChannel) -## Installation +## Quick Start 1. Create your own Telegram bot from @BotFather and take the bot token From 64821e8ff4e8837c113e29e187a253271f2e0754 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Thu, 14 Jan 2021 11:04:37 +0100 Subject: [PATCH 050/120] Update handlers_messages.py Lower maximum allowed message length --- src/transcriberbot/handlers_messages.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index eb38514..8659d4e 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -63,7 +63,7 @@ def transcribe_audio_file(bot, update, path): while retry and TranscriberBot.get().thread_running(message_id): try: - if len(text + speech) >= 4080: + if len(text + speech) >= 4000: text = R.get_string_resource("transcription_continues", lang) + "\n" message = bot.send_message( chat_id=chat_id, @@ -371,4 +371,4 @@ def left_chat_member(bot, update): if message.left_chat_member.id == bot.get_me().id: logger.info('Marking chat {} as inactive'.format(chat_id)) bot.active_chats_cache[chat_id] = 0 - TBDB.set_chat_active(chat_id, bot.active_chats_cache[chat_id]) \ No newline at end of file + TBDB.set_chat_active(chat_id, bot.active_chats_cache[chat_id]) From cb7857de1b0a12582461255904bd324652068af3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Thu, 25 Feb 2021 17:50:47 -0300 Subject: [PATCH 051/120] Organize imports according to PEP8 and remove spaces --- src/audiotools/speech.py | 25 +++++++++++++------------ src/config/__init__.py | 4 ++-- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index 9505fc8..3fa54d4 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -1,13 +1,14 @@ -import functional -import requests -import config +import io import logging import traceback -import pydub -import io +import requests +import pydub from pydub import AudioSegment +import config + + logger = logging.getLogger("speech") def __transcribe_chunk(chunk, lang): @@ -15,7 +16,7 @@ def __transcribe_chunk(chunk, lang): logger.error("Language not found in wit.json %s", lang) return None - logging.debug("Using key %s %s", lang, config.get_config_prop("wit")[lang]) + logger.debug("Using key %s %s", lang, config.get_config_prop("wit")[lang]) headers = { 'authorization': 'Bearer ' + config.get_config_prop("wit")[lang], @@ -24,18 +25,18 @@ def __transcribe_chunk(chunk, lang): } text = None - try: + try: request = requests.request( "POST", - "https://api.wit.ai/speech", - headers=headers, + "https://api.wit.ai/speech", + headers=headers, params = {'verbose': True}, data=io.BufferedReader(io.BytesIO(chunk.raw_data)) ) logger.debug("Request response %s", request.text) res = request.json() - + if '_text' in res: text = res['_text'] elif 'text' in res: # Changed in may 2020 @@ -46,7 +47,7 @@ def __transcribe_chunk(chunk, lang): return text -def __generate_chunks(segment, length=20000/1001, split_on_silence=False, noise_threshold=-36): +def __generate_chunks(segment, length=20000/1001, split_on_silence=False, noise_threshold=-36): chunks = list() if split_on_silence is False: for i in range(0, len(segment), int(length*1000)): @@ -56,7 +57,7 @@ def __generate_chunks(segment, length=20000/1001, split_on_silence=False, noise_ logger.debug('split_on_silence (threshold %d)', noise_threshold) chunks = pydub.silence.split_on_silence(segment, noise_threshold) noise_threshold += 4 - + for i, chunk in enumerate(chunks): if len(chunk) > int(length*1000): subchunks = __generate_chunks(chunk, length, split_on_silence, noise_threshold+4) diff --git a/src/config/__init__.py b/src/config/__init__.py index b54173a..c71e460 100644 --- a/src/config/__init__.py +++ b/src/config/__init__.py @@ -11,7 +11,7 @@ def parse_file(file): logger.info("Loading config file %s", file) - + with open(file) as f: data = json.load(f) return data @@ -37,4 +37,4 @@ def init(config_folder): def get_config_prop(key): global __configs - return __configs[key] \ No newline at end of file + return __configs[key] From 8f85b0c4fc04c29c0e0aca242c9b4515468a754a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Thu, 25 Feb 2021 17:52:26 -0300 Subject: [PATCH 052/120] Use specific logger instead of logging module --- src/audiotools/speech.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index 3fa54d4..52708a9 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -69,16 +69,16 @@ def __preprocess_audio(audio): return audio.set_sample_width(2).set_channels(1).set_frame_rate(8000) def transcribe(path, lang): - logging.info("Transcribing file %s", path) + logger.info("Transcribing file %s", path) audio = AudioSegment.from_file(path) chunks = __generate_chunks(__preprocess_audio(audio)) - logging.debug("Got %d chunks", len(chunks)) + logger.debug("Got %d chunks", len(chunks)) for i, chunk in enumerate(chunks): - logging.debug("Transcribing chunk %d", i) + logger.debug("Transcribing chunk %d", i) r = __transcribe_chunk(chunk, lang) - logging.debug(r) + logger.debug(r) if r is not None: yield r From 2b49849eb25a45a2f79ad234e38e01ccbc0e50c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Thu, 25 Feb 2021 17:55:02 -0300 Subject: [PATCH 053/120] Refactor speech.py and add CLI --- README.md | 10 ++- src/audiotools/speech.py | 44 ++++++++----- src/transcriberbot/handlers_messages.py | 82 +++++++++++++++---------- values/strings.xml | 12 ++-- values/strings_es-ES.xml | 5 +- values/strings_it-IT.xml | 7 ++- values/strings_pt-BR.xml | 2 + 7 files changed, 104 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 995cd39..be9d6b4 100644 --- a/README.md +++ b/README.md @@ -25,9 +25,15 @@ You can repeat the points 3 and 4 for support multiple languages. + You can test if your token is working by running: + + ` + $ python src/audiotools/speech.py wit_api_key some_file.mp3 transcription.txt + ` + 5. Create your own Yandex translate token on [Yandex website](https://tech.yandex.com/translate/) -6. Edit the file **config/yandex.json** +6. Edit the file **config/yandex.json** `{ "translate_key": "YOUR YANDEX TOKEN" @@ -70,7 +76,7 @@ You can install easily with Docker. 2. Run the script **dockerRun.sh** to create and start the docker container. - In the run script, the docker directories **config**, **data** and **values** are binding with the repository directory. + In the run script, the docker directories **config**, **data** and **values** are binding with the repository directory. If you want to edit the files in the configuration directories you can do this simply by stopping the container. As soon as you finish editing the files, just restart the container to make them active. diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index 52708a9..a88d01e 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -6,20 +6,12 @@ import pydub from pydub import AudioSegment -import config - logger = logging.getLogger("speech") -def __transcribe_chunk(chunk, lang): - if lang not in config.get_config_prop("wit"): - logger.error("Language not found in wit.json %s", lang) - return None - - logger.debug("Using key %s %s", lang, config.get_config_prop("wit")[lang]) - +def __transcribe_chunk(chunk, api_key): headers = { - 'authorization': 'Bearer ' + config.get_config_prop("wit")[lang], + 'authorization': 'Bearer ' + api_key, 'accept': 'application/vnd.wit.20180705+json', 'content-type': 'audio/raw;encoding=signed-integer;bits=16;rate=8000;endian=little', } @@ -30,7 +22,7 @@ def __transcribe_chunk(chunk, lang): "POST", "https://api.wit.ai/speech", headers=headers, - params = {'verbose': True}, + params={'verbose': True}, data=io.BufferedReader(io.BytesIO(chunk.raw_data)) ) @@ -68,7 +60,8 @@ def __generate_chunks(segment, length=20000/1001, split_on_silence=False, noise_ def __preprocess_audio(audio): return audio.set_sample_width(2).set_channels(1).set_frame_rate(8000) -def transcribe(path, lang): + +def transcribe(path, api_key): logger.info("Transcribing file %s", path) audio = AudioSegment.from_file(path) @@ -77,8 +70,31 @@ def transcribe(path, lang): for i, chunk in enumerate(chunks): logger.debug("Transcribing chunk %d", i) - r = __transcribe_chunk(chunk, lang) - logger.debug(r) + r = __transcribe_chunk(chunk, api_key) + logger.debug("Response received: %s", r) if r is not None: yield r + + +if __name__ == "__main__": + import argparse + import sys + + parser = argparse.ArgumentParser() + parser.add_argument("api_key") + parser.add_argument("input_filename") + parser.add_argument("output_filename") + args = parser.parse_args() + + if args.output_filename == "-": + output = sys.stdout + else: + output = open(args.output_filename, mode="w") + + result = transcribe(args.input_filename, args.api_key) + for part in result: + output.write(part + "\n") + output.flush() + + output.close() diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index 8659d4e..5edade9 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -25,7 +25,7 @@ def private_message(bot, update): chat_id = get_chat_id(update) bot.send_message( - chat_id=chat_id, + chat_id=chat_id, text=R.get_string_resource("message_private", TBDB.get_chat_lang(chat_id)) ) @@ -35,14 +35,27 @@ def transcribe_audio_file(bot, update, path): message_id = get_message_id(update) is_group = chat_id < 0 + api_key = config.get_config_prop("wit").get(lang, None) + if api_key is None: + logger.error("Language not found in wit.json %s", lang) + message = bot.send_message( + chat_id=chat_id, + text=R.get_string_resource("unknown_api_key", lang).format(language=lang) + "\n", + reply_to_message_id=message_id, + parse_mode="html", + is_group=is_group + ).result() + return + logger.debug("Using key %s for lang %s", api_key, lang) + message = bot.send_message( - chat_id=chat_id, + chat_id=chat_id, text=R.get_string_resource("transcribing", lang) + "\n", reply_to_message_id=message_id, parse_mode="html", is_group=is_group ).result() - + TranscriberBot.get().start_thread(message_id) logger.debug("Starting thread %d", message_id) @@ -52,7 +65,8 @@ def transcribe_audio_file(bot, update, path): text = R.get_string_resource("transcription_text", lang) + "\n" success = False - for speech in audiotools.transcribe(path, lang): + + for speech in audiotools.transcribe(path, api_key): logger.debug("Thread %d running: %r", message_id, TranscriberBot.get().thread_running(message_id)) if TranscriberBot.get().thread_running(message_id) is False: TranscriberBot.get().del_thread(message_id) @@ -75,8 +89,8 @@ def transcribe_audio_file(bot, update, path): ).result() else: message = bot.edit_message_text( - text=text + speech + " [..]", - chat_id=chat_id, + text=text + speech + " [..]", + chat_id=chat_id, message_id=message.message_id, parse_mode="html", is_group=is_group, @@ -92,7 +106,7 @@ def transcribe_audio_file(bot, update, path): retry_num += 1 if retry_num >= 3: retry = False - + except telegram.error.RetryAfter as r: logger.warning("Retrying after %d", r.retry_after) time.sleep(r.retry_after) @@ -111,8 +125,8 @@ def transcribe_audio_file(bot, update, path): try: if success: bot.edit_message_text( - text=text, - chat_id=chat_id, + text=text, + chat_id=chat_id, message_id=message.message_id, parse_mode="html", is_group=is_group @@ -131,7 +145,7 @@ def transcribe_audio_file(bot, update, path): retry_num += 1 if retry_num >= 3: retry = False - + except telegram.error.RetryAfter as r: logger.warning("Retrying after %d", r.retry_after) time.sleep(r.retry_after) @@ -142,7 +156,7 @@ def transcribe_audio_file(bot, update, path): except Exception as e: logger.error("Exception %s", traceback.format_exc()) - retry = False + retry = False TranscriberBot.get().del_thread(message_id) @@ -153,7 +167,7 @@ def process_media_voice(bot, update, media, name): if file_size >= 20*(1024**2): message_id = get_message_id(update) bot.send_message( - chat_id=chat_id, + chat_id=chat_id, text=R.get_string_resource("file_too_big", TBDB.get_chat_lang(chat_id)) + "\n", reply_to_message_id=message_id, parse_mode="html", @@ -163,7 +177,7 @@ def process_media_voice(bot, update, media, name): file_id = media.file_id file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) - file = bot.get_file(file_id) + file = bot.get_file(file_id) file.download(file_path) try: @@ -179,10 +193,10 @@ def voice(bot, update): voice_enabled = TBDB.get_chat_voice_enabled(chat_id) if voice_enabled == 0: return - + message = update.message or update.channel_post v = message.voice - + if voice_enabled == 2: pass else: @@ -197,7 +211,7 @@ def audio(bot, update): if voice_enabled == 0: return - + message = update.message or update.channel_post a = message.audio @@ -241,7 +255,7 @@ def video_note(bot, update): message = update.message or update.channel_post vn = message.video_note - + if voice_enabled == 2: pass else: @@ -258,8 +272,8 @@ def process_media_photo(bot, update, photo, chat): if chat["photos_enabled"] == 1: message = bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("photo_recognizing", chat["lang"]), + chat_id=chat_id, + text=R.get_string_resource("photo_recognizing", chat["lang"]), reply_to_message_id=message_id, parse_mode="html", is_group=is_group @@ -277,10 +291,10 @@ def process(message): if message is not None: bot.edit_message_text( - text=qr, - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", + text=qr, + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", is_group=is_group ) return @@ -298,19 +312,19 @@ def process(message): if text is not None: text = R.get_string_resource("ocr_result", chat["lang"]) + "\n" + text bot.edit_message_text( - text=text, - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", + text=text, + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", is_group=is_group ) return bot.edit_message_text( - text=R.get_string_resource("photo_no_text", chat["lang"]), - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", + text=R.get_string_resource("photo_no_text", chat["lang"]), + chat_id=chat_id, + message_id=message.message_id, + parse_mode="html", is_group=is_group ) @@ -326,7 +340,7 @@ def process(message): retry_num += 1 if retry_num >= 3: retry = False - + except telegram.error.RetryAfter as r: logger.warning("Retrying after %d", r.retry_after) time.sleep(r.retry_after) @@ -337,8 +351,8 @@ def process(message): except Exception as e: logger.error("Exception %s", traceback.format_exc()) - retry = False - + retry = False + finally: os.remove(file_path) diff --git a/values/strings.xml b/values/strings.xml index 4f63eb8..c5ae68f 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -63,11 +63,13 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} You must reply to a message in order to translate it -We do not store any personal data or media content (such as audio or pictures). -The only user data we store is the telegram chat id along with the chosen settings. -Voice/audio messages are sent to (wit.ai https://wit.ai/terms) for transcription, and are immediately deleted after the transcription is completed. -Pictures are immediately deleted from our server after OCR or QR recognition is perfomed (offline). +We do not store any personal data or media content (such as audio or pictures). +The only user data we store is the telegram chat id along with the chosen settings. +Voice/audio messages are sent to (wit.ai https://wit.ai/terms) for transcription, and are immediately deleted after the transcription is completed. +Pictures are immediately deleted from our server after OCR or QR recognition is perfomed (offline). We do NOT store ANY message content (text, multimedia or anything else). - \ No newline at end of file +{b}ERROR:{/b} oops, cannot find Wit API key for language {language}. :( + + diff --git a/values/strings_es-ES.xml b/values/strings_es-ES.xml index b75f187..34ed793 100644 --- a/values/strings_es-ES.xml +++ b/values/strings_es-ES.xml @@ -70,4 +70,7 @@ Los mensajes de audio se envían a (wit.ai https://wit.ai/terms) para la transcr Las fotos se borran inmediatamente de nuestro servidor una vez se ha escandado en busca de texto o QR (offline). NO guardamos el contenido de NINGÚN mensaje (textp, multimedia o cualquier otra cosa) - \ No newline at end of file + +{b}ERROR:{/b} oops, no encontré la llave API Wit para la lengua {language}. :( + + diff --git a/values/strings_it-IT.xml b/values/strings_it-IT.xml index 2b65ac7..8c4aff2 100644 --- a/values/strings_it-IT.xml +++ b/values/strings_it-IT.xml @@ -10,7 +10,7 @@ Aggiungimi ad un gruppo o inoltrami i messaggi vocali ricevuti. Scegli una lingua (per i messaggi vocali): {languages} -Per qualsiasi problema, o per metterti in contatto con gli sviluppatori, usa @transcribersupport_bot. +Per qualsiasi problema, o per metterti in contatto con gli sviluppatori, usa @transcribersupport_bot. Puoi effettuare una donazione con il comando /donate, ci aiuterà a sostenere i costi del servizio e a migliorarlo. {b}Nota{/b}: nei gruppi, il bot risponderà solo ai comandi dati {b}dagli admin{/b} @@ -71,4 +71,7 @@ Le immagini vengono rimosse dai nostri server dopo che l'OCR o il rilevamento di NON memorizziamo nessun CONTENUTO dei messaggi (testo, multimedia o altro). - \ No newline at end of file + +{b}ERRORE:{/b} ops, non ho trovato la chiave API Wit per la lingua {language}. :( + + diff --git a/values/strings_pt-BR.xml b/values/strings_pt-BR.xml index f14a432..8495e0c 100644 --- a/values/strings_pt-BR.xml +++ b/values/strings_pt-BR.xml @@ -71,4 +71,6 @@ Imagens são imediatamente apagadas do nosso servidor após o reconhecimento de Nós NÃO armazenamos NENHUM conteúdo de mensagens (texto, multimídia ou qualquer outra coisa). +{b}ERRO:{/b} ops, não encontrei a chave de API Wit para a língua {language}. :( + From 027adb85b80373e680c241ab94d6836dd2dbce46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Thu, 25 Feb 2021 19:45:12 -0300 Subject: [PATCH 054/120] Add space between each speech chunk Was fixed on a8242741bedb1c2320c2a3125db408c0fba27935 but only for final text. --- src/transcriberbot/handlers_messages.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index 5edade9..545ab86 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -77,11 +77,11 @@ def transcribe_audio_file(bot, update, path): while retry and TranscriberBot.get().thread_running(message_id): try: - if len(text + speech) >= 4000: + if len(text + " " + speech) >= 4000: text = R.get_string_resource("transcription_continues", lang) + "\n" message = bot.send_message( chat_id=chat_id, - text=text + speech + " [..]", + text=text + " " + speech + " [..]", reply_to_message_id=message.message_id, parse_mode="html", is_group=is_group, @@ -89,7 +89,7 @@ def transcribe_audio_file(bot, update, path): ).result() else: message = bot.edit_message_text( - text=text + speech + " [..]", + text=text + " " + speech + " [..]", chat_id=chat_id, message_id=message.message_id, parse_mode="html", @@ -97,7 +97,7 @@ def transcribe_audio_file(bot, update, path): reply_markup=keyboard ).result() - text += ' ' + speech + text += " " + speech retry = False success = True From bfbad44cba9d228c73d26d5c25e6d25a77e66fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Sun, 28 Feb 2021 06:57:19 -0300 Subject: [PATCH 055/120] Add more ignores to gitignore --- .gitignore | 119 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 104 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index e84709d..2547aad 100644 --- a/.gitignore +++ b/.gitignore @@ -1,17 +1,106 @@ -src/antiflood/__pycache__/ -src/audiotools/__pycache__/ -src/config/__pycache__/ -src/database/__pycache__/ -src/functional/__pycache__/ -src/metaclass/__pycache__/ -src/phototools/__pycache__/ -src/resources/__pycache__/ -src/tests/__pycache__/ -src/transcriberbot/__pycache__/ -src/translator/__pycache__/ -src/__pycache__/ -.pytest_cache/ -data/database.db +# TranscriberBot-specific ignores +config/ media/ + +# Generic data-related ignores +*.csv +*.db +*.sqlite +*.sqlite3 +data/ +db.sqlite3 +db.sqlite3-journal + +# Generic Python-related ignores +*$py.class +*.cover +*.egg +*.egg-info/ +*.log +*.manifest +*.mo +*.pot +*.py,cover +*.py[cod] +*.pyc +*.sage.py +*.spec +.Python +.activate +.cache +.coverage +.coverage.* +.directory +.dmypy.json +.eggs/ +.env +.hypothesis/ +.idea/* +.installed.cfg +.ipynb_checkpoints +.ipynb_checkpoints/ +.mypy_cache/ +.nox/ +.pybuilder/ +.pyre/ +.pytest_cache/ +.pytype/ +.ropeproject +.scrapy +.spyderproject +.spyproject +.tox +.tox/ +.venv +.webassets-cache +/site +ENV/ +MANIFEST +__pycache__/ +__pypackages__/ +build/ +build/* +celerybeat-schedule +celerybeat.pid +cover/ +coverage.xml +cython_debug/ +develop-eggs/ +dist/ +dist/* +dmypy.json +docs-build/ +docs/_build/ +docs/man/ +docs/reference/ +downloads/ +eggs/ +env.bak/ +env/ +htmlcov/ +instance/ +ipython_config.py +lib/ +lib64/ +local_settings.py +nosetests.xml +parts/ +pip-delete-this-directory.txt +pip-log.txt +profile_default/ +reg_settings.py +sdist/ +share/python-wheels/ +target/ +var/ +venv.bak/ +venv/ +wheels/ + +# Other ignores +*.so +*.sw? +*~ +.*.sw? +.DS_Store .vscode/ -config/ From c41db13cfc9e361a9d24d100ddd7cabbdf7e815d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Sun, 28 Feb 2021 06:57:32 -0300 Subject: [PATCH 056/120] Add a Docker ignore list --- .dockerignore | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..7fe22af --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +**/*.pyc +**/__pycache__ +.git +.pytest_cache From ab611f3629a4573ae4c4d1664ab04547680410d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Sun, 28 Feb 2021 06:58:03 -0300 Subject: [PATCH 057/120] Enhance Dockerfile - Clean apt and pip cache in same RUN command, so the Docker commit will be smaller - Explicitly disable installing recommended APT packages - Update pip before installing Python dependencies --- Dockerfile | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/Dockerfile b/Dockerfile index 4ad9ca1..20a3975 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,13 +1,26 @@ -FROM python:3.8.5-buster -RUN apt-get update -RUN apt-get install libzbar-dev libleptonica-dev libtesseract-dev ffmpeg -y -RUN rm -rf /var/lib/apt/lists/* -COPY requirements.txt . +FROM python:3.9-buster + +# Set global configs +WORKDIR / RUN export LC_ALL=C RUN export LC_CTYPE=C RUN export LC_NUMERIC=C -RUN pip3 install -r requirements.txt -RUN pip cache purge -COPY src/ src/ -CMD [ "python3.8", "src/main.py" ] +# Install system dependencies +RUN apt-get update +RUN apt-get install --no-install-recommends -y \ + ffmpeg \ + libleptonica-dev \ + libtesseract-dev \ + libzbar-dev \ + && \ + apt-get clean + +# Install Python dependencies +COPY requirements.txt . +RUN pip install --no-cache-dir -U pip && \ + pip install --no-cache-dir -r requirements.txt + +# Copy code and define default command +COPY src/ src/ +CMD [ "python", "src/main.py" ] From adf3fed5777790547c0a06944ff497c6b16d6867 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Sun, 28 Feb 2021 07:33:31 -0300 Subject: [PATCH 058/120] Use python-slim instead of buster as base image --- Dockerfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 20a3975..b4f5190 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.9-buster +FROM python:3.9-slim # Set global configs WORKDIR / @@ -9,10 +9,12 @@ RUN export LC_NUMERIC=C # Install system dependencies RUN apt-get update RUN apt-get install --no-install-recommends -y \ + build-essential \ ffmpeg \ libleptonica-dev \ libtesseract-dev \ libzbar-dev \ + python3-dev \ && \ apt-get clean From b901f10c8958f3cdb7c318f416b9c712a31c76a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Sun, 28 Feb 2021 07:59:03 -0300 Subject: [PATCH 059/120] Fix telegram.json example --- README.md | 2 +- config/telegram.json | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index be9d6b4..3edc145 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ You can install easily with Docker. In the run script, the docker directories **config**, **data** and **values** are binding with the repository directory. If you want to edit the files in the configuration directories you can do this simply by stopping the container. - As soon as you finish editing the files, just restart the container to make them active. + As soon as you finish editing the files, just restart the container to make them active. ## TODO diff --git a/config/telegram.json b/config/telegram.json index 235de3d..9d1ac26 100644 --- a/config/telegram.json +++ b/config/telegram.json @@ -1,9 +1,8 @@ { "username": "xxxx", "token": "xxxxx", - "admins": [ - "xxxx", "xxxx", + "xxxx" ] -} \ No newline at end of file +} From 535ad8c27f9373b72c78fcc7d52736ddb49c28b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Sun, 28 Feb 2021 08:16:14 -0300 Subject: [PATCH 060/120] Use requests.Session instead of separate requests This optimization will reuse TCP connections so the total transcription time will be smaller for large files (with dozens of chunks). --- src/audiotools/speech.py | 66 +++++++++++++++++++++++----------------- 1 file changed, 38 insertions(+), 28 deletions(-) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index a88d01e..bebfff2 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -9,35 +9,43 @@ logger = logging.getLogger("speech") -def __transcribe_chunk(chunk, api_key): - headers = { - 'authorization': 'Bearer ' + api_key, - 'accept': 'application/vnd.wit.20180705+json', - 'content-type': 'audio/raw;encoding=signed-integer;bits=16;rate=8000;endian=little', - } - - text = None - try: - request = requests.request( - "POST", - "https://api.wit.ai/speech", - headers=headers, - params={'verbose': True}, - data=io.BufferedReader(io.BytesIO(chunk.raw_data)) + +class WitTranscriber: + speech_url = "https://api.wit.ai/speech" + + def __init__(self, api_key): + self.session = requests.Session() + self.session.headers.update( + { + "Authorization": "Bearer " + api_key, + "Accept": "application/vnd.wit.20180705+json", + "Content-Type": "audio/raw;encoding=signed-integer;bits=16;rate=8000;endian=little", + } ) - logger.debug("Request response %s", request.text) - res = request.json() + def transcribe(self, chunk): + text = None + try: + response = self.session.post( + self.speech_url, + params={"verbose": True}, + data=io.BufferedReader(io.BytesIO(chunk.raw_data)) + ) + logger.debug("Request response %s", response.text) + data = response.json() + if "_text" in data: + text = data["_text"] + elif "text" in data: # Changed in may 2020 + text = data["text"] + + except requests.exceptions.RequestException as e: + logger.error("Could not transcribe chunk: %s", traceback.format_exc()) - if '_text' in res: - text = res['_text'] - elif 'text' in res: # Changed in may 2020 - text = res['text'] + return text - except Exception as e: - logger.error("Could not transcribe chunk: %s", traceback.format_exc()) + def close(self): + self.session.close() - return text def __generate_chunks(segment, length=20000/1001, split_on_silence=False, noise_threshold=-36): chunks = list() @@ -68,13 +76,15 @@ def transcribe(path, api_key): chunks = __generate_chunks(__preprocess_audio(audio)) logger.debug("Got %d chunks", len(chunks)) + transcriber = WitTranscriber(api_key) for i, chunk in enumerate(chunks): logger.debug("Transcribing chunk %d", i) - r = __transcribe_chunk(chunk, api_key) - logger.debug("Response received: %s", r) + text = transcriber.transcribe(chunk) + logger.debug("Response received: %s", text) - if r is not None: - yield r + if text is not None: + yield text + transcriber.close() if __name__ == "__main__": From f1334a574a80a48da368e073febfe6143b4e8084 Mon Sep 17 00:00:00 2001 From: Stefano Delbosco Date: Mon, 1 Mar 2021 18:15:59 +0100 Subject: [PATCH 061/120] Create Action for docker build and push --- .github/workflows/docker_build_push.yml | 46 +++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 .github/workflows/docker_build_push.yml diff --git a/.github/workflows/docker_build_push.yml b/.github/workflows/docker_build_push.yml new file mode 100644 index 0000000..51e89cd --- /dev/null +++ b/.github/workflows/docker_build_push.yml @@ -0,0 +1,46 @@ +name: DockerBuildAndPush + +on: + push: + branches: + - master + - developement + tags: + - v* + +env: + IMAGE_NAME: transcriberbot + +jobs: + push: + runs-on: ubuntu-latest + if: github.event_name == 'push' + + steps: + - uses: actions/checkout@v2 + + - name: Login to ghcr registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ secrets.GH_USERNAME }} + password: ${{ secrets.GH_ACCESS_TOKEN }} + + - name: Build image + run: docker build . --file Dockerfile --tag $IMAGE_NAME + + - name: Push image + run: | + IMAGE_ID=ghcr.io/${{ github.repository_owner }}/$IMAGE_NAME + # Change all uppercase to lowercase + IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + # Strip git ref prefix from version + VERSION=$(echo "${{ github.ref }}" | sed -e 's,.*/\(.*\),\1,') + # Strip "v" prefix from tag name + [[ "${{ github.ref }}" == "refs/tags/"* ]] && VERSION=$(echo $VERSION | sed -e 's/^v//') + # Use Docker `latest` tag convention + [ "$VERSION" == "master" ] && VERSION=latest + echo IMAGE_ID=$IMAGE_ID + echo VERSION=$VERSION + docker tag $IMAGE_NAME $IMAGE_ID:$VERSION + docker push $IMAGE_ID:$VERSION From c51ea47141acd6832863c2ca330a9fa78b2076c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Thu, 4 Mar 2021 03:15:42 -0300 Subject: [PATCH 062/120] Add support for video extensions (+ more audio) --- config/app.json | 19 ++++++++++++++----- src/transcriberbot/handlers_messages.py | 5 ++++- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/config/app.json b/config/app.json index 982ca4e..f781677 100644 --- a/config/app.json +++ b/config/app.json @@ -32,11 +32,20 @@ "photos_max_threads": 10, "audio_ext": [ - "wav", - "opus", - "3gpp", - "m4a", - "ogg" + "3gpp", + "m4a", + "ogg", + "ogx", + "opus", + "wav" + ], + + "video_ext": [ + "avi", + "mkv", + "mp4", + "ogv", + "webm" ], "antiflood": { diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index 545ab86..3edf046 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -230,8 +230,11 @@ def document(bot, update): m = update.message or update.channel_post file_name = m.document.file_name _, file_ext = os.path.splitext(file_name) + file_extension = file_ext[1:] + supported_audio_extensions = config.get_config_prop("app").get("audio_ext", []) + supported_video_extensions = config.get_config_prop("app").get("video_ext", []) - if file_ext[1:] not in config.get_config_prop("app")["audio_ext"]: + if file_extension not in supported_audio_extensions + supported_video_extensions: logger.info('extension %s not recognized', file_ext) return From 2d4958b5f9a28cc0efef35c2068c9b3e7425695a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Thu, 4 Mar 2021 03:15:58 -0300 Subject: [PATCH 063/120] Refactor if/elif/else --- src/transcriberbot/handlers_messages.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index 3edf046..51e95db 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -238,11 +238,9 @@ def document(bot, update): logger.info('extension %s not recognized', file_ext) return - if voice_enabled == 0: + elif voice_enabled in (0, 2): return - if voice_enabled == 2: - pass else: TranscriberBot.get().voice_thread_pool.submit( process_media_voice, bot, update, m.document, 'audio_document' From cb5172bb9b9a2711f43dd5010f0ee3368a55f941 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Thu, 4 Mar 2021 03:19:51 -0300 Subject: [PATCH 064/120] Fix ellipsis representation --- src/transcriberbot/handlers_messages.py | 4 ++-- values/strings.xml | 4 ++-- values/strings_it-IT.xml | 4 ++-- values/strings_pt-BR.xml | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index 51e95db..c916fb7 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -81,7 +81,7 @@ def transcribe_audio_file(bot, update, path): text = R.get_string_resource("transcription_continues", lang) + "\n" message = bot.send_message( chat_id=chat_id, - text=text + " " + speech + " [..]", + text=text + " " + speech + " [...]", reply_to_message_id=message.message_id, parse_mode="html", is_group=is_group, @@ -89,7 +89,7 @@ def transcribe_audio_file(bot, update, path): ).result() else: message = bot.edit_message_text( - text=text + " " + speech + " [..]", + text=text + " " + speech + " [...]", chat_id=chat_id, message_id=message.message_id, parse_mode="html", diff --git a/values/strings.xml b/values/strings.xml index c5ae68f..dea5965 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -44,14 +44,14 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} Sorry, file is too big! (20MB limit) -Transcribing.. +Transcribing... Audio is very long ({0}s), this will take some time {b}Text:{/b} {b}[continues]:{/b} Could not transcribe audio {b}[Stopped]{/b} -Recognizing.. +Recognizing... {b}Recognized Text:{/b} No text recognized {b}QR Code found:{/b} diff --git a/values/strings_it-IT.xml b/values/strings_it-IT.xml index 8c4aff2..c368b20 100644 --- a/values/strings_it-IT.xml +++ b/values/strings_it-IT.xml @@ -45,14 +45,14 @@ Mandami un messaggio vocale o un'immagine con del testo Spiacente, il file è troppo grande! (20MB max) -Trascrizione.. +Trascrizione... L'audio è molto lungo ({0}s), ci vorrà un po' {b}Testo:{/b} {b}[continua]:{/b} Non sono riuscito a trascrivere l'audio {b}[Fermato]{/b} -Riconoscimento.. +Riconoscimento... {b}Testo riconosciuto:{/b} Nessun testo riconosciuto {b}Codice QR rilevato:{/b} diff --git a/values/strings_pt-BR.xml b/values/strings_pt-BR.xml index 8495e0c..6255ab8 100644 --- a/values/strings_pt-BR.xml +++ b/values/strings_pt-BR.xml @@ -44,14 +44,14 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} Desculpe, arquivo muito grande! (limite de 20MB) -Transcrevendo.. +Transcrevendo... Áudio muito longo ({0}s), isso demorará um pouco {b}Texto:{/b} {b}[continua]:{/b} Não pude transcrever o áudio {b}[Parado]{/b} -Reconhecendo.. +Reconhecendo... {b}Texto reconhecido:{/b} Texto não reconhecido {b}Código QR encontrado:{/b} From cdc7226294e677c54879e74994ecee8471642582 Mon Sep 17 00:00:00 2001 From: Stefano Delbosco Date: Thu, 4 Mar 2021 13:56:45 +0100 Subject: [PATCH 065/120] Added user transcriber in Dockerfile and fix install tesseract --- Dockerfile | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Dockerfile b/Dockerfile index b4f5190..e42b32f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,6 +15,7 @@ RUN apt-get install --no-install-recommends -y \ libtesseract-dev \ libzbar-dev \ python3-dev \ + tesseract-ocr \ && \ apt-get clean @@ -25,4 +26,11 @@ RUN pip install --no-cache-dir -U pip && \ # Copy code and define default command COPY src/ src/ + +RUN useradd -m transcriber +RUN chown -R transcriber src/ +RUN chown -R transcriber media/ + +USER transcriber + CMD [ "python", "src/main.py" ] From 0c16b763e3cf0d7899972cabc4fe31d6135bc0a0 Mon Sep 17 00:00:00 2001 From: Stefano Delbosco Date: Thu, 4 Mar 2021 14:25:30 +0100 Subject: [PATCH 066/120] Added html escape in image ocr response --- src/transcriberbot/handlers_messages.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index 545ab86..ccb950b 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -12,6 +12,7 @@ from telegram import InlineKeyboardButton, InlineKeyboardMarkup import audiotools +import html import phototools import logging import traceback @@ -310,7 +311,7 @@ def process(message): if chat["photos_enabled"] == 1: text = phototools.image_ocr(file_path, chat["lang"]) if text is not None: - text = R.get_string_resource("ocr_result", chat["lang"]) + "\n" + text + text = R.get_string_resource("ocr_result", chat["lang"]) + "\n" + html.escape(text) bot.edit_message_text( text=text, chat_id=chat_id, From 29491c7b243259adf316e2011f4986e963c650e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Sun, 7 Mar 2021 13:59:17 -0300 Subject: [PATCH 067/120] Restrict audio transcription from video to private chats --- src/transcriberbot/handlers_messages.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index c916fb7..49a483e 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -225,10 +225,11 @@ def audio(bot, update): @message(Filters.document) def document(bot, update): chat_id = get_chat_id(update) + is_group = chat_id < 0 voice_enabled = TBDB.get_chat_voice_enabled(chat_id) - m = update.message or update.channel_post - file_name = m.document.file_name + message = update.message or update.channel_post + file_name = message.document.file_name _, file_ext = os.path.splitext(file_name) file_extension = file_ext[1:] supported_audio_extensions = config.get_config_prop("app").get("audio_ext", []) @@ -238,12 +239,16 @@ def document(bot, update): logger.info('extension %s not recognized', file_ext) return + elif file_extension in supported_video_extensions and is_group: + # discard videos in groups + return + elif voice_enabled in (0, 2): return else: TranscriberBot.get().voice_thread_pool.submit( - process_media_voice, bot, update, m.document, 'audio_document' + process_media_voice, bot, update, message.document, 'audio_document' ) @message(Filters.video_note) From 49761f9abf1b13ad8772e21043148dea01044dd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Sun, 7 Mar 2021 14:14:02 -0300 Subject: [PATCH 068/120] Add config for max media voice file size --- config/app.json | 1 + src/resources/loader.py | 11 +++++------ src/transcriberbot/handlers_messages.py | 6 ++++-- values/strings.xml | 2 +- values/strings_es-ES.xml | 2 +- values/strings_it-IT.xml | 2 +- values/strings_pt-BR.xml | 2 +- 7 files changed, 14 insertions(+), 12 deletions(-) diff --git a/config/app.json b/config/app.json index f781677..3eba13a 100644 --- a/config/app.json +++ b/config/app.json @@ -30,6 +30,7 @@ }, "voice_max_threads": 30, "photos_max_threads": 10, + "max_media_voice_file_size": 20971520, "audio_ext": [ "3gpp", diff --git a/src/resources/loader.py b/src/resources/loader.py index a78cf99..cb600ef 100644 --- a/src/resources/loader.py +++ b/src/resources/loader.py @@ -32,12 +32,12 @@ def _load_xml_resouce(path): if lang not in strings_r: strings_r[lang] = {} - replacements = (('{b}', ''), ('{/b}', ''), - ('{i}', ''), ('{/i}', ''), - ('{code}', ''), ('{/code}', '')) - + replacements = (('{b}', ''), ('{/b}', ''), + ('{i}', ''), ('{/i}', ''), + ('{code}', ''), ('{/code}', '')) + for string in e.findall('string'): - if string.text is None: + if string.text is None: continue value = functools.reduce(lambda s, kv: s.replace(*kv), replacements, string.text) @@ -73,4 +73,3 @@ def get_string_resource(id, lang=None): rr = strings_r['default'][id] return rr - diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index 49a483e..ee428eb 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -163,12 +163,14 @@ def transcribe_audio_file(bot, update, path): def process_media_voice(bot, update, media, name): chat_id = get_chat_id(update) file_size = media.file_size + max_size = config.get_config_prop("app").get("max_media_voice_file_size", 20 * 1024 * 1024) - if file_size >= 20*(1024**2): + if file_size > max_size: message_id = get_message_id(update) + error_message = R.get_string_resource("file_too_big", TBDB.get_chat_lang(chat_id)).format(max_size / (1024 * 1024)) + "\n" bot.send_message( chat_id=chat_id, - text=R.get_string_resource("file_too_big", TBDB.get_chat_lang(chat_id)) + "\n", + text=error_message, reply_to_message_id=message_id, parse_mode="html", is_group=chat_id < 0 diff --git a/values/strings.xml b/values/strings.xml index dea5965..52f380b 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -42,7 +42,7 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} QR enabled QR disabled -Sorry, file is too big! (20MB limit) +Sorry, file is too big! (limit: {0}MB) Transcribing... Audio is very long ({0}s), this will take some time diff --git a/values/strings_es-ES.xml b/values/strings_es-ES.xml index 34ed793..099516d 100644 --- a/values/strings_es-ES.xml +++ b/values/strings_es-ES.xml @@ -43,7 +43,7 @@ Mandame un mensaje de voz o una imagen con texto. QR activado QR desactivado -¡Lo siento, el archivo es demasiado grande! (20MB max) +¡Lo siento, el archivo es demasiado grande! ({0}MB max) Transcribiendo... El audio es muy largo ({0}s), esto llevará un tiempo... diff --git a/values/strings_it-IT.xml b/values/strings_it-IT.xml index c368b20..8eb524a 100644 --- a/values/strings_it-IT.xml +++ b/values/strings_it-IT.xml @@ -43,7 +43,7 @@ Mandami un messaggio vocale o un'immagine con del testo QR abilitato QR disabilitato -Spiacente, il file è troppo grande! (20MB max) +Spiacente, il file è troppo grande! ({0}MB max) Trascrizione... L'audio è molto lungo ({0}s), ci vorrà un po' diff --git a/values/strings_pt-BR.xml b/values/strings_pt-BR.xml index 6255ab8..773efbf 100644 --- a/values/strings_pt-BR.xml +++ b/values/strings_pt-BR.xml @@ -42,7 +42,7 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} QR ativado QR desativado -Desculpe, arquivo muito grande! (limite de 20MB) +Desculpe, arquivo muito grande! (limite de {0}MB) Transcrevendo... Áudio muito longo ({0}s), isso demorará um pouco From 599865de742fefd800f968764ce9db0be310ef42 Mon Sep 17 00:00:00 2001 From: Lorenzo Lapucci Date: Tue, 23 Mar 2021 12:33:52 +0100 Subject: [PATCH 069/120] Update punctuations mark (ellipses) for pt-BR --- values/strings_pt-BR.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/values/strings_pt-BR.xml b/values/strings_pt-BR.xml index 8495e0c..6255ab8 100644 --- a/values/strings_pt-BR.xml +++ b/values/strings_pt-BR.xml @@ -44,14 +44,14 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} Desculpe, arquivo muito grande! (limite de 20MB) -Transcrevendo.. +Transcrevendo... Áudio muito longo ({0}s), isso demorará um pouco {b}Texto:{/b} {b}[continua]:{/b} Não pude transcrever o áudio {b}[Parado]{/b} -Reconhecendo.. +Reconhecendo... {b}Texto reconhecido:{/b} Texto não reconhecido {b}Código QR encontrado:{/b} From 90fe9772c3d5ca8b5ce9b8ffc1b0b7988e270fd8 Mon Sep 17 00:00:00 2001 From: Lorenzo Lapucci Date: Tue, 23 Mar 2021 12:34:08 +0100 Subject: [PATCH 070/120] Update punctuations mark (ellipses) for it-IT --- values/strings_it-IT.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/values/strings_it-IT.xml b/values/strings_it-IT.xml index 8c4aff2..c368b20 100644 --- a/values/strings_it-IT.xml +++ b/values/strings_it-IT.xml @@ -45,14 +45,14 @@ Mandami un messaggio vocale o un'immagine con del testo Spiacente, il file è troppo grande! (20MB max) -Trascrizione.. +Trascrizione... L'audio è molto lungo ({0}s), ci vorrà un po' {b}Testo:{/b} {b}[continua]:{/b} Non sono riuscito a trascrivere l'audio {b}[Fermato]{/b} -Riconoscimento.. +Riconoscimento... {b}Testo riconosciuto:{/b} Nessun testo riconosciuto {b}Codice QR rilevato:{/b} From 0d1ec6d9328fdb15313af1207196d85107658f47 Mon Sep 17 00:00:00 2001 From: Lorenzo Lapucci Date: Tue, 23 Mar 2021 12:34:43 +0100 Subject: [PATCH 071/120] Update punctuations mark (ellipses) --- values/strings.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/values/strings.xml b/values/strings.xml index c5ae68f..dea5965 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -44,14 +44,14 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} Sorry, file is too big! (20MB limit) -Transcribing.. +Transcribing... Audio is very long ({0}s), this will take some time {b}Text:{/b} {b}[continues]:{/b} Could not transcribe audio {b}[Stopped]{/b} -Recognizing.. +Recognizing... {b}Recognized Text:{/b} No text recognized {b}QR Code found:{/b} From 9b5518240d38538f03994f0ba059c1a607929be0 Mon Sep 17 00:00:00 2001 From: Lorenzo Lapucci Date: Tue, 23 Mar 2021 12:39:03 +0100 Subject: [PATCH 072/120] Fix minor puntuaction typos and translate an untranslated word --- values/strings_it-IT.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/values/strings_it-IT.xml b/values/strings_it-IT.xml index c368b20..8d676a6 100644 --- a/values/strings_it-IT.xml +++ b/values/strings_it-IT.xml @@ -19,7 +19,7 @@ Puoi effettuare una donazione con il comando /donate, ci aiuterà a sostenere i Puoi fare una donazione per TranscriberBot su PayPal. Le donazioni ci sono di grande aiuto, grazie! -I ricavi verranno utilizzati per pagare il costo dei server e consentire lo sviluppo di nuove features. +I ricavi verranno utilizzati per pagare il costo dei server e consentire lo sviluppo di nuove funzioni. @@ -33,7 +33,7 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} -Mandami un messaggio vocale o un'immagine con del testo +Mandami un messaggio vocale o un'immagine contenente del testo Voce abilitata @@ -66,7 +66,7 @@ Mandami un messaggio vocale o un'immagine con del testo Non memorizziamo nessun dato personale o contenuto multimediale (come audio o immagini). Gli unici dati che conserviamo sono l'id della chat di telegram, insieme alle impostazioni scelte. -I messaggi vocali/file audio sono inoltrati a wit.ai (https://wit.ai/terms) per la trascrizione,e vengono immediatamente cancellati al termine. +I messaggi vocali/file audio sono inoltrati a wit.ai (https://wit.ai/terms) per la trascrizione, e vengono immediatamente cancellati al termine. Le immagini vengono rimosse dai nostri server dopo che l'OCR o il rilevamento di QR sono stati effettuati (offline). NON memorizziamo nessun CONTENUTO dei messaggi (testo, multimedia o altro). From 66b311955827637623f64957385c2d4c34cf906e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Justen=20=28=40turicas=29?= Date: Fri, 26 Mar 2021 16:31:29 -0300 Subject: [PATCH 073/120] Remove translation prefixes on private chats Fix #27 --- src/transcriberbot/handlers_messages.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py index 545ab86..4f673c9 100644 --- a/src/transcriberbot/handlers_messages.py +++ b/src/transcriberbot/handlers_messages.py @@ -63,7 +63,9 @@ def transcribe_audio_file(bot, update, path): [[InlineKeyboardButton("Stop", callback_data=message_id)]] ) - text = R.get_string_resource("transcription_text", lang) + "\n" + text = "" + if is_group: + text = R.get_string_resource("transcription_text", lang) + "\n" success = False for speech in audiotools.transcribe(path, api_key): @@ -81,7 +83,7 @@ def transcribe_audio_file(bot, update, path): text = R.get_string_resource("transcription_continues", lang) + "\n" message = bot.send_message( chat_id=chat_id, - text=text + " " + speech + " [..]", + text=text + " " + speech + " [...]", reply_to_message_id=message.message_id, parse_mode="html", is_group=is_group, @@ -89,7 +91,7 @@ def transcribe_audio_file(bot, update, path): ).result() else: message = bot.edit_message_text( - text=text + " " + speech + " [..]", + text=text + " " + speech + " [...]", chat_id=chat_id, message_id=message.message_id, parse_mode="html", @@ -287,7 +289,8 @@ def process(message): if chat["qr_enabled"] == 1: qr = phototools.read_qr(file_path, chat["lang"]) if qr is not None: - qr = R.get_string_resource("qr_result", chat["lang"]) + "\n" + qr + if is_group: + qr = R.get_string_resource("qr_result", chat["lang"]) + "\n" + qr if message is not None: bot.edit_message_text( @@ -310,7 +313,8 @@ def process(message): if chat["photos_enabled"] == 1: text = phototools.image_ocr(file_path, chat["lang"]) if text is not None: - text = R.get_string_resource("ocr_result", chat["lang"]) + "\n" + text + if is_group: + text = R.get_string_resource("ocr_result", chat["lang"]) + "\n" + text bot.edit_message_text( text=text, chat_id=chat_id, From 5118a8569d29d821bb36677686a9fcfc939552db Mon Sep 17 00:00:00 2001 From: dodekaphilist <31287077+dodekaphilist@users.noreply.github.com> Date: Sat, 17 Apr 2021 17:25:17 +0200 Subject: [PATCH 074/120] Improved English strings I hope the formatting option for inline links is correct --- values/strings.xml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/values/strings.xml b/values/strings.xml index dea5965..5704902 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -4,17 +4,17 @@ Language set to {lang} -This bot transcribes audio and pictures into text. -Add me to a group or forward audio messages and pictures to me! +This bot transcribes audio and pictures into text. Add it to a group or forward audio messages and pictures to it. +{b}Note{/b}: Within groups, the bot will respond to {b}admin commands only{/b} -Choose language (for voice messages): +Choose a language (for voice messages): {languages} -/rate this bot or leave your feedback here (https://telegram.me/storebot?start=transcriber_bot) +/rate this bot or leave your feedback on {a href="https://telegram.me/storebot?start=transcriber_bot"}Store Bot{/a} If you have any trouble, or want to get in touch with the developers, contact @transcribersupport_bot -You can /donate if you like this bot. This will help us maintain the service and keep on improving it -{b}Note{/b}: in groups, the bot will respond to {b}admin commands only{/b} + +If you like this bot, you can /donate. This will help us maintain the service and keep on improving it. Thank you! https://telegram.me/storebot?start=transcriber_bot @@ -24,7 +24,7 @@ Money from donations will be used for paying the server and backend costs and le -You can also donate with BTC, ETH or LTC +You can also donate with Bitcoin, Ethereum oder Litecoin BTC: {code}1DTrCfoNb9RLJnR5dfJvo9zwRjBZj8j1PY{/code} @@ -33,7 +33,7 @@ ETH: {code}0x0b784efc808527c75a8ef12a80622c41c28d45bd{/code} LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} -Send me a voice message or a picture with some text +Send a voice message or a picture with some text Voice enabled Voice disabled @@ -42,7 +42,7 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} QR enabled QR disabled -Sorry, file is too big! (20MB limit) +Sorry, file is too big! (limit: 20 MB) Transcribing... Audio is very long ({0}s), this will take some time @@ -57,7 +57,7 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} {b}QR Code found:{/b} No QR code found -{b}WARNING:{/b} flood detected. Stop spamming please +{b}WARNING:{/b} Flood detected. Stop spamming please Unknown language: {language} You must reply to a message in order to translate it @@ -65,11 +65,11 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} We do not store any personal data or media content (such as audio or pictures). The only user data we store is the telegram chat id along with the chosen settings. -Voice/audio messages are sent to (wit.ai https://wit.ai/terms) for transcription, and are immediately deleted after the transcription is completed. +Voice/audio messages are sent to {a href="https://wit.ai/terms"}wit.ai{/a} for transcription, and are immediately deleted after the transcription is completed. Pictures are immediately deleted from our server after OCR or QR recognition is perfomed (offline). We do NOT store ANY message content (text, multimedia or anything else). -{b}ERROR:{/b} oops, cannot find Wit API key for language {language}. :( +{b}ERROR:{/b} Oops, no wit.ai API key could be found for the language {language}. :( From 807c6c2e2e8d75304e97de0e26aa71d3a0c95171 Mon Sep 17 00:00:00 2001 From: dodekaphilist <31287077+dodekaphilist@users.noreply.github.com> Date: Sat, 17 Apr 2021 17:26:14 +0200 Subject: [PATCH 075/120] Added German translation --- values/strings_de-DE.xml | 75 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 values/strings_de-DE.xml diff --git a/values/strings_de-DE.xml b/values/strings_de-DE.xml new file mode 100644 index 0000000..48c8837 --- /dev/null +++ b/values/strings_de-DE.xml @@ -0,0 +1,75 @@ + + + +{lang} als Sprache festgelegt + + +Dieser Bot transkribiert Audio und Bilder in Text. Du kannst ihn einer Gruppe hinzufügen, oder Bilder und Sprachnachrichten an ihn weiterleiten. +{b}Wichtig{/b}: Innerhalb von Gruppen antwortet dieser Bot {b}nur Admin-Kommandos{/b} + +Wähle eine Sprache (für Sprachnachrichten): +{languages} + +Im {a href="https://telegram.me/storebot?start=transcriber_bot"}Store-Bot{/a} kannst du diesen Bot bewerten (/rate) oder Feedback hinterlassen! + +Wenn du Probleme hast oder mit den Entwicklern in Kontakt treten möchtest, nutze den Support-Bot @transcribersupport_bot! + +Wenn dir der Bot gefällt, kannst du den Entwicklern etwas spenden (/donate). Damit hilft du, den Dienst zu aufrecht zu erhalten und weiter zu verbessern. Vielen Dank! + + +https://telegram.me/storebot?start=transcriber_bot + +Du kannst für TranscriberBot etwas über PayPal spenden. Das hilft uns wirklich sehr, vielen Dank für deine Unterstützung! +Einnahmen aus Spenden nutzen wir für Server- und Backend-Kosten, außerdem können die Entwickler neue Funktionen einbauen! + + + +Du kannst auf in Bitcoin, Ethereum oder Litecoin spenden + +BTC: {code}1DTrCfoNb9RLJnR5dfJvo9zwRjBZj8j1PY{/code} + +ETH: {code}0x0b784efc808527c75a8ef12a80622c41c28d45bd{/code} + +LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} + + +Schicke eine Sprachnachricht oder ein Bild mit Text + +Sprache aktiviert +Sprache deaktiviert +Bilder aktiviert +Bilder deaktiviert +QR aktiviert +QR deaktiviert + +Entschuldigung, diese Datei ist zu groß! (Limit: 20 MB) + +Wird transkribiert... +Sprachnachricht ist sehr lang ({0} s), es dauert ein bisschen +{b}Text:{/b} +{b}[Fortsetzung]:{/b} +Sprachnachricht konnte nicht transkribiert werden +{b}[Ende]{/b} + +Wird erkannt... +{b}Erkannter Text:{/b} +Kein Text erkannt +{b}QR-Code gefunden:{/b} +Kein QR-Code gefunden + +{b}WARNUNG:{/b} Zu viele Nachrichten. Bitte höre auf, zu spammen + +Unbekannte Sprache: {language} +Du musst auf eine Nachricht antworten, um die übersetzen zu können + + +Wir speichern keinerlei persönliche Daten oder Dateien (z.B. Sprachnachrichten oder Bilder). +Die einzigen Nutzerdaten, die wir erheben, ist die Telegram-Chat-ID zusammen mit deinen Einstellungen. +Sprachnachrichten werden zur Transkription an {a href="https://wit.ai/terms"}wit.ai{/a} gesendet und direkt nach der Transkription gelöscht. +Bilder werden direkt von unserem Server gelöscht, sobald die Text- oder QR-Erkennung abgeschlossen ist. +Wir speichern keinerlei andere Nachrichteninhalte (Textnachrichten, Multimedia o.ä.) + + +{b}FEHLER:{/b} Ups, für die Sprache {language} konnte kein wit.ai API-Schlüssel gefunden werden. :( + + From 2c9a8bbe771e1e4139fecc297eae40a9751736a6 Mon Sep 17 00:00:00 2001 From: dodekaphilist <31287077+dodekaphilist@users.noreply.github.com> Date: Sat, 17 Apr 2021 19:22:45 +0200 Subject: [PATCH 076/120] Update values/strings.xml MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Álvaro Justen --- values/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/values/strings.xml b/values/strings.xml index 5704902..20a7b5c 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -24,7 +24,7 @@ Money from donations will be used for paying the server and backend costs and le -You can also donate with Bitcoin, Ethereum oder Litecoin +You can also donate with Bitcoin, Ethereum or Litecoin BTC: {code}1DTrCfoNb9RLJnR5dfJvo9zwRjBZj8j1PY{/code} From 3235c63a212a9b0a27a16ebbd4f8d5bf5847b2da Mon Sep 17 00:00:00 2001 From: dodekaphilist <31287077+dodekaphilist@users.noreply.github.com> Date: Sat, 17 Apr 2021 19:26:29 +0200 Subject: [PATCH 077/120] Update strings.xml --- values/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/values/strings.xml b/values/strings.xml index 20a7b5c..e060904 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -5,7 +5,7 @@ This bot transcribes audio and pictures into text. Add it to a group or forward audio messages and pictures to it. -{b}Note{/b}: Within groups, the bot will respond to {b}admin commands only{/b} +{b}Note{/b}: Within groups, the bot will respond to commands by {b}non-anonymous admins only{/b} Choose a language (for voice messages): {languages} From 77e031681967e67b56fbe4636e13f008afa04a70 Mon Sep 17 00:00:00 2001 From: dodekaphilist <31287077+dodekaphilist@users.noreply.github.com> Date: Sat, 17 Apr 2021 19:29:19 +0200 Subject: [PATCH 078/120] Update strings_de-DE.xml --- values/strings_de-DE.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/values/strings_de-DE.xml b/values/strings_de-DE.xml index 48c8837..d33970f 100644 --- a/values/strings_de-DE.xml +++ b/values/strings_de-DE.xml @@ -5,7 +5,7 @@ Dieser Bot transkribiert Audio und Bilder in Text. Du kannst ihn einer Gruppe hinzufügen, oder Bilder und Sprachnachrichten an ihn weiterleiten. -{b}Wichtig{/b}: Innerhalb von Gruppen antwortet dieser Bot {b}nur Admin-Kommandos{/b} +{b}Wichtig{/b}: Innerhalb von Gruppen antwortet dieser Bot nur auf Kommandos von {b}nicht-anonymen Admins{/b} Wähle eine Sprache (für Sprachnachrichten): {languages} From fe18ee632a05d157121bd5dc2b80c712cc270eaa Mon Sep 17 00:00:00 2001 From: Stefano Delbosco Date: Sun, 19 Jun 2022 17:11:03 +0200 Subject: [PATCH 079/120] Update docker_build_push.yml Removed tag 'start' --- .github/workflows/docker_build_push.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/docker_build_push.yml b/.github/workflows/docker_build_push.yml index 51e89cd..0f0482e 100644 --- a/.github/workflows/docker_build_push.yml +++ b/.github/workflows/docker_build_push.yml @@ -5,8 +5,6 @@ on: branches: - master - developement - tags: - - v* env: IMAGE_NAME: transcriberbot From a08edcd022c899fedad309954bc1b0aa9702c067 Mon Sep 17 00:00:00 2001 From: Stefano Delbosco Date: Sun, 19 Jun 2022 17:23:06 +0200 Subject: [PATCH 080/120] Update docker_build_push.yml New login method for ghcr --- .github/workflows/docker_build_push.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.github/workflows/docker_build_push.yml b/.github/workflows/docker_build_push.yml index 0f0482e..230d48f 100644 --- a/.github/workflows/docker_build_push.yml +++ b/.github/workflows/docker_build_push.yml @@ -18,11 +18,7 @@ jobs: - uses: actions/checkout@v2 - name: Login to ghcr registry - uses: docker/login-action@v1 - with: - registry: ghcr.io - username: ${{ secrets.GH_USERNAME }} - password: ${{ secrets.GH_ACCESS_TOKEN }} + run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u $ --password-stdin - name: Build image run: docker build . --file Dockerfile --tag $IMAGE_NAME From d1ed337e86a67a7a1a055438b5b64f1f314b71e6 Mon Sep 17 00:00:00 2001 From: Stefano Delbosco Date: Sun, 19 Jun 2022 18:35:10 +0200 Subject: [PATCH 081/120] Added support for anonymous Admins --- src/transcriberbot/tbfilters.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/transcriberbot/tbfilters.py b/src/transcriberbot/tbfilters.py index 70d12ca..6c19947 100644 --- a/src/transcriberbot/tbfilters.py +++ b/src/transcriberbot/tbfilters.py @@ -9,6 +9,9 @@ def filter(self, message): if message.chat.type == 'channel': return True + if message.from_user.id == 1087968824: + return True + sender = message.from_user admins = message.chat.get_administrators() @@ -22,10 +25,10 @@ def filter(self, message): class FilterIsOwner(BaseFilter): #def __init__(self): #self.admins = config.get_config_prop('telegram')['admins'] - + def filter(self, message): admins = config.get_config_prop('telegram')['admins'] is_owner = list(filter(lambda admin: admin == str(message.chat.id), admins)) return len(is_owner) > 0 -bot_admin = FilterIsOwner() \ No newline at end of file +bot_admin = FilterIsOwner() From 3598cb10e5033539825afdd910685599a4c19e56 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Fri, 14 Feb 2025 22:18:12 +0100 Subject: [PATCH 082/120] split backend --- src/audiotools/speech.py | 9 ++++++++- src/main.py | 2 -- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index bebfff2..68970a9 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -69,7 +69,7 @@ def __preprocess_audio(audio): return audio.set_sample_width(2).set_channels(1).set_frame_rate(8000) -def transcribe(path, api_key): +def transcribe_wit(path, api_key): logger.info("Transcribing file %s", path) audio = AudioSegment.from_file(path) @@ -87,6 +87,13 @@ def transcribe(path, api_key): transcriber.close() +def transcribe(path, api_key, backend="wit"): + if backend == "wit": + return transcribe_wit(path, api_key) + + raise ValueError("Unknown backend: %s" % backend) + + if __name__ == "__main__": import argparse import sys diff --git a/src/main.py b/src/main.py index 7bb992b..a3796b2 100644 --- a/src/main.py +++ b/src/main.py @@ -4,8 +4,6 @@ import database import antiflood -from telegram.ext import Filters - import transcriberbot from transcriberbot import TranscriberBot From 98c5c001b6a16197518997fd40066b82da3b92e2 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Fri, 14 Feb 2025 22:26:14 +0100 Subject: [PATCH 083/120] rename build scripts --- dockerBuild.sh => build.sh | 0 dockerRun.sh => run.sh | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename dockerBuild.sh => build.sh (100%) rename dockerRun.sh => run.sh (100%) diff --git a/dockerBuild.sh b/build.sh similarity index 100% rename from dockerBuild.sh rename to build.sh diff --git a/dockerRun.sh b/run.sh similarity index 100% rename from dockerRun.sh rename to run.sh From 9fc704776a154c082a79903300a439b7def2a107 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sat, 15 Feb 2025 00:23:53 +0100 Subject: [PATCH 084/120] add whisper backend --- config/app.json | 4 ++++ requirements.txt | 2 +- src/audiotools/speech.py | 14 +++++++++++++- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/config/app.json b/config/app.json index 3eba13a..a3e2b50 100644 --- a/config/app.json +++ b/config/app.json @@ -56,5 +56,9 @@ "time_threshold_warning": 4, "time_threshold_flood": 5, "timeout": 10 + }, + + "whisper": { + "api_endpoint": "http://192.168.5.2:8000" } } diff --git a/requirements.txt b/requirements.txt index b29f863..ef5a1dd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ python-telegram-bot==12.3.0 coloredlogs pillow watchdog -tesserocr +# tesserocr pydub zbarlight requests diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index 68970a9..43af703 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -1,10 +1,12 @@ import io import logging import traceback +import os import requests import pydub from pydub import AudioSegment +import config logger = logging.getLogger("speech") @@ -87,10 +89,20 @@ def transcribe_wit(path, api_key): transcriber.close() -def transcribe(path, api_key, backend="wit"): +def transcribe_whisper(path): + resp = requests.get(f"{config.get_config_prop('app')['whisper']['api_endpoint']}/transcribe?file_id={path}") + yield resp.text + + +def transcribe(path, api_key, backend="whisper"): if backend == "wit": + print("Transcribing with wit") return transcribe_wit(path, api_key) + elif backend == "whisper": + print("Transcribing with whisper") + return transcribe_whisper(os.path.basename(path)) + raise ValueError("Unknown backend: %s" % backend) From 0582fbc64c2563b211bcc8315d6c369de8033687 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sat, 15 Feb 2025 00:24:46 +0100 Subject: [PATCH 085/120] remove workflow --- .github/workflows/docker_build_push.yml | 40 ------------------------- 1 file changed, 40 deletions(-) delete mode 100644 .github/workflows/docker_build_push.yml diff --git a/.github/workflows/docker_build_push.yml b/.github/workflows/docker_build_push.yml deleted file mode 100644 index 230d48f..0000000 --- a/.github/workflows/docker_build_push.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: DockerBuildAndPush - -on: - push: - branches: - - master - - developement - -env: - IMAGE_NAME: transcriberbot - -jobs: - push: - runs-on: ubuntu-latest - if: github.event_name == 'push' - - steps: - - uses: actions/checkout@v2 - - - name: Login to ghcr registry - run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u $ --password-stdin - - - name: Build image - run: docker build . --file Dockerfile --tag $IMAGE_NAME - - - name: Push image - run: | - IMAGE_ID=ghcr.io/${{ github.repository_owner }}/$IMAGE_NAME - # Change all uppercase to lowercase - IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') - # Strip git ref prefix from version - VERSION=$(echo "${{ github.ref }}" | sed -e 's,.*/\(.*\),\1,') - # Strip "v" prefix from tag name - [[ "${{ github.ref }}" == "refs/tags/"* ]] && VERSION=$(echo $VERSION | sed -e 's/^v//') - # Use Docker `latest` tag convention - [ "$VERSION" == "master" ] && VERSION=latest - echo IMAGE_ID=$IMAGE_ID - echo VERSION=$VERSION - docker tag $IMAGE_NAME $IMAGE_ID:$VERSION - docker push $IMAGE_ID:$VERSION From 77a1ea4cff417a880e8fe8e84c40ddde4a0eff3f Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sat, 15 Feb 2025 15:47:25 +0100 Subject: [PATCH 086/120] [wip] refactor to wonda --- .python-version | 1 + requirements.txt | 2 +- src/config/__init__.py | 8 +- src/main.py | 31 +- src/transcriberbot/__init__.py | 4 - src/transcriberbot/blueprints/__init__.py | 10 + src/transcriberbot/blueprints/command.py | 145 +++++++ src/transcriberbot/blueprints/message.py | 27 ++ src/transcriberbot/blueprints/photos.py | 4 + src/transcriberbot/blueprints/voice.py | 4 + src/transcriberbot/bot.py | 304 +------------ src/transcriberbot/channel_command_handler.py | 16 - src/transcriberbot/handlers_commands.py | 209 --------- src/transcriberbot/handlers_messages.py | 401 ------------------ src/transcriberbot/handlers_query.py | 34 -- src/transcriberbot/middlewares/__init__.py | 5 + src/transcriberbot/middlewares/chat_admin.py | 11 + src/transcriberbot/rules/__init__.py | 5 + src/transcriberbot/rules/rules.py | 51 +++ src/transcriberbot/tbfilters.py | 34 -- src/translator/translator.py | 1 + values/strings.xml | 1 + 22 files changed, 303 insertions(+), 1005 deletions(-) create mode 100644 .python-version delete mode 100644 src/transcriberbot/__init__.py create mode 100644 src/transcriberbot/blueprints/__init__.py create mode 100644 src/transcriberbot/blueprints/command.py create mode 100644 src/transcriberbot/blueprints/message.py create mode 100644 src/transcriberbot/blueprints/photos.py create mode 100644 src/transcriberbot/blueprints/voice.py delete mode 100644 src/transcriberbot/channel_command_handler.py delete mode 100644 src/transcriberbot/handlers_commands.py delete mode 100644 src/transcriberbot/handlers_messages.py delete mode 100644 src/transcriberbot/handlers_query.py create mode 100644 src/transcriberbot/middlewares/__init__.py create mode 100644 src/transcriberbot/middlewares/chat_admin.py create mode 100644 src/transcriberbot/rules/__init__.py create mode 100644 src/transcriberbot/rules/rules.py delete mode 100644 src/transcriberbot/tbfilters.py diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..275cfdd --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +transcriber-bot-wonda diff --git a/requirements.txt b/requirements.txt index ef5a1dd..b486605 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -python-telegram-bot==12.3.0 +wonda==0.7.9 coloredlogs pillow watchdog diff --git a/src/config/__init__.py b/src/config/__init__.py index c71e460..e0a2ad7 100644 --- a/src/config/__init__.py +++ b/src/config/__init__.py @@ -2,9 +2,9 @@ import json import functional import logging - import pprint + logger = logging.getLogger(__name__) __configs = {} @@ -16,6 +16,7 @@ def parse_file(file): data = json.load(f) return data + def init(config_folder): global __configs files = glob.glob(os.path.join(config_folder, "*.json")) @@ -35,6 +36,11 @@ def init(config_folder): if not os.path.isdir(__configs['app']['media_path']): os.mkdir(__configs['app']['media_path']) + def get_config_prop(key): global __configs return __configs[key] + + +def bot_token(): + return get_config_prop("telegram")["token"] diff --git a/src/main.py b/src/main.py index a3796b2..7b0d09c 100644 --- a/src/main.py +++ b/src/main.py @@ -1,23 +1,24 @@ -import coloredlogs,logging +import coloredlogs import config import resources import database import antiflood +import transcriberbot.bot -import transcriberbot -from transcriberbot import TranscriberBot -coloredlogs.install( - level='DEBUG', - fmt='%(asctime)s - %(name)s - %(levelname)s - %(filename)s [%(funcName)s:%(lineno)d] - %(message)s' -) -logger = logging.getLogger(__name__) +def main(): + coloredlogs.install( + level='DEBUG', + fmt='%(asctime)s - %(name)s - %(levelname)s - %(filename)s [%(funcName)s:%(lineno)d] - %(message)s' + ) -if __name__ == '__main__': - config.init('../config') - resources.init("../values") - antiflood.init() - transcriberbot.init() - database.init_schema(config.get_config_prop("app")["database"]) + config.init('../config') + resources.init("../values") + antiflood.init() + database.init_schema(config.get_config_prop("app")["database"]) + + transcriberbot.bot.run(config.bot_token()) - TranscriberBot.get().start(config.get_config_prop("telegram")["token"]) \ No newline at end of file + +if __name__ == '__main__': + main() diff --git a/src/transcriberbot/__init__.py b/src/transcriberbot/__init__.py deleted file mode 100644 index f88bbe9..0000000 --- a/src/transcriberbot/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from transcriberbot.bot import TranscriberBot -from transcriberbot.bot import message -from transcriberbot.bot import init -from transcriberbot import handlers_commands, handlers_messages, handlers_query \ No newline at end of file diff --git a/src/transcriberbot/blueprints/__init__.py b/src/transcriberbot/blueprints/__init__.py new file mode 100644 index 0000000..96189d1 --- /dev/null +++ b/src/transcriberbot/blueprints/__init__.py @@ -0,0 +1,10 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +from . import message, command + +blueprints = [ + command.bp, + message.bp, +] \ No newline at end of file diff --git a/src/transcriberbot/blueprints/command.py b/src/transcriberbot/blueprints/command.py new file mode 100644 index 0000000..47af4bd --- /dev/null +++ b/src/transcriberbot/blueprints/command.py @@ -0,0 +1,145 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +import logging +import resources as R +import config +import translator + +from wonda import Blueprint, Message, Command +from wonda.bot.rules import Text +from database import TBDB +from transcriberbot.rules import ChatAdmin + +logger = logging.getLogger(__name__) +bp = Blueprint() + + +@bp.on.message(Command("start", "help")) +async def start(m: Message): + await welcome_message(m) + + +@bp.on.message(Command("rate") & ChatAdmin()) +async def rate(m: Message): + await m.answer(R.get_string_resource("message_rate", TBDB.get_chat_lang(m.chat.id))) + +@bp.on.message(Command("disable_voice") & ChatAdmin()) +async def disable_voice(m: Message): + chat_id = m.chat.id + TBDB.set_chat_voice_enabled(chat_id, 0) + await m.answer(R.get_string_resource("voice_disabled", TBDB.get_chat_lang(chat_id))) + + +@bp.on.message(Command("enable_voice") & ChatAdmin()) +async def enable_voice(m: Message): + chat_id = m.chat.id + TBDB.set_chat_voice_enabled(chat_id, 1) + await m.answer(R.get_string_resource("voice_enabled", TBDB.get_chat_lang(chat_id))) + + +@bp.on.message(Command("disable_photos") & ChatAdmin()) +async def disable_photos(m: Message): + chat_id = m.chat.id + TBDB.set_chat_photos_enabled(chat_id, 0) + await m.answer(R.get_string_resource("photos_disabled", TBDB.get_chat_lang(chat_id))) + + +@bp.on.message(Command("enable_photos") & ChatAdmin()) +async def enable_photos(m: Message): + chat_id = m.chat.id + TBDB.set_chat_photos_enabled(chat_id, 1) + await m.answer(R.get_string_resource("photos_enabled", TBDB.get_chat_lang(chat_id))) + + +@bp.on.message(Command("disable_qr") & ChatAdmin()) +async def disable_qr(m: Message): + chat_id = m.chat.id + TBDB.set_chat_qr_enabled(chat_id, 0) + await m.answer(R.get_string_resource("qr_disabled", TBDB.get_chat_lang(chat_id))) + + +@bp.on.message(Command("enable_qr") & ChatAdmin()) +async def enable_qr(m: Message): + chat_id = m.chat.id + TBDB.set_chat_qr_enabled(chat_id, 1) + await m.answer(R.get_string_resource("qr_enabled", TBDB.get_chat_lang(chat_id))) + + +@bp.on.message(Command("translate") & ChatAdmin()) +async def translate(m: Message): + chat_id = m.chat.id + + lang = m.text + lang = lang.replace("/translate", "").strip() + logger.debug("Language %s", lang) + + if not m.reply_to_message: + await m.reply(R.get_string_resource("translate_reply_to_message", TBDB.get_chat_lang(chat_id))) + return + + if not lang: + await m.reply(R.get_string_resource("translate_language_missing", TBDB.get_chat_lang(chat_id))) + return + + if lang not in config.get_config_prop("app")["languages"]: + await m.reply(R.get_string_resource("translate_language_not_found", TBDB.get_chat_lang(chat_id)).format(lang)) + return + + lang = config.get_config_prop("app")["languages"][lang].split('-')[0] + translation = translator.translate( + source=TBDB.get_chat_lang(chat_id), + target=lang, + text=m.reply_to_message.text + ) + + await m.reply(translation) + + +@bp.on.message(Command("donate") & ChatAdmin()) +async def donate(m: Message): + chat_id = m.chat.id + await m.reply(R.get_string_resource("message_donate", TBDB.get_chat_lang(chat_id)), parse_mode="html") + + +@bp.on.message(Command("privacy")) +async def privacy(m: Message): + chat_id = m.chat.id + await m.reply(R.get_string_resource("privacy_policy", TBDB.get_chat_lang(chat_id)), parse_mode='html') + + +def get_language_list(): + return config.get_config_prop("app")["languages"].keys() + + +async def welcome_message(m: Message): + chat_record = TBDB.get_chat_entry(m.chat.id) + + language = None + if chat_record is not None: + language = chat_record["lang"] + elif m.from_.language_code is not None: + # Channel posts do not have a language_code attribute + logger.info("Language_code: %s", m.from_.language_code) + language = m.from_.language_code + + message = R.get_string_resource("message_welcome", language) + message = message.replace("{languages}", + "/" + "\n/".join(get_language_list())) # Format them to be a list of commands + + await m.reply( + text=message, + parse_mode="html" + ) + + if chat_record is None: + if language is None: + language = "en-US" + + if len(language) < 5: + language = R.iso639_2_to_639_1(language) + + logger.info("No record found for chat {}, creating one with lang {}".format(m.chat.id, language)) + TBDB.create_default_chat_entry(m.chat.id, language) + diff --git a/src/transcriberbot/blueprints/message.py b/src/transcriberbot/blueprints/message.py new file mode 100644 index 0000000..e1c67b5 --- /dev/null +++ b/src/transcriberbot/blueprints/message.py @@ -0,0 +1,27 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +import resources as R + +from wonda import Blueprint, Message +from wonda.bot.rules import Text +from database import TBDB +from transcriberbot.rules import FromPrivate + +bp = Blueprint() + + +@bp.on.message(Text("bye", "cheers", ignore_case=True)) +async def bye_handler(m: Message) -> None: + await m.answer("See you soon!") + + +@bp.on.message(Text("take care", "have a good day", ignore_case=True)) +async def goodbye_handler(m: Message) -> None: + await m.answer("You too, bye!") + + +@bp.on.message(FromPrivate()) +async def private_message(m: Message): + await m.answer(R.get_string_resource("message_private", TBDB.get_chat_lang(m.chat.id))) \ No newline at end of file diff --git a/src/transcriberbot/blueprints/photos.py b/src/transcriberbot/blueprints/photos.py new file mode 100644 index 0000000..0e0223b --- /dev/null +++ b/src/transcriberbot/blueprints/photos.py @@ -0,0 +1,4 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py new file mode 100644 index 0000000..0e0223b --- /dev/null +++ b/src/transcriberbot/blueprints/voice.py @@ -0,0 +1,4 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index 71f5efa..77bf82f 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -1,296 +1,20 @@ -import config -import database -import resources as R -import metaclass -import functional -import audiotools -import phototools -import pprint -import logging -import os -import traceback -import telegram -import time -import antiflood -import translator - -from datetime import datetime - -from database import TBDB -from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackQueryHandler, Filters -from telegram.ext import messagequeue as mq -from telegram.utils.request import Request -from telegram.error import Unauthorized - -from concurrent.futures import ThreadPoolExecutor - -from transcriberbot import tbfilters -from transcriberbot.channel_command_handler import ChannelCommandHandler - -logger = logging.getLogger(__name__) - -# Utils -def get_language_list(): - return config.get_config_prop("app")["languages"].keys() - -def get_chat_id(update): - chat_id = None - if update.message is not None: - chat_id = update.message.chat.id - elif update.channel_post is not None: - chat_id = update.channel_post.chat.id - return chat_id - -def get_message_id(update): - if update.message is not None: - return update.message.message_id - elif update.channel_post is not None: - return update.channel_post.message_id - - return None - -class TranscriberBot(metaclass=metaclass.Singleton): - class MQBot(telegram.bot.Bot): - def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs): - super().__init__(*args, **kwargs) - self._is_messages_queued_default = is_queued_def - self._msg_queue = mqueue or mq.MessageQueue() - - chats = TBDB.get_chats() - self.active_chats_cache = dict(zip( - [c['chat_id'] for c in chats], - [c['active'] for c in chats] - )) - - def __del__(self): - try: - self._msg_queue.stop() - except: - pass - super().__del__() - - def active_check(self, fn, *args, **kwargs): - err = None - res = None - - try: - res = fn(*args, **kwargs) - except Unauthorized as e: - pprint.pprint(e) - logger.error(e) - err = e - - if err is not None: - chat_id = kwargs['chat_id'] - if chat_id not in self.active_chats_cache or self.active_chats_cache[chat_id] == 1: - logger.debug("Marking chat {} as inactive".format(chat_id)) - self.active_chats_cache[chat_id] = 0 - TBDB.set_chat_active(chat_id, self.active_chats_cache[chat_id]) - raise err - - return res - - @mq.queuedmessage - def send_message(self, *args, **kwargs): - return self.active_check(super().send_message, *args, **kwargs) - - @mq.queuedmessage - def edit_message_text(self, *args, **kwargs): - return self.active_check(super().edit_message_text, *args, **kwargs) - - def __init__(self): - self.error_handler = None - self.message_handlers = {} - self.command_handlers = {} - self.callback_handlers = {} - self.floods = {} - self.workers = {} - - antiflood.register_flood_warning_callback( - lambda chat_id: TranscriberBot.get().bot().send_message( - chat_id=chat_id, - text=R.get_string_resource("flood_warning", TBDB.get_chat_lang(chat_id)), - parse_mode = "html", - is_group = chat_id < 0 - ) - ) - - def flood_started(chat_id): - logger.info("Flood detected in %d, ignoring messages", chat_id) - self.floods[chat_id] = True - - def flood_ended(chat_id): - logger.info("Flood ended for %d", chat_id) - self.floods[chat_id] = False - - antiflood.register_flood_started_callback(flood_started) - antiflood.register_flood_ended_callback(flood_ended) - - @staticmethod - def get(): - return TranscriberBot() - - def bot(self): - return self.mqbot - - def start(self, token): - self.voice_thread_pool = ThreadPoolExecutor( - max_workers=config.get_config_prop("app")["voice_max_threads"] - ) - self.photos_thread_pool = ThreadPoolExecutor( - max_workers=config.get_config_prop("app")["photos_max_threads"] - ) +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" - self.misc_thread_pool = ThreadPoolExecutor( - max_workers=2 - ) - - self.queue = mq.MessageQueue() - self.request = Request(con_pool_size=10) - self.mqbot = self.MQBot(token, request=self.request, mqueue=self.queue) - self.updater = Updater(bot=self.mqbot, use_context=True) - self.dispatcher = self.updater.dispatcher - self.__register_handlers() - self.updater.start_polling(clean=True) - self.updater.idle() - - def register_message_handler(self, filter, fn): - self.message_handlers[filter] = fn - - def register_command_handler(self, fn, filters=None): - self.command_handlers[fn.__name__] = (fn, filters) - - def register_callback_handler(self, fn): - self.callback_handlers[fn.__name__] = fn - - def start_thread(self, id): - self.workers[str(id)] = True - - def stop_thread(self, id): - self.workers[str(id)] = False - - def thread_running(self, id): - return self.workers[str(id)] - - def del_thread(self, id): - del self.workers[str(id)] - - def __add_handler(self, handler): - self.dispatcher.add_handler(handler) - - def __add_error_handler(self, handler): - self.dispatcher.add_error_handler(handler) - - def __pre__hook(self, fn, u, c, **kwargs): - b = c.bot - - m = u.message or u.channel_post - if not m: - return - - age = (datetime.utcnow() - m.date.replace(tzinfo=None)).total_seconds() - if age > config.get_config_prop("app")["antiflood"]["age_threshold"]: - return - - chat_id = get_chat_id(u) - antiflood.on_chat_msg_received(chat_id) - - if chat_id in self.floods and self.floods[chat_id] is True: - return - - if not TBDB.get_chat_entry(chat_id): - # happens when welcome/joined message is not received - TBDB.create_default_chat_entry(chat_id, 'en-US') - - if chat_id in self.mqbot.active_chats_cache and self.mqbot.active_chats_cache[chat_id] == 0: - logger.debug("Marking chat {} as active".format(chat_id)) - self.mqbot.active_chats_cache[chat_id] = 1 - TBDB.set_chat_active(chat_id, self.mqbot.active_chats_cache[chat_id]) - - return fn(b, u, **kwargs) - - def __register_handlers(self): - functional.apply_fn( - self.message_handlers.items(), - lambda h: self.__add_handler(MessageHandler( - h[0], - lambda b, u, **kwargs: self.__pre__hook(h[1], b, u, **kwargs))) - ) - - functional.apply_fn( - self.command_handlers.items(), - lambda h: self.__add_handler(ChannelCommandHandler( - h[0], - lambda b, u, **kwargs: self.__pre__hook(h[1][0], b, u, **kwargs), - filters=h[1][1])) - ) - - functional.apply_fn( - self.callback_handlers.items(), - lambda h: self.__add_handler(CallbackQueryHandler(h[1])) - ) - -# Decorators for adding callbacks -def message(filter): - def decor(fn): - TranscriberBot.get().register_message_handler(filter, fn) - return decor - -def command(filters=None): - def decor(fn): - TranscriberBot.get().register_command_handler(fn, filters) - return decor - -def callback_query(fn): - TranscriberBot.get().register_callback_handler(fn) - -# Install language command callbacks -def language_handler(bot, update, language): - chat_id = get_chat_id(update) - lang = config.get_config_prop("app")["languages"][language] #ISO 639-1 code for language - TBDB.set_chat_lang(chat_id, lang) - message = R.get_string_resource("language_set", lang).replace("{lang}", language) - reply = update.message or update.channel_post - reply.reply_text(message) - -def install_language_handlers(language): - handler = lambda b, u: language_handler(b, u, language) - handler.__name__ = language - TranscriberBot.get().register_command_handler(handler, filters=tbfilters.chat_admin) +import wonda +import config -# Init -def init(): - functional.apply_fn(get_language_list(), install_language_handlers) +from wonda.api.utils import Token +from transcriberbot.blueprints import blueprints +from transcriberbot.middlewares import ChatAdminMiddleware -def welcome_message(bot, update): - chat_id = get_chat_id(update) - message_id = get_message_id(update) - chat_record = TBDB.get_chat_entry(chat_id) - language = None - if chat_record is not None: - language = chat_record["lang"] - elif update.message is not None and update.message.from_user.language_code is not None: - # Channel posts do not have a language_code attribute - logger.debug("Language_code: %s", update.message.from_user.language_code) - language = update.message.from_user.language_code - - message = R.get_string_resource("message_welcome", language) - message = message.replace("{languages}", "/" + "\n/".join(get_language_list())) #Format them to be a list of commands - bot.send_message( - chat_id=chat_id, - text=message, - reply_to_message_id = message_id, - parse_mode = "html", - is_group = chat_id < 0 - ) +def run(bot_token: str): + bot = wonda.Bot(Token(bot_token)) - if chat_record is None: - if language is None: - language = "en-US" + for bp in blueprints: + bp.load_into(bot) - if len(language) < 5: - language = R.iso639_2_to_639_1(language) - - logger.debug("No record found for chat {}, creating one with lang {}".format(chat_id, language)) - TBDB.create_default_chat_entry(chat_id, language) \ No newline at end of file + bot.run_forever() \ No newline at end of file diff --git a/src/transcriberbot/channel_command_handler.py b/src/transcriberbot/channel_command_handler.py deleted file mode 100644 index 760f2a7..0000000 --- a/src/transcriberbot/channel_command_handler.py +++ /dev/null @@ -1,16 +0,0 @@ -import telegram - -class ChannelCommandHandler(telegram.ext.CommandHandler): - def check_update(self, update): - is_channel = False - - if update.channel_post: - update.message = update.channel_post - is_channel = True - - res = super().check_update(update) - - if is_channel: - update.message = None - - return res \ No newline at end of file diff --git a/src/transcriberbot/handlers_commands.py b/src/transcriberbot/handlers_commands.py deleted file mode 100644 index 5efea9d..0000000 --- a/src/transcriberbot/handlers_commands.py +++ /dev/null @@ -1,209 +0,0 @@ -import config -from database import TBDB -import resources as R - -from transcriberbot import tbfilters -from transcriberbot.bot import TranscriberBot -from transcriberbot.bot import get_chat_id, get_message_id, get_language_list, welcome_message, command - -from telegram.ext import Filters -from transcriberbot import tbfilters - -import translator -import time -import traceback -import logging -logger = logging.getLogger(__name__) - -@command(filters=tbfilters.chat_admin) -def start(bot, update): - welcome_message(bot, update) - -@command(filters=tbfilters.chat_admin) -def help(bot, update): - welcome_message(bot, update) - -@command(filters=tbfilters.chat_admin) -def lang(bot, update): - chat_id = get_chat_id(update) - bot.send_message(chat_id=chat_id, text=TBDB.get_chat_lang(chat_id)) - -@command(filters=tbfilters.chat_admin) -def rate(bot, update): - chat_id = get_chat_id(update) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("message_rate", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def disable_voice(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_voice_enabled(chat_id, 0) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("voice_disabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def enable_voice(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_voice_enabled(chat_id, 1) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("voice_enabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def voice_ask(bot, update): - pass - -@command(tbfilters.chat_admin) -def disable_photos(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_photos_enabled(chat_id, 0) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("photos_disabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def enable_photos(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_photos_enabled(chat_id, 1) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("photos_enabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def disable_qr(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_qr_enabled(chat_id, 0) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("qr_disabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command(tbfilters.chat_admin) -def enable_qr(bot, update): - chat_id = get_chat_id(update) - TBDB.set_chat_qr_enabled(chat_id, 1) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("qr_enabled", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - -@command() -def translate(bot, update): - chat_id = get_chat_id(update) - message = update.message or update.channel_post - if not message: - return - - lang = message.text - lang = lang.replace("/translate", "").strip() - logger.debug("Language %s", lang) - - if lang not in config.get_config_prop("app")["languages"]: - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("translate_language_not_found", TBDB.get_chat_lang(chat_id)).format(lang), - is_group = chat_id < 0 - ) - return - - lang = config.get_config_prop("app")["languages"][lang].split('-')[0] - - if not message.reply_to_message: - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("translate_reply_to_message", TBDB.get_chat_lang(chat_id)), - is_group = chat_id < 0 - ) - return - - translation = translator.translate( - source=TBDB.get_chat_lang(chat_id), - target=lang, - text=message.reply_to_message.text - ) - - message.reply_text(translation) - -@command(tbfilters.chat_admin) -def stats(bot, update): - pass - -@command(tbfilters.chat_admin) -def donate(bot, update): - chat_id = get_chat_id(update) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("message_donate", TBDB.get_chat_lang(chat_id)), - parse_mode="html", - is_group = chat_id < 0 - ) - -@command(filters=None) -def privacy(bot, update): - chat_id = get_chat_id(update) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("privacy_policy", TBDB.get_chat_lang(chat_id)), - parse_mode='html', - is_group = chat_id < 0 - ) - -# Admins commands -@command(tbfilters.bot_admin) -def users(bot, update): - chat_id = get_chat_id(update) - tot_chats = TBDB.get_chats_num() - active_chats = TBDB.get_active_chats_num() - bot.send_message( - chat_id=chat_id, - text='Total users: {}\nActive users: {}'.format(tot_chats, active_chats), - parse_mode='html', - is_group=chat_id < 0 - ) - -@command(tbfilters.bot_admin) -def post(bot, update): - chat_id = get_chat_id(update) - text = update.message.text[6:] - - def __post(): - chats = TBDB.get_chats() - sent = 0 - - for chat in chats: - try: - bot.send_message( - chat_id=chat['chat_id'], - text=text, - parse_mode='html', - is_group=int(chat['chat_id']) < 0 - ) - sent += 1 - time.sleep(0.1) - except Exception as e: - logger.error( - "Exception sending broadcast to %d: (%s) %s", - chat['chat_id'], e, traceback.format_exc()) - - bot.send_message( - chat_id=chat_id, - text='Broadcast sent to {}/{} chats'.format(sent, len(chats)), - is_group = chat_id < 0 - ) - TranscriberBot.get().command_handlers['users'](bot, update) - - TranscriberBot.get().misc_thread_pool.submit(__post) \ No newline at end of file diff --git a/src/transcriberbot/handlers_messages.py b/src/transcriberbot/handlers_messages.py deleted file mode 100644 index 14bd3fe..0000000 --- a/src/transcriberbot/handlers_messages.py +++ /dev/null @@ -1,401 +0,0 @@ -import config -from database import TBDB -import resources as R - -from transcriberbot import tbfilters -from transcriberbot.bot import TranscriberBot -from transcriberbot.bot import get_chat_id, get_message_id, get_language_list, welcome_message, message - -import telegram -from telegram.ext import Filters -from transcriberbot import tbfilters -from telegram import InlineKeyboardButton, InlineKeyboardMarkup - -import audiotools -import html -import phototools -import logging -import traceback -import time -import os - -logger = logging.getLogger(__name__) - -# Message callbacks -@message(Filters.text & Filters.private) -def private_message(bot, update): - chat_id = get_chat_id(update) - bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("message_private", TBDB.get_chat_lang(chat_id)) - ) - -def transcribe_audio_file(bot, update, path): - chat_id = get_chat_id(update) - lang = TBDB.get_chat_lang(chat_id) - message_id = get_message_id(update) - is_group = chat_id < 0 - - api_key = config.get_config_prop("wit").get(lang, None) - if api_key is None: - logger.error("Language not found in wit.json %s", lang) - message = bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("unknown_api_key", lang).format(language=lang) + "\n", - reply_to_message_id=message_id, - parse_mode="html", - is_group=is_group - ).result() - return - logger.debug("Using key %s for lang %s", api_key, lang) - - message = bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("transcribing", lang) + "\n", - reply_to_message_id=message_id, - parse_mode="html", - is_group=is_group - ).result() - - TranscriberBot.get().start_thread(message_id) - logger.debug("Starting thread %d", message_id) - - keyboard = InlineKeyboardMarkup( - [[InlineKeyboardButton("Stop", callback_data=message_id)]] - ) - - text = "" - if is_group: - text = R.get_string_resource("transcription_text", lang) + "\n" - success = False - - for speech in audiotools.transcribe(path, api_key): - logger.debug("Thread %d running: %r", message_id, TranscriberBot.get().thread_running(message_id)) - if TranscriberBot.get().thread_running(message_id) is False: - TranscriberBot.get().del_thread(message_id) - return - - retry = True - retry_num = 0 - - while retry and TranscriberBot.get().thread_running(message_id): - try: - if len(text + " " + speech) >= 4000: - text = R.get_string_resource("transcription_continues", lang) + "\n" - message = bot.send_message( - chat_id=chat_id, - text=text + " " + speech + " [...]", - reply_to_message_id=message.message_id, - parse_mode="html", - is_group=is_group, - reply_markup=keyboard - ).result() - else: - message = bot.edit_message_text( - text=text + " " + speech + " [...]", - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group, - reply_markup=keyboard - ).result() - - text += " " + speech - retry = False - success = True - - except telegram.error.TimedOut as t: - logger.error("Timeout error %s", traceback.format_exc()) - retry_num += 1 - if retry_num >= 3: - retry = False - - except telegram.error.RetryAfter as r: - logger.warning("Retrying after %d", r.retry_after) - time.sleep(r.retry_after) - - except telegram.error.TelegramError as te: - logger.error("Telegram error %s", traceback.format_exc()) - retry = False - - except Exception as e: - logger.error("Exception %s", traceback.format_exc()) - retry = False - - retry = True - retry_num = 0 - while retry and TranscriberBot.get().thread_running(message_id): - try: - if success: - bot.edit_message_text( - text=text, - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - ) - else: - bot.edit_message_text( - R.get_string_resource("transcription_failed", lang), - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - ) - retry = False - except telegram.error.TimedOut as t: - logger.error("Timeout error %s", traceback.format_exc()) - retry_num += 1 - if retry_num >= 3: - retry = False - - except telegram.error.RetryAfter as r: - logger.warning("Retrying after %d", r.retry_after) - time.sleep(r.retry_after) - - except telegram.error.TelegramError as te: - logger.error("Telegram error %s", traceback.format_exc()) - retry = False - - except Exception as e: - logger.error("Exception %s", traceback.format_exc()) - retry = False - - TranscriberBot.get().del_thread(message_id) - -def process_media_voice(bot, update, media, name): - chat_id = get_chat_id(update) - file_size = media.file_size - max_size = config.get_config_prop("app").get("max_media_voice_file_size", 20 * 1024 * 1024) - - if file_size > max_size: - message_id = get_message_id(update) - error_message = R.get_string_resource("file_too_big", TBDB.get_chat_lang(chat_id)).format(max_size / (1024 * 1024)) + "\n" - bot.send_message( - chat_id=chat_id, - text=error_message, - reply_to_message_id=message_id, - parse_mode="html", - is_group=chat_id < 0 - ) - return - - file_id = media.file_id - file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) - file = bot.get_file(file_id) - file.download(file_path) - - try: - transcribe_audio_file(bot, update, file_path) - except Exception as e: - logger.error("Exception handling %s from %d: %s", name, chat_id, traceback.format_exc()) - finally: - os.remove(file_path) - -@message(Filters.voice) -def voice(bot, update): - chat_id = get_chat_id(update) - voice_enabled = TBDB.get_chat_voice_enabled(chat_id) - if voice_enabled == 0: - return - - message = update.message or update.channel_post - v = message.voice - - if voice_enabled == 2: - pass - else: - TranscriberBot.get().voice_thread_pool.submit( - process_media_voice, bot, update, v, "voice" - ) - -@message(Filters.audio) -def audio(bot, update): - chat_id = get_chat_id(update) - voice_enabled = TBDB.get_chat_voice_enabled(chat_id) - - if voice_enabled == 0: - return - - message = update.message or update.channel_post - a = message.audio - - if voice_enabled == 2: - pass - else: - TranscriberBot.get().voice_thread_pool.submit( - process_media_voice, bot, update, a, "audio" - ) - -@message(Filters.document) -def document(bot, update): - chat_id = get_chat_id(update) - is_group = chat_id < 0 - voice_enabled = TBDB.get_chat_voice_enabled(chat_id) - - message = update.message or update.channel_post - file_name = message.document.file_name - _, file_ext = os.path.splitext(file_name) - file_extension = file_ext[1:] - supported_audio_extensions = config.get_config_prop("app").get("audio_ext", []) - supported_video_extensions = config.get_config_prop("app").get("video_ext", []) - - if file_extension not in supported_audio_extensions + supported_video_extensions: - logger.info('extension %s not recognized', file_ext) - return - - elif file_extension in supported_video_extensions and is_group: - # discard videos in groups - return - - elif voice_enabled in (0, 2): - return - - else: - TranscriberBot.get().voice_thread_pool.submit( - process_media_voice, bot, update, message.document, 'audio_document' - ) - -@message(Filters.video_note) -def video_note(bot, update): - chat_id = get_chat_id(update) - voice_enabled = TBDB.get_chat_voice_enabled(chat_id) - - if voice_enabled == 0: - return - - message = update.message or update.channel_post - vn = message.video_note - - if voice_enabled == 2: - pass - else: - TranscriberBot.get().voice_thread_pool.submit( - process_media_voice, bot, update, vn, "video_note" - ) - -def process_media_photo(bot, update, photo, chat): - chat_id = get_chat_id(update) - message_id = get_message_id(update) - is_group = chat_id < 0 - - message = None - - if chat["photos_enabled"] == 1: - message = bot.send_message( - chat_id=chat_id, - text=R.get_string_resource("photo_recognizing", chat["lang"]), - reply_to_message_id=message_id, - parse_mode="html", - is_group=is_group - ).result() - - file_id = photo[-1].file_id - file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) - bot.get_file(file_id).download(file_path) - - def process(message): - if chat["qr_enabled"] == 1: - qr = phototools.read_qr(file_path, chat["lang"]) - if qr is not None: - if is_group: - qr = R.get_string_resource("qr_result", chat["lang"]) + "\n" + qr - - if message is not None: - bot.edit_message_text( - text=qr, - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - ) - return - else: - message = bot.send_message( - chat_id=chat_id, - text=qr, - reply_to_message_id=message_id, - parse_mode="html", - is_group=is_group - ).result() - - if chat["photos_enabled"] == 1: - text = phototools.image_ocr(file_path, chat["lang"]) - if text is not None: - if is_group: - text = R.get_string_resource("ocr_result", chat["lang"]) + "\n" + html.escape(text) - bot.edit_message_text( - text=text, - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - ) - return - - bot.edit_message_text( - text=R.get_string_resource("photo_no_text", chat["lang"]), - chat_id=chat_id, - message_id=message.message_id, - parse_mode="html", - is_group=is_group - ) - - retry = True - retry_num = 0 - try: - while retry: - process(message) - retry = False - - except telegram.error.TimedOut as t: - logger.error("Timeout error %s", traceback.format_exc()) - retry_num += 1 - if retry_num >= 3: - retry = False - - except telegram.error.RetryAfter as r: - logger.warning("Retrying after %d", r.retry_after) - time.sleep(r.retry_after) - - except telegram.error.TelegramError as te: - logger.error("Telegram error %s", traceback.format_exc()) - retry = False - - except Exception as e: - logger.error("Exception %s", traceback.format_exc()) - retry = False - - finally: - os.remove(file_path) - -@message(Filters.photo) -def photo(bot, update): - chat_id = get_chat_id(update) - chat = TBDB.get_chat_entry(chat_id) - if chat["qr_enabled"] == 0 and chat["photos_enabled"] == 0: - return - - message = update.message or update.channel_post - - if message.photo: - TranscriberBot.get().photos_thread_pool.submit( - process_media_photo, bot, update, message.photo, chat - ) - -@message(Filters.status_update.new_chat_members) -def new_chat_member(bot, update): - message = update.message or update.channel_post - - if bot.get_me() in message.new_chat_members: - welcome_message(bot, update) - -@message(Filters.status_update.left_chat_member) -def left_chat_member(bot, update): - chat_id = get_chat_id(update) - message = update.message or update.channel_post - - if message.left_chat_member.id == bot.get_me().id: - logger.info('Marking chat {} as inactive'.format(chat_id)) - bot.active_chats_cache[chat_id] = 0 - TBDB.set_chat_active(chat_id, bot.active_chats_cache[chat_id]) diff --git a/src/transcriberbot/handlers_query.py b/src/transcriberbot/handlers_query.py deleted file mode 100644 index 849ab94..0000000 --- a/src/transcriberbot/handlers_query.py +++ /dev/null @@ -1,34 +0,0 @@ -import config -from database import TBDB -import resources as R - -from transcriberbot import tbfilters -from transcriberbot.bot import TranscriberBot -from transcriberbot.bot import get_chat_id, get_message_id, get_language_list, callback_query - -from telegram.ext import Filters -from transcriberbot import tbfilters - -import logging -logger = logging.getLogger(__name__) - -@callback_query -def stop(bot, update): - query = update.callback_query - - TranscriberBot.get().stop_thread(query.data) - logger.debug("Stopping thread %s", query.data) - logger.debug("Thread %s running: %r", query.data, TranscriberBot.get().thread_running(query.data)) - - string_stopped = R.get_string_resource( - "transcription_stopped", - TBDB.get_chat_lang(query.message.chat_id) - ) - - bot.edit_message_text( - text=query.message.text + " " + string_stopped, - chat_id=query.message.chat_id, - message_id=query.message.message_id, - parse_mode="html", - is_group=query.message.chat_id < 0 - ) \ No newline at end of file diff --git a/src/transcriberbot/middlewares/__init__.py b/src/transcriberbot/middlewares/__init__.py new file mode 100644 index 0000000..38af240 --- /dev/null +++ b/src/transcriberbot/middlewares/__init__.py @@ -0,0 +1,5 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +from .chat_admin import ChatAdminMiddleware \ No newline at end of file diff --git a/src/transcriberbot/middlewares/chat_admin.py b/src/transcriberbot/middlewares/chat_admin.py new file mode 100644 index 0000000..9c197f6 --- /dev/null +++ b/src/transcriberbot/middlewares/chat_admin.py @@ -0,0 +1,11 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +from wonda import ABCMiddleware, Bot, Message, Token, ChatMemberUpdate +from wonda.bot.rules import Command +from wonda.types import ChatType +from wonda.types.objects import User + +class ChatAdminMiddleware(ABCMiddleware[Message]): + pass \ No newline at end of file diff --git a/src/transcriberbot/rules/__init__.py b/src/transcriberbot/rules/__init__.py new file mode 100644 index 0000000..2d80ee5 --- /dev/null +++ b/src/transcriberbot/rules/__init__.py @@ -0,0 +1,5 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +from .rules import * \ No newline at end of file diff --git a/src/transcriberbot/rules/rules.py b/src/transcriberbot/rules/rules.py new file mode 100644 index 0000000..1f17aac --- /dev/null +++ b/src/transcriberbot/rules/rules.py @@ -0,0 +1,51 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +from wonda.bot.rules.abc import ABCRule +from wonda.bot.updates import MessageUpdate +from wonda.types import ChatType +from wonda.types.objects import User + + +class Voice(ABCRule[MessageUpdate]): + """ + Checks if the message has voice media + """ + def __init__(self, *allowed_exts) -> None: + self.allowed_exts = allowed_exts + + async def check(self, m: MessageUpdate, _) -> bool: + if m.document: + filename = m.document.file_name + ext = filename.split('.')[-1] + return ext in self.allowed_exts + + return bool(m.voice or m.audio or m.video_note) + +class FromPrivate(ABCRule[MessageUpdate]): + """ + Checks if the message was sent in a channel. + """ + + async def check(self, m: MessageUpdate, _) -> bool: + return m.chat.type == ChatType.PRIVATE + + +class ChatAdmin(ABCRule[MessageUpdate]): + """ + Checks if the message was sent by a chat admin. + """ + + async def check(self, m: MessageUpdate, _) -> bool: + if m.chat.type in (ChatType.PRIVATE, ChatType.CHANNEL): + return True + + user: User = m.from_ + chat_admins = await m.ctx_api.get_chat_administrators(m.chat.id) + print("CHAT ADMINS", chat_admins) + + is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) + is_admin = len(is_admin) > 0 + + return is_admin \ No newline at end of file diff --git a/src/transcriberbot/tbfilters.py b/src/transcriberbot/tbfilters.py deleted file mode 100644 index 6c19947..0000000 --- a/src/transcriberbot/tbfilters.py +++ /dev/null @@ -1,34 +0,0 @@ -import config -from telegram.ext import BaseFilter - -class FilterIsAdmin(BaseFilter): - def filter(self, message): - if message.chat.id >= 0: - return True - - if message.chat.type == 'channel': - return True - - if message.from_user.id == 1087968824: - return True - - sender = message.from_user - admins = message.chat.get_administrators() - - is_admin = list(filter(lambda cm: cm.user.id == sender.id, admins)) - is_admin = len(is_admin) > 0 - - return is_admin - -chat_admin = FilterIsAdmin() - -class FilterIsOwner(BaseFilter): - #def __init__(self): - #self.admins = config.get_config_prop('telegram')['admins'] - - def filter(self, message): - admins = config.get_config_prop('telegram')['admins'] - is_owner = list(filter(lambda admin: admin == str(message.chat.id), admins)) - return len(is_owner) > 0 - -bot_admin = FilterIsOwner() diff --git a/src/translator/translator.py b/src/translator/translator.py index 305e46b..b668e85 100644 --- a/src/translator/translator.py +++ b/src/translator/translator.py @@ -21,6 +21,7 @@ def detect_language(text): def translate(source, target, text): + return "Translation service currently unavailable." global yandex_translate_url autodetect = detect_language(text) diff --git a/values/strings.xml b/values/strings.xml index a453e7f..5793b5e 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -60,6 +60,7 @@ LTC: {code}LdsVPxqHR6PuKeMNvGYmMEkBRQ7M3AP3uY{/code} {b}WARNING:{/b} Flood detected. Stop spamming please Unknown language: {language} +Please specify a language to translate to, e.g. "/translate english" You must reply to a message in order to translate it From 8301631aec173702b6100441619072f0011fbaa7 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sat, 15 Feb 2025 16:14:06 +0100 Subject: [PATCH 087/120] fix indent --- src/transcriberbot/blueprints/command.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/transcriberbot/blueprints/command.py b/src/transcriberbot/blueprints/command.py index 47af4bd..8bbfd43 100644 --- a/src/transcriberbot/blueprints/command.py +++ b/src/transcriberbot/blueprints/command.py @@ -25,6 +25,7 @@ async def start(m: Message): async def rate(m: Message): await m.answer(R.get_string_resource("message_rate", TBDB.get_chat_lang(m.chat.id))) + @bp.on.message(Command("disable_voice") & ChatAdmin()) async def disable_voice(m: Message): chat_id = m.chat.id From cf1b4138979dc9a486466e3bf723c42b0f2e5267 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sat, 15 Feb 2025 19:14:55 +0100 Subject: [PATCH 088/120] [wip] add wonda --- src/audiotools/speech.py | 2 +- src/config/__init__.py | 42 ++--- src/main.py | 6 +- src/transcriberbot/blueprints/__init__.py | 3 +- src/transcriberbot/blueprints/command.py | 38 ++++- src/transcriberbot/blueprints/message.py | 13 +- src/transcriberbot/blueprints/voice.py | 160 ++++++++++++++++++ src/transcriberbot/bot.py | 14 +- .../multiprocessing/__init__.py | 5 + src/transcriberbot/multiprocessing/pools.py | 34 ++++ src/transcriberbot/rules/rules.py | 25 ++- values/strings.xml | 1 + values/strings_de-DE.xml | 2 +- 13 files changed, 300 insertions(+), 45 deletions(-) create mode 100644 src/transcriberbot/multiprocessing/__init__.py create mode 100644 src/transcriberbot/multiprocessing/pools.py diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index 43af703..36ee686 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -94,7 +94,7 @@ def transcribe_whisper(path): yield resp.text -def transcribe(path, api_key, backend="whisper"): +def transcribe(path, api_key, backend="wit"): if backend == "wit": print("Transcribing with wit") return transcribe_wit(path, api_key) diff --git a/src/config/__init__.py b/src/config/__init__.py index e0a2ad7..b0d9abc 100644 --- a/src/config/__init__.py +++ b/src/config/__init__.py @@ -4,43 +4,47 @@ import logging import pprint - logger = logging.getLogger(__name__) __configs = {} + def parse_file(file): - logger.info("Loading config file %s", file) + logger.info("Loading config file %s", file) - with open(file) as f: - data = json.load(f) - return data + with open(file) as f: + data = json.load(f) + return data def init(config_folder): - global __configs - files = glob.glob(os.path.join(config_folder, "*.json")) + global __configs + files = glob.glob(os.path.join(config_folder, "*.json")) - keys = [x.replace(config_folder, "").replace(".json", "").replace("/", "") for x in files] - configs = map(parse_file, files) - __configs = dict(zip(keys, configs)) + keys = [x.replace(config_folder, "").replace(".json", "").replace("/", "") for x in files] + configs = map(parse_file, files) + __configs = dict(zip(keys, configs)) - base = os.path.join(os.path.dirname(__file__), "../../") + base = os.path.join(os.path.dirname(__file__), "../../") - if not os.path.isabs(__configs['app']['database']): - __configs['app']['database'] = os.path.join(base, __configs['app']['database']) + if not os.path.isabs(__configs['app']['database']): + __configs['app']['database'] = os.path.join(base, __configs['app']['database']) - if not os.path.isabs(__configs['app']['media_path']): - __configs['app']['media_path'] = os.path.join(base, __configs['app']['media_path']) + if not os.path.isabs(__configs['app']['media_path']): + __configs['app']['media_path'] = os.path.join(base, __configs['app']['media_path']) - if not os.path.isdir(__configs['app']['media_path']): - os.mkdir(__configs['app']['media_path']) + if not os.path.isdir(__configs['app']['media_path']): + os.mkdir(__configs['app']['media_path']) def get_config_prop(key): - global __configs - return __configs[key] + global __configs + return __configs[key] def bot_token(): return get_config_prop("telegram")["token"] + + +def get_language_list(): + return get_config_prop("app")["languages"].keys() diff --git a/src/main.py b/src/main.py index 7b0d09c..718323a 100644 --- a/src/main.py +++ b/src/main.py @@ -4,15 +4,19 @@ import database import antiflood import transcriberbot.bot +import transcriberbot.multiprocessing def main(): coloredlogs.install( - level='DEBUG', + level='INFO', fmt='%(asctime)s - %(name)s - %(levelname)s - %(filename)s [%(funcName)s:%(lineno)d] - %(message)s' ) config.init('../config') + transcriberbot.multiprocessing.init() + print("VOICE POOL:", transcriberbot.multiprocessing.voice_pool()) + resources.init("../values") antiflood.init() database.init_schema(config.get_config_prop("app")["database"]) diff --git a/src/transcriberbot/blueprints/__init__.py b/src/transcriberbot/blueprints/__init__.py index 96189d1..85c3d93 100644 --- a/src/transcriberbot/blueprints/__init__.py +++ b/src/transcriberbot/blueprints/__init__.py @@ -2,9 +2,10 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ -from . import message, command +from . import message, command, voice blueprints = [ command.bp, + voice.bp, message.bp, ] \ No newline at end of file diff --git a/src/transcriberbot/blueprints/command.py b/src/transcriberbot/blueprints/command.py index 8bbfd43..74e3a03 100644 --- a/src/transcriberbot/blueprints/command.py +++ b/src/transcriberbot/blueprints/command.py @@ -3,12 +3,12 @@ Date: 15/02/25 """ import logging + import resources as R import config import translator from wonda import Blueprint, Message, Command -from wonda.bot.rules import Text from database import TBDB from transcriberbot.rules import ChatAdmin @@ -16,17 +16,27 @@ bp = Blueprint() -@bp.on.message(Command("start", "help")) +@bp.on.message(Command("start", "help") & ChatAdmin()) +@bp.on.channel_post(Command("start", "help") & ChatAdmin()) async def start(m: Message): await welcome_message(m) +@bp.on.message(Command("lang") & ChatAdmin()) +@bp.on.channel_post(Command("lang") & ChatAdmin()) +async def lang(m: Message): + chat_lang = TBDB.get_chat_lang(m.chat.id) + await m.reply(R.get_string_resource("language_get", chat_lang).replace("{lang}", chat_lang)) + + @bp.on.message(Command("rate") & ChatAdmin()) +@bp.on.channel_post(Command("rate") & ChatAdmin()) async def rate(m: Message): await m.answer(R.get_string_resource("message_rate", TBDB.get_chat_lang(m.chat.id))) @bp.on.message(Command("disable_voice") & ChatAdmin()) +@bp.on.channel_post(Command("disable_voice") & ChatAdmin()) async def disable_voice(m: Message): chat_id = m.chat.id TBDB.set_chat_voice_enabled(chat_id, 0) @@ -34,6 +44,7 @@ async def disable_voice(m: Message): @bp.on.message(Command("enable_voice") & ChatAdmin()) +@bp.on.channel_post(Command("enable_voice") & ChatAdmin()) async def enable_voice(m: Message): chat_id = m.chat.id TBDB.set_chat_voice_enabled(chat_id, 1) @@ -41,6 +52,7 @@ async def enable_voice(m: Message): @bp.on.message(Command("disable_photos") & ChatAdmin()) +@bp.on.channel_post(Command("disable_photos") & ChatAdmin()) async def disable_photos(m: Message): chat_id = m.chat.id TBDB.set_chat_photos_enabled(chat_id, 0) @@ -48,6 +60,7 @@ async def disable_photos(m: Message): @bp.on.message(Command("enable_photos") & ChatAdmin()) +@bp.on.channel_post(Command("enable_photos") & ChatAdmin()) async def enable_photos(m: Message): chat_id = m.chat.id TBDB.set_chat_photos_enabled(chat_id, 1) @@ -55,6 +68,7 @@ async def enable_photos(m: Message): @bp.on.message(Command("disable_qr") & ChatAdmin()) +@bp.on.channel_post(Command("disable_qr") & ChatAdmin()) async def disable_qr(m: Message): chat_id = m.chat.id TBDB.set_chat_qr_enabled(chat_id, 0) @@ -62,6 +76,7 @@ async def disable_qr(m: Message): @bp.on.message(Command("enable_qr") & ChatAdmin()) +@bp.on.channel_post(Command("enable_qr") & ChatAdmin()) async def enable_qr(m: Message): chat_id = m.chat.id TBDB.set_chat_qr_enabled(chat_id, 1) @@ -69,6 +84,7 @@ async def enable_qr(m: Message): @bp.on.message(Command("translate") & ChatAdmin()) +@bp.on.channel_post(Command("translate") & ChatAdmin()) async def translate(m: Message): chat_id = m.chat.id @@ -99,35 +115,33 @@ async def translate(m: Message): @bp.on.message(Command("donate") & ChatAdmin()) +@bp.on.channel_post(Command("donate") & ChatAdmin()) async def donate(m: Message): chat_id = m.chat.id await m.reply(R.get_string_resource("message_donate", TBDB.get_chat_lang(chat_id)), parse_mode="html") @bp.on.message(Command("privacy")) +@bp.on.channel_post(Command("privacy")) async def privacy(m: Message): chat_id = m.chat.id await m.reply(R.get_string_resource("privacy_policy", TBDB.get_chat_lang(chat_id)), parse_mode='html') -def get_language_list(): - return config.get_config_prop("app")["languages"].keys() - - async def welcome_message(m: Message): chat_record = TBDB.get_chat_entry(m.chat.id) language = None if chat_record is not None: language = chat_record["lang"] - elif m.from_.language_code is not None: + elif m.from_ and m.from_.language_code is not None: # Channel posts do not have a language_code attribute logger.info("Language_code: %s", m.from_.language_code) language = m.from_.language_code message = R.get_string_resource("message_welcome", language) message = message.replace("{languages}", - "/" + "\n/".join(get_language_list())) # Format them to be a list of commands + "/" + "\n/".join(config.get_language_list())) # Format them to be a list of commands await m.reply( text=message, @@ -144,3 +158,11 @@ async def welcome_message(m: Message): logger.info("No record found for chat {}, creating one with lang {}".format(m.chat.id, language)) TBDB.create_default_chat_entry(m.chat.id, language) + +async def set_language(m: Message, language): + chat_id = m.chat.id + lang_ = config.get_config_prop("app")["languages"][language] #ISO 639-1 code for language + TBDB.set_chat_lang(chat_id, lang_) + message = R.get_string_resource("language_set", lang_).replace("{lang}", language) + await m.reply(message) + diff --git a/src/transcriberbot/blueprints/message.py b/src/transcriberbot/blueprints/message.py index e1c67b5..cb354e4 100644 --- a/src/transcriberbot/blueprints/message.py +++ b/src/transcriberbot/blueprints/message.py @@ -12,16 +12,7 @@ bp = Blueprint() -@bp.on.message(Text("bye", "cheers", ignore_case=True)) -async def bye_handler(m: Message) -> None: - await m.answer("See you soon!") - - -@bp.on.message(Text("take care", "have a good day", ignore_case=True)) -async def goodbye_handler(m: Message) -> None: - await m.answer("You too, bye!") - - @bp.on.message(FromPrivate()) async def private_message(m: Message): - await m.answer(R.get_string_resource("message_private", TBDB.get_chat_lang(m.chat.id))) \ No newline at end of file + await m.answer(R.get_string_resource("message_private", TBDB.get_chat_lang(m.chat.id))) + diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index 0e0223b..438b0ba 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -2,3 +2,163 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ +import logging + +import resources as R +import config +import time +import transcriberbot.multiprocessing as tbmp +import transcriberbot.rules +import os +import requests +import traceback +import asyncio + +import audiotools + +from wonda.types import Audio, Voice, Document, ChatType, ReplyParameters +from wonda import Blueprint, Message, Command, APIException +from database import TBDB + +logger = logging.getLogger(__name__) +bp = Blueprint() + + +async def transcribe_audio_file(m: Message, path): + chat_id = m.chat.id + lang = TBDB.get_chat_lang(chat_id) + is_group = m.chat.type != ChatType.PRIVATE + + api_key = config.get_config_prop("wit").get(lang, None) + if api_key is None: + logger.error("Language not found in wit.json %s", lang) + await m.reply(R.get_string_resource("unknown_api_key", lang).format(language=lang), parse_mode="html") + return + + logger.debug("Using key %s for lang %s", api_key, lang) + + print("CTX API", m.ctx_api) + message = await m.reply(R.get_string_resource("transcribing", lang), parse_mode="html") + print("CTX API", message.ctx_api) + message_id = message.message_id + + # TranscriberBot.get().start_thread(message_id) + logger.debug("Starting thread %d", message_id) + + # keyboard = InlineKeyboardMarkup( + # [[InlineKeyboardButton("Stop", callback_data=message_id)]] + # ) + + text = "" + if is_group: + text = R.get_string_resource("transcription_text", lang) + "\n" + success = False + + + try: + for speech in audiotools.transcribe(path, api_key): + # logger.debug("Thread %d running: %r", message_id, TranscriberBot.get().thread_running(message_id)) + # if TranscriberBot.get().thread_running(message_id) is False: + # TranscriberBot.get().del_thread(message_id) + # return + + retry = True + retry_num = 0 + + while retry: # and TranscriberBot.get().thread_running(message_id): + try: + if len(text + " " + speech) >= 4000: + text = R.get_string_resource("transcription_continues", lang) + "\n" + message = await message.ctx_api.send_message( + text=text + " " + speech + " [...]", chat_id=chat_id, + reply_parameters=ReplyParameters(message_id=message_id, chat_id=chat_id), parse_mode="html" + ) + else: + message = await message.ctx_api.edit_message_text( + text + " " + speech, chat_id=chat_id, message_id=message_id, parse_mode="html" + ) + + text += " " + speech + retry = False + success = True + + except APIException[51] as e: + logger.error("Network error") + retry = False + + except APIException as e: + print(e) + logger.error("Timeout error %s", traceback.format_exc()) + retry_num += 1 + if retry_num >= 3: + retry = False + + # except telegram.error.RetryAfter as r: + # logger.warning("Retrying after %d", r.retry_after) + # time.sleep(r.retry_after) + # + # except telegram.error.TelegramError as te: + # logger.error("Telegram error %s", traceback.format_exc()) + # retry = False + # + # except Exception as e: + # logger.error("Exception %s", traceback.format_exc()) + # retry = False + except Exception as e: + logger.error("Could not transcribe audio") + + if not success: + await message.ctx_api.edit_message_text( + R.get_string_resource("transcription_failed", lang), chat_id=chat_id, + message_id=message_id, parse_mode="html" + ) + + # TranscriberBot.get().del_thread(message_id) + + +def download_file(file_id, output_path): + print("Downloading file id:", file_id) + bot_token = config.bot_token() + url = f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}" + response = requests.get(url) + file_path = response.json()["result"]["file_path"] + file_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}" + response = requests.get(file_url) + + with open(output_path, "wb") as f: + f.write(response.content) + + +async def process_media_voice(m: Message, media: Voice, name): + chat_id = m.chat.id + file_size = media.file_size + max_size = config.get_config_prop("app").get("max_media_voice_file_size", 20 * 1024 * 1024) + + if file_size > max_size: + error_message = R.get_string_resource("file_too_big", TBDB.get_chat_lang(chat_id)).format( + max_size / (1024 * 1024)) + "\n" + await m.reply(error_message, parse_mode="html") + return + + file_id = media.file_id + file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) + download_file(file_id, file_path) + + try: + await transcribe_audio_file(m, file_path) + except Exception as e: + logger.error("Exception handling %s from %d: %s", name, chat_id, traceback.format_exc()) + finally: + os.remove(file_path) + +def wrapper(message, voice, name): + asyncio.run(process_media_voice(message, voice, name)) + +@bp.on.message(transcriberbot.rules.Voice()) +@bp.on.channel_post(transcriberbot.rules.Voice()) +async def handler(m: Message) -> None: + if TBDB.get_chat_voice_enabled(m.chat.id) == 0: + return + + task = asyncio.get_event_loop().create_task(process_media_voice(m, m.voice, "voice")) + # tbmp.voice_pool().submit(wrapper, m, m.voice, "voice") diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index 77bf82f..f63059b 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -5,16 +5,28 @@ import wonda import config +import logging +from functools import partial +from wonda import Command from wonda.api.utils import Token from transcriberbot.blueprints import blueprints -from transcriberbot.middlewares import ChatAdminMiddleware +from transcriberbot.blueprints.command import set_language +from transcriberbot.rules import ChatAdmin def run(bot_token: str): bot = wonda.Bot(Token(bot_token)) + logger = logging.getLogger(__name__) + logger.info("Installing language handlers..") + for language in config.get_language_list(): + bot.on.message(Command(language) & ChatAdmin())(lambda m, l=language: set_language(m, l)) + bot.on.channel_post(Command(language) & ChatAdmin())(lambda m, l=language: set_language(m, l)) + + logger.info("Installing blueprints..") for bp in blueprints: bp.load_into(bot) + logger.info("Starting bot..") bot.run_forever() \ No newline at end of file diff --git a/src/transcriberbot/multiprocessing/__init__.py b/src/transcriberbot/multiprocessing/__init__.py new file mode 100644 index 0000000..f11af0d --- /dev/null +++ b/src/transcriberbot/multiprocessing/__init__.py @@ -0,0 +1,5 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +from .pools import voice_pool, init \ No newline at end of file diff --git a/src/transcriberbot/multiprocessing/pools.py b/src/transcriberbot/multiprocessing/pools.py new file mode 100644 index 0000000..eab432c --- /dev/null +++ b/src/transcriberbot/multiprocessing/pools.py @@ -0,0 +1,34 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +import logging +import config +from concurrent.futures import ThreadPoolExecutor + +voice_thread_pool, photos_thread_pool, misc_thread_pool = None, None, None + + +def init(): + global voice_thread_pool + global photos_thread_pool + global misc_thread_pool + + voice_thread_pool = ThreadPoolExecutor( + max_workers=config.get_config_prop("app")["voice_max_threads"] + ) + photos_thread_pool = ThreadPoolExecutor( + max_workers=config.get_config_prop("app")["photos_max_threads"] + ) + + misc_thread_pool = ThreadPoolExecutor( + max_workers=2 + ) + + print("POOLS INITIALIZED:", voice_thread_pool, photos_thread_pool, misc_thread_pool) + logging.info("Thread pools initialized") + + +def voice_pool(): + global voice_thread_pool + return voice_thread_pool \ No newline at end of file diff --git a/src/transcriberbot/rules/rules.py b/src/transcriberbot/rules/rules.py index 1f17aac..d52d988 100644 --- a/src/transcriberbot/rules/rules.py +++ b/src/transcriberbot/rules/rules.py @@ -2,18 +2,39 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ +import logging from wonda.bot.rules.abc import ABCRule from wonda.bot.updates import MessageUpdate from wonda.types import ChatType from wonda.types.objects import User +logger = logging.getLogger(__name__) + + class Voice(ABCRule[MessageUpdate]): + async def check(self, m: MessageUpdate, _) -> bool: + return bool(m.voice) + +class Audio(ABCRule[MessageUpdate]): + async def check(self, m: MessageUpdate, _) -> bool: + return bool(m.audio) + + +class VideoNote(ABCRule[MessageUpdate]): + async def check(self, m: MessageUpdate, _) -> bool: + return bool(m.video_note) + + +class Document(ABCRule[MessageUpdate]): """ Checks if the message has voice media """ + def __init__(self, *allowed_exts) -> None: self.allowed_exts = allowed_exts + if len(allowed_exts) == 0: + logger.warning("No allowed extensions were provided. Documents will be disabled") async def check(self, m: MessageUpdate, _) -> bool: if m.document: @@ -21,7 +42,8 @@ async def check(self, m: MessageUpdate, _) -> bool: ext = filename.split('.')[-1] return ext in self.allowed_exts - return bool(m.voice or m.audio or m.video_note) + return False + class FromPrivate(ABCRule[MessageUpdate]): """ @@ -43,7 +65,6 @@ async def check(self, m: MessageUpdate, _) -> bool: user: User = m.from_ chat_admins = await m.ctx_api.get_chat_administrators(m.chat.id) - print("CHAT ADMINS", chat_admins) is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) is_admin = len(is_admin) > 0 diff --git a/values/strings.xml b/values/strings.xml index 5793b5e..cba0064 100644 --- a/values/strings.xml +++ b/values/strings.xml @@ -2,6 +2,7 @@ Language set to {lang} +Current language: {lang} This bot transcribes audio and pictures into text. Add it to a group or forward audio messages and pictures to it. diff --git a/values/strings_de-DE.xml b/values/strings_de-DE.xml index d33970f..c869218 100644 --- a/values/strings_de-DE.xml +++ b/values/strings_de-DE.xml @@ -1,6 +1,6 @@ - + {lang} als Sprache festgelegt From e6f900f0958ae17b47f8ea5ad49a60b9fda2fae4 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sat, 15 Feb 2025 20:26:54 +0100 Subject: [PATCH 089/120] [wip] upgrade to latest PTB --- src/transcriberbot/blueprints/__init__.py | 7 +- src/transcriberbot/blueprints/command.py | 168 ------------------ src/transcriberbot/blueprints/commands.py | 168 ++++++++++++++++++ src/transcriberbot/blueprints/message.py | 18 -- src/transcriberbot/blueprints/messages.py | 16 ++ src/transcriberbot/blueprints/voice.py | 165 ++++++++--------- src/transcriberbot/bot.py | 43 +++-- .../{rules => filters}/__init__.py | 2 +- src/transcriberbot/filters/filters.py | 69 +++++++ src/transcriberbot/middlewares/__init__.py | 5 - src/transcriberbot/middlewares/chat_admin.py | 11 -- src/transcriberbot/rules/rules.py | 72 -------- 12 files changed, 361 insertions(+), 383 deletions(-) delete mode 100644 src/transcriberbot/blueprints/command.py create mode 100644 src/transcriberbot/blueprints/commands.py delete mode 100644 src/transcriberbot/blueprints/message.py create mode 100644 src/transcriberbot/blueprints/messages.py rename src/transcriberbot/{rules => filters}/__init__.py (80%) create mode 100644 src/transcriberbot/filters/filters.py delete mode 100644 src/transcriberbot/middlewares/__init__.py delete mode 100644 src/transcriberbot/middlewares/chat_admin.py delete mode 100644 src/transcriberbot/rules/rules.py diff --git a/src/transcriberbot/blueprints/__init__.py b/src/transcriberbot/blueprints/__init__.py index 85c3d93..43a25eb 100644 --- a/src/transcriberbot/blueprints/__init__.py +++ b/src/transcriberbot/blueprints/__init__.py @@ -2,10 +2,5 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ -from . import message, command, voice +from . import commands, messages, voice -blueprints = [ - command.bp, - voice.bp, - message.bp, -] \ No newline at end of file diff --git a/src/transcriberbot/blueprints/command.py b/src/transcriberbot/blueprints/command.py deleted file mode 100644 index 74e3a03..0000000 --- a/src/transcriberbot/blueprints/command.py +++ /dev/null @@ -1,168 +0,0 @@ -""" -Author: Carlo Alberto Barbano -Date: 15/02/25 -""" -import logging - -import resources as R -import config -import translator - -from wonda import Blueprint, Message, Command -from database import TBDB -from transcriberbot.rules import ChatAdmin - -logger = logging.getLogger(__name__) -bp = Blueprint() - - -@bp.on.message(Command("start", "help") & ChatAdmin()) -@bp.on.channel_post(Command("start", "help") & ChatAdmin()) -async def start(m: Message): - await welcome_message(m) - - -@bp.on.message(Command("lang") & ChatAdmin()) -@bp.on.channel_post(Command("lang") & ChatAdmin()) -async def lang(m: Message): - chat_lang = TBDB.get_chat_lang(m.chat.id) - await m.reply(R.get_string_resource("language_get", chat_lang).replace("{lang}", chat_lang)) - - -@bp.on.message(Command("rate") & ChatAdmin()) -@bp.on.channel_post(Command("rate") & ChatAdmin()) -async def rate(m: Message): - await m.answer(R.get_string_resource("message_rate", TBDB.get_chat_lang(m.chat.id))) - - -@bp.on.message(Command("disable_voice") & ChatAdmin()) -@bp.on.channel_post(Command("disable_voice") & ChatAdmin()) -async def disable_voice(m: Message): - chat_id = m.chat.id - TBDB.set_chat_voice_enabled(chat_id, 0) - await m.answer(R.get_string_resource("voice_disabled", TBDB.get_chat_lang(chat_id))) - - -@bp.on.message(Command("enable_voice") & ChatAdmin()) -@bp.on.channel_post(Command("enable_voice") & ChatAdmin()) -async def enable_voice(m: Message): - chat_id = m.chat.id - TBDB.set_chat_voice_enabled(chat_id, 1) - await m.answer(R.get_string_resource("voice_enabled", TBDB.get_chat_lang(chat_id))) - - -@bp.on.message(Command("disable_photos") & ChatAdmin()) -@bp.on.channel_post(Command("disable_photos") & ChatAdmin()) -async def disable_photos(m: Message): - chat_id = m.chat.id - TBDB.set_chat_photos_enabled(chat_id, 0) - await m.answer(R.get_string_resource("photos_disabled", TBDB.get_chat_lang(chat_id))) - - -@bp.on.message(Command("enable_photos") & ChatAdmin()) -@bp.on.channel_post(Command("enable_photos") & ChatAdmin()) -async def enable_photos(m: Message): - chat_id = m.chat.id - TBDB.set_chat_photos_enabled(chat_id, 1) - await m.answer(R.get_string_resource("photos_enabled", TBDB.get_chat_lang(chat_id))) - - -@bp.on.message(Command("disable_qr") & ChatAdmin()) -@bp.on.channel_post(Command("disable_qr") & ChatAdmin()) -async def disable_qr(m: Message): - chat_id = m.chat.id - TBDB.set_chat_qr_enabled(chat_id, 0) - await m.answer(R.get_string_resource("qr_disabled", TBDB.get_chat_lang(chat_id))) - - -@bp.on.message(Command("enable_qr") & ChatAdmin()) -@bp.on.channel_post(Command("enable_qr") & ChatAdmin()) -async def enable_qr(m: Message): - chat_id = m.chat.id - TBDB.set_chat_qr_enabled(chat_id, 1) - await m.answer(R.get_string_resource("qr_enabled", TBDB.get_chat_lang(chat_id))) - - -@bp.on.message(Command("translate") & ChatAdmin()) -@bp.on.channel_post(Command("translate") & ChatAdmin()) -async def translate(m: Message): - chat_id = m.chat.id - - lang = m.text - lang = lang.replace("/translate", "").strip() - logger.debug("Language %s", lang) - - if not m.reply_to_message: - await m.reply(R.get_string_resource("translate_reply_to_message", TBDB.get_chat_lang(chat_id))) - return - - if not lang: - await m.reply(R.get_string_resource("translate_language_missing", TBDB.get_chat_lang(chat_id))) - return - - if lang not in config.get_config_prop("app")["languages"]: - await m.reply(R.get_string_resource("translate_language_not_found", TBDB.get_chat_lang(chat_id)).format(lang)) - return - - lang = config.get_config_prop("app")["languages"][lang].split('-')[0] - translation = translator.translate( - source=TBDB.get_chat_lang(chat_id), - target=lang, - text=m.reply_to_message.text - ) - - await m.reply(translation) - - -@bp.on.message(Command("donate") & ChatAdmin()) -@bp.on.channel_post(Command("donate") & ChatAdmin()) -async def donate(m: Message): - chat_id = m.chat.id - await m.reply(R.get_string_resource("message_donate", TBDB.get_chat_lang(chat_id)), parse_mode="html") - - -@bp.on.message(Command("privacy")) -@bp.on.channel_post(Command("privacy")) -async def privacy(m: Message): - chat_id = m.chat.id - await m.reply(R.get_string_resource("privacy_policy", TBDB.get_chat_lang(chat_id)), parse_mode='html') - - -async def welcome_message(m: Message): - chat_record = TBDB.get_chat_entry(m.chat.id) - - language = None - if chat_record is not None: - language = chat_record["lang"] - elif m.from_ and m.from_.language_code is not None: - # Channel posts do not have a language_code attribute - logger.info("Language_code: %s", m.from_.language_code) - language = m.from_.language_code - - message = R.get_string_resource("message_welcome", language) - message = message.replace("{languages}", - "/" + "\n/".join(config.get_language_list())) # Format them to be a list of commands - - await m.reply( - text=message, - parse_mode="html" - ) - - if chat_record is None: - if language is None: - language = "en-US" - - if len(language) < 5: - language = R.iso639_2_to_639_1(language) - - logger.info("No record found for chat {}, creating one with lang {}".format(m.chat.id, language)) - TBDB.create_default_chat_entry(m.chat.id, language) - - -async def set_language(m: Message, language): - chat_id = m.chat.id - lang_ = config.get_config_prop("app")["languages"][language] #ISO 639-1 code for language - TBDB.set_chat_lang(chat_id, lang_) - message = R.get_string_resource("language_set", lang_).replace("{lang}", language) - await m.reply(message) - diff --git a/src/transcriberbot/blueprints/commands.py b/src/transcriberbot/blueprints/commands.py new file mode 100644 index 0000000..407e9d8 --- /dev/null +++ b/src/transcriberbot/blueprints/commands.py @@ -0,0 +1,168 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +import logging + +from telegram import Update +from telegram.ext import ContextTypes + +import config +import resources as R +import translator +from database import TBDB + +logger = logging.getLogger(__name__) + + +async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): + await welcome_message(update, context) + + +async def lang(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_lang = TBDB.get_chat_lang(update.effective_chat.id) + await context.bot.send_message( + update.effective_chat.id, R.get_string_resource("language_get", chat_lang).replace("{lang}", chat_lang) + ) + + +async def rate(update: Update, context: ContextTypes.DEFAULT_TYPE): + await context.bot.send_message( + update.effective_chat.id, + R.get_string_resource("message_rate", TBDB.get_chat_lang(update.effective_chat.id)) + ) + + +async def disable_voice(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + TBDB.set_chat_voice_enabled(chat_id, 0) + await context.bot.send_message( + chat_id, R.get_string_resource("voice_disabled", TBDB.get_chat_lang(chat_id)) + ) + + +async def enable_voice(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + TBDB.set_chat_voice_enabled(chat_id, 1) + await context.bot.send_message( + chat_id, R.get_string_resource("voice_enabled", TBDB.get_chat_lang(chat_id)) + ) + + +async def disable_photos(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + TBDB.set_chat_photos_enabled(chat_id, 0) + await context.bot.send_message( + chat_id, R.get_string_resource("photos_disabled", TBDB.get_chat_lang(chat_id)) + ) + + +async def enable_photos(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + TBDB.set_chat_photos_enabled(chat_id, 1) + await context.bot.send_message( + chat_id, R.get_string_resource("photos_enabled", TBDB.get_chat_lang(chat_id)) + ) + + +async def disable_qr(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + TBDB.set_chat_qr_enabled(chat_id, 0) + await context.bot.send_message( + chat_id, R.get_string_resource("qr_disabled", TBDB.get_chat_lang(chat_id)) + ) + + +async def enable_qr(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + TBDB.set_chat_qr_enabled(chat_id, 1) + await context.bot.send_message( + chat_id, R.get_string_resource("qr_enabled", TBDB.get_chat_lang(chat_id)) + ) + + +async def translate(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + + lang = update.effective_message.text + lang = lang.replace("/translate", "").strip() + logger.debug("Language %s", lang) + + if not update.effective_message.reply_to_message: + await context.bot.send_message( + chat_id, R.get_string_resource("translate_reply_to_message", TBDB.get_chat_lang(chat_id)) + ) + return + + if not lang: + await context.bot.send_message( + chat_id, R.get_string_resource("translate_language_missing", TBDB.get_chat_lang(chat_id)) + ) + return + + if lang not in config.get_config_prop("app")["languages"]: + await context.bot.send_message( + chat_id, R.get_string_resource("translate_language_not_found", TBDB.get_chat_lang(chat_id)).format(lang) + ) + return + + lang = config.get_config_prop("app")["languages"][lang].split('-')[0] + translation = translator.translate( + source=TBDB.get_chat_lang(chat_id), + target=lang, + text=update.effective_message.reply_to_message.text + ) + + await context.bot.send_message( + chat_id, translation, reply_to_message_id=update.effective_message.reply_to_message.message_id + ) + + +async def donate(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + await context.bot.send_message( + chat_id, R.get_string_resource("message_donate", TBDB.get_chat_lang(chat_id)), parse_mode="html" + ) + + +async def privacy(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + await context.bot.send_message( + chat_id, R.get_string_resource("privacy_policy", TBDB.get_chat_lang(chat_id)), parse_mode="html" + ) + + +async def welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_record = TBDB.get_chat_entry(update.effective_chat.id) + + language = None + if chat_record is not None: + language = chat_record["lang"] + elif update.effective_user.language_code is not None: + # Channel posts do not have a language_code attribute + logger.info("Language_code: %s", update.effective_user.language_code) + language = update.effective_user.language_code + + message = R.get_string_resource("message_welcome", language) + message = message.replace("{languages}", + "/" + "\n/".join(config.get_language_list())) # Format them to be a list of commands + + await context.bot.send_message(update.effective_chat.id, message, "html") + + if chat_record is None: + if language is None: + language = "en-US" + + if len(language) < 5: + language = R.iso639_2_to_639_1(language) + + logger.info("No record found for chat {}, creating one with lang {}".format(update.effective_chat.id, language)) + TBDB.create_default_chat_entry(update.effective_chat.id, language) + + +async def set_language(update: Update, context: ContextTypes.DEFAULT_TYPE, language): + chat_id = update.effective_chat.id + lang_ = config.get_config_prop("app")["languages"][language] # ISO 639-1 code for language + TBDB.set_chat_lang(chat_id, lang_) + message = R.get_string_resource("language_set", lang_).replace("{lang}", language) + await context.bot.send_message(chat_id, message, parse_mode="html") diff --git a/src/transcriberbot/blueprints/message.py b/src/transcriberbot/blueprints/message.py deleted file mode 100644 index cb354e4..0000000 --- a/src/transcriberbot/blueprints/message.py +++ /dev/null @@ -1,18 +0,0 @@ -""" -Author: Carlo Alberto Barbano -Date: 15/02/25 -""" -import resources as R - -from wonda import Blueprint, Message -from wonda.bot.rules import Text -from database import TBDB -from transcriberbot.rules import FromPrivate - -bp = Blueprint() - - -@bp.on.message(FromPrivate()) -async def private_message(m: Message): - await m.answer(R.get_string_resource("message_private", TBDB.get_chat_lang(m.chat.id))) - diff --git a/src/transcriberbot/blueprints/messages.py b/src/transcriberbot/blueprints/messages.py new file mode 100644 index 0000000..e9469b0 --- /dev/null +++ b/src/transcriberbot/blueprints/messages.py @@ -0,0 +1,16 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +import resources as R + +from telegram import Update +from telegram.ext import ContextTypes +from database import TBDB + + +async def private_message(update: Update, context: ContextTypes.DEFAULT_TYPE): + await context.bot.send_message( + update.effective_chat.id, + R.get_string_resource("message_private", TBDB.get_chat_lang(update.effective_chat.id)) + ) diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index 438b0ba..c1449ee 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -2,44 +2,80 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ +import asyncio import logging - -import resources as R -import config -import time -import transcriberbot.multiprocessing as tbmp -import transcriberbot.rules import os -import requests import traceback -import asyncio +import time -import audiotools +import telegram +from telegram import Update, Voice +from telegram.constants import ChatType +from telegram.ext import ContextTypes -from wonda.types import Audio, Voice, Document, ChatType, ReplyParameters -from wonda import Blueprint, Message, Command, APIException +import audiotools +import config +import resources as R from database import TBDB logger = logging.getLogger(__name__) -bp = Blueprint() -async def transcribe_audio_file(m: Message, path): - chat_id = m.chat.id + +async def voice_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: + return + + task = asyncio.get_event_loop().create_task( + process_media_voice(update, context, update.effective_message.voice, "voice") + ) + +async def process_media_voice(update: Update, context: ContextTypes.DEFAULT_TYPE, media: Voice, name: str) -> None: + chat_id = update.effective_chat.id + file_size = media.file_size + max_size = config.get_config_prop("app").get("max_media_voice_file_size", 20 * 1024 * 1024) + + if file_size > max_size: + error_message = R.get_string_resource("file_too_big", TBDB.get_chat_lang(chat_id)).format( + max_size / (1024 * 1024)) + "\n" + await context.bot.send_message( + chat_id, error_message, parse_mode="html", reply_to_message_id=update.effective_message.message_id + ) + return + + file_id = media.file_id + file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) + file: telegram.File = await context.bot.get_file(file_id) + await file.download_to_drive(file_path) + + try: + await transcribe_audio_file(update, context, file_path) + except Exception as e: + logger.error("Exception handling %s from %d: %s", name, chat_id, traceback.format_exc()) + finally: + os.remove(file_path) + + +async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TYPE, path: str): + chat_id = update.effective_chat.id lang = TBDB.get_chat_lang(chat_id) - is_group = m.chat.type != ChatType.PRIVATE + is_group = update.effective_chat.type != ChatType.PRIVATE api_key = config.get_config_prop("wit").get(lang, None) if api_key is None: logger.error("Language not found in wit.json %s", lang) - await m.reply(R.get_string_resource("unknown_api_key", lang).format(language=lang), parse_mode="html") + await context.bot.send_message( + chat_id, R.get_string_resource("unknown_api_key", lang).format(language=lang), parse_mode="html", + reply_to_message_id=update.effective_message.message_id + ) return logger.debug("Using key %s for lang %s", api_key, lang) - print("CTX API", m.ctx_api) - message = await m.reply(R.get_string_resource("transcribing", lang), parse_mode="html") - print("CTX API", message.ctx_api) + message = await context.bot.send_message( + chat_id, R.get_string_resource("transcribing", lang), parse_mode="html", + reply_to_message_id=update.effective_message.message_id + ) message_id = message.message_id # TranscriberBot.get().start_thread(message_id) @@ -54,61 +90,54 @@ async def transcribe_audio_file(m: Message, path): text = R.get_string_resource("transcription_text", lang) + "\n" success = False - try: for speech in audiotools.transcribe(path, api_key): - # logger.debug("Thread %d running: %r", message_id, TranscriberBot.get().thread_running(message_id)) - # if TranscriberBot.get().thread_running(message_id) is False: - # TranscriberBot.get().del_thread(message_id) - # return - retry = True retry_num = 0 + print("SPEECH:", speech) while retry: # and TranscriberBot.get().thread_running(message_id): try: if len(text + " " + speech) >= 4000: text = R.get_string_resource("transcription_continues", lang) + "\n" - message = await message.ctx_api.send_message( - text=text + " " + speech + " [...]", chat_id=chat_id, - reply_parameters=ReplyParameters(message_id=message_id, chat_id=chat_id), parse_mode="html" + message = await context.bot.send_message( + chat_id, text + speech + " [...]", + reply_to_message_id=message_id, parse_mode="html" ) else: - message = await message.ctx_api.edit_message_text( - text + " " + speech, chat_id=chat_id, message_id=message_id, parse_mode="html" + await context.bot.edit_message_text( + text + " " + speech + " [...]", chat_id=chat_id, + message_id=message_id, parse_mode="html" ) text += " " + speech retry = False success = True - except APIException[51] as e: - logger.error("Network error") - retry = False - - except APIException as e: + except telegram.error.TimedOut as e: print(e) logger.error("Timeout error %s", traceback.format_exc()) retry_num += 1 if retry_num >= 3: retry = False - # except telegram.error.RetryAfter as r: - # logger.warning("Retrying after %d", r.retry_after) - # time.sleep(r.retry_after) - # - # except telegram.error.TelegramError as te: - # logger.error("Telegram error %s", traceback.format_exc()) - # retry = False - # - # except Exception as e: - # logger.error("Exception %s", traceback.format_exc()) - # retry = False + except telegram.error.RetryAfter as r: + logger.warning("Retrying after %d", r.retry_after) + time.sleep(r.retry_after) + + except telegram.error.TelegramError as te: + logger.error("Telegram error %s", traceback.format_exc()) + retry = False + + except Exception as e: + logger.error("Exception %s", traceback.format_exc()) + retry = False + except Exception as e: logger.error("Could not transcribe audio") if not success: - await message.ctx_api.edit_message_text( + await context.bot.edit_message_text( R.get_string_resource("transcription_failed", lang), chat_id=chat_id, message_id=message_id, parse_mode="html" ) @@ -116,49 +145,7 @@ async def transcribe_audio_file(m: Message, path): # TranscriberBot.get().del_thread(message_id) -def download_file(file_id, output_path): - print("Downloading file id:", file_id) - bot_token = config.bot_token() - url = f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}" - response = requests.get(url) - file_path = response.json()["result"]["file_path"] - file_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}" - response = requests.get(file_url) - - with open(output_path, "wb") as f: - f.write(response.content) - - -async def process_media_voice(m: Message, media: Voice, name): - chat_id = m.chat.id - file_size = media.file_size - max_size = config.get_config_prop("app").get("max_media_voice_file_size", 20 * 1024 * 1024) - - if file_size > max_size: - error_message = R.get_string_resource("file_too_big", TBDB.get_chat_lang(chat_id)).format( - max_size / (1024 * 1024)) + "\n" - await m.reply(error_message, parse_mode="html") - return - file_id = media.file_id - file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) - download_file(file_id, file_path) - try: - await transcribe_audio_file(m, file_path) - except Exception as e: - logger.error("Exception handling %s from %d: %s", name, chat_id, traceback.format_exc()) - finally: - os.remove(file_path) - -def wrapper(message, voice, name): - asyncio.run(process_media_voice(message, voice, name)) -@bp.on.message(transcriberbot.rules.Voice()) -@bp.on.channel_post(transcriberbot.rules.Voice()) -async def handler(m: Message) -> None: - if TBDB.get_chat_voice_enabled(m.chat.id) == 0: - return - task = asyncio.get_event_loop().create_task(process_media_voice(m, m.voice, "voice")) - # tbmp.voice_pool().submit(wrapper, m, m.voice, "voice") diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index f63059b..ad05bbc 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -3,30 +3,47 @@ Date: 15/02/25 """ -import wonda import config import logging +from telegram.ext import MessageHandler, ApplicationBuilder, CommandHandler, ContextTypes from functools import partial -from wonda import Command -from wonda.api.utils import Token -from transcriberbot.blueprints import blueprints -from transcriberbot.blueprints.command import set_language -from transcriberbot.rules import ChatAdmin +from transcriberbot.blueprints import commands, messages, voice +from transcriberbot.blueprints.commands import set_language + +from telegram.ext.filters import VOICE +from transcriberbot.filters import ChatAdmin, FromPrivate def run(bot_token: str): - bot = wonda.Bot(Token(bot_token)) + application = ApplicationBuilder().token(bot_token).build() logger = logging.getLogger(__name__) + + logging.info("Installing handlers") + application.add_handler(CommandHandler('start', commands.start, filters=ChatAdmin())) + application.add_handler(CommandHandler('help', commands.start, filters=ChatAdmin())) + application.add_handler(CommandHandler('lang', commands.lang, filters=ChatAdmin())) + application.add_handler(CommandHandler('rate', commands.rate, filters=ChatAdmin())) + application.add_handler(CommandHandler('disable_voice', commands.disable_voice, filters=ChatAdmin())) + application.add_handler(CommandHandler('enable_voice', commands.enable_voice, filters=ChatAdmin())) + application.add_handler(CommandHandler('disable_photos', commands.disable_photos, filters=ChatAdmin())) + application.add_handler(CommandHandler('enable_photos', commands.enable_photos, filters=ChatAdmin())) + application.add_handler(CommandHandler('disable_qr', commands.disable_qr, filters=ChatAdmin())) + application.add_handler(CommandHandler('enable_qr', commands.enable_qr, filters=ChatAdmin())) + application.add_handler(CommandHandler('translate', commands.translate, filters=ChatAdmin())) + application.add_handler(CommandHandler('donate', commands.donate, filters=ChatAdmin())) + application.add_handler(CommandHandler('privacy', commands.privacy)) + logger.info("Installing language handlers..") for language in config.get_language_list(): - bot.on.message(Command(language) & ChatAdmin())(lambda m, l=language: set_language(m, l)) - bot.on.channel_post(Command(language) & ChatAdmin())(lambda m, l=language: set_language(m, l)) + application.add_handler( + CommandHandler(language, partial(set_language, language=language), filters=ChatAdmin()) + ) + + application.add_handler(MessageHandler(VOICE, voice.voice_message)) - logger.info("Installing blueprints..") - for bp in blueprints: - bp.load_into(bot) + application.add_handler(MessageHandler(FromPrivate(), messages.private_message)) logger.info("Starting bot..") - bot.run_forever() \ No newline at end of file + application.run_polling() \ No newline at end of file diff --git a/src/transcriberbot/rules/__init__.py b/src/transcriberbot/filters/__init__.py similarity index 80% rename from src/transcriberbot/rules/__init__.py rename to src/transcriberbot/filters/__init__.py index 2d80ee5..c3dc5eb 100644 --- a/src/transcriberbot/rules/__init__.py +++ b/src/transcriberbot/filters/__init__.py @@ -2,4 +2,4 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ -from .rules import * \ No newline at end of file +from .filters import * \ No newline at end of file diff --git a/src/transcriberbot/filters/filters.py b/src/transcriberbot/filters/filters.py new file mode 100644 index 0000000..2aa72b2 --- /dev/null +++ b/src/transcriberbot/filters/filters.py @@ -0,0 +1,69 @@ +""" +Author: Carlo Alberto Barbano +Date: 15/02/25 +""" +import logging + +from telegram.constants import ChatType +from telegram.ext.filters import UpdateFilter +from telegram import Update, ChatMember + +logger = logging.getLogger(__name__) + + + +# class Voice(ABCRule[MessageUpdate]): +# async def check(self, m: MessageUpdate, _) -> bool: +# return bool(m.voice) +# +# class Audio(ABCRule[MessageUpdate]): +# async def check(self, m: MessageUpdate, _) -> bool: +# return bool(m.audio) +# +# +# class VideoNote(ABCRule[MessageUpdate]): +# async def check(self, m: MessageUpdate, _) -> bool: +# return bool(m.video_note) +# +# +# class Document(ABCRule[MessageUpdate]): +# """ +# Checks if the message has voice media +# """ +# +# def __init__(self, *allowed_exts) -> None: +# self.allowed_exts = allowed_exts +# if len(allowed_exts) == 0: +# logger.warning("No allowed extensions were provided. Documents will be disabled") +# +# async def check(self, m: MessageUpdate, _) -> bool: +# if m.document: +# filename = m.document.file_name +# ext = filename.split('.')[-1] +# return ext in self.allowed_exts +# +# return False + +class FromPrivate(UpdateFilter): + """ + Checks if the message was sent in a private conversation. + """ + def filter(self, update: Update) -> bool: + return update.effective_chat.type == ChatType.PRIVATE + + +class ChatAdmin(UpdateFilter): + """ + Checks if the message was sent by a chat admin. + """ + async def filter(self, update: Update) -> bool: + if update.effective_chat.type in (ChatType.PRIVATE, ChatType.CHANNEL): + return True + + user = update.effective_user + chat_admins: list[ChatMember] = update.effective_chat.get_administrators() + + is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) + is_admin = len(is_admin) > 0 + + return is_admin \ No newline at end of file diff --git a/src/transcriberbot/middlewares/__init__.py b/src/transcriberbot/middlewares/__init__.py deleted file mode 100644 index 38af240..0000000 --- a/src/transcriberbot/middlewares/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -""" -Author: Carlo Alberto Barbano -Date: 15/02/25 -""" -from .chat_admin import ChatAdminMiddleware \ No newline at end of file diff --git a/src/transcriberbot/middlewares/chat_admin.py b/src/transcriberbot/middlewares/chat_admin.py deleted file mode 100644 index 9c197f6..0000000 --- a/src/transcriberbot/middlewares/chat_admin.py +++ /dev/null @@ -1,11 +0,0 @@ -""" -Author: Carlo Alberto Barbano -Date: 15/02/25 -""" -from wonda import ABCMiddleware, Bot, Message, Token, ChatMemberUpdate -from wonda.bot.rules import Command -from wonda.types import ChatType -from wonda.types.objects import User - -class ChatAdminMiddleware(ABCMiddleware[Message]): - pass \ No newline at end of file diff --git a/src/transcriberbot/rules/rules.py b/src/transcriberbot/rules/rules.py deleted file mode 100644 index d52d988..0000000 --- a/src/transcriberbot/rules/rules.py +++ /dev/null @@ -1,72 +0,0 @@ -""" -Author: Carlo Alberto Barbano -Date: 15/02/25 -""" -import logging -from wonda.bot.rules.abc import ABCRule -from wonda.bot.updates import MessageUpdate -from wonda.types import ChatType -from wonda.types.objects import User - - -logger = logging.getLogger(__name__) - - -class Voice(ABCRule[MessageUpdate]): - async def check(self, m: MessageUpdate, _) -> bool: - return bool(m.voice) - -class Audio(ABCRule[MessageUpdate]): - async def check(self, m: MessageUpdate, _) -> bool: - return bool(m.audio) - - -class VideoNote(ABCRule[MessageUpdate]): - async def check(self, m: MessageUpdate, _) -> bool: - return bool(m.video_note) - - -class Document(ABCRule[MessageUpdate]): - """ - Checks if the message has voice media - """ - - def __init__(self, *allowed_exts) -> None: - self.allowed_exts = allowed_exts - if len(allowed_exts) == 0: - logger.warning("No allowed extensions were provided. Documents will be disabled") - - async def check(self, m: MessageUpdate, _) -> bool: - if m.document: - filename = m.document.file_name - ext = filename.split('.')[-1] - return ext in self.allowed_exts - - return False - - -class FromPrivate(ABCRule[MessageUpdate]): - """ - Checks if the message was sent in a channel. - """ - - async def check(self, m: MessageUpdate, _) -> bool: - return m.chat.type == ChatType.PRIVATE - - -class ChatAdmin(ABCRule[MessageUpdate]): - """ - Checks if the message was sent by a chat admin. - """ - - async def check(self, m: MessageUpdate, _) -> bool: - if m.chat.type in (ChatType.PRIVATE, ChatType.CHANNEL): - return True - - user: User = m.from_ - chat_admins = await m.ctx_api.get_chat_administrators(m.chat.id) - - is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) - is_admin = len(is_admin) > 0 - - return is_admin \ No newline at end of file From 1b3efcf0235a6e6128e3b2dadbdcb0ab2130274c Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sat, 15 Feb 2025 20:27:00 +0100 Subject: [PATCH 090/120] [wip] upgrade to latest PTB --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index b486605..b539209 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -wonda==0.7.9 +python-telegram-bot coloredlogs pillow watchdog From 643ca06777f6f052305a31d968e01184d4dd20d3 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sat, 15 Feb 2025 20:57:05 +0100 Subject: [PATCH 091/120] [wip] upgrade to latest PTB --- src/audiotools/speech.py | 4 ++-- src/transcriberbot/blueprints/voice.py | 30 +++++++++++++++----------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index 36ee686..ec284e5 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -85,7 +85,7 @@ def transcribe_wit(path, api_key): logger.debug("Response received: %s", text) if text is not None: - yield text + yield text, len(chunks) transcriber.close() @@ -122,7 +122,7 @@ def transcribe(path, api_key, backend="wit"): output = open(args.output_filename, mode="w") result = transcribe(args.input_filename, args.api_key) - for part in result: + for part, tot in result: output.write(part + "\n") output.flush() diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index c1449ee..26edc99 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -9,7 +9,7 @@ import time import telegram -from telegram import Update, Voice +from telegram import Update, Voice, InlineKeyboardMarkup, InlineKeyboardButton from telegram.constants import ChatType from telegram.ext import ContextTypes @@ -81,9 +81,10 @@ async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TY # TranscriberBot.get().start_thread(message_id) logger.debug("Starting thread %d", message_id) - # keyboard = InlineKeyboardMarkup( - # [[InlineKeyboardButton("Stop", callback_data=message_id)]] - # ) + keyboard = InlineKeyboardMarkup( + [[InlineKeyboardButton("Stop", callback_data=message_id)]] + ) + text = "" if is_group: @@ -91,23 +92,27 @@ async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TY success = False try: - for speech in audiotools.transcribe(path, api_key): + for idx, (speech, n_chunks) in enumerate(audiotools.transcribe(path, api_key)): + print(f"Transcription idx={idx} n_chunks={n_chunks}, text={speech}") + + suffix = f" [{idx+1}/{n_chunks}]" if idx < n_chunks - 1 else "" + retry = True retry_num = 0 - - print("SPEECH:", speech) - while retry: # and TranscriberBot.get().thread_running(message_id): + while retry: # Retry loop try: if len(text + " " + speech) >= 4000: text = R.get_string_resource("transcription_continues", lang) + "\n" message = await context.bot.send_message( - chat_id, text + speech + " [...]", - reply_to_message_id=message_id, parse_mode="html" + chat_id, f"{text} {speech} {suffix}", + reply_to_message_id=message_id, parse_mode="html", + reply_markup=keyboard ) else: await context.bot.edit_message_text( - text + " " + speech + " [...]", chat_id=chat_id, - message_id=message_id, parse_mode="html" + f"{text} {speech} {suffix}", chat_id=chat_id, + message_id=message_id, parse_mode="html", + reply_markup=keyboard ) text += " " + speech @@ -135,6 +140,7 @@ async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TY except Exception as e: logger.error("Could not transcribe audio") + raise e if not success: await context.bot.edit_message_text( From 6a14388bba8d79d9868986bb80bc2021748e40ae Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 00:07:51 +0100 Subject: [PATCH 092/120] debug print From a83a440120e36235a0cc308a674d52363ac66a6c Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 01:59:37 +0100 Subject: [PATCH 093/120] fix asyncio transcription --- config/app.json | 2 +- src/audiotools/speech.py | 205 ++++++++++++---------- src/main.py | 8 +- src/transcriberbot/blueprints/commands.py | 1 + src/transcriberbot/blueprints/voice.py | 76 +++++--- src/transcriberbot/bot.py | 14 +- 6 files changed, 172 insertions(+), 134 deletions(-) diff --git a/config/app.json b/config/app.json index a3e2b50..d20e1e4 100644 --- a/config/app.json +++ b/config/app.json @@ -59,6 +59,6 @@ }, "whisper": { - "api_endpoint": "http://192.168.5.2:8000" + "api_endpoint": "http://127.0.0.1:8000" } } diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index ec284e5..1f2630d 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -3,127 +3,138 @@ import traceback import os +import asyncio import requests +from functools import partial + import pydub from pydub import AudioSegment import config - +import textwrap logger = logging.getLogger("speech") class WitTranscriber: - speech_url = "https://api.wit.ai/speech" - - def __init__(self, api_key): - self.session = requests.Session() - self.session.headers.update( - { - "Authorization": "Bearer " + api_key, - "Accept": "application/vnd.wit.20180705+json", - "Content-Type": "audio/raw;encoding=signed-integer;bits=16;rate=8000;endian=little", - } - ) - - def transcribe(self, chunk): - text = None - try: - response = self.session.post( - self.speech_url, - params={"verbose": True}, - data=io.BufferedReader(io.BytesIO(chunk.raw_data)) - ) - logger.debug("Request response %s", response.text) - data = response.json() - if "_text" in data: - text = data["_text"] - elif "text" in data: # Changed in may 2020 - text = data["text"] - - except requests.exceptions.RequestException as e: - logger.error("Could not transcribe chunk: %s", traceback.format_exc()) - - return text - - def close(self): - self.session.close() - - -def __generate_chunks(segment, length=20000/1001, split_on_silence=False, noise_threshold=-36): - chunks = list() - if split_on_silence is False: - for i in range(0, len(segment), int(length*1000)): - chunks.append(segment[i:i+int(length*1000)]) - else: - while len(chunks) < 1: - logger.debug('split_on_silence (threshold %d)', noise_threshold) - chunks = pydub.silence.split_on_silence(segment, noise_threshold) - noise_threshold += 4 - - for i, chunk in enumerate(chunks): - if len(chunk) > int(length*1000): - subchunks = __generate_chunks(chunk, length, split_on_silence, noise_threshold+4) - chunks = chunks[:i-1] + subchunks + chunks[i+1:] + speech_url = "https://api.wit.ai/speech" + + def __init__(self, api_key): + self.session = requests.Session() + self.session.headers.update( + { + "Authorization": "Bearer " + api_key, + "Accept": "application/vnd.wit.20180705+json", + "Content-Type": "audio/raw;encoding=signed-integer;bits=16;rate=8000;endian=little", + } + ) + + async def transcribe(self, chunk): + text = None + try: + loop = asyncio.get_event_loop() + response = await loop.run_in_executor( + None, partial(self.session.post, + url=self.speech_url, + params={"verbose": True}, + data=io.BufferedReader(io.BytesIO(chunk.raw_data))) + ) + + logger.debug("Request response %s", response.text) + data = response.json() + if "_text" in data: + text = data["_text"] + elif "text" in data: # Changed in may 2020 + text = data["text"] + + except requests.exceptions.RequestException as e: + logger.error("Could not transcribe chunk: %s", traceback.format_exc()) + + return text + + def close(self): + self.session.close() + + +def __generate_chunks(segment, length=20000 / 1001, split_on_silence=False, noise_threshold=-36): + chunks = list() + if split_on_silence is False: + for i in range(0, len(segment), int(length * 1000)): + chunks.append(segment[i:i + int(length * 1000)]) + else: + while len(chunks) < 1: + logger.debug('split_on_silence (threshold %d)', noise_threshold) + chunks = pydub.silence.split_on_silence(segment, noise_threshold) + noise_threshold += 4 + + for i, chunk in enumerate(chunks): + if len(chunk) > int(length * 1000): + subchunks = __generate_chunks(chunk, length, split_on_silence, noise_threshold + 4) + chunks = chunks[:i - 1] + subchunks + chunks[i + 1:] + + return chunks - return chunks def __preprocess_audio(audio): - return audio.set_sample_width(2).set_channels(1).set_frame_rate(8000) + return audio.set_sample_width(2).set_channels(1).set_frame_rate(8000) + +async def transcribe_wit(path, api_key): + logger.info("Transcribing file %s", path) + audio = AudioSegment.from_file(path) -def transcribe_wit(path, api_key): - logger.info("Transcribing file %s", path) - audio = AudioSegment.from_file(path) + chunks = __generate_chunks(__preprocess_audio(audio)) + logger.debug("Got %d chunks", len(chunks)) - chunks = __generate_chunks(__preprocess_audio(audio)) - logger.debug("Got %d chunks", len(chunks)) + transcriber = WitTranscriber(api_key) + for i, chunk in enumerate(chunks): + logger.debug("Transcribing chunk %d", i) + text = await transcriber.transcribe(chunk) + logger.debug("Response received: %s", text) - transcriber = WitTranscriber(api_key) - for i, chunk in enumerate(chunks): - logger.debug("Transcribing chunk %d", i) - text = transcriber.transcribe(chunk) - logger.debug("Response received: %s", text) + if text is not None: + yield i, text, len(chunks) + transcriber.close() - if text is not None: - yield text, len(chunks) - transcriber.close() +async def transcribe_whisper(path): + resp = requests.get(f"{config.get_config_prop('app')['whisper']['api_endpoint']}/transcribe?file_id={path}") -def transcribe_whisper(path): - resp = requests.get(f"{config.get_config_prop('app')['whisper']['api_endpoint']}/transcribe?file_id={path}") - yield resp.text + # split the response into chunks of 4000 characters + chunks = textwrap.wrap(resp.text, 4000) + for idx, chunk in enumerate(chunks): + yield idx, chunk, len(chunks) def transcribe(path, api_key, backend="wit"): - if backend == "wit": - print("Transcribing with wit") - return transcribe_wit(path, api_key) + if backend == "wit": + print("Transcribing with wit") + return transcribe_wit(path, api_key) - elif backend == "whisper": - print("Transcribing with whisper") - return transcribe_whisper(os.path.basename(path)) + elif backend == "whisper": + print("Transcribing with whisper") + return transcribe_whisper(os.path.basename(path)) - raise ValueError("Unknown backend: %s" % backend) + raise ValueError("Unknown backend: %s" % backend) if __name__ == "__main__": - import argparse - import sys - - parser = argparse.ArgumentParser() - parser.add_argument("api_key") - parser.add_argument("input_filename") - parser.add_argument("output_filename") - args = parser.parse_args() - - if args.output_filename == "-": - output = sys.stdout - else: - output = open(args.output_filename, mode="w") - - result = transcribe(args.input_filename, args.api_key) - for part, tot in result: - output.write(part + "\n") - output.flush() - - output.close() + import argparse + import sys + + parser = argparse.ArgumentParser() + parser.add_argument("api_key") + parser.add_argument("input_filename") + parser.add_argument("output_filename") + args = parser.parse_args() + + if args.output_filename == "-": + output = sys.stdout + else: + output = open(args.output_filename, mode="w") + + result = transcribe(args.input_filename, args.api_key) + for part, tot in result: + output.write(part + "\n") + output.flush() + + output.close() diff --git a/src/main.py b/src/main.py index 718323a..50c606a 100644 --- a/src/main.py +++ b/src/main.py @@ -4,18 +4,18 @@ import database import antiflood import transcriberbot.bot -import transcriberbot.multiprocessing +# import transcriberbot.multiprocessing def main(): coloredlogs.install( - level='INFO', + level='WARNING', fmt='%(asctime)s - %(name)s - %(levelname)s - %(filename)s [%(funcName)s:%(lineno)d] - %(message)s' ) config.init('../config') - transcriberbot.multiprocessing.init() - print("VOICE POOL:", transcriberbot.multiprocessing.voice_pool()) + # transcriberbot.multiprocessing.init() + # print("VOICE POOL:", transcriberbot.multiprocessing.voice_pool()) resources.init("../values") antiflood.init() diff --git a/src/transcriberbot/blueprints/commands.py b/src/transcriberbot/blueprints/commands.py index 407e9d8..832537b 100644 --- a/src/transcriberbot/blueprints/commands.py +++ b/src/transcriberbot/blueprints/commands.py @@ -3,6 +3,7 @@ Date: 15/02/25 """ import logging +import asyncio from telegram import Update from telegram.ext import ContextTypes diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index 26edc99..518b059 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -6,7 +6,8 @@ import logging import os import traceback -import time +from asyncio import CancelledError +from concurrent.futures.process import ProcessPoolExecutor import telegram from telegram import Update, Voice, InlineKeyboardMarkup, InlineKeyboardButton @@ -21,15 +22,39 @@ logger = logging.getLogger(__name__) - async def voice_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: return - task = asyncio.get_event_loop().create_task( + # with ProcessPoolExecutor() as pool: + # task: asyncio.Task = asyncio.get_event_loop().run_in_executor( + # pool, process_media_voice, context, update.effective_message.voice, "voice" + # ) + + task: asyncio.Task = context.application.create_task( process_media_voice(update, context, update.effective_message.voice, "voice") ) + context.bot_data[update.effective_message.message_id] = task + print("TASK ID", update.effective_message.message_id) + print(context.bot_data) + + +async def stop_task(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + task_id = update.callback_query.data + task: asyncio.Task = context.bot_data.get(task_id) + print("CANCELLING TASK:", task_id, task) + print("CONTEXT BOT DATA", context.bot_data) + + if task is not None: + task.cancel() + await context.bot.edit_message_text( + update.message.text + " " + R.get_string_resource("transcription_stopped", TBDB.get_chat_lang(update.effective_chat.id)), + chat_id=update.effective_chat.id, message_id=task_id, parse_mode="html" + ) + else: + print("Task not found") + async def process_media_voice(update: Update, context: ContextTypes.DEFAULT_TYPE, media: Voice, name: str) -> None: chat_id = update.effective_chat.id file_size = media.file_size @@ -58,6 +83,7 @@ async def process_media_voice(update: Update, context: ContextTypes.DEFAULT_TYPE async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TYPE, path: str): chat_id = update.effective_chat.id + task_id = update.effective_message.message_id lang = TBDB.get_chat_lang(chat_id) is_group = update.effective_chat.type != ChatType.PRIVATE @@ -76,42 +102,38 @@ async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TY chat_id, R.get_string_resource("transcribing", lang), parse_mode="html", reply_to_message_id=update.effective_message.message_id ) - message_id = message.message_id - - # TranscriberBot.get().start_thread(message_id) - logger.debug("Starting thread %d", message_id) + logger.debug("Starting task %d", task_id) keyboard = InlineKeyboardMarkup( - [[InlineKeyboardButton("Stop", callback_data=message_id)]] + [[InlineKeyboardButton("Stop", callback_data=task_id)]] ) - text = "" if is_group: text = R.get_string_resource("transcription_text", lang) + "\n" success = False try: - for idx, (speech, n_chunks) in enumerate(audiotools.transcribe(path, api_key)): + async for idx, speech, n_chunks in audiotools.transcribe(path, api_key): print(f"Transcription idx={idx} n_chunks={n_chunks}, text={speech}") - suffix = f" [{idx+1}/{n_chunks}]" if idx < n_chunks - 1 else "" + suffix = f" [{idx + 1}/{n_chunks}]" if idx < n_chunks - 1 else "" retry = True retry_num = 0 - while retry: # Retry loop + while retry: # Retry loop try: if len(text + " " + speech) >= 4000: text = R.get_string_resource("transcription_continues", lang) + "\n" message = await context.bot.send_message( chat_id, f"{text} {speech} {suffix}", - reply_to_message_id=message_id, parse_mode="html", + reply_to_message_id=message.message_id, parse_mode="html", reply_markup=keyboard ) else: await context.bot.edit_message_text( f"{text} {speech} {suffix}", chat_id=chat_id, - message_id=message_id, parse_mode="html", + message_id=message.message_id, parse_mode="html", reply_markup=keyboard ) @@ -127,16 +149,21 @@ async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TY retry = False except telegram.error.RetryAfter as r: - logger.warning("Retrying after %d", r.retry_after) - time.sleep(r.retry_after) + logger.warning("Retrying after %d", r.retry_after) + await asyncio.sleep(r.retry_after) except telegram.error.TelegramError as te: - logger.error("Telegram error %s", traceback.format_exc()) - retry = False + logger.error("Telegram error %s", traceback.format_exc()) + retry = False + + except CancelledError as ce: + logger.error("Task cancelled") + raise ce except Exception as e: - logger.error("Exception %s", traceback.format_exc()) - retry = False + logger.error("Exception %s", traceback.format_exc()) + raise e + except Exception as e: logger.error("Could not transcribe audio") @@ -145,13 +172,6 @@ async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TY if not success: await context.bot.edit_message_text( R.get_string_resource("transcription_failed", lang), chat_id=chat_id, - message_id=message_id, parse_mode="html" + message_id=message.message_id, parse_mode="html" ) - # TranscriberBot.get().del_thread(message_id) - - - - - - diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index ad05bbc..f03e679 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -2,11 +2,12 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ +from telegram import Update import config import logging -from telegram.ext import MessageHandler, ApplicationBuilder, CommandHandler, ContextTypes +from telegram.ext import MessageHandler, ApplicationBuilder, CommandHandler, ContextTypes, CallbackQueryHandler from functools import partial from transcriberbot.blueprints import commands, messages, voice from transcriberbot.blueprints.commands import set_language @@ -16,11 +17,16 @@ def run(bot_token: str): - application = ApplicationBuilder().token(bot_token).build() + application = (ApplicationBuilder() + .token(bot_token) + .concurrent_updates(True) + .build()) logger = logging.getLogger(__name__) logging.info("Installing handlers") + application.add_handler(CallbackQueryHandler(voice.stop_task)) + application.add_handler(CommandHandler('start', commands.start, filters=ChatAdmin())) application.add_handler(CommandHandler('help', commands.start, filters=ChatAdmin())) application.add_handler(CommandHandler('lang', commands.lang, filters=ChatAdmin())) @@ -41,9 +47,9 @@ def run(bot_token: str): CommandHandler(language, partial(set_language, language=language), filters=ChatAdmin()) ) - application.add_handler(MessageHandler(VOICE, voice.voice_message)) + application.add_handler(MessageHandler(VOICE, voice.voice_message, block=False)) application.add_handler(MessageHandler(FromPrivate(), messages.private_message)) logger.info("Starting bot..") - application.run_polling() \ No newline at end of file + application.run_polling(allowed_updates=Update.ALL_TYPES) \ No newline at end of file From 0876cfed5e52c6eb35e5c3f5fed7dc4d2afd44dd Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 11:30:00 +0100 Subject: [PATCH 094/120] complete support for audio/video --- src/config/__init__.py | 14 +++ src/transcriberbot/blueprints/voice.py | 161 ++++++++++++++----------- src/transcriberbot/bot.py | 11 +- src/transcriberbot/filters/filters.py | 40 +++--- 4 files changed, 134 insertions(+), 92 deletions(-) diff --git a/src/config/__init__.py b/src/config/__init__.py index b0d9abc..c77bc54 100644 --- a/src/config/__init__.py +++ b/src/config/__init__.py @@ -48,3 +48,17 @@ def bot_token(): def get_language_list(): return get_config_prop("app")["languages"].keys() + + +def get_audio_extensions(): + return get_config_prop("app").get("audio_ext", []) + + +def get_video_extensions(): + return get_config_prop("app").get("video_ext", []) + + +def get_document_extensions(): + audio_ext = get_audio_extensions() + video_ext = get_video_extensions() + return audio_ext + video_ext diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index 518b059..b58f304 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -10,7 +10,7 @@ from concurrent.futures.process import ProcessPoolExecutor import telegram -from telegram import Update, Voice, InlineKeyboardMarkup, InlineKeyboardButton +from telegram import Update, Voice, InlineKeyboardMarkup, InlineKeyboardButton, VideoNote, Document from telegram.constants import ChatType from telegram.ext import ContextTypes @@ -26,36 +26,46 @@ async def voice_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> N if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: return - # with ProcessPoolExecutor() as pool: - # task: asyncio.Task = asyncio.get_event_loop().run_in_executor( - # pool, process_media_voice, context, update.effective_message.voice, "voice" - # ) + task = asyncio.create_task(process_media_voice(update, context, update.effective_message.voice, "voice")) + context.bot_data[update.effective_message.message_id] = task - task: asyncio.Task = context.application.create_task( - process_media_voice(update, context, update.effective_message.voice, "voice") - ) +async def audio_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: + return + + task = asyncio.create_task(process_media_voice(update, context, update.effective_message.audio, "audio")) + context.bot_data[update.effective_message.message_id] = task + + +async def video_note_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: + return + + task = asyncio.create_task(process_media_voice(update, context, update.effective_message.video_note, "video_note")) + context.bot_data[update.effective_message.message_id] = task + + +async def document_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: + return + + task = asyncio.create_task(process_media_voice(update, context, update.effective_message.document, "document")) context.bot_data[update.effective_message.message_id] = task - print("TASK ID", update.effective_message.message_id) - print(context.bot_data) async def stop_task(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: - task_id = update.callback_query.data + task_id = int(update.callback_query.data) task: asyncio.Task = context.bot_data.get(task_id) - print("CANCELLING TASK:", task_id, task) - print("CONTEXT BOT DATA", context.bot_data) if task is not None: task.cancel() - await context.bot.edit_message_text( - update.message.text + " " + R.get_string_resource("transcription_stopped", TBDB.get_chat_lang(update.effective_chat.id)), - chat_id=update.effective_chat.id, message_id=task_id, parse_mode="html" - ) else: print("Task not found") -async def process_media_voice(update: Update, context: ContextTypes.DEFAULT_TYPE, media: Voice, name: str) -> None: + +async def process_media_voice(update: Update, context: ContextTypes.DEFAULT_TYPE, media: [Voice | VideoNote | Document], + name: str) -> None: chat_id = update.effective_chat.id file_size = media.file_size max_size = config.get_config_prop("app").get("max_media_voice_file_size", 20 * 1024 * 1024) @@ -75,7 +85,7 @@ async def process_media_voice(update: Update, context: ContextTypes.DEFAULT_TYPE try: await transcribe_audio_file(update, context, file_path) - except Exception as e: + except Exception: logger.error("Exception handling %s from %d: %s", name, chat_id, traceback.format_exc()) finally: os.remove(file_path) @@ -111,67 +121,80 @@ async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TY text = "" if is_group: text = R.get_string_resource("transcription_text", lang) + "\n" - success = False try: async for idx, speech, n_chunks in audiotools.transcribe(path, api_key): print(f"Transcription idx={idx} n_chunks={n_chunks}, text={speech}") - suffix = f" [{idx + 1}/{n_chunks}]" if idx < n_chunks - 1 else "" - - retry = True - retry_num = 0 - while retry: # Retry loop - try: - if len(text + " " + speech) >= 4000: - text = R.get_string_resource("transcription_continues", lang) + "\n" - message = await context.bot.send_message( - chat_id, f"{text} {speech} {suffix}", - reply_to_message_id=message.message_id, parse_mode="html", - reply_markup=keyboard - ) - else: - await context.bot.edit_message_text( - f"{text} {speech} {suffix}", chat_id=chat_id, - message_id=message.message_id, parse_mode="html", - reply_markup=keyboard - ) - - text += " " + speech - retry = False - success = True - - except telegram.error.TimedOut as e: - print(e) - logger.error("Timeout error %s", traceback.format_exc()) - retry_num += 1 - if retry_num >= 3: - retry = False - - except telegram.error.RetryAfter as r: - logger.warning("Retrying after %d", r.retry_after) - await asyncio.sleep(r.retry_after) - - except telegram.error.TelegramError as te: - logger.error("Telegram error %s", traceback.format_exc()) - retry = False - - except CancelledError as ce: - logger.error("Task cancelled") - raise ce - - except Exception as e: - logger.error("Exception %s", traceback.format_exc()) - raise e - + reply_markup = keyboard if idx < n_chunks - 1 else None + + if len(text + " " + speech) >= 4000: + text = R.get_string_resource("transcription_continues", lang) + "\n" + message = await context.bot.send_message( + chat_id, f"{text} {speech} {suffix}", + reply_to_message_id=message.message_id, parse_mode="html", + reply_markup=reply_markup + ) + else: + message = await context.bot.edit_message_text( + f"{text} {speech} {suffix}", chat_id=chat_id, + message_id=message.message_id, parse_mode="html", + reply_markup=reply_markup + ) + + text = f"{text} {speech}" + + # retry_num = 0 + # retry = True + # while retry: # Retry loop + # try: + # if len(text + " " + speech) >= 4000: + # text = R.get_string_resource("transcription_continues", lang) + "\n" + # message = await context.bot.send_message( + # chat_id, f"{text} {speech} {suffix}", + # reply_to_message_id=message.message_id, parse_mode="html", + # reply_markup=keyboard + # ) + # else: + # message = await context.bot.edit_message_text( + # f"{text} {speech} {suffix}", chat_id=chat_id, + # message_id=message.message_id, parse_mode="html", + # reply_markup=keyboard + # ) + # + # text += " " + speech + # retry = False + # + # except telegram.error.TimedOut as e: + # print(e) + # logger.error("Timeout error %s", traceback.format_exc()) + # retry_num += 1 + # if retry_num >= 3: + # retry = False + # + # except telegram.error.RetryAfter as r: + # logger.warning("Retrying after %d", r.retry_after) + # await asyncio.sleep(r.retry_after) + # + # except telegram.error.TelegramError: + # logger.error("Telegram error %s", traceback.format_exc()) + # retry = False + + + except CancelledError: + print("Task cancelled") + await context.bot.edit_message_text( + message.text + " " + R.get_string_resource("transcription_stopped", lang), chat_id=chat_id, + message_id=message.message_id, parse_mode="html" + ) + return except Exception as e: logger.error("Could not transcribe audio") - raise e - if not success: await context.bot.edit_message_text( R.get_string_resource("transcription_failed", lang), chat_id=chat_id, message_id=message.message_id, parse_mode="html" ) + raise e diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index f03e679..d106560 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -12,8 +12,8 @@ from transcriberbot.blueprints import commands, messages, voice from transcriberbot.blueprints.commands import set_language -from telegram.ext.filters import VOICE -from transcriberbot.filters import ChatAdmin, FromPrivate +from telegram.ext.filters import VOICE, VIDEO_NOTE, AUDIO +from transcriberbot.filters import ChatAdmin, FromPrivate, AllowedDocument def run(bot_token: str): @@ -47,9 +47,12 @@ def run(bot_token: str): CommandHandler(language, partial(set_language, language=language), filters=ChatAdmin()) ) - application.add_handler(MessageHandler(VOICE, voice.voice_message, block=False)) + application.add_handler(MessageHandler(VOICE, voice.voice_message)) + application.add_handler(MessageHandler(AUDIO, voice.audio_message)) + application.add_handler(MessageHandler(VIDEO_NOTE, voice.video_note_message)) + application.add_handler(MessageHandler(AllowedDocument(config.get_document_extensions()), voice.document_message)) application.add_handler(MessageHandler(FromPrivate(), messages.private_message)) logger.info("Starting bot..") - application.run_polling(allowed_updates=Update.ALL_TYPES) \ No newline at end of file + application.run_polling(allowed_updates=Update.ALL_TYPES) diff --git a/src/transcriberbot/filters/filters.py b/src/transcriberbot/filters/filters.py index 2aa72b2..05efb34 100644 --- a/src/transcriberbot/filters/filters.py +++ b/src/transcriberbot/filters/filters.py @@ -11,7 +11,6 @@ logger = logging.getLogger(__name__) - # class Voice(ABCRule[MessageUpdate]): # async def check(self, m: MessageUpdate, _) -> bool: # return bool(m.voice) @@ -26,28 +25,30 @@ # return bool(m.video_note) # # -# class Document(ABCRule[MessageUpdate]): -# """ -# Checks if the message has voice media -# """ -# -# def __init__(self, *allowed_exts) -> None: -# self.allowed_exts = allowed_exts -# if len(allowed_exts) == 0: -# logger.warning("No allowed extensions were provided. Documents will be disabled") -# -# async def check(self, m: MessageUpdate, _) -> bool: -# if m.document: -# filename = m.document.file_name -# ext = filename.split('.')[-1] -# return ext in self.allowed_exts -# -# return False +class AllowedDocument(UpdateFilter): + """ + Checks if the message has document media with allowed extensions. + """ + + def __init__(self, allowed_exts) -> None: + super().__init__() + self.allowed_exts = allowed_exts + if len(allowed_exts) == 0: + logger.warning("No allowed extensions were provided. Documents will be disabled") + + def filter(self, update: Update) -> bool: + if update.effective_message.document: + filename = update.effective_message.document.file_name + ext = filename.split('.')[-1] + return ext in self.allowed_exts + return False + class FromPrivate(UpdateFilter): """ Checks if the message was sent in a private conversation. """ + def filter(self, update: Update) -> bool: return update.effective_chat.type == ChatType.PRIVATE @@ -56,6 +57,7 @@ class ChatAdmin(UpdateFilter): """ Checks if the message was sent by a chat admin. """ + async def filter(self, update: Update) -> bool: if update.effective_chat.type in (ChatType.PRIVATE, ChatType.CHANNEL): return True @@ -66,4 +68,4 @@ async def filter(self, update: Update) -> bool: is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) is_admin = len(is_admin) > 0 - return is_admin \ No newline at end of file + return is_admin From dc3c0b6298be0f0ea8e5bcc2dc98ab3dde4ce688 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 11:30:22 +0100 Subject: [PATCH 095/120] reformat code (PEP) --- src/antiflood/__init__.py | 2 +- src/antiflood/antiflood.py | 131 ++++---- src/audiotools/__init__.py | 2 +- src/audiotools/speech.py | 6 +- src/database/__init__.py | 9 +- src/database/db.py | 279 +++++++++--------- src/functional/__init__.py | 4 +- src/main.py | 2 + src/metaclass/__init__.py | 2 +- src/metaclass/singleton.py | 12 +- src/phototools/__init__.py | 2 +- src/phototools/ocr.py | 11 +- src/phototools/qr.py | 18 +- src/resources/__init__.py | 2 +- src/resources/loader.py | 89 +++--- src/tests/test_db.py | 50 ++-- src/transcriberbot/blueprints/__init__.py | 1 - src/transcriberbot/filters/__init__.py | 2 +- .../multiprocessing/__init__.py | 2 +- src/transcriberbot/multiprocessing/pools.py | 2 +- src/translator/__init__.py | 2 +- src/translator/translator.py | 62 ++-- 22 files changed, 352 insertions(+), 340 deletions(-) diff --git a/src/antiflood/__init__.py b/src/antiflood/__init__.py index f5065ae..429e8ea 100644 --- a/src/antiflood/__init__.py +++ b/src/antiflood/__init__.py @@ -2,4 +2,4 @@ from antiflood.antiflood import register_flood_warning_callback from antiflood.antiflood import register_flood_started_callback from antiflood.antiflood import register_flood_ended_callback -from antiflood.antiflood import init \ No newline at end of file +from antiflood.antiflood import init diff --git a/src/antiflood/antiflood.py b/src/antiflood/antiflood.py index 16604ef..b32256f 100644 --- a/src/antiflood/antiflood.py +++ b/src/antiflood/antiflood.py @@ -4,11 +4,11 @@ logger = logging.getLogger(__name__) -flood_ratio = 2 # messages/seconds +flood_ratio = 2 # messages/seconds max_flood_ratio = 10 time_threshold_warning = 5 # ratio > flood_ratio for {time_threshold_warning} seconds -time_threshold_flood = 10 # ratio > flood_ratio for {time_threshold_flood} seconds -timeout = 4 # flood ends after ratio < flood_ratio for {timeout} seconds +time_threshold_flood = 10 # ratio > flood_ratio for {time_threshold_flood} seconds +timeout = 4 # flood ends after ratio < flood_ratio for {timeout} seconds callback_flood_warning = None callback_flood_started = None @@ -20,74 +20,77 @@ # chat_id -> (level, ratio, msg_num, duration, last_update) stats = {} -def register_flood_warning_callback(callback): - global callback_flood_warning - callback_flood_warning = callback - -def register_flood_started_callback(callback): - global callback_flood_started - callback_flood_started = callback - -def register_flood_ended_callback(callback): - global callback_flood_ended - callback_flood_ended = callback - -def init(): - global flood_ratio, max_flood_ratio, time_threshold_warning, time_threshold_flood, timeout - flood_ratio = config.get_config_prop("app")["antiflood"]["flood_ratio"] - max_flood_ratio = config.get_config_prop("app")["antiflood"]["max_flood_ratio"] - time_threshold_warning = config.get_config_prop("app")["antiflood"]["time_threshold_warning"] - time_threshold_flood = config.get_config_prop("app")["antiflood"]["time_threshold_flood"] - timeout = config.get_config_prop("app")["antiflood"]["timeout"] - - logger.info("Ratio: %d", flood_ratio) - logger.info("Max flood ratio: %d", max_flood_ratio) - logger.info("Thr warning: %d", time_threshold_warning) - logger.info("Thr flood: %d", time_threshold_flood) - logger.info("Timeout: %d", timeout) -def on_chat_msg_received(chat_id): - global flood_ratio, time_threshold_warning, time_threshold_flood, timeout - global callback_flood_warning, callback_flood_started, callback_flood_ended - - curr_time = time.time() - - if chat_id not in stats: - stats[chat_id] = [LEVEL_NORMAL, 1.0, 1, 0.0, curr_time] +def register_flood_warning_callback(callback): + global callback_flood_warning + callback_flood_warning = callback - else: - level, ratio, msg_num, duration, last_update = stats[chat_id] - updated_duration = duration + curr_time - last_update - msg_num += 1 - curr_ratio = msg_num / updated_duration - if curr_ratio < flood_ratio and updated_duration > timeout: - curr_ratio, updated_duration, msg_num = 0, 0, 0 - level = LEVEL_NORMAL - if callback_flood_ended: - callback_flood_ended(chat_id) +def register_flood_started_callback(callback): + global callback_flood_started + callback_flood_started = callback - elif updated_duration > 1 and curr_ratio > max_flood_ratio and level < LEVEL_FLOOD: - level = LEVEL_FLOOD - logger.warning("Flood ratio for chat %d is over the top", chat_id) - if callback_flood_started: - callback_flood_started(chat_id) - elif curr_ratio > flood_ratio: - if updated_duration >= time_threshold_flood and level < LEVEL_FLOOD: - logger.warning("Flood detected for chat %d", chat_id) - level = LEVEL_FLOOD - if callback_flood_started: - callback_flood_started(chat_id) +def register_flood_ended_callback(callback): + global callback_flood_ended + callback_flood_ended = callback - elif updated_duration >= time_threshold_warning and level < LEVEL_WARNING: - logger.info("Potential flood for chat %d", chat_id) - level = LEVEL_WARNING - if callback_flood_warning is not None: - callback_flood_warning(chat_id) - stats[chat_id] = (level, curr_ratio, msg_num, updated_duration, curr_time) +def init(): + global flood_ratio, max_flood_ratio, time_threshold_warning, time_threshold_flood, timeout + flood_ratio = config.get_config_prop("app")["antiflood"]["flood_ratio"] + max_flood_ratio = config.get_config_prop("app")["antiflood"]["max_flood_ratio"] + time_threshold_warning = config.get_config_prop("app")["antiflood"]["time_threshold_warning"] + time_threshold_flood = config.get_config_prop("app")["antiflood"]["time_threshold_flood"] + timeout = config.get_config_prop("app")["antiflood"]["timeout"] - logger.info("stats[{}]: {}".format(chat_id, stats[chat_id])) + logger.info("Ratio: %d", flood_ratio) + logger.info("Max flood ratio: %d", max_flood_ratio) + logger.info("Thr warning: %d", time_threshold_warning) + logger.info("Thr flood: %d", time_threshold_flood) + logger.info("Timeout: %d", timeout) +def on_chat_msg_received(chat_id): + global flood_ratio, time_threshold_warning, time_threshold_flood, timeout + global callback_flood_warning, callback_flood_started, callback_flood_ended + + curr_time = time.time() + + if chat_id not in stats: + stats[chat_id] = [LEVEL_NORMAL, 1.0, 1, 0.0, curr_time] + + else: + level, ratio, msg_num, duration, last_update = stats[chat_id] + updated_duration = duration + curr_time - last_update + msg_num += 1 + curr_ratio = msg_num / updated_duration + + if curr_ratio < flood_ratio and updated_duration > timeout: + curr_ratio, updated_duration, msg_num = 0, 0, 0 + level = LEVEL_NORMAL + if callback_flood_ended: + callback_flood_ended(chat_id) + + elif updated_duration > 1 and curr_ratio > max_flood_ratio and level < LEVEL_FLOOD: + level = LEVEL_FLOOD + logger.warning("Flood ratio for chat %d is over the top", chat_id) + if callback_flood_started: + callback_flood_started(chat_id) + + elif curr_ratio > flood_ratio: + if updated_duration >= time_threshold_flood and level < LEVEL_FLOOD: + logger.warning("Flood detected for chat %d", chat_id) + level = LEVEL_FLOOD + if callback_flood_started: + callback_flood_started(chat_id) + + elif updated_duration >= time_threshold_warning and level < LEVEL_WARNING: + logger.info("Potential flood for chat %d", chat_id) + level = LEVEL_WARNING + if callback_flood_warning is not None: + callback_flood_warning(chat_id) + + stats[chat_id] = (level, curr_ratio, msg_num, updated_duration, curr_time) + + logger.info("stats[{}]: {}".format(chat_id, stats[chat_id])) diff --git a/src/audiotools/__init__.py b/src/audiotools/__init__.py index b63ff77..22aa887 100644 --- a/src/audiotools/__init__.py +++ b/src/audiotools/__init__.py @@ -1 +1 @@ -from audiotools.speech import transcribe \ No newline at end of file +from audiotools.speech import transcribe diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index 1f2630d..d6995d9 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -34,9 +34,9 @@ async def transcribe(self, chunk): loop = asyncio.get_event_loop() response = await loop.run_in_executor( None, partial(self.session.post, - url=self.speech_url, - params={"verbose": True}, - data=io.BufferedReader(io.BytesIO(chunk.raw_data))) + url=self.speech_url, + params={"verbose": True}, + data=io.BufferedReader(io.BytesIO(chunk.raw_data))) ) logger.debug("Request response %s", response.text) diff --git a/src/database/__init__.py b/src/database/__init__.py index 526f15f..d882f98 100644 --- a/src/database/__init__.py +++ b/src/database/__init__.py @@ -16,9 +16,10 @@ """ + def init_schema(database): - with Database(database) as db: - db.execute("""CREATE TABLE IF NOT EXISTS chats ( + with Database(database) as db: + db.execute("""CREATE TABLE IF NOT EXISTS chats ( chat_id INTEGER PRIMARY KEY, lang VARCHAR(5) NOT NULL, voice_enabled INTEGER, @@ -28,10 +29,10 @@ def init_schema(database): ban INTEGER) """) - db.execute("""CREATE TABLE IF NOT EXISTS stats ( + db.execute("""CREATE TABLE IF NOT EXISTS stats ( month_year INTEGER PRIMARY KEY, audio_num INTEGER, min_tot_audio INTEGER, min_transcribed_audio INTEGER, num_pictures INTEGER) - """) \ No newline at end of file + """) diff --git a/src/database/db.py b/src/database/db.py index 4a92579..20e5964 100644 --- a/src/database/db.py +++ b/src/database/db.py @@ -6,158 +6,153 @@ logger = logging.getLogger(__name__) + class Database(): - __instance = None + __instance = None - def __init__(self, database): - self.database = database + def __init__(self, database): + self.database = database - def __connect(self): - self.__connection = sqlite3.connect(self.database) - self.__cursor = self.__connection.cursor() + def __connect(self): + self.__connection = sqlite3.connect(self.database) + self.__cursor = self.__connection.cursor() - def __close(self): - self.__connection.commit() - self.__connection.close() + def __close(self): + self.__connection.commit() + self.__connection.close() - def __enter__(self): - logger.debug("__enter__") - self.__connect() - return self + def __enter__(self): + logger.debug("__enter__") + self.__connect() + return self - def assoc(self): - self.__connection.row_factory = sqlite3.Row - self.__cursor = self.__connection.cursor() + def assoc(self): + self.__connection.row_factory = sqlite3.Row + self.__cursor = self.__connection.cursor() + def __exit__(self, exc_type, exc_value, exc_traceback): + logger.debug("__exit__") + self.__close() - def __exit__(self, exc_type, exc_value, exc_traceback): - logger.debug("__exit__") - self.__close() + if exc_type: + logger.error("exc_type: {}".format(exc_type)) + logger.error("exc_value: {}".format(exc_value)) + logger.error("exc_traceback: {}".format(exc_traceback)) + logger.error(traceback.format_exc()) - if exc_type: - logger.error("exc_type: {}".format(exc_type)) - logger.error("exc_value: {}".format(exc_value)) - logger.error("exc_traceback: {}".format(exc_traceback)) - logger.error(traceback.format_exc()) + return True - return True + def execute(self, query, *args): + res = self.__cursor.execute(query, *args) + return self.__cursor - def execute(self, query, *args): - res = self.__cursor.execute(query, *args) - return self.__cursor class TBDB(): - @staticmethod - def _get_db(): - return Database(config.get_config_prop("app")["database"]) - - - @staticmethod - def create_default_chat_entry(chat_id, lang): - with TBDB._get_db() as db: - db.execute( - "INSERT INTO chats(chat_id, lang, voice_enabled, photos_enabled, qr_enabled, active, ban) VALUES(?,?,?,?,?,?,?)", - (chat_id, lang, 1, 0, 0, 1, 0) - ) - - @staticmethod - def get_chat_entry(chat_id): - with TBDB._get_db() as db: - db.assoc() - cursor = db.execute("SELECT * FROM chats WHERE chat_id='{0}'".format(chat_id)) - return cursor.fetchone() - - @staticmethod - def get_chats(): - with TBDB._get_db() as db: - db.assoc() - cursor = db.execute("SELECT * FROM chats") - return [dict(x) for x in cursor.fetchall()] - - @staticmethod - def get_chat_lang(chat_id): - chat_record = TBDB.get_chat_entry(chat_id) - if not chat_record: - logger.debug("Record for chat {} not found, creating one.".format(chat_id)) - TBDB.create_default_chat_entry(chat_id, "en-US") - - with TBDB._get_db() as db: - cursor = db.execute("SELECT lang FROM chats WHERE chat_id='{0}'".format(chat_id)) - return cursor.fetchone()[0] - - @staticmethod - def set_chat_lang(chat_id, lang): - with TBDB._get_db() as db: - db.execute("UPDATE chats SET lang='{0}' WHERE chat_id='{1}'".format(lang, chat_id)) - - - @staticmethod - def get_chat_voice_enabled(chat_id): - with TBDB._get_db() as db: - c = db.execute("SELECT voice_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) - return c.fetchone()[0] - - @staticmethod - def set_chat_voice_enabled(chat_id, voice_enabled): - with TBDB._get_db() as db: - db.execute("UPDATE chats SET voice_enabled='{0}' WHERE chat_id='{1}'".format(voice_enabled, chat_id)) - - - @staticmethod - def get_chat_photos_enabled(chat_id): - with TBDB._get_db() as db: - c = db.execute("SELECT photos_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) - return c.fetchone()[0] - - @staticmethod - def set_chat_photos_enabled(chat_id, photos_enabled): - with TBDB._get_db() as db: - db.execute("UPDATE chats SET photos_enabled='{0}' WHERE chat_id='{1}'".format(photos_enabled, chat_id)) - - - @staticmethod - def get_chat_qr_enabled(chat_id): - with TBDB._get_db() as db: - c = db.execute("SELECT qr_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) - return c.fetchone()[0] - - @staticmethod - def set_chat_qr_enabled(chat_id, qr_enabled): - with TBDB._get_db() as db: - db.execute("UPDATE chats SET qr_enabled='{0}' WHERE chat_id='{1}'".format(qr_enabled, chat_id)) - - @staticmethod - def get_chat_active(chat_id): - with TBDB._get_db() as db: - c = db.execute("SELECT active FROM chats WHERE chat_id='{0}'".format(chat_id)) - return c.fetchone()[0] - - @staticmethod - def set_chat_active(chat_id, active): - with TBDB._get_db() as db: - db.execute("UPDATE chats SET active='{0}' WHERE chat_id='{1}'".format(active, chat_id)) - - @staticmethod - def get_chat_ban(chat_id): - with TBDB._get_db() as db: - c = db.execute("SELECT ban FROM chats WHERE chat_id='{0}'".format(chat_id)) - return c.fetchone()[0] - - @staticmethod - def set_chat_ban(chat_id, ban): - with TBDB._get_db() as db: - db.execute("UPDATE chats SET ban='{0}' WHERE chat_id='{1}'".format(ban, chat_id)) - - - @staticmethod - def get_chats_num(): - with TBDB._get_db() as db: - c = db.execute("SELECT count(*) FROM chats") - return int(c.fetchone()[0]) - - @staticmethod - def get_active_chats_num(): - with TBDB._get_db() as db: - c = db.execute("SELECT count(*) FROM chats where active=1") - return int(c.fetchone()[0]) - + @staticmethod + def _get_db(): + return Database(config.get_config_prop("app")["database"]) + + @staticmethod + def create_default_chat_entry(chat_id, lang): + with TBDB._get_db() as db: + db.execute( + "INSERT INTO chats(chat_id, lang, voice_enabled, photos_enabled, qr_enabled, active, ban) VALUES(?,?,?,?,?,?,?)", + (chat_id, lang, 1, 0, 0, 1, 0) + ) + + @staticmethod + def get_chat_entry(chat_id): + with TBDB._get_db() as db: + db.assoc() + cursor = db.execute("SELECT * FROM chats WHERE chat_id='{0}'".format(chat_id)) + return cursor.fetchone() + + @staticmethod + def get_chats(): + with TBDB._get_db() as db: + db.assoc() + cursor = db.execute("SELECT * FROM chats") + return [dict(x) for x in cursor.fetchall()] + + @staticmethod + def get_chat_lang(chat_id): + chat_record = TBDB.get_chat_entry(chat_id) + if not chat_record: + logger.debug("Record for chat {} not found, creating one.".format(chat_id)) + TBDB.create_default_chat_entry(chat_id, "en-US") + + with TBDB._get_db() as db: + cursor = db.execute("SELECT lang FROM chats WHERE chat_id='{0}'".format(chat_id)) + return cursor.fetchone()[0] + + @staticmethod + def set_chat_lang(chat_id, lang): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET lang='{0}' WHERE chat_id='{1}'".format(lang, chat_id)) + + @staticmethod + def get_chat_voice_enabled(chat_id): + with TBDB._get_db() as db: + c = db.execute("SELECT voice_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + + @staticmethod + def set_chat_voice_enabled(chat_id, voice_enabled): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET voice_enabled='{0}' WHERE chat_id='{1}'".format(voice_enabled, chat_id)) + + @staticmethod + def get_chat_photos_enabled(chat_id): + with TBDB._get_db() as db: + c = db.execute("SELECT photos_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + + @staticmethod + def set_chat_photos_enabled(chat_id, photos_enabled): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET photos_enabled='{0}' WHERE chat_id='{1}'".format(photos_enabled, chat_id)) + + @staticmethod + def get_chat_qr_enabled(chat_id): + with TBDB._get_db() as db: + c = db.execute("SELECT qr_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + + @staticmethod + def set_chat_qr_enabled(chat_id, qr_enabled): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET qr_enabled='{0}' WHERE chat_id='{1}'".format(qr_enabled, chat_id)) + + @staticmethod + def get_chat_active(chat_id): + with TBDB._get_db() as db: + c = db.execute("SELECT active FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + + @staticmethod + def set_chat_active(chat_id, active): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET active='{0}' WHERE chat_id='{1}'".format(active, chat_id)) + + @staticmethod + def get_chat_ban(chat_id): + with TBDB._get_db() as db: + c = db.execute("SELECT ban FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + + @staticmethod + def set_chat_ban(chat_id, ban): + with TBDB._get_db() as db: + db.execute("UPDATE chats SET ban='{0}' WHERE chat_id='{1}'".format(ban, chat_id)) + + @staticmethod + def get_chats_num(): + with TBDB._get_db() as db: + c = db.execute("SELECT count(*) FROM chats") + return int(c.fetchone()[0]) + + @staticmethod + def get_active_chats_num(): + with TBDB._get_db() as db: + c = db.execute("SELECT count(*) FROM chats where active=1") + return int(c.fetchone()[0]) diff --git a/src/functional/__init__.py b/src/functional/__init__.py index e1a5fde..6a686cc 100644 --- a/src/functional/__init__.py +++ b/src/functional/__init__.py @@ -1,3 +1,3 @@ def apply_fn(list, fn): - for item in list: - fn(item) \ No newline at end of file + for item in list: + fn(item) diff --git a/src/main.py b/src/main.py index 50c606a..d22a324 100644 --- a/src/main.py +++ b/src/main.py @@ -4,6 +4,8 @@ import database import antiflood import transcriberbot.bot + + # import transcriberbot.multiprocessing diff --git a/src/metaclass/__init__.py b/src/metaclass/__init__.py index 81c9a72..657df0c 100644 --- a/src/metaclass/__init__.py +++ b/src/metaclass/__init__.py @@ -1 +1 @@ -from metaclass.singleton import Singleton \ No newline at end of file +from metaclass.singleton import Singleton diff --git a/src/metaclass/singleton.py b/src/metaclass/singleton.py index d199fb8..162eb15 100644 --- a/src/metaclass/singleton.py +++ b/src/metaclass/singleton.py @@ -1,8 +1,8 @@ class Singleton(type): - _instances = {} + _instances = {} - def __call__(cls, *args, **kwargs): - k = (cls, args) - if k not in cls._instances: - cls._instances[k] = super(Singleton, cls).__call__(*args, **kwargs) - return cls._instances[k] \ No newline at end of file + def __call__(cls, *args, **kwargs): + k = (cls, args) + if k not in cls._instances: + cls._instances[k] = super(Singleton, cls).__call__(*args, **kwargs) + return cls._instances[k] diff --git a/src/phototools/__init__.py b/src/phototools/__init__.py index 3fe0f0d..6b2f26f 100644 --- a/src/phototools/__init__.py +++ b/src/phototools/__init__.py @@ -1,2 +1,2 @@ from phototools.ocr import image_ocr -from phototools.qr import read_qr \ No newline at end of file +from phototools.qr import read_qr diff --git a/src/phototools/ocr.py b/src/phototools/ocr.py index c682ac7..e6c248f 100644 --- a/src/phototools/ocr.py +++ b/src/phototools/ocr.py @@ -4,11 +4,12 @@ logger = logging.getLogger(__name__) + def image_ocr(path, lang): - logger.info("opening %s", path) + logger.info("opening %s", path) - with PyTessBaseAPI() as api: - api.SetImageFile(path) - text = api.GetUTF8Text().strip() + with PyTessBaseAPI() as api: + api.SetImageFile(path) + text = api.GetUTF8Text().strip() - return text \ No newline at end of file + return text diff --git a/src/phototools/qr.py b/src/phototools/qr.py index 5c1e8a3..b4f4c7f 100644 --- a/src/phototools/qr.py +++ b/src/phototools/qr.py @@ -4,15 +4,15 @@ logger = logging.getLogger(__name__) -def read_qr(path, lang): - logger.info("opening %s", path) - with open(path, 'rb') as f: - image = Image.open(f) - image.load() - qr = zbarlight.scan_codes('qrcode', image) - if qr is not None: - qr = qr[0].decode("utf-8") +def read_qr(path, lang): + logger.info("opening %s", path) - return qr + with open(path, 'rb') as f: + image = Image.open(f) + image.load() + qr = zbarlight.scan_codes('qrcode', image) + if qr is not None: + qr = qr[0].decode("utf-8") + return qr diff --git a/src/resources/__init__.py b/src/resources/__init__.py index 98505c5..4aab8cd 100644 --- a/src/resources/__init__.py +++ b/src/resources/__init__.py @@ -1 +1 @@ -from resources.loader import init, get_string_resource, iso639_2_to_639_1 \ No newline at end of file +from resources.loader import init, get_string_resource, iso639_2_to_639_1 diff --git a/src/resources/loader.py b/src/resources/loader.py index cb600ef..c2534c9 100644 --- a/src/resources/loader.py +++ b/src/resources/loader.py @@ -11,65 +11,72 @@ strings_r = {} __resources_directory = None + class EventHandler(FileSystemEventHandler): - @staticmethod - def on_any_event(event): - if event.event_type == "modified" or event.event_type == "created": - logger.info("Reloading resource folder") - load_config() + @staticmethod + def on_any_event(event): + if event.event_type == "modified" or event.event_type == "created": + logger.info("Reloading resource folder") + load_config() + def install_observer(): - handler = EventHandler() - observer = Observer() - observer.schedule(handler, __resources_directory) - observer.start() + handler = EventHandler() + observer = Observer() + observer.schedule(handler, __resources_directory) + observer.start() + def _load_xml_resouce(path): - logger.info("Loading resource %s", path) + logger.info("Loading resource %s", path) + + e = ElementTree.parse(path).getroot() + lang = e.get('lang') + if lang not in strings_r: + strings_r[lang] = {} - e = ElementTree.parse(path).getroot() - lang = e.get('lang') - if lang not in strings_r: - strings_r[lang] = {} + replacements = (('{b}', ''), ('{/b}', ''), + ('{i}', ''), ('{/i}', ''), + ('{code}', ''), ('{/code}', '')) - replacements = (('{b}', ''), ('{/b}', ''), - ('{i}', ''), ('{/i}', ''), - ('{code}', ''), ('{/code}', '')) + for string in e.findall('string'): + if string.text is None: + continue - for string in e.findall('string'): - if string.text is None: - continue + value = functools.reduce(lambda s, kv: s.replace(*kv), replacements, string.text) + value = value.strip() + strings_r[lang][string.get('name')] = value + logger.debug("Loaded string resource [%s] (%s): %s", string.get('name'), lang, value) - value = functools.reduce(lambda s, kv: s.replace(*kv), replacements, string.text) - value = value.strip() - strings_r[lang][string.get('name')] = value - logger.debug("Loaded string resource [%s] (%s): %s", string.get('name'), lang, value) def load_config(): - files = glob.glob(os.path.join(__resources_directory, "strings*.xml")) - functional.apply_fn(files, _load_xml_resouce) + files = glob.glob(os.path.join(__resources_directory, "strings*.xml")) + functional.apply_fn(files, _load_xml_resouce) + def init(values_folder): - global __resources_directory - __resources_directory = values_folder + global __resources_directory + __resources_directory = values_folder + + load_config() + install_observer() - load_config() - install_observer() def iso639_2_to_639_1(lang): - # Convert ISO 639-2 to 639-1 based on available translations (i.e it -> it-IT) - return next(iter(list(filter(lambda s: s.startswith(lang), strings_r.keys()))), "en-US") + # Convert ISO 639-2 to 639-1 based on available translations (i.e it -> it-IT) + return next(iter(list(filter(lambda s: s.startswith(lang), strings_r.keys()))), "en-US") + def get_string_resource(id, lang=None): - global strings_r + global strings_r - if lang is not None and len(lang) < 5: - lang = iso639_2_to_639_1(lang) + if lang is not None and len(lang) < 5: + lang = iso639_2_to_639_1(lang) - rr = None - if lang in strings_r and id in strings_r[lang]: - rr = strings_r[lang][id] - elif id in strings_r['default']: - rr = strings_r['default'][id] + rr = None + if lang in strings_r and id in strings_r[lang]: + rr = strings_r[lang][id] + elif id in strings_r['default']: + rr = strings_r['default'][id] - return rr + return rr diff --git a/src/tests/test_db.py b/src/tests/test_db.py index fcf2bb4..461aa2d 100644 --- a/src/tests/test_db.py +++ b/src/tests/test_db.py @@ -1,35 +1,39 @@ import sys, os + sys.path.append(os.path.abspath(os.path.join('.', 'src'))) import config import database from database import TBDB + def setup_function(function): - config.init(os.path.abspath('config')) - config.get_config_prop("app")["database"] = "tmp.db" - database.init_schema(config.get_config_prop("app")["database"]) + config.init(os.path.abspath('config')) + config.get_config_prop("app")["database"] = "tmp.db" + database.init_schema(config.get_config_prop("app")["database"]) + def teardown_function(function): - os.remove(config.get_config_prop("app")["database"]) + os.remove(config.get_config_prop("app")["database"]) + def test_db(): - id = 1234 - - TBDB.create_default_chat_entry(id, 'en-US') - assert TBDB.get_chat_lang(id) == 'en-US' - assert TBDB.get_chat_active(id) == 1 - - TBDB.set_chat_lang(id, 'lang') - TBDB.set_chat_voice_enabled(id, 2) - TBDB.set_chat_photos_enabled(id, 1) - TBDB.set_chat_qr_enabled(id, 1) - TBDB.set_chat_active(id, 0) - TBDB.set_chat_ban(id, 1) - - assert TBDB.get_chat_lang(id) == 'lang' - assert TBDB.get_chat_voice_enabled(id) == 2 - assert TBDB.get_chat_photos_enabled(id) == 1 - assert TBDB.get_chat_qr_enabled(id) == 1 - assert TBDB.get_chat_active(id) == 0 - assert TBDB.get_chat_ban(id) == 1 \ No newline at end of file + id = 1234 + + TBDB.create_default_chat_entry(id, 'en-US') + assert TBDB.get_chat_lang(id) == 'en-US' + assert TBDB.get_chat_active(id) == 1 + + TBDB.set_chat_lang(id, 'lang') + TBDB.set_chat_voice_enabled(id, 2) + TBDB.set_chat_photos_enabled(id, 1) + TBDB.set_chat_qr_enabled(id, 1) + TBDB.set_chat_active(id, 0) + TBDB.set_chat_ban(id, 1) + + assert TBDB.get_chat_lang(id) == 'lang' + assert TBDB.get_chat_voice_enabled(id) == 2 + assert TBDB.get_chat_photos_enabled(id) == 1 + assert TBDB.get_chat_qr_enabled(id) == 1 + assert TBDB.get_chat_active(id) == 0 + assert TBDB.get_chat_ban(id) == 1 diff --git a/src/transcriberbot/blueprints/__init__.py b/src/transcriberbot/blueprints/__init__.py index 43a25eb..32bacb4 100644 --- a/src/transcriberbot/blueprints/__init__.py +++ b/src/transcriberbot/blueprints/__init__.py @@ -3,4 +3,3 @@ Date: 15/02/25 """ from . import commands, messages, voice - diff --git a/src/transcriberbot/filters/__init__.py b/src/transcriberbot/filters/__init__.py index c3dc5eb..4d5e935 100644 --- a/src/transcriberbot/filters/__init__.py +++ b/src/transcriberbot/filters/__init__.py @@ -2,4 +2,4 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ -from .filters import * \ No newline at end of file +from .filters import * diff --git a/src/transcriberbot/multiprocessing/__init__.py b/src/transcriberbot/multiprocessing/__init__.py index f11af0d..616f1a1 100644 --- a/src/transcriberbot/multiprocessing/__init__.py +++ b/src/transcriberbot/multiprocessing/__init__.py @@ -2,4 +2,4 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ -from .pools import voice_pool, init \ No newline at end of file +from .pools import voice_pool, init diff --git a/src/transcriberbot/multiprocessing/pools.py b/src/transcriberbot/multiprocessing/pools.py index eab432c..0af1db9 100644 --- a/src/transcriberbot/multiprocessing/pools.py +++ b/src/transcriberbot/multiprocessing/pools.py @@ -31,4 +31,4 @@ def init(): def voice_pool(): global voice_thread_pool - return voice_thread_pool \ No newline at end of file + return voice_thread_pool diff --git a/src/translator/__init__.py b/src/translator/__init__.py index 114bcb2..b8e58e5 100644 --- a/src/translator/__init__.py +++ b/src/translator/__init__.py @@ -1 +1 @@ -from translator.translator import detect_language, translate \ No newline at end of file +from translator.translator import detect_language, translate diff --git a/src/translator/translator.py b/src/translator/translator.py index b668e85..1a75d4f 100644 --- a/src/translator/translator.py +++ b/src/translator/translator.py @@ -6,39 +6,39 @@ def detect_language(text): - global yandex_detect_url + global yandex_detect_url - r = requests.post( - yandex_detect_url.format(config.get_config_prop("yandex")["translate_key"]), - data={'text': text} - ) - res = r.json() + r = requests.post( + yandex_detect_url.format(config.get_config_prop("yandex")["translate_key"]), + data={'text': text} + ) + res = r.json() - if 'lang' in res: - return res['lang'] - else: - return None + if 'lang' in res: + return res['lang'] + else: + return None def translate(source, target, text): - return "Translation service currently unavailable." - global yandex_translate_url - - autodetect = detect_language(text) - - if autodetect is not None: - source = autodetect - print("Autodetected language: {0}".format(autodetect)) - - lang = source + "-" + target - print(lang) - - r = requests.post( - yandex_translate_url.format(config.get_config_prop("yandex")["translate_key"]), - data={'lang': lang, 'text': text} - ) - - print(r) - res = r.json() - print(res) - return str(res['text'][0]) + "\n\nPowered by Yandex.Translate http://translate.yandex.com" + return "Translation service currently unavailable." + global yandex_translate_url + + autodetect = detect_language(text) + + if autodetect is not None: + source = autodetect + print("Autodetected language: {0}".format(autodetect)) + + lang = source + "-" + target + print(lang) + + r = requests.post( + yandex_translate_url.format(config.get_config_prop("yandex")["translate_key"]), + data={'lang': lang, 'text': text} + ) + + print(r) + res = r.json() + print(res) + return str(res['text'][0]) + "\n\nPowered by Yandex.Translate http://translate.yandex.com" From 81c84346b4007c4ce5a612e52ec5d2a31b3c36f6 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 14:31:56 +0100 Subject: [PATCH 096/120] add logging & chat member handler --- config/app.json | 4 ++ src/config/__init__.py | 6 +++ src/database/__init__.py | 34 ++++++------- src/main.py | 20 ++++---- src/transcriberbot/blueprints/__init__.py | 2 +- .../blueprints/chat_handlers.py | 25 ++++++++++ src/transcriberbot/blueprints/commands.py | 48 +++++++++++++++++-- src/transcriberbot/bot.py | 25 ++++++---- src/transcriberbot/filters/filters.py | 39 +++++++-------- 9 files changed, 145 insertions(+), 58 deletions(-) create mode 100644 src/transcriberbot/blueprints/chat_handlers.py diff --git a/config/app.json b/config/app.json index d20e1e4..65422d9 100644 --- a/config/app.json +++ b/config/app.json @@ -60,5 +60,9 @@ "whisper": { "api_endpoint": "http://127.0.0.1:8000" + }, + + "logging": { + "level": "APP" } } diff --git a/src/config/__init__.py b/src/config/__init__.py index c77bc54..9986c2a 100644 --- a/src/config/__init__.py +++ b/src/config/__init__.py @@ -4,6 +4,8 @@ import logging import pprint +APP_LOG = 25 + logger = logging.getLogger(__name__) __configs = {} @@ -62,3 +64,7 @@ def get_document_extensions(): audio_ext = get_audio_extensions() video_ext = get_video_extensions() return audio_ext + video_ext + + +def get_bot_admins(): + return [int(id) for id in get_config_prop("telegram")["admins"]] diff --git a/src/database/__init__.py b/src/database/__init__.py index d882f98..7a23c2d 100644 --- a/src/database/__init__.py +++ b/src/database/__init__.py @@ -19,20 +19,22 @@ def init_schema(database): with Database(database) as db: - db.execute("""CREATE TABLE IF NOT EXISTS chats ( - chat_id INTEGER PRIMARY KEY, - lang VARCHAR(5) NOT NULL, - voice_enabled INTEGER, - photos_enabled INTEGER, - qr_enabled INTEGER, - active INTEGER, - ban INTEGER) - """) + db.execute( + "CREATE TABLE IF NOT EXISTS chats (" + "chat_id INTEGER PRIMARY KEY, " + "lang VARCHAR(5) NOT NULL, " + "voice_enabled INTEGER," + "photos_enabled INTEGER," + "qr_enabled INTEGER," + "active INTEGER," + "ban INTEGER)" + ) - db.execute("""CREATE TABLE IF NOT EXISTS stats ( - month_year INTEGER PRIMARY KEY, - audio_num INTEGER, - min_tot_audio INTEGER, - min_transcribed_audio INTEGER, - num_pictures INTEGER) - """) + db.execute( + "CREATE TABLE IF NOT EXISTS stats (" + "month_year INTEGER PRIMARY KEY," + "audio_num INTEGER, " + "min_tot_audio INTEGER," + "min_transcribed_audio INTEGER," + "num_pictures INTEGER)" + ) diff --git a/src/main.py b/src/main.py index d22a324..30847f4 100644 --- a/src/main.py +++ b/src/main.py @@ -1,4 +1,5 @@ -import coloredlogs +import logging + import config import resources import database @@ -6,18 +7,17 @@ import transcriberbot.bot -# import transcriberbot.multiprocessing +def main(): + config.init('../config') + logging.addLevelName(config.APP_LOG, "APP") -def main(): - coloredlogs.install( - level='WARNING', - fmt='%(asctime)s - %(name)s - %(levelname)s - %(filename)s [%(funcName)s:%(lineno)d] - %(message)s' + log_level = config.get_config_prop("app")["logging"]["level"] + logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(filename)s [%(funcName)s:%(lineno)d] - %(message)s', + level=log_level ) - - config.init('../config') - # transcriberbot.multiprocessing.init() - # print("VOICE POOL:", transcriberbot.multiprocessing.voice_pool()) + logging.log(config.APP_LOG, "Setting log level to %s", log_level) resources.init("../values") antiflood.init() diff --git a/src/transcriberbot/blueprints/__init__.py b/src/transcriberbot/blueprints/__init__.py index 32bacb4..61882aa 100644 --- a/src/transcriberbot/blueprints/__init__.py +++ b/src/transcriberbot/blueprints/__init__.py @@ -2,4 +2,4 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ -from . import commands, messages, voice +from . import commands, messages, voice, chat_handlers diff --git a/src/transcriberbot/blueprints/chat_handlers.py b/src/transcriberbot/blueprints/chat_handlers.py new file mode 100644 index 0000000..8f76acb --- /dev/null +++ b/src/transcriberbot/blueprints/chat_handlers.py @@ -0,0 +1,25 @@ +""" +Author: Carlo Alberto Barbano +Date: 16/02/25 +""" +import logging +import config + +from telegram import Update, ChatMember +from telegram.ext import ContextTypes + +from database import TBDB + + +async def chat_member_update(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + logging.log(config.APP_LOG, "Chat {chat_id} member update: %s", update) + + left = update.my_chat_member.new_chat_member.status in (ChatMember.LEFT, ChatMember.BANNED) + + if left: + TBDB.set_chat_active(chat_id, False) + logging.log(config.APP_LOG, f"Chat {chat_id} deactivated") + else: + # TBDB.set_chat_active(chat_id, True) + logging.log(config.APP_LOG, f"Chat {chat_id} activated") diff --git a/src/transcriberbot/blueprints/commands.py b/src/transcriberbot/blueprints/commands.py index 832537b..6e32c6f 100644 --- a/src/transcriberbot/blueprints/commands.py +++ b/src/transcriberbot/blueprints/commands.py @@ -4,6 +4,7 @@ """ import logging import asyncio +import traceback from telegram import Update from telegram.ext import ContextTypes @@ -13,7 +14,6 @@ import translator from database import TBDB -logger = logging.getLogger(__name__) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): @@ -87,7 +87,7 @@ async def translate(update: Update, context: ContextTypes.DEFAULT_TYPE): lang = update.effective_message.text lang = lang.replace("/translate", "").strip() - logger.debug("Language %s", lang) + logging.debug("Language %s", lang) if not update.effective_message.reply_to_message: await context.bot.send_message( @@ -141,7 +141,7 @@ async def welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE): language = chat_record["lang"] elif update.effective_user.language_code is not None: # Channel posts do not have a language_code attribute - logger.info("Language_code: %s", update.effective_user.language_code) + logging.debug("Language_code: %s", update.effective_user.language_code) language = update.effective_user.language_code message = R.get_string_resource("message_welcome", language) @@ -157,7 +157,7 @@ async def welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE): if len(language) < 5: language = R.iso639_2_to_639_1(language) - logger.info("No record found for chat {}, creating one with lang {}".format(update.effective_chat.id, language)) + logging.debug("No record found for chat {}, creating one with lang {}".format(update.effective_chat.id, language)) TBDB.create_default_chat_entry(update.effective_chat.id, language) @@ -167,3 +167,43 @@ async def set_language(update: Update, context: ContextTypes.DEFAULT_TYPE, langu TBDB.set_chat_lang(chat_id, lang_) message = R.get_string_resource("language_set", lang_).replace("{lang}", language) await context.bot.send_message(chat_id, message, parse_mode="html") + + +async def users(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + tot_chats = TBDB.get_chats_num() + active_chats = TBDB.get_active_chats_num() + await context.bot.send_message( + chat_id=chat_id, text='Total users: {}\nActive users: {}'.format(tot_chats, active_chats), parse_mode='html', + ) + + +async def broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat_id = update.effective_chat.id + text = " ".join(context.args) + + async def __post(): + chats = TBDB.get_chats() + sent = 0 + + for chat in chats: + try: + await context.bot.send_message( + chat_id=chat['chat_id'], + text=text, + parse_mode='html', + ) + sent += 1 + await asyncio.sleep(0.1) + except Exception as e: + logging.error( + "Exception sending broadcast to %d: (%s) %s", + chat['chat_id'], e, traceback.format_exc() + ) + + await context.bot.send_message( + chat_id=chat_id, + text='Broadcast sent to {}/{} chats'.format(sent, len(chats)), + ) + + await __post() diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index d106560..c593e41 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -7,13 +7,14 @@ import config import logging -from telegram.ext import MessageHandler, ApplicationBuilder, CommandHandler, ContextTypes, CallbackQueryHandler +from telegram.ext import MessageHandler, ApplicationBuilder, CommandHandler, ContextTypes, CallbackQueryHandler, \ + ChatMemberHandler from functools import partial -from transcriberbot.blueprints import commands, messages, voice +from transcriberbot.blueprints import commands, messages, voice, chat_handlers from transcriberbot.blueprints.commands import set_language from telegram.ext.filters import VOICE, VIDEO_NOTE, AUDIO -from transcriberbot.filters import ChatAdmin, FromPrivate, AllowedDocument +from transcriberbot.filters import ChatAdmin, FromPrivate, AllowedDocument, BotAdmin def run(bot_token: str): @@ -22,11 +23,15 @@ def run(bot_token: str): .concurrent_updates(True) .build()) - logger = logging.getLogger(__name__) - - logging.info("Installing handlers") + logging.log(config.APP_LOG, "Installing handlers") application.add_handler(CallbackQueryHandler(voice.stop_task)) + # application.add_handler(ChatMemberHandler(chat_handlers.chat_member_update)) + application.add_handler(ChatMemberHandler( + chat_handlers.chat_member_update, + chat_member_types=ChatMemberHandler.MY_CHAT_MEMBER + )) + application.add_handler(CommandHandler('start', commands.start, filters=ChatAdmin())) application.add_handler(CommandHandler('help', commands.start, filters=ChatAdmin())) application.add_handler(CommandHandler('lang', commands.lang, filters=ChatAdmin())) @@ -41,7 +46,11 @@ def run(bot_token: str): application.add_handler(CommandHandler('donate', commands.donate, filters=ChatAdmin())) application.add_handler(CommandHandler('privacy', commands.privacy)) - logger.info("Installing language handlers..") + logging.log(config.APP_LOG, "Installing admin controls") + application.add_handler(CommandHandler("users", commands.users, filters=BotAdmin())) + application.add_handler(CommandHandler("broadcast", commands.broadcast, filters=BotAdmin())) + + logging.log(config.APP_LOG, "Installing language handlers..") for language in config.get_language_list(): application.add_handler( CommandHandler(language, partial(set_language, language=language), filters=ChatAdmin()) @@ -54,5 +63,5 @@ def run(bot_token: str): application.add_handler(MessageHandler(FromPrivate(), messages.private_message)) - logger.info("Starting bot..") + logging.log(config.APP_LOG, "Starting bot..") application.run_polling(allowed_updates=Update.ALL_TYPES) diff --git a/src/transcriberbot/filters/filters.py b/src/transcriberbot/filters/filters.py index 05efb34..0909690 100644 --- a/src/transcriberbot/filters/filters.py +++ b/src/transcriberbot/filters/filters.py @@ -8,23 +8,9 @@ from telegram.ext.filters import UpdateFilter from telegram import Update, ChatMember -logger = logging.getLogger(__name__) - - -# class Voice(ABCRule[MessageUpdate]): -# async def check(self, m: MessageUpdate, _) -> bool: -# return bool(m.voice) -# -# class Audio(ABCRule[MessageUpdate]): -# async def check(self, m: MessageUpdate, _) -> bool: -# return bool(m.audio) -# -# -# class VideoNote(ABCRule[MessageUpdate]): -# async def check(self, m: MessageUpdate, _) -> bool: -# return bool(m.video_note) -# -# +import config + + class AllowedDocument(UpdateFilter): """ Checks if the message has document media with allowed extensions. @@ -34,7 +20,7 @@ def __init__(self, allowed_exts) -> None: super().__init__() self.allowed_exts = allowed_exts if len(allowed_exts) == 0: - logger.warning("No allowed extensions were provided. Documents will be disabled") + logging.warning("No allowed extensions were provided. Documents will be disabled") def filter(self, update: Update) -> bool: if update.effective_message.document: @@ -63,9 +49,24 @@ async def filter(self, update: Update) -> bool: return True user = update.effective_user - chat_admins: list[ChatMember] = update.effective_chat.get_administrators() + chat_admins: list[ChatMember] = await update.effective_chat.get_administrators() is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) is_admin = len(is_admin) > 0 return is_admin + + +class BotAdmin(UpdateFilter): + """ + Checks if the message was sent by the bot admin. + """ + + def filter(self, update: Update) -> bool: + user = update.effective_user + bot_admins = config.get_bot_admins() + + is_admin = list(filter(lambda admin_id: admin_id == user.id, bot_admins)) + is_admin = len(is_admin) > 0 + + return is_admin From 2b2591b290e3a21191983f5ec4f1531e43367725 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 20:41:57 +0100 Subject: [PATCH 097/120] fix async chat_admin filter --- src/transcriberbot/bot.py | 44 +++++++++++++++------------ src/transcriberbot/filters/filters.py | 21 +++++++++++-- 2 files changed, 44 insertions(+), 21 deletions(-) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index c593e41..c4cdc6b 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -14,7 +14,7 @@ from transcriberbot.blueprints.commands import set_language from telegram.ext.filters import VOICE, VIDEO_NOTE, AUDIO -from transcriberbot.filters import ChatAdmin, FromPrivate, AllowedDocument, BotAdmin +from transcriberbot.filters import chat_admin, FromPrivate, AllowedDocument, BotAdmin def run(bot_token: str): @@ -26,36 +26,42 @@ def run(bot_token: str): logging.log(config.APP_LOG, "Installing handlers") application.add_handler(CallbackQueryHandler(voice.stop_task)) - # application.add_handler(ChatMemberHandler(chat_handlers.chat_member_update)) application.add_handler(ChatMemberHandler( chat_handlers.chat_member_update, chat_member_types=ChatMemberHandler.MY_CHAT_MEMBER )) - application.add_handler(CommandHandler('start', commands.start, filters=ChatAdmin())) - application.add_handler(CommandHandler('help', commands.start, filters=ChatAdmin())) - application.add_handler(CommandHandler('lang', commands.lang, filters=ChatAdmin())) - application.add_handler(CommandHandler('rate', commands.rate, filters=ChatAdmin())) - application.add_handler(CommandHandler('disable_voice', commands.disable_voice, filters=ChatAdmin())) - application.add_handler(CommandHandler('enable_voice', commands.enable_voice, filters=ChatAdmin())) - application.add_handler(CommandHandler('disable_photos', commands.disable_photos, filters=ChatAdmin())) - application.add_handler(CommandHandler('enable_photos', commands.enable_photos, filters=ChatAdmin())) - application.add_handler(CommandHandler('disable_qr', commands.disable_qr, filters=ChatAdmin())) - application.add_handler(CommandHandler('enable_qr', commands.enable_qr, filters=ChatAdmin())) - application.add_handler(CommandHandler('translate', commands.translate, filters=ChatAdmin())) - application.add_handler(CommandHandler('donate', commands.donate, filters=ChatAdmin())) - application.add_handler(CommandHandler('privacy', commands.privacy)) + chat_admin_handlers = { + 'start': commands.start, + 'help': commands.start, + 'lang': commands.lang, + 'rate': commands.rate, + 'disable_voice': commands.disable_voice, + 'enable_voice': commands.enable_voice, + 'disable_photos': commands.disable_photos, + 'enable_photos': commands.enable_photos, + 'disable_qr': commands.disable_qr, + 'enable_qr': commands.enable_qr, + 'translate': commands.translate, + 'donate': commands.donate, + 'privacy': commands.privacy + } - logging.log(config.APP_LOG, "Installing admin controls") - application.add_handler(CommandHandler("users", commands.users, filters=BotAdmin())) - application.add_handler(CommandHandler("broadcast", commands.broadcast, filters=BotAdmin())) + for command, callback in chat_admin_handlers.items(): + application.add_handler(CommandHandler(command, lambda u, c, cb=callback: chat_admin(u, c, cb))) logging.log(config.APP_LOG, "Installing language handlers..") for language in config.get_language_list(): + callback = partial(set_language, language=language) application.add_handler( - CommandHandler(language, partial(set_language, language=language), filters=ChatAdmin()) + CommandHandler(language, lambda u, c, cb=callback: chat_admin(u, c, cb)) ) + logging.log(config.APP_LOG, "Installing admin controls") + application.add_handler(CommandHandler("users", commands.users, filters=BotAdmin())) + application.add_handler(CommandHandler("broadcast", commands.broadcast, filters=BotAdmin())) + + logging.log(config.APP_LOG, "Installing message handlers") application.add_handler(MessageHandler(VOICE, voice.voice_message)) application.add_handler(MessageHandler(AUDIO, voice.audio_message)) application.add_handler(MessageHandler(VIDEO_NOTE, voice.video_note_message)) diff --git a/src/transcriberbot/filters/filters.py b/src/transcriberbot/filters/filters.py index 0909690..0fb05b4 100644 --- a/src/transcriberbot/filters/filters.py +++ b/src/transcriberbot/filters/filters.py @@ -3,8 +3,10 @@ Date: 15/02/25 """ import logging +import asyncio from telegram.constants import ChatType +from telegram.ext import ContextTypes from telegram.ext.filters import UpdateFilter from telegram import Update, ChatMember @@ -44,12 +46,13 @@ class ChatAdmin(UpdateFilter): Checks if the message was sent by a chat admin. """ - async def filter(self, update: Update) -> bool: + def filter(self, update: Update) -> bool: if update.effective_chat.type in (ChatType.PRIVATE, ChatType.CHANNEL): return True user = update.effective_user - chat_admins: list[ChatMember] = await update.effective_chat.get_administrators() + chat_admins: list[ChatMember] = asyncio.get_event_loop().run_until_complete( + update.effective_chat.get_administrators()) is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) is_admin = len(is_admin) > 0 @@ -57,6 +60,20 @@ async def filter(self, update: Update) -> bool: return is_admin +async def chat_admin(update: Update, context: ContextTypes.DEFAULT_TYPE, callback): + if update.effective_chat.type in (ChatType.PRIVATE, ChatType.CHANNEL): + return True + + user = update.effective_user + chat_admins: list[ChatMember] = await update.effective_chat.get_administrators() + + is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) + is_admin = len(is_admin) > 0 + + if is_admin: + return await callback(update, context) + + class BotAdmin(UpdateFilter): """ Checks if the message was sent by the bot admin. From 284992a70038378f06e71e87bed8deedcb5eb65f Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 20:53:25 +0100 Subject: [PATCH 098/120] optimize db usage --- src/database/db.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/database/db.py b/src/database/db.py index 20e5964..8fd151b 100644 --- a/src/database/db.py +++ b/src/database/db.py @@ -80,10 +80,9 @@ def get_chat_lang(chat_id): if not chat_record: logger.debug("Record for chat {} not found, creating one.".format(chat_id)) TBDB.create_default_chat_entry(chat_id, "en-US") + return "en-US" - with TBDB._get_db() as db: - cursor = db.execute("SELECT lang FROM chats WHERE chat_id='{0}'".format(chat_id)) - return cursor.fetchone()[0] + return chat_record["lang"] @staticmethod def set_chat_lang(chat_id, lang): From b52f30bba3f4564b1d0ee751c87e8c982f5203d7 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 21:01:12 +0100 Subject: [PATCH 099/120] fix async chat_admin filter --- src/transcriberbot/filters/filters.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/transcriberbot/filters/filters.py b/src/transcriberbot/filters/filters.py index 0fb05b4..69f925a 100644 --- a/src/transcriberbot/filters/filters.py +++ b/src/transcriberbot/filters/filters.py @@ -61,14 +61,15 @@ def filter(self, update: Update) -> bool: async def chat_admin(update: Update, context: ContextTypes.DEFAULT_TYPE, callback): - if update.effective_chat.type in (ChatType.PRIVATE, ChatType.CHANNEL): - return True - user = update.effective_user - chat_admins: list[ChatMember] = await update.effective_chat.get_administrators() + if update.effective_chat.type in (ChatType.PRIVATE, ChatType.CHANNEL): + is_admin = True + else: + user = update.effective_user + chat_admins: list[ChatMember] = await update.effective_chat.get_administrators() - is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) - is_admin = len(is_admin) > 0 + is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) + is_admin = len(is_admin) > 0 if is_admin: return await callback(update, context) From 2edc4edebe4b48a68e2a81aabe9765ff3cd21e1e Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 21:07:56 +0100 Subject: [PATCH 100/120] add chat member handler --- src/transcriberbot/blueprints/chat_handlers.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/transcriberbot/blueprints/chat_handlers.py b/src/transcriberbot/blueprints/chat_handlers.py index 8f76acb..de64f44 100644 --- a/src/transcriberbot/blueprints/chat_handlers.py +++ b/src/transcriberbot/blueprints/chat_handlers.py @@ -21,5 +21,7 @@ async def chat_member_update(update: Update, context: ContextTypes.DEFAULT_TYPE) TBDB.set_chat_active(chat_id, False) logging.log(config.APP_LOG, f"Chat {chat_id} deactivated") else: - # TBDB.set_chat_active(chat_id, True) - logging.log(config.APP_LOG, f"Chat {chat_id} activated") + chat_record = TBDB.get_chat_entry(chat_id) + if chat_record: + TBDB.set_chat_active(chat_id, 1) + logging.log(config.APP_LOG, f"Chat {chat_id} reactivated") From 634cabe0e04621b7bb1989ecdd1d6067f7f591d3 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 21:08:02 +0100 Subject: [PATCH 101/120] add todo --- src/transcriberbot/blueprints/voice.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index b58f304..8fede53 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -7,7 +7,6 @@ import os import traceback from asyncio import CancelledError -from concurrent.futures.process import ProcessPoolExecutor import telegram from telegram import Update, Voice, InlineKeyboardMarkup, InlineKeyboardButton, VideoNote, Document @@ -22,6 +21,8 @@ logger = logging.getLogger(__name__) +# TODO: check if cpu usage is too high, if so, use ProcessPoolExecutor + async def voice_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: return From cc761a028f03488f709659d648bc204e237fa3a3 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 21:37:35 +0100 Subject: [PATCH 102/120] add anonymous admin --- src/transcriberbot/filters/filters.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/transcriberbot/filters/filters.py b/src/transcriberbot/filters/filters.py index 69f925a..8ff11d3 100644 --- a/src/transcriberbot/filters/filters.py +++ b/src/transcriberbot/filters/filters.py @@ -66,10 +66,15 @@ async def chat_admin(update: Update, context: ContextTypes.DEFAULT_TYPE, callbac is_admin = True else: user = update.effective_user - chat_admins: list[ChatMember] = await update.effective_chat.get_administrators() - is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) - is_admin = len(is_admin) > 0 + if user.id == 1087968824: # Anonymous admin + is_admin = True + + else: + chat_admins: list[ChatMember] = await update.effective_chat.get_administrators() + + is_admin = list(filter(lambda admin: admin.user.id == user.id, chat_admins)) + is_admin = len(is_admin) > 0 if is_admin: return await callback(update, context) From 4c6ee90be52632860902264416973cbe532bb08c Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 22:08:20 +0100 Subject: [PATCH 103/120] add sentry config --- config/sentry.json | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 config/sentry.json diff --git a/config/sentry.json b/config/sentry.json new file mode 100644 index 0000000..cb8ef39 --- /dev/null +++ b/config/sentry.json @@ -0,0 +1,3 @@ +{ + "dsn": "xxx" +} \ No newline at end of file From af2d5581e9b36918445de0d9398dc41124f7f735 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 22:08:55 +0100 Subject: [PATCH 104/120] add sentry --- .gitignore | 1 - requirements.txt | 1 + src/main.py | 21 ++++++++++++++++++++- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 2547aad..39ace71 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ # TranscriberBot-specific ignores -config/ media/ # Generic data-related ignores diff --git a/requirements.txt b/requirements.txt index b539209..4e37046 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,3 +6,4 @@ watchdog pydub zbarlight requests +sentry-sdk \ No newline at end of file diff --git a/src/main.py b/src/main.py index 30847f4..971368d 100644 --- a/src/main.py +++ b/src/main.py @@ -5,7 +5,8 @@ import database import antiflood import transcriberbot.bot - +import sentry_sdk +from sentry_sdk.integrations.asyncio import AsyncioIntegration def main(): config.init('../config') @@ -23,6 +24,24 @@ def main(): antiflood.init() database.init_schema(config.get_config_prop("app")["database"]) + sentry_sdk.init( + dsn=config.get_config_prop("sentry")["dsn"], + # Add data like request headers and IP for users, if applicable; + # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info + send_default_pii=True, + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for tracing. + traces_sample_rate=1.0, + # Set profiles_sample_rate to 1.0 to profile 100% + # of sampled transactions. + # We recommend adjusting this value in production. + profiles_sample_rate=1.0, + integrations=[ + AsyncioIntegration(), + ], + ) + + sentry_sdk.profiler.start_profiler() transcriberbot.bot.run(config.bot_token()) From 6c54c788de1fe599eb9411e37888b24ac5f28fe9 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 22:15:11 +0100 Subject: [PATCH 105/120] check if no extension is present --- src/transcriberbot/filters/filters.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/transcriberbot/filters/filters.py b/src/transcriberbot/filters/filters.py index 8ff11d3..3d7b968 100644 --- a/src/transcriberbot/filters/filters.py +++ b/src/transcriberbot/filters/filters.py @@ -27,6 +27,8 @@ def __init__(self, allowed_exts) -> None: def filter(self, update: Update) -> bool: if update.effective_message.document: filename = update.effective_message.document.file_name + if '.' not in filename: # No extension + return False ext = filename.split('.')[-1] return ext in self.allowed_exts return False From 6de910ede6bf95df79cf11ee9fcaa210216906fb Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 22:30:50 +0100 Subject: [PATCH 106/120] add logging --- src/transcriberbot/blueprints/voice.py | 2 +- src/transcriberbot/filters/filters.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index 8fede53..d23ed08 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -183,7 +183,7 @@ async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TY except CancelledError: - print("Task cancelled") + logging.debug("Task cancelled") await context.bot.edit_message_text( message.text + " " + R.get_string_resource("transcription_stopped", lang), chat_id=chat_id, message_id=message.message_id, parse_mode="html" diff --git a/src/transcriberbot/filters/filters.py b/src/transcriberbot/filters/filters.py index 3d7b968..0186255 100644 --- a/src/transcriberbot/filters/filters.py +++ b/src/transcriberbot/filters/filters.py @@ -26,6 +26,7 @@ def __init__(self, allowed_exts) -> None: def filter(self, update: Update) -> bool: if update.effective_message.document: + logging.debug("Received document %s", update.effective_message.document.file_id) filename = update.effective_message.document.file_name if '.' not in filename: # No extension return False From 72b01700ec85616be1925bb04fa054a7f9120670 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Sun, 16 Feb 2025 22:36:41 +0100 Subject: [PATCH 107/120] handle animations --- src/transcriberbot/filters/filters.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/transcriberbot/filters/filters.py b/src/transcriberbot/filters/filters.py index 0186255..bc89d30 100644 --- a/src/transcriberbot/filters/filters.py +++ b/src/transcriberbot/filters/filters.py @@ -25,6 +25,9 @@ def __init__(self, allowed_exts) -> None: logging.warning("No allowed extensions were provided. Documents will be disabled") def filter(self, update: Update) -> bool: + if update.effective_message.animation: + return False + if update.effective_message.document: logging.debug("Received document %s", update.effective_message.document.file_id) filename = update.effective_message.document.file_name From 4576f541027fab7144fdbcf2859ca3e50915ad90 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 00:09:42 +0100 Subject: [PATCH 108/120] add photo handlers --- requirements.txt | 2 +- src/phototools/ocr.py | 27 ++++++++- src/phototools/qr.py | 2 +- src/transcriberbot/blueprints/__init__.py | 2 +- src/transcriberbot/blueprints/photos.py | 72 +++++++++++++++++++++++ src/transcriberbot/bot.py | 6 +- 6 files changed, 105 insertions(+), 6 deletions(-) diff --git a/requirements.txt b/requirements.txt index 4e37046..8b8bc35 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,7 +2,7 @@ python-telegram-bot coloredlogs pillow watchdog -# tesserocr +tesserocr pydub zbarlight requests diff --git a/src/phototools/ocr.py b/src/phototools/ocr.py index e6c248f..03cd134 100644 --- a/src/phototools/ocr.py +++ b/src/phototools/ocr.py @@ -6,9 +6,34 @@ def image_ocr(path, lang): + return image_ocr_tesserocr(path, lang) + + +def image_ocr_docts(path, lang): + from doctr.models import ocr_predictor + + predictor = ocr_predictor.create_predictor() + + # Perform OCR on the image + predictor(path) + + +def image_ocr_easyocr(path, lang): + import easyocr + + logger.info("opening %s", path) + + reader = easyocr.Reader(['en'], gpu=False) + result = reader.readtext(path) + text = " ".join([x[1] for x in result]) + + return text + + +def image_ocr_tesserocr(path, lang): logger.info("opening %s", path) - with PyTessBaseAPI() as api: + with PyTessBaseAPI(path='/usr/share/tesseract-ocr/5/tessdata/') as api: api.SetImageFile(path) text = api.GetUTF8Text().strip() diff --git a/src/phototools/qr.py b/src/phototools/qr.py index b4f4c7f..605f815 100644 --- a/src/phototools/qr.py +++ b/src/phototools/qr.py @@ -5,7 +5,7 @@ logger = logging.getLogger(__name__) -def read_qr(path, lang): +def read_qr(path): logger.info("opening %s", path) with open(path, 'rb') as f: diff --git a/src/transcriberbot/blueprints/__init__.py b/src/transcriberbot/blueprints/__init__.py index 61882aa..7fc3b7e 100644 --- a/src/transcriberbot/blueprints/__init__.py +++ b/src/transcriberbot/blueprints/__init__.py @@ -2,4 +2,4 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ -from . import commands, messages, voice, chat_handlers +from . import commands, messages, voice, photos, chat_handlers diff --git a/src/transcriberbot/blueprints/photos.py b/src/transcriberbot/blueprints/photos.py index 0e0223b..b7c6c79 100644 --- a/src/transcriberbot/blueprints/photos.py +++ b/src/transcriberbot/blueprints/photos.py @@ -2,3 +2,75 @@ Author: Carlo Alberto Barbano Date: 15/02/25 """ +import html +import logging +import os +import traceback + +import telegram +from telegram import Update +from telegram.ext import ContextTypes + +import config +import phototools +import resources as R +from database import TBDB + + +async def photo(update: Update, context: ContextTypes.DEFAULT_TYPE): + photo_enabled = TBDB.get_chat_photos_enabled(update.effective_chat.id) + qr_enabled = TBDB.get_chat_qr_enabled(update.effective_chat.id) + + if not photo_enabled and not qr_enabled: + return + + message = update.message or update.channel_post + await process_media_photo(update, context, message.photo) + + +async def process_media_photo(update: Update, context: ContextTypes.DEFAULT_TYPE, photo): + chat_id = update.effective_chat.id + message_id = update.effective_message.id + lang = TBDB.get_chat_lang(chat_id) + + file_id = photo[-1].file_id + file_path = os.path.join(config.get_config_prop("app")["media_path"], file_id) + file: telegram.File = await context.bot.get_file(file_id) + await file.download_to_drive(file_path) + + try: + qr_enabled = TBDB.get_chat_qr_enabled(update.effective_chat.id) + if qr_enabled: + qr = phototools.read_qr(file_path) + if qr is not None: + qr = R.get_string_resource("qr_result", lang) + f"\n{qr}" + + await context.bot.send_message( + chat_id=chat_id, text=qr, reply_to_message_id=message_id, + parse_mode="html" + ) + return + + photo_enabled = TBDB.get_chat_photos_enabled(update.effective_chat.id) + if photo_enabled: + text = phototools.image_ocr(file_path, lang) + if text is not None: + text = R.get_string_resource("ocr_result", lang) + "\n" + html.escape(text) + await context.bot.send_message( + text=text, chat_id=chat_id, reply_to_message_id=message_id, + parse_mode="html", + ) + return + + + await context.bot.send_message( + text=R.get_string_resource("photo_no_text", lang), + chat_id=chat_id, reply_to_message_id=message_id, + parse_mode="html", + ) + + except Exception as e: + logging.error("Exception handling photo from %d: %s", chat_id, traceback.format_exc()) + + finally: + os.remove(file_path) diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index c4cdc6b..83de733 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -10,10 +10,10 @@ from telegram.ext import MessageHandler, ApplicationBuilder, CommandHandler, ContextTypes, CallbackQueryHandler, \ ChatMemberHandler from functools import partial -from transcriberbot.blueprints import commands, messages, voice, chat_handlers +from transcriberbot.blueprints import commands, messages, voice, photos, chat_handlers from transcriberbot.blueprints.commands import set_language -from telegram.ext.filters import VOICE, VIDEO_NOTE, AUDIO +from telegram.ext.filters import VOICE, VIDEO_NOTE, AUDIO, PHOTO from transcriberbot.filters import chat_admin, FromPrivate, AllowedDocument, BotAdmin @@ -67,6 +67,8 @@ def run(bot_token: str): application.add_handler(MessageHandler(VIDEO_NOTE, voice.video_note_message)) application.add_handler(MessageHandler(AllowedDocument(config.get_document_extensions()), voice.document_message)) + application.add_handler(MessageHandler(PHOTO, photos.photo)) + application.add_handler(MessageHandler(FromPrivate(), messages.private_message)) logging.log(config.APP_LOG, "Starting bot..") From 986958d46fd493022edabb61cff4b539223844ac Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 00:13:48 +0100 Subject: [PATCH 109/120] always enable photos for private chats --- src/transcriberbot/blueprints/photos.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/transcriberbot/blueprints/photos.py b/src/transcriberbot/blueprints/photos.py index b7c6c79..9be4f4b 100644 --- a/src/transcriberbot/blueprints/photos.py +++ b/src/transcriberbot/blueprints/photos.py @@ -9,6 +9,7 @@ import telegram from telegram import Update +from telegram.constants import ChatType from telegram.ext import ContextTypes import config @@ -18,8 +19,8 @@ async def photo(update: Update, context: ContextTypes.DEFAULT_TYPE): - photo_enabled = TBDB.get_chat_photos_enabled(update.effective_chat.id) - qr_enabled = TBDB.get_chat_qr_enabled(update.effective_chat.id) + photo_enabled = update.effective_chat.type == ChatType.PRIVATE or TBDB.get_chat_photos_enabled(update.effective_chat.id) + qr_enabled = update.effective_chat.type == ChatType.PRIVATE or TBDB.get_chat_qr_enabled(update.effective_chat.id) if not photo_enabled and not qr_enabled: return @@ -39,8 +40,7 @@ async def process_media_photo(update: Update, context: ContextTypes.DEFAULT_TYPE await file.download_to_drive(file_path) try: - qr_enabled = TBDB.get_chat_qr_enabled(update.effective_chat.id) - if qr_enabled: + if update.effective_chat.type == ChatType.PRIVATE or TBDB.get_chat_qr_enabled(update.effective_chat.id): qr = phototools.read_qr(file_path) if qr is not None: qr = R.get_string_resource("qr_result", lang) + f"\n{qr}" @@ -51,8 +51,7 @@ async def process_media_photo(update: Update, context: ContextTypes.DEFAULT_TYPE ) return - photo_enabled = TBDB.get_chat_photos_enabled(update.effective_chat.id) - if photo_enabled: + if update.effective_chat.type == ChatType.PRIVATE or TBDB.get_chat_photos_enabled(update.effective_chat.id): text = phototools.image_ocr(file_path, lang) if text is not None: text = R.get_string_resource("ocr_result", lang) + "\n" + html.escape(text) From 8e05bdaf21ebaccabe1d23face21f047baa12dc3 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 13:55:16 +0100 Subject: [PATCH 110/120] add teseract_path in config --- config/app.json | 4 ++++ src/phototools/ocr.py | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/config/app.json b/config/app.json index 65422d9..fad2d12 100644 --- a/config/app.json +++ b/config/app.json @@ -49,6 +49,10 @@ "webm" ], + "ocr": { + "tesseract_path": "/usr/share/tesseract-ocr/5/tessdata/" + }, + "antiflood": { "age_threshold": 10, "flood_ratio": 2, diff --git a/src/phototools/ocr.py b/src/phototools/ocr.py index 03cd134..b992d86 100644 --- a/src/phototools/ocr.py +++ b/src/phototools/ocr.py @@ -2,6 +2,8 @@ from tesserocr import PyTessBaseAPI +import config + logger = logging.getLogger(__name__) @@ -33,7 +35,7 @@ def image_ocr_easyocr(path, lang): def image_ocr_tesserocr(path, lang): logger.info("opening %s", path) - with PyTessBaseAPI(path='/usr/share/tesseract-ocr/5/tessdata/') as api: + with PyTessBaseAPI(path=config.get_config_prop("ocr")["tesseract_path"]) as api: api.SetImageFile(path) text = api.GetUTF8Text().strip() From 3cc02a2bce439750f726f2774106be5d5d5ceb9d Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 13:55:31 +0100 Subject: [PATCH 111/120] update base docker image --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index e42b32f..4e882af 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.9-slim +FROM python:3.12.0-slim # Set global configs WORKDIR / From bf61203c10dfc253abe5119c5d0c0c3285687664 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 13:57:56 +0100 Subject: [PATCH 112/120] add build action --- .github/workflows/build_image.yml | 41 +++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 .github/workflows/build_image.yml diff --git a/.github/workflows/build_image.yml b/.github/workflows/build_image.yml new file mode 100644 index 0000000..475763b --- /dev/null +++ b/.github/workflows/build_image.yml @@ -0,0 +1,41 @@ +name: DockerBuildAndPush + +on: + push: + branches: + - master + - developement + - ptb-async + +env: + IMAGE_NAME: transcriberbot + +jobs: + push: + runs-on: ubuntu-latest + if: github.event_name == 'push' + + steps: + - uses: actions/checkout@v2 + + - name: Login to ghcr registry + run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u $ --password-stdin + + - name: Build image + run: docker build . --file Dockerfile --tag $IMAGE_NAME + + - name: Push image + run: | + IMAGE_ID=ghcr.io/${{ github.repository_owner }}/$IMAGE_NAME + # Change all uppercase to lowercase + IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + # Strip git ref prefix from version + VERSION=$(echo "${{ github.ref }}" | sed -e 's,.*/\(.*\),\1,') + # Strip "v" prefix from tag name + [[ "${{ github.ref }}" == "refs/tags/"* ]] && VERSION=$(echo $VERSION | sed -e 's/^v//') + # Use Docker `latest` tag convention + [ "$VERSION" == "master" ] && VERSION=latest + echo IMAGE_ID=$IMAGE_ID + echo VERSION=$VERSION + docker tag $IMAGE_NAME $IMAGE_ID:$VERSION + docker push $IMAGE_ID:$VERSION \ No newline at end of file From 7fa93371a2b5186c00b1ac1cfa3a2fd08faac440 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 21:02:30 +0100 Subject: [PATCH 113/120] update run.sh --- run.sh | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/run.sh b/run.sh index 3826e74..0fe85f7 100755 --- a/run.sh +++ b/run.sh @@ -1,8 +1,15 @@ +#!/bin/sh + +docker pull ghcr.io/charslab/transcriberbot:ptb-async docker run \ -e LC_ALL=C \ -d --restart unless-stopped \ - --name "transcriberbot" \ + --name "transcriberbot-async" \ -v "$(pwd)"/data:/data \ -v "$(pwd)"/config:/config \ -v "$(pwd)"/values:/values \ - transcriberbot + -v "$(pwd)"/media:/media \ + --cpus=4.0 \ + --memory=3000m \ + -u "$(id -u):1337" \ + ghcr.io/charslab/transcriberbot:ptb-async \ No newline at end of file From 59fbc21b39a729e8b5a6b0cb81179ef4ef17abc2 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 21:09:53 +0100 Subject: [PATCH 114/120] fix prop key --- src/phototools/ocr.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/phototools/ocr.py b/src/phototools/ocr.py index b992d86..163ac13 100644 --- a/src/phototools/ocr.py +++ b/src/phototools/ocr.py @@ -35,7 +35,7 @@ def image_ocr_easyocr(path, lang): def image_ocr_tesserocr(path, lang): logger.info("opening %s", path) - with PyTessBaseAPI(path=config.get_config_prop("ocr")["tesseract_path"]) as api: + with PyTessBaseAPI(path=config.get_config_prop("app")["ocr"]["tesseract_path"]) as api: api.SetImageFile(path) text = api.GetUTF8Text().strip() From 964f16ea836d0ca2de8e3587ffde2891efa44941 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 21:21:14 +0100 Subject: [PATCH 115/120] remove prints --- src/audiotools/speech.py | 4 ++-- src/transcriberbot/blueprints/voice.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index d6995d9..829a734 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -107,11 +107,11 @@ async def transcribe_whisper(path): def transcribe(path, api_key, backend="wit"): if backend == "wit": - print("Transcribing with wit") + logging.debug("Transcribing with wit") return transcribe_wit(path, api_key) elif backend == "whisper": - print("Transcribing with whisper") + logging.debug("Transcribing with whisper") return transcribe_whisper(os.path.basename(path)) raise ValueError("Unknown backend: %s" % backend) diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index d23ed08..e56b5f6 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -62,7 +62,7 @@ async def stop_task(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: if task is not None: task.cancel() else: - print("Task not found") + logging.warning("Task not found") async def process_media_voice(update: Update, context: ContextTypes.DEFAULT_TYPE, media: [Voice | VideoNote | Document], @@ -125,7 +125,7 @@ async def transcribe_audio_file(update: Update, context: ContextTypes.DEFAULT_TY try: async for idx, speech, n_chunks in audiotools.transcribe(path, api_key): - print(f"Transcription idx={idx} n_chunks={n_chunks}, text={speech}") + logging.debug(f"Transcription idx={idx} n_chunks={n_chunks}, text={speech}") suffix = f" [{idx + 1}/{n_chunks}]" if idx < n_chunks - 1 else "" reply_markup = keyboard if idx < n_chunks - 1 else None From b8cf408e755c5c318916f51a4110a470a2581ca0 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 21:58:54 +0100 Subject: [PATCH 116/120] log chat_id for TypeError in get_chat_voice_enabled --- src/database/db.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/database/db.py b/src/database/db.py index 8fd151b..5847b30 100644 --- a/src/database/db.py +++ b/src/database/db.py @@ -91,9 +91,13 @@ def set_chat_lang(chat_id, lang): @staticmethod def get_chat_voice_enabled(chat_id): - with TBDB._get_db() as db: - c = db.execute("SELECT voice_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) - return c.fetchone()[0] + try: + with TBDB._get_db() as db: + c = db.execute("SELECT voice_enabled FROM chats WHERE chat_id='{0}'".format(chat_id)) + return c.fetchone()[0] + except TypeError as e: + logger.error("Error getting voice_enabled for chat %d: %s", chat_id, e) + raise e @staticmethod def set_chat_voice_enabled(chat_id, voice_enabled): From ee62b741e732d839830d5c303c073ea52d62728a Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 22:44:42 +0100 Subject: [PATCH 117/120] add audio queue --- src/transcriberbot/blueprints/commands.py | 14 +++++++-- src/transcriberbot/blueprints/voice.py | 38 ++++++++++++++++++----- src/transcriberbot/bot.py | 1 + 3 files changed, 43 insertions(+), 10 deletions(-) diff --git a/src/transcriberbot/blueprints/commands.py b/src/transcriberbot/blueprints/commands.py index 6e32c6f..ebd0e53 100644 --- a/src/transcriberbot/blueprints/commands.py +++ b/src/transcriberbot/blueprints/commands.py @@ -15,7 +15,6 @@ from database import TBDB - async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await welcome_message(update, context) @@ -157,7 +156,8 @@ async def welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE): if len(language) < 5: language = R.iso639_2_to_639_1(language) - logging.debug("No record found for chat {}, creating one with lang {}".format(update.effective_chat.id, language)) + logging.debug( + "No record found for chat {}, creating one with lang {}".format(update.effective_chat.id, language)) TBDB.create_default_chat_entry(update.effective_chat.id, language) @@ -178,6 +178,16 @@ async def users(update: Update, context: ContextTypes.DEFAULT_TYPE): ) +async def stats(update: Update, context: ContextTypes.DEFAULT_TYPE): + num_audios = len(context.bot_data) + num_queues = context.bot_data.get('queue_len', 0) + await context.bot.send_message( + update.effective_chat.id, f"Number of audios being currently processed: {num_audios}\n" + f"Number of audios in queue: {num_queues}\n\n" + f"{list(context.bot_data.keys())}" + ) + + async def broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE): chat_id = update.effective_chat.id text = " ".join(context.args) diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index e56b5f6..ab8cdbf 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -23,36 +23,33 @@ # TODO: check if cpu usage is too high, if so, use ProcessPoolExecutor + async def voice_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: return - task = asyncio.create_task(process_media_voice(update, context, update.effective_message.voice, "voice")) - context.bot_data[update.effective_message.message_id] = task + await run_voice_task(update, context, update.effective_message.voice, "voice") async def audio_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: return - task = asyncio.create_task(process_media_voice(update, context, update.effective_message.audio, "audio")) - context.bot_data[update.effective_message.message_id] = task + await run_voice_task(update, context, update.effective_message.audio, "audio") async def video_note_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: return - task = asyncio.create_task(process_media_voice(update, context, update.effective_message.video_note, "video_note")) - context.bot_data[update.effective_message.message_id] = task + await run_voice_task(update, context, update.effective_message.video_note, "video_note") async def document_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: if TBDB.get_chat_voice_enabled(update.effective_chat.id) == 0: return - task = asyncio.create_task(process_media_voice(update, context, update.effective_message.document, "document")) - context.bot_data[update.effective_message.message_id] = task + await run_voice_task(update, context, update.effective_message.document, "document") async def stop_task(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: @@ -61,10 +58,35 @@ async def stop_task(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: if task is not None: task.cancel() + context.bot_data.pop(task_id) else: logging.warning("Task not found") +async def wait_for_task_queue(context: ContextTypes.DEFAULT_TYPE): + # wait until there are less than N tasks in bot_data + context.bot_data['queue_len'] = context.bot_data.get('queue_len', 0) + 1 + + while len(context.bot_data) >= config.get_config_prop("app")["voice_max_threads"] + 1: + logging.debug("Waiting for tasks to finish") + await asyncio.sleep(1) + + context.bot_data['queue_len'] -= 1 + logging.debug("Task queue has available space") + + +async def run_voice_task(update: Update, context: ContextTypes.DEFAULT_TYPE, media: [Voice | VideoNote | Document], + name): + await wait_for_task_queue(context) + + try: + task = asyncio.create_task(process_media_voice(update, context, media, name)) + context.bot_data[update.effective_message.message_id] = task + await asyncio.gather(task) + finally: + context.bot_data.pop(update.effective_message.message_id) + + async def process_media_voice(update: Update, context: ContextTypes.DEFAULT_TYPE, media: [Voice | VideoNote | Document], name: str) -> None: chat_id = update.effective_chat.id diff --git a/src/transcriberbot/bot.py b/src/transcriberbot/bot.py index 83de733..06c170c 100644 --- a/src/transcriberbot/bot.py +++ b/src/transcriberbot/bot.py @@ -60,6 +60,7 @@ def run(bot_token: str): logging.log(config.APP_LOG, "Installing admin controls") application.add_handler(CommandHandler("users", commands.users, filters=BotAdmin())) application.add_handler(CommandHandler("broadcast", commands.broadcast, filters=BotAdmin())) + application.add_handler(CommandHandler("stats", commands.stats, filters=BotAdmin())) logging.log(config.APP_LOG, "Installing message handlers") application.add_handler(MessageHandler(VOICE, voice.voice_message)) From bd45046e0e8c27bf3e667a8765a6827d217a7008 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Wed, 19 Feb 2025 23:10:35 +0100 Subject: [PATCH 118/120] improve stats command --- src/transcriberbot/blueprints/commands.py | 11 +++++++++-- src/transcriberbot/blueprints/voice.py | 11 ++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/transcriberbot/blueprints/commands.py b/src/transcriberbot/blueprints/commands.py index ebd0e53..bab817f 100644 --- a/src/transcriberbot/blueprints/commands.py +++ b/src/transcriberbot/blueprints/commands.py @@ -5,6 +5,7 @@ import logging import asyncio import traceback +import datetime from telegram import Update from telegram.ext import ContextTypes @@ -179,12 +180,18 @@ async def users(update: Update, context: ContextTypes.DEFAULT_TYPE): async def stats(update: Update, context: ContextTypes.DEFAULT_TYPE): - num_audios = len(context.bot_data) + num_audios = len(context.bot_data) - 1 num_queues = context.bot_data.get('queue_len', 0) + + audio_queue = [f"{audio_id} duration {datetime.timedelta(seconds=v['duration'])} (received {v['time']}" for + audio_id, v in + context.bot_data.items() if + audio_id != 'queue_len'] + await context.bot.send_message( update.effective_chat.id, f"Number of audios being currently processed: {num_audios}\n" f"Number of audios in queue: {num_queues}\n\n" - f"{list(context.bot_data.keys())}" + f"{'\n'.join(audio_queue)}" ) diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index ab8cdbf..8074e2f 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -6,6 +6,7 @@ import logging import os import traceback +import datetime from asyncio import CancelledError import telegram @@ -54,7 +55,7 @@ async def document_message(update: Update, context: ContextTypes.DEFAULT_TYPE) - async def stop_task(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: task_id = int(update.callback_query.data) - task: asyncio.Task = context.bot_data.get(task_id) + task: asyncio.Task = context.bot_data.get(task_id)["task"] if task is not None: task.cancel() @@ -75,13 +76,17 @@ async def wait_for_task_queue(context: ContextTypes.DEFAULT_TYPE): logging.debug("Task queue has available space") -async def run_voice_task(update: Update, context: ContextTypes.DEFAULT_TYPE, media: [Voice | VideoNote | Document], +async def run_voice_task(update: Update, context: ContextTypes.DEFAULT_TYPE, media: Voice, name): await wait_for_task_queue(context) try: task = asyncio.create_task(process_media_voice(update, context, media, name)) - context.bot_data[update.effective_message.message_id] = task + context.bot_data[update.effective_message.message_id] = { + 'task': task, + 'duration': media.duration, + 'time': datetime.datetime.now(datetime.timezone.utc) + } await asyncio.gather(task) finally: context.bot_data.pop(update.effective_message.message_id) From 6a007243cdc5d094c7468bd4bc994576ebf63065 Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Thu, 20 Feb 2025 12:40:51 +0100 Subject: [PATCH 119/120] use exc_info in logging --- src/audiotools/speech.py | 2 +- src/database/db.py | 2 +- src/transcriberbot/blueprints/commands.py | 4 ++-- src/transcriberbot/blueprints/photos.py | 2 +- src/transcriberbot/blueprints/voice.py | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/audiotools/speech.py b/src/audiotools/speech.py index 829a734..188bf8b 100644 --- a/src/audiotools/speech.py +++ b/src/audiotools/speech.py @@ -47,7 +47,7 @@ async def transcribe(self, chunk): text = data["text"] except requests.exceptions.RequestException as e: - logger.error("Could not transcribe chunk: %s", traceback.format_exc()) + logger.error("Could not transcribe chunk", exc_info=True) return text diff --git a/src/database/db.py b/src/database/db.py index 5847b30..a928ab0 100644 --- a/src/database/db.py +++ b/src/database/db.py @@ -38,7 +38,7 @@ def __exit__(self, exc_type, exc_value, exc_traceback): logger.error("exc_type: {}".format(exc_type)) logger.error("exc_value: {}".format(exc_value)) logger.error("exc_traceback: {}".format(exc_traceback)) - logger.error(traceback.format_exc()) + logger.error("Caught exception", exc_info=True) return True diff --git a/src/transcriberbot/blueprints/commands.py b/src/transcriberbot/blueprints/commands.py index bab817f..297f3a6 100644 --- a/src/transcriberbot/blueprints/commands.py +++ b/src/transcriberbot/blueprints/commands.py @@ -214,8 +214,8 @@ async def __post(): await asyncio.sleep(0.1) except Exception as e: logging.error( - "Exception sending broadcast to %d: (%s) %s", - chat['chat_id'], e, traceback.format_exc() + "Exception sending broadcast to %d: (%s)", + chat['chat_id'], e, exc_info=True ) await context.bot.send_message( diff --git a/src/transcriberbot/blueprints/photos.py b/src/transcriberbot/blueprints/photos.py index 9be4f4b..b4cdf78 100644 --- a/src/transcriberbot/blueprints/photos.py +++ b/src/transcriberbot/blueprints/photos.py @@ -69,7 +69,7 @@ async def process_media_photo(update: Update, context: ContextTypes.DEFAULT_TYPE ) except Exception as e: - logging.error("Exception handling photo from %d: %s", chat_id, traceback.format_exc()) + logging.error("Exception handling photo from %d", chat_id, exc_info=True) finally: os.remove(file_path) diff --git a/src/transcriberbot/blueprints/voice.py b/src/transcriberbot/blueprints/voice.py index 8074e2f..7c5bf90 100644 --- a/src/transcriberbot/blueprints/voice.py +++ b/src/transcriberbot/blueprints/voice.py @@ -114,7 +114,7 @@ async def process_media_voice(update: Update, context: ContextTypes.DEFAULT_TYPE try: await transcribe_audio_file(update, context, file_path) except Exception: - logger.error("Exception handling %s from %d: %s", name, chat_id, traceback.format_exc()) + logger.error("Exception handling %s from %d", name, chat_id, exc_info=True) finally: os.remove(file_path) From 4334fbdb4241be9610d630e00274d999a9c35c3a Mon Sep 17 00:00:00 2001 From: Carlo Alberto Barbano Date: Thu, 20 Feb 2025 18:55:47 +0100 Subject: [PATCH 120/120] remove old docker scripts --- dockerBuild.sh | 1 - dockerRun.sh | 8 -------- 2 files changed, 9 deletions(-) delete mode 100755 dockerBuild.sh delete mode 100755 dockerRun.sh diff --git a/dockerBuild.sh b/dockerBuild.sh deleted file mode 100755 index 6230571..0000000 --- a/dockerBuild.sh +++ /dev/null @@ -1 +0,0 @@ -docker build --tag transcriberbot . diff --git a/dockerRun.sh b/dockerRun.sh deleted file mode 100755 index 3826e74..0000000 --- a/dockerRun.sh +++ /dev/null @@ -1,8 +0,0 @@ -docker run \ - -e LC_ALL=C \ - -d --restart unless-stopped \ - --name "transcriberbot" \ - -v "$(pwd)"/data:/data \ - -v "$(pwd)"/config:/config \ - -v "$(pwd)"/values:/values \ - transcriberbot