Repository: WithHades/banfoStyle Branch: master Commit: b6aef3428e88 Files: 12 Total size: 96.6 KB Directory structure: gitextract_cl4n5zmz/ ├── LICENSE ├── README.md ├── banfoTextSpider.py ├── conf.py ├── edit.py ├── generation.py ├── main.py ├── mainWindow.py ├── preprocess.py ├── requirements.txt ├── train.py └── utils.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ 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 . ================================================ FILE: README.md ================================================ # 半佛视频风格生成器 视频地址: [看我如何克隆半佛仙人,批量产出视频!](https://www.bilibili.com/video/BV12v411u7kw) ## 项目背景 半佛在2020年凭借众多沙雕表情包视频 + 魔性的文案迅速出圈。正如上一句所说,一个优秀的视频需要两部分组成,优秀的文案以及优秀的视频。那么半佛的成功是否可以复制呢?我认为在一定程度上是可以复制的。那么具体应该如何复制呢?我们尝试分析一下: ### 优秀的文案 半佛仙人的文案普遍比较nice,直接分析视频的文案似乎有点儿难度。好在半佛仙人还有微信公众号,直接学习微信公众号的写作风格是一个不错的选择,但是需要我们付出比较多的时间成本,并且学习效果不够直观。有没有什么更省事更直观效果更nice的方法呢?有。得益于GPT2模型强大的文本生成能力,我们也可以借助该模型训练一个半佛仙人风格文章生成器。 ### 优秀的视频 直观上来说视频的生成似乎要简单一些,事实上确实如此。半佛仙人的视频大部分是由相关性不是很强的表情包堆砌起来,我们不可能有大量精力来寻找下载一个个导入视频制作软件并设置字幕。有没有什么自动化的方法?有。搞一个图片搜索接口,不妨我们自定义一个视频制作软件。 **理论存在,实践开始。** ## 思路: 我们再来详细复习一下思路,理清一下我们要做的每一件事情。 ### 文案生成 直接生成大篇幅文案似乎不太现实,因为就目前来看,GPT2模型逻辑性不够强,上下文能力也有待提高,雪上加霜的是我们的电脑性能也不太行,只能采用GPT2蒸馏过后的模型,效果进一步下降,因此我们可以做一个文案提示器。当我们撰写文案的时候,轻松一按,即可生成相应的下文提示,这个思路是没有任何问题的。 1. 爬取半佛仙人微信公众号历史文章 2. 此处我们思考了一下框架的选择。不是很想在本地训练,目前体验以及部署最快的方案应该属于百度的AI Studio了。正好百度paddlenlp提供了中文GPT2预训练模型,因此我们就利用AI studio对GPT2Chinese预训练模型进行微调。 3. 数据集预处理。既然要微调自然需要预处理,由于只爬取到800+文章,为了扩大数据量,我们将滑动窗口设置的小一些。 4. 直接开整训练,数据不是很多的情况下,并不需要训练太久。百度每天8个小时免费GPU,训练几天也就ok了。 5. 写一个小小的窗口。 ### 视频生成 1. 输入断句后的文案 2. 将文案根据短句分割,每句作为一条字幕 3. 根据字幕搜索表情包并选择设置 4. 利用语音合成手段合成配音 5. 重复3、4步骤,直到所有的字幕均完成表情包设定、字幕设定、配音设定 6. 合成视频并加入背景音乐 7. 导出成品 ## 安装 1. 安装python3.8.3 2. 安装requirements.txt依赖 3. 运行`python main.py` 4. 运行`edit.py`请先按照百度paddlepaddle安装教程安装相应的库 ## 使用 ### 文案生成 1. 输入文件名或拖入文件 2. 输入文案 3. 按F1或者点击提示获取提示 4. 导出文案 5. 需要注意的是,导出文案需手动逐句分割 ### 视频生成 1. 确定文件名,点击设置按钮可以新建工程。 2. 可以拖入txt格式的文案或者直接拖入软件内,或者直接增加文案。 3. 点击上一句以及下一句文案,预览区可预览字幕,搜索区可搜索相关图片/表情包。 4. 预览字幕时,若需要将一句话分为两页,则应用\n分开。 5. 所有字幕均设置完毕可进行生成视频。 6. 软件每5秒保存一次工程文件。崩溃时可重新拖放加载工程文件。工程文件位置:`material/{ProgectName}/*.bfs` 7. 工程所用到的素材默认会存放至`material/{ProgectName}/audio/`以及`material/{ProgectName}/img/` 8. 可将工程文件拖放入软件加载上一次的工程内容。需要注意的是加载工程要求素材文件夹必须存在! 9. 可将txt格式的文案拖入软件! 10. 可将表情包图片/gif文件拖入软件,用于设置当前字幕的表情包! ## TODO - [x] 优化gif显示 - [x] 表情包尺寸的统一问题 - [x] 编辑保存防止异常退出工作丢失 - [x] 支持修改文案 - [x] 文件名自定义 - [x] 使用的图片与未使用的图片缓存分开,依据文件名归档 - [x] 使用过的配音缓存分类归档 - [x] 支持字幕不设置表情包 - [x] 修复只修改字幕最后成品无效果的bug - [x] 修改单词拼写错误的小问题 - [x] 支持单条字幕分割成多页, 需要分割请在单条字幕分割的地方加上\n - [ ] 自定义背景音乐 - [x] 跳转到n条文案 - [x] 生成视频的过程中主页面卡死问题 - [x] 生成视频显示进度条 - [ ] 下拉到底继续加载图片 - [x] 文案生成 ## Reference [一键生成半佛仙人视频,表情包之王你也可以!](https://www.bilibili.com/video/BV1oz411e7Jk) [MoviePy](https://zulko.github.io/moviepy/) [斗图啦](https://www.doutula.com/article/list/) [百度图片](https://image.baidu.com/) [百度在线语音合成](https://cloud.baidu.com/product/speech/tts_online) [百度飞桨AI studio](https://aistudio.baidu.com/aistudio/index) [百度飞桨NLP](https://paddlenlp.readthedocs.io/zh/latest/) [deepai](https://deepai.org/) ## License [GNU General Public License v3.0](LICENSE) ================================================ FILE: banfoTextSpider.py ================================================ import json import os.path import re from collections.abc import Iterable import requests from config import BANFOMSGURL, BANFOMSGHEADERS def getAllMsgUrl(start: int = 0) -> [Iterable, None]: """ 获取半佛仙人公众号文章. :param start: 起始索引 :return: None """ offset = start # 请将下面两个参数换成自己的!抓包公众号历史消息即可. while True: url = BANFOMSGURL.format(offset) headers = BANFOMSGHEADERS ret = requests.get(url, headers=headers) if ret.status_code != 200: return None data = json.loads(ret.text) if 'general_msg_list' not in data: return None can_msg_continue = data['can_msg_continue'] data = json.loads(data['general_msg_list']) data = data['list'] for msg in data: if 'app_msg_ext_info' not in msg: continue msgUrl = msg['app_msg_ext_info']['content_url'] if len(msgUrl) >= 1: yield msgUrl if can_msg_continue == 1: offset += 10 else: return None def getText(msgUrl: str) -> str: """ 获取公众号单条文章的文本记录 :param msgUrl: :return: """ data = requests.get(msgUrl) if data.status_code != 200: return '' pattern = '

([^(([^<]*?)|

([^<]*?)

' matchs = re.findall(pattern, data.text) ret = '' for match in matchs: ret += match[0].strip() + match[1].strip() + match[2].strip() return ret.replace('半佛仙人', '').replace('看一看入口已关闭', '') if __name__ == '__main__': for index, msgUrl in enumerate(getAllMsgUrl(start=0)): if index < 557: if index < 217 or index > 226: continue ret = getText(msgUrl) if ret == '': continue print(index, msgUrl) print(ret) with open(os.path.join('banfoText', '{}.txt'.format(index)), 'w+', encoding='utf-8') as f: f.write(ret) print('done!') ================================================ FILE: conf.py ================================================ BackgroundMusic = 'backgroundMusic.mp3' DoutulaButton = 0 BaiduButton = 1 MODELNAME = 'gpt-cpm-small-cn-distill' ================================================ FILE: edit.py ================================================ # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'edit.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. import os import sys import time from PyQt5 import QtCore, QtWidgets from PyQt5.QtCore import QThread, pyqtSignal, QObject from system_hotkey import SystemHotkey from generation import getPredictText from utils import getTips class getTipsThread(QThread): """ 获取提示线程类 """ signal = pyqtSignal(str) def __init__(self, mText: str) -> None: """ 初始化获取提示线程类 :param mText: 关键词句 """ super().__init__() self.text = mText def __del__(self): self.wait() def run(self): """ 文本生成 :return: None """ ''' # 使用deepai的文本生成服务 text = getTips(self.text) self.signal.emit(text) ''' text = getPredictText(self.text.replace('\n', ''), length=500) self.signal.emit(text) class Ui_MainWindow(QObject): hotkeySign = pyqtSignal() def __init__(self): super().__init__() self.subThread = None self.fileName = None def setupUi(self, MainWindow): MainWindow.resize(862, 579) self.mainWindow = MainWindow self.centralwidget = QtWidgets.QWidget(MainWindow) # 文案输入&编辑框 self.writingEdit = QtWidgets.QPlainTextEdit(self.centralwidget) self.writingEdit.setGeometry(QtCore.QRect(10, 10, 431, 501)) # 给文案提示加个框框 self.groupBox = QtWidgets.QGroupBox(self.centralwidget) self.groupBox.setGeometry(QtCore.QRect(450, 10, 401, 501)) self.groupBox.setCheckable(False) self.groupBox.setTitle('提示') # 文案提示框框 self.tipsEdit = QtWidgets.QPlainTextEdit(self.groupBox) self.tipsEdit.setGeometry(QtCore.QRect(10, 20, 381, 471)) # 文件名 self.FileNameLabel = QtWidgets.QLabel(self.centralwidget) self.FileNameLabel.setGeometry(QtCore.QRect(10, 520, 101, 31)) self.FileNameLabel.setText('文件路径:') self.fileNameEdit = QtWidgets.QLineEdit(self.centralwidget) self.fileNameEdit.setGeometry(QtCore.QRect(90, 520, 351, 31)) # 三个按钮水平分布 self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget) self.horizontalLayoutWidget.setGeometry(QtCore.QRect(450, 514, 401, 41)) self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.horizontalLayout.setObjectName('horizontalLayout') # 打开 self.openButton = QtWidgets.QPushButton(self.horizontalLayoutWidget) self.openButton.setText('打开') self.openButton.clicked.connect(self.openFile) self.horizontalLayout.addWidget(self.openButton) # 保存 self.saveButton = QtWidgets.QPushButton(self.horizontalLayoutWidget) self.saveButton.setText('保存') self.saveButton.clicked.connect(self.saveFile) self.horizontalLayout.addWidget(self.saveButton) # 提示 self.tipsButton = QtWidgets.QPushButton(self.horizontalLayoutWidget) self.tipsButton.setText('提示') self.tipsButton.clicked.connect(self.tips) self.horizontalLayout.addWidget(self.tipsButton) # 热键 self.hotkeySign.connect(self.tips) self.F1Hotkey = SystemHotkey() self.F1Hotkey.register(['f1'], callback=lambda x: self.hotkeyEvent()) MainWindow.setCentralWidget(self.centralwidget) QtCore.QMetaObject.connectSlotsByName(MainWindow) def hotkeyEvent(self): self.hotkeySign.emit() def msgBox(self, msg: str, hasQuery: bool = False) -> bool: """ :param msg: 消息 :param hasQuery: 是否带询问 :return: 如果hasQuery为True,返回值为用户是否点击了确定 """ if not hasQuery: QtWidgets.QMessageBox.information(self.mainWindow, '提示', msg, QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok) return True reply = QtWidgets.QMessageBox.question(self.mainWindow, '提示', msg, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) return reply == QtWidgets.QMessageBox.Yes def openFile(self) -> None: """ 打开一个文件 :return: None """ fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self.mainWindow, '选择文案', os.path.join(os.getcwd(), 'writing'), 'Text Files (*.txt)') if not os.path.exists(fileName): self.msgBox('未选择文件!') return with open(fileName, 'r+', encoding='UTF-8') as f: data = f.read() self.writingEdit.appendPlainText(data) self.fileName = fileName self.fileNameEdit.setText(fileName) def saveFile(self) -> None: """ 保存文件 :return: None """ fileName = self.fileNameEdit.text() if os.path.sep not in fileName: if fileName == '': self.msgBox('请先设置文件名!') return if len(fileName) <= 4: self.msgBox('文件名非法!') return fileName = os.path.join('writing', fileName) if not os.path.exists('writing'): os.mkdir('writing') self.fileName = fileName with open(fileName, 'w+', encoding='UTF-8') as f: f.write(self.writingEdit.toPlainText()) self.msgBox('文件已保存在{}'.format(fileName)) def tips(self) -> None: text = self.writingEdit.toPlainText() if text == '': return self.tipsEdit.setPlainText('') if self.subThread is not None: self.subThread.terminate() while self.subThread.isRunning() and not self.subThread.isFinished(): time.sleep(0.1) self.subThread = getTipsThread(self.writingEdit.toPlainText()) self.subThread.signal.connect(self.setTips) self.subThread.start() def setTips(self, text: str) -> None: """ 设置提示 :param text: 提示文本 :return: None """ self.tipsEdit.setPlainText(text) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) ================================================ FILE: generation.py ================================================ import paddle import paddlenlp from conf import MODELNAME paddle.set_device('gpu') gptModel = paddlenlp.transformers.GPTModel.from_pretrained('models') gptModel = paddlenlp.transformers.GPTForPretraining(gptModel) gptModel.eval() tokenizer = paddlenlp.transformers.GPTChineseTokenizer.from_pretrained(MODELNAME) def getPredictText(text: str, length: int = 200) -> str: """ 生成半佛风格文本 :param text: 前面部分的文本 :param length: 生成文本长度 :return: 生成的文本 """ encodedText = tokenizer(text=text, return_token_type_ids=False) inputIds = paddle.to_tensor(encodedText['input_ids'], dtype='int64').unsqueeze(0) ids, _ = gptModel.generate(input_ids=inputIds, max_length=length, min_length=32, decode_strategy='sampling') ids = ids[0].numpy().tolist() # 使用tokenizer将生成的id转为文本 generatedText = tokenizer.convert_ids_to_string(ids) return generatedText getPredictText('开始预测模型会先初始化一下, 抵消掉这个时间') ================================================ FILE: main.py ================================================ import logging import math import os.path import pickle import random import shutil import threading import time from PyQt5 import QtWidgets from PyQt5.QtCore import QThread, pyqtSignal from PyQt5.QtGui import QDropEvent, QDragEnterEvent, QStandardItem import mainWindow from PyQt5.QtWidgets import QApplication, QDialog from moviepy.editor import * from conf import BackgroundMusic, BaiduButton, DoutulaButton from utils import getUuid, getBaiDuAudio, getBaiduImgPath, getDoutulaImgPath, resizeImg, convertToRGB class genVideoThread(QThread): """ 生成视频线程类 """ signal = pyqtSignal(str) def __init__(self, sections: list, materialName: str, fileName: str) -> None: """ 初始化几个参数 :param sections: 字幕以及图片信息 :param materialName: 素材路径 :param fileName: 保存视频名称 """ super().__init__() self.sections = sections self.materialName = materialName self.fileName = fileName def __del__(self): self.wait() def run(self): screensize = (800, 600) videoClips = [] for i, section in enumerate(self.sections): imgPath, text = section[0], section[1] if len(text) >= 1: mark = text[-1] if mark == '$': text = text[:-1] text = text.split(r'\\') text = '\\'.join([x.replace(r'\n', '\n') for x in text]) text = text.strip().split('\n') if imgPath is None: imgPath = 'background.png' # gif用到,用于标记当前字幕对应的gif从哪儿开始 index = 0 print(text, imgPath) if imgPath.endswith('.gif'): # 首先计算一下当前所有语音时间长度 clip = VideoFileClip(imgPath) clip = clip.loop() else: convertToRGB(imgPath) clip = ImageClip(imgPath) # 设置一下图片/gif大小 if mark != '$': width, height = clip.size width, height = resizeImg(width, height) clip = clip.resize((width, height)) # 考虑到每张表情包可能对应多句字幕 for txt in text: # 合成语音 txtAudio = getBaiDuAudio(txt, os.path.join(self.materialName, 'audio')) if len(txt) < 12: fontsize = 50 else: fontsize = 40 txtClip = TextClip(txt, color='white', font='STKaiti', kerning=5, fontsize=fontsize, align='South') if txtAudio is None: logging.error('get the audio of {} failed!'.format(txt)) continue txtAudio = AudioFileClip(txtAudio) # 表情包视频与字幕融合 cvc = CompositeVideoClip([clip.set_position(('center', 'center')).subclip(index, txtAudio.duration), txtClip.set_position(('center', 0.85), relative=True)], size=screensize) cvc = cvc.subclip(0, txtAudio.duration) index += txtAudio.duration # 添加配音 cvc = cvc.set_audio(txtAudio) videoClips.append(cvc) self.signal.emit('进度: {}%'.format(math.ceil((i * 80) / len(self.sections)))) finalClip = concatenate_videoclips(videoClips) # 获取原视频声音 audio = finalClip.audio # 整体背景音乐 audioClip = AudioFileClip(BackgroundMusic) if audioClip.duration > finalClip.duration: audioClip = audioClip.subclip(0, audio.duration) elif audioClip.duration < finalClip.duration: audioClip = afx.audio_loop(audioClip, duration=audio.duration) audioClip = afx.volumex(audioClip, factor=0.35) self.signal.emit('进度: {}%'.format(math.ceil(i * 80 / len(self.sections)) + random.randint(5, 15))) # 声音结合起来 audio = CompositeAudioClip([audio, audioClip]) finalClip = finalClip.set_audio(audio) fileName = os.path.join('out', self.fileName) self.signal.emit('进度: {}'.format('处理完成! 正在写出文件...')) finalClip.write_videofile(fileName, fps=25, codec='mpeg4') self.signal.emit(fileName) class addImgThread(QThread): """ 获取网络表情包线程类 """ signal = pyqtSignal(str) def __init__(self, mText: str, mButton: int) -> None: """ 初始化获取网络表情包线程类 :param mText: 搜索关键词 :param mButton: 采用哪个搜索引擎 """ super().__init__() self.text = mText self.button = mButton def __del__(self): self.wait() def run(self): if self.button == BaiduButton: for path in getBaiduImgPath(self.text): self.signal.emit(path) if self.button == DoutulaButton: for path in getDoutulaImgPath(self.text): self.signal.emit(path) class MainDialog(QDialog): def __init__(self, parent=None): super(QDialog, self).__init__(parent) # 当前指向的句子 self.nowPos = None # 获取表情包线程句柄 self.subThread = None # 已经设定好的句子以及表情包,三元组(图片路径, 文案, 时间戳),时间戳一旦生成不再修改,主要用于区分文案并生成对应的图片路径 self.sections = [] # 接收拖放对象 self.setAcceptDrops(True) self.fileName = None self.materialName = None # lock of save and read the bfs file self.lock = threading.Lock() self.ui = mainWindow.Ui_MainWindow() self.ui.setupUi(self) # start save thread self.saveThread = threading.Thread(target=self.save) self.saveThread.start() def save(self) -> None: """ 每隔5秒保存一次工程信息 :return: None """ time.sleep(5) # 窗口存在则一直保存 while self.ui.windowIsVisible(): self.lock.acquire() if len(self.sections) <= 0: self.lock.release() time.sleep(5) continue data = dict() data['nowPos'] = self.nowPos data['sections'] = self.sections data['fileName'] = self.fileName data['materialName'] = self.materialName fileName = os.path.join(self.materialName, self.fileName[:self.fileName.rfind('.')] + '.bfs') with open(fileName, 'wb') as f: pickle.dump(data, f) self.lock.release() time.sleep(5) def dragEnterEvent(self, event: QDragEnterEvent) -> None: """ 拖放事件 :param event: QDragEnterEvent :return: None """ if event.mimeData().hasText(): event.accept() else: event.ignore() def dropEvent(self, event: QDropEvent) -> None: """ 拖放事件,主要处理.bfs工程文件, .txt文案文件, .gif/.png等图片文件 :param event: 拖放对象事件 :return: None """ filePathList = event.mimeData().text() filePath = filePathList.split('\n')[0].replace('file:///', '', 1) # 说明是加载的工程文件 if filePath.endswith('.bfs'): self.loadBfs(filePath) return # 说明加载的是文案文件 if filePath.endswith('.txt'): if self.fileName is None: self.ui.msgBox('请先设置工程目录!') return self.loadText(True, filePath) return # 其他情况应该是加载的图片文件,先判断是不是gif/图片 if not filePath.endswith('.gif'): # 通过加载文件来判断是否为图片,不是则返回 try: ImageClip(filePath) except: return self.loadPic(filePath) def loadBfs(self, filePath: str) -> None: """ 加载工程文件 :param filePath: 工程文件路径 :return: None """ if len(self.sections) > 0: if not self.ui.msgBox('导入工程文件将清空当前工作内容,可能导致部分内容丢失,是否继续?', True): return # 需要在material目录下有对应的文件夹,没有的禁止载入 fileName = os.path.basename(filePath).replace('.bfs', '') if not os.path.exists(os.path.join('material', fileName)): self.ui.msgBox('未找到对应的素材文件夹!') return with open(filePath, 'rb') as f: data = pickle.load(f) self.lock.acquire() self.nowPos = data['nowPos'] self.sections = data['sections'] # 检查资源文件是否都存在 for section in self.sections: if section[0] is not None and not os.path.exists(section[0]): self.nowPos = None self.sections = [] self.ui.msgBox('对应的素材缺失!') self.lock.release() return self.fileName = data['fileName'] self.ui.setFileName(self.fileName) self.materialName = data['materialName'] # 将sections的内容填充到表格 self.ui.delAllRow() for section in self.sections: self.ui.addRow(section[1]) if self.nowPos is not None: self.ui.setSubTileText(self.sections[self.nowPos][1]) self.ui.setSearchText(self.sections[self.nowPos][1]) imgPath = self.sections[self.nowPos][0] if imgPath is None: self.ui.delVideoImg() else: self.ui.changeVideoImg(imgPath) else: self.ui.delVideoImg() self.lock.release() def loadPic(self, imgPath: str) -> None: """ 加载拖放进来的图片文件 :param imgPath: 图片文件路径 :return: None """ if self.nowPos is None: # 没有工程内容则忽略该次拖入文件 self.ui.msgBox('请先设置字幕内容!') return self.ui.changeVideoImg(imgPath) imgBaseName = os.path.basename(imgPath) suffix = imgBaseName[imgBaseName.rfind('.') + 1:] uuid = self.sections[self.nowPos][2] newPath = '{}.{}'.format(uuid, suffix) newPath = os.path.join(os.path.join(self.materialName, 'img'), newPath) shutil.copyfile(imgPath, newPath) # 保存图片与字幕信息 self.sections[self.nowPos] = [newPath, self.ui.getSubtitle(), uuid] self.ui.setRowText(self.nowPos, self.ui.getSubtitle()) def setFilename(self) -> None: """ 设置文件名 :return: None """ # 加锁,禁止保存或者载入工程文件 self.lock.acquire() fileName = self.ui.getFileName() materialName = os.path.join('material', fileName[:fileName.rfind('.')]) # 当前工作区没内容,说明是新建的工程,新建的工程的名字不能和之前重复 if len(self.sections) <= 0 and os.path.exists(materialName): self.ui.msgBox('文件名已存在,请更换名字或加载之前缓存!') self.lock.release() return self.fileName = fileName # 文件名并未更改,可能是未修改或者只修改了后缀名,都可以忽略 if self.materialName == materialName: self.ui.msgBox('设置工程文件夹成功!') self.lock.release() return # 当前工作区无内容,说明是新建的工程,需要新建文件夹 if len(self.sections) <= 0: os.makedirs(os.path.join(materialName, 'audio')) os.makedirs(os.path.join(materialName, 'img')) self.ui.msgBox('新建工程文件夹成功!') else: # 当前工作区有内容,说明工程已经存在,需要对所有数据进行重命名 self.changeFileName(self.materialName, materialName) self.ui.msgBox('重命名工程文件夹成功!') self.materialName = materialName self.lock.release() def changeFileName(self, oldMaterialName: str, materialName: str) -> None: """ 修改了文件名需要对文件夹等全部进行修改 :param oldMaterialName: 旧的素材文件夹名 :param materialName: 新的素材文件夹名 :return: """ # 对sections里面包含的图片信息的地址进行修改 for section in self.sections: if section[0] is None: continue imgBaseName = os.path.basename(section[0]) newPath = os.path.join(os.path.join(materialName, 'img'), imgBaseName) section[0] = newPath # 更改文件夹名字 os.rename(oldMaterialName, materialName) def setSubtitleInfo(self) -> None: """ 设置上一句/下一句对应的字幕以及图片信息 :return: None """ self.ui.setSubTileText(self.sections[self.nowPos][1]) self.ui.setSearchText(self.sections[self.nowPos][1]) # 如果已经设置好了表情包,显示出来;否则就清空 imgPath = self.sections[self.nowPos][0] if imgPath is None: self.ui.delVideoImg() else: self.ui.changeVideoImg(imgPath) def last(self) -> None: """ 上一句,加载上一句字幕与图片 :return: None """ if len(self.sections) <= 0: self.ui.msgBox('当前工作区暂无内容!') return # 计算当前应该到达的光标 if self.nowPos is None: self.nowPos = 1 else: # 保存下一句的字幕信息 self.sections[self.nowPos][1] = self.ui.getSubtitle() self.ui.setRowText(self.nowPos, self.ui.getSubtitle()) self.nowPos = self.nowPos - 1 if self.nowPos > 0 else len(self.sections) - 1 self.setSubtitleInfo() def next(self) -> None: """ 下一句,加载下一句字幕与图片 :return: None """ if len(self.sections) <= 0: self.ui.msgBox('当前工作区暂无内容!') return if self.nowPos is None: self.nowPos = -1 else: # 保存上一句的字幕信息 self.sections[self.nowPos][1] = self.ui.getSubtitle() self.ui.setRowText(self.nowPos, self.ui.getSubtitle()) self.nowPos = self.nowPos + 1 if self.nowPos < len(self.sections) - 1 else 0 self.setSubtitleInfo() def changeThePicText(self, text: str) -> None: """ 视频字幕实时更改 :param text: 字幕信息 :return: None """ if len(self.sections) <= 0: return self.ui.setVideoText(text) self.sections[self.nowPos][1] = text self.ui.setRowText(self.nowPos, text) def previewImg(self, path: str) -> None: """ 将网络表情包加载预览以供选择 :param path: 网络表情包路径 :return: None """ self.ui.addImg(path) def search(self, button: int) -> None: """ 搜索表情包,button代表了不同的搜索引擎 :param button: 来自哪个按钮,代表了不同的搜索引擎 :return: None """ if len(self.sections) <= 0 or self.ui.getSearchText() == '': self.ui.msgBox('工作区暂无内容或未输入搜索文字!') return if self.subThread is not None: self.subThread.terminate() while self.subThread.isRunning() and not self.subThread.isFinished(): time.sleep(0.1) # 清空当前的所有表情包图片 self.ui.delImg() self.subThread = addImgThread(self.ui.getSearchText(), button) self.subThread.signal.connect(self.previewImg) self.subThread.start() def imgClicked(self, index: int) -> None: """ 表情包点击回调函数,将选好的表情包加载到视频预览区 :param index: 选好的表情包索引 :return: None """ if len(self.sections) <= 0: self.ui.msgBox('工作区无内容!') return if self.nowPos is None: self.ui.msgBox('暂未选择文案与字幕!') return imgPath = self.ui.getImgPathByIndex(index) self.ui.changeVideoImg(imgPath) # 将表情包复制到material目录 imgBaseName = os.path.basename(imgPath) suffix = imgBaseName[imgBaseName.rfind('.') + 1:] uuid = self.sections[self.nowPos][2] newPath = '{}.{}'.format(uuid, suffix) newPath = os.path.join(os.path.join(self.materialName, 'img'), newPath) shutil.copyfile(imgPath, newPath) # 保存图片与字幕信息 self.sections[self.nowPos] = [newPath, self.ui.getSubtitle(), uuid] self.ui.setRowText(self.nowPos, self.ui.getSubtitle()) def genVideo(self) -> None: """ 开始生成视频 :return: None """ if len(self.sections) <= 0: self.ui.msgBox('工作区无内容!') return self.setDisabled(True) self.gvt = genVideoThread(self.sections, self.materialName, self.fileName) self.gvt.signal.connect(self.genVideoFinished) self.gvt.start() def genVideoFinished(self, msg: str) -> None: """ 视频生成完成回调函数 :param msg: 生成视频传回的信息。主要有两种,第一是进度,第二是输出的视频的路径 :return: None """ if ': ' in msg: self.ui.setGenVideoText(msg) return self.setDisabled(False) self.ui.setGenVideoText('生成视频') self.ui.msgBox('生成完毕!位置:{}'.format(msg)) def loadText(self, drag=False, fileName: str=None) -> None: """ 文件浏览器回调函数/同时支持拖放导入文案解析 :param drag: 是否是拖放导入的 :param fileName: 拖放进来的文件名 :return: None """ if self.fileName is None: self.ui.msgBox('请先设置工程目录!') return if len(self.sections) > 0 and not self.ui.msgBox('当前导入会覆盖工作区内容,不可撤销!是否继续?', True): return self.ui.delAllRow() if not drag: fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, '选择文案', os.getcwd(), 'Text Files (*.txt)') if not os.path.exists(fileName): self.ui.msgBox('未选择文件!') return with open(fileName, 'r', encoding='utf-8') as f: data = f.read() self.sections = list() for text in data.split('\n'): if text == '': continue text = text.strip() self.ui.addRow(text) self.sections.append([None, text, getUuid()]) self.ui.msgBox('导入完成!') def addFrontText(self) -> None: """ 在当前选中的表格单元前面增加一行空白行 :return: None """ if len(self.sections) <= 0: if self.fileName is not None: index = 0 else: self.ui.msgBox('请设置文件名后再添加!') return else: index = self.ui.getCurrentSelected() if index == -1: self.ui.msgBox('未选中表格!') return if self.nowPos is not None and self.nowPos >= index: self.nowPos += 1 self.ui.insertRow(index) self.sections.insert(index, [None, '', getUuid()]) def addBehindText(self) -> None: """ 在当前选中的表格单元后面增加一行空白行 :return: None """ if len(self.sections) <= 0: if self.fileName is not None: index = -1 else: self.ui.msgBox('请设置文件名后再添加!') return else: index = self.ui.getCurrentSelected() if index == -1: self.ui.msgBox('未选中表格!') return if self.nowPos is not None and self.nowPos > index: self.nowPos += 1 self.ui.insertRow(index + 1) self.sections.insert(index + 1, [None, '', getUuid()]) def delText(self) -> None: """ 删除该行 :return: None """ if len(self.sections) <= 0: self.ui.msgBox('请先创建工程或输入文案!') return index = self.ui.getCurrentSelected() if index == -1: self.ui.msgBox('未选中表格!') return # 如果删除了当前预览位置的文案 if self.nowPos is not None and self.nowPos == index: # 加载下一句文案 self.next() # 如果在当前位置之前删除了一个文案,那么当前位置-1 if self.nowPos is not None and self.nowPos >= index: self.nowPos -= 1 self.ui.delRow(index) del self.sections[index] def exportText(self) -> None: """ 导出文案内容 :return: None """ if len(self.sections) <= 0: self.ui.msgBox('当前工作区没有内容!') return texts = '' for section in self.sections: texts += section[1] + '\n' path = os.path.join(self.materialName, 'work.txt') with open(path, 'w+') as f: f.write(texts) self.ui.msgBox('导出文案成功!位置:{}'.format(path)) def tableItemChange(self, item: QStandardItem) -> None: """ 文案内容被修改时,同步到sections :param item: 被修改的表格item :return: """ if len(self.sections) > item.row(): self.sections[item.row()][1] = item.text() # 如果当前单句字幕正好是修改的单元格部分,则修改的内容同步修改到单句字幕编辑处. 需要排除由于单句字幕修改造成的表格修改的情况 if self.nowPos is not None and self.nowPos == item.row() and self.ui.getSubtitle() != item.text(): self.ui.setSubTileText(item.text()) self.ui.setSearchText(item.text()) def jumpToIndex(self) -> None: """ 跳转到指定的文案 :return: None """ if self.nowPos is not None and self.ui.getCurrentSelected() != -1: # 保存上一句的字幕信息 self.sections[self.nowPos][1] = self.ui.getSubtitle() self.ui.setRowText(self.nowPos, self.ui.getSubtitle()) self.nowPos = self.ui.getCurrentSelected() self.setSubtitleInfo() if __name__ == '__main__': if os.path.exists('tmp'): shutil.rmtree('tmp') os.mkdir('tmp') if not os.path.exists('out'): os.mkdir('out') myapp = QApplication(sys.argv) myDlg = MainDialog() myDlg.show() sys.exit(myapp.exec_()) ================================================ FILE: mainWindow.py ================================================ # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainWindow.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. import math import os.path import shutil import time from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtGui import QMovie, QStandardItemModel, QStandardItem from moviepy.video.VideoClip import ImageClip from moviepy.video.io.VideoFileClip import VideoFileClip from conf import DoutulaButton, BaiduButton from utils import resizeImg class clickedButton(QtWidgets.QPushButton): """ 搜索表情包按钮事件,主要可以区分哪个按钮 """ clicked = QtCore.pyqtSignal(int) def __init__(self, button, parent=None): super(clickedButton, self).__init__(parent) self.button = button def mouseReleaseEvent(self, QMouseEvent): self.clicked.emit(self.button) class clickedLabel(QtWidgets.QLabel): """ 标签类,主要增加了点击事件,用于图片缓存区,用户点击了图片后可知道点击了哪张图 """ clicked = QtCore.pyqtSignal(int) def __init__(self, index: int, parent=None): """ :param index: 图片索引 :param parent: """ super(clickedLabel, self).__init__(parent) self.index = index def mouseReleaseEvent(self, QMouseEvent): self.clicked.emit(self.index) class Ui_MainWindow(object): def __init__(self): # 所有缓存的图片 self.img = [] # 当前视频预览区gif self.gif = None # 当前视频预览区图片 self.videoImg = None def setupUi(self, MainWindow): # 初始设置窗口信息 MainWindow.setObjectName('MainWindow') MainWindow.resize(1890, 702) MainWindow.setLayoutDirection(QtCore.Qt.LeftToRight) MainWindow.setWindowTitle('半佛风格视频生成') self.mainWindow = MainWindow self.centralwidget = QtWidgets.QWidget(MainWindow) # 输入文件名标签 self.fileLabel = QtWidgets.QLabel(self.centralwidget) self.fileLabel.setGeometry(QtCore.QRect(10, 23, 121, 16)) self.fileLabel.setText('导出视频名称: ') # 文件名 self.filenName = QtWidgets.QLineEdit(self.centralwidget) self.filenName.setGeometry(QtCore.QRect(140, 16, 361, 31)) self.filenName.setText('{}.mp4'.format(int(time.time()))) # 输入文件名确定按钮 self.filenameButton = QtWidgets.QPushButton(self.centralwidget) self.filenameButton.setGeometry(QtCore.QRect(501, 16, 60, 31)) self.filenameButton.setText('设置') self.filenameButton.clicked.connect(MainWindow.setFilename) # 给输入框加个分组box self.groupBox = QtWidgets.QGroupBox(self.centralwidget) self.groupBox.setGeometry(QtCore.QRect(0, 53, 561, 618)) self.groupBox.setTitle('在此输入/编辑文案') # 文案以表格的形式展示 self.model = QStandardItemModel(0, 0) self.model.itemChanged.connect(MainWindow.tableItemChange) # 设置水平方向四个头标签文本内容 self.model.setHorizontalHeaderLabels(['文案&字幕']) self.row = 0 self.tableView = QtWidgets.QTableView(self.groupBox) self.tableView.setGeometry(QtCore.QRect(10, 20, 541, 542)) self.tableView.setShowGrid(True) self.tableView.setModel(self.model) self.tableView.horizontalHeader().setStretchLastSection(True) self.tableView.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch) self.tableView.clicked.connect(MainWindow.jumpToIndex) # 打开文案/前增一句/后增一句/删除一句/修改一句/导出文案按钮布局 self.tableButtonWidget = QtWidgets.QWidget(self.groupBox) self.tableButtonWidget.setGeometry(QtCore.QRect(10, 561, 541, 55)) # 水平分布 self.hbox = QtWidgets.QHBoxLayout() self.hbox.setGeometry(QtCore.QRect()) self.hbox.setContentsMargins(0, 0, 0, 0) # 打开文案 self.openText = QtWidgets.QPushButton() self.openText.setText('打开') self.openText.clicked.connect(MainWindow.loadText) self.hbox.addWidget(self.openText) # 在前面增加一句 self.addFrontText = QtWidgets.QPushButton() self.addFrontText.setText('前增一句') self.addFrontText.clicked.connect(MainWindow.addFrontText) self.hbox.addWidget(self.addFrontText) # 在后面增加一句 self.addBehindText = QtWidgets.QPushButton() self.addBehindText.setText('后增一句') self.addBehindText.clicked.connect(MainWindow.addBehindText) self.hbox.addWidget(self.addBehindText) # 删除该句 self.delText = QtWidgets.QPushButton() self.delText.setText('删除该句') self.delText.clicked.connect(MainWindow.delText) self.hbox.addWidget(self.delText) # 导出文案 self.exportText = QtWidgets.QPushButton() self.exportText.setText('导出文案') self.exportText.clicked.connect(MainWindow.exportText) self.hbox.addWidget(self.exportText) self.tableButtonWidget.setLayout(self.hbox) # 单句字幕 self.singleText = QtWidgets.QLineEdit(self.centralwidget) self.singleText.setGeometry(QtCore.QRect(660, 620, 611, 50)) self.singleText.textChanged.connect(MainWindow.changeThePicText) # 搜索框文本 self.searchText = QtWidgets.QLineEdit(self.centralwidget) self.searchText.setGeometry(QtCore.QRect(1360, 17, 421, 41)) # 斗图啦/百度搜索按钮 self.searchDou = clickedButton(DoutulaButton, self.centralwidget) self.searchDou.setGeometry(QtCore.QRect(1785, 17, 45, 41)) self.searchDou.setText('斗图') self.searchDou.clicked.connect(MainWindow.search) self.searchBai = clickedButton(BaiduButton, self.centralwidget) self.searchBai.setGeometry(QtCore.QRect(1834, 17, 45, 41)) self.searchBai.setText('百度') self.searchBai.clicked.connect(MainWindow.search) # 视频背景图 self.videoBackgroud = QtWidgets.QLabel(self.centralwidget) self.videoBackgroud.setGeometry(QtCore.QRect(560, 16, 800, 600)) self.videoBackgroud.setPixmap(QtGui.QPixmap('background.png')) self.videoBackgroud.setScaledContents(True) # 视频字幕 self.addSubtitleLayout() # 上一句按钮 self.last = QtWidgets.QPushButton(self.centralwidget) self.last.setGeometry(QtCore.QRect(560, 620, 101, 51)) self.last.setText('上一句') self.last.clicked.connect(MainWindow.last) # 下一句按钮 self.next = QtWidgets.QPushButton(self.centralwidget) self.next.setGeometry(QtCore.QRect(1270, 620, 91, 51)) self.next.setText('下一句') self.next.clicked.connect(MainWindow.next) # 生成视频按钮 self.genVideo = QtWidgets.QPushButton(self.centralwidget) self.genVideo.setGeometry(QtCore.QRect(1360, 620, 521, 51)) self.genVideo.setText('生成视频') self.genVideo.clicked.connect(MainWindow.genVideo) # 表情包图片位置布局 self.widget = QtWidgets.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(1349, 48, 540, 579)) self.topFiller = QtWidgets.QWidget() self.scroll = QtWidgets.QScrollArea() self.scroll.setWidget(self.topFiller) self.vbox = QtWidgets.QVBoxLayout() self.vbox.addWidget(self.scroll) self.widget.setLayout(self.vbox) QtCore.QMetaObject.connectSlotsByName(MainWindow) def addSubtitleLayout(self) -> None: """ 视频字幕设置布局 :return: """ # 视频字幕 self.videoText = QtWidgets.QLabel(self.centralwidget) self.videoText.setGeometry(QtCore.QRect(560, 526, 801, 51)) # 视频字幕字体颜色 palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.videoText.setPalette(palette) # 视频字幕字体设置 font = QtGui.QFont() font.setFamily('华文楷体') font.setPointSize(20) self.videoText.setFont(font) self.videoText.setTextFormat(QtCore.Qt.PlainText) self.videoText.setScaledContents(False) self.videoText.setAlignment(QtCore.Qt.AlignCenter) self.videoText.setWordWrap(False) def delVideoImg(self) -> None: """ 清空视频预览区图片 :return: None """ if self.videoImg is not None: self.videoImg.deleteLater() self.videoImg = None if self.gif is not None: self.gif.deleteLater() self.gif = None def getResizedOfVideoImg(self, path) -> (int, int): """ 获取路径图片重新调整过的大小 :param path: 图片路径 :return: (width, height) """ try: clip = VideoFileClip(path) except: clip = ImageClip(path) width, height = clip.size return resizeImg(width, height) def changeVideoImg(self, path: str) -> None: """ 加载图片到视频预览区 :param path: 图片路径 :return: None """ # 如果图片不是在tmp目录保存,则转到tmp目录再加载,不然重命名工程会有问题 if not path.startswith('tmp' + os.path.sep): newPath = os.path.join('tmp', os.path.basename(path)) if not os.path.exists(newPath): shutil.copyfile(path, newPath) path = newPath self.delVideoImg() self.videoImg = QtWidgets.QLabel(self.centralwidget) wight, height = self.getResizedOfVideoImg(path) self.videoImg.setGeometry(QtCore.QRect(int(960 - wight / 2), int(316 - height / 2), wight, height)) self.videoImg.setScaledContents(True) self.gif = QMovie(path) self.videoImg.setMovie(self.gif) self.videoImg.setAlignment(QtCore.Qt.AlignCenter) self.gif.start() self.videoImg.show() self.centralwidget.show() def addImg(self, path: str) -> None: """ 给图片缓存区加一张图片 :param path: 图片路径 :return: None """ # 计算图片框位置 row = math.ceil((len(self.img) + 1) / 3) - 1 col = len(self.img) % 3 img_label = clickedLabel(len(self.img), self.topFiller) img_label.setGeometry(QtCore.QRect(1370, 60, 151, 151)) gif = QMovie(path) img_label.setMovie(gif) img_label.setScaledContents(True) gif.start() img_label.move(col * (151 + 10) + 10, row * (151 + 10) + 10) self.img.append((img_label, gif, path)) self.topFiller.setMinimumSize(490, (row + 1) * (151 + 10)) self.scroll.setWidget(self.topFiller) img_label.clicked.connect(self.mainWindow.imgClicked) img_label.show() self.topFiller.show() self.widget.show() def delImg(self) -> None: """ 清空从网络获取的所有的表情包 :return: None """ for imgLabel, gif, _ in self.img: imgLabel.deleteLater() gif.deleteLater() self.img = [] self.widget.show() def getImgPathByIndex(self, index: int) -> str: """ 通过表情包缓存区的索引获取表情包的实际路径 :param index: 表情包缓存区的索引 :return: 表情包的实际位置 """ return self.img[index][2] def addRow(self, text: str) -> None: """ 向表中添加一行新的数据 :param text: :return: """ item = QStandardItem(text) self.model.setItem(self.row, 0, item) self.row += 1 def delRow(self, row: int) -> None: """ 删除一行表中的数据 :param row: 删除索引 :return: """ self.model.removeRow(row) def delAllRow(self) -> None: """ 删除所有行 :return: """ for index in range(self.model.rowCount())[::-1]: self.delRow(index) def msgBox(self, msg: str, hasQuery: bool = False) -> bool: """ :param msg: 消息 :param hasQuery: 是否带询问 :return: 如果hasQuery为True,返回值为用户是否点击了确定 """ if not hasQuery: QtWidgets.QMessageBox.information(self.mainWindow, '提示', msg, QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok) return True reply = QtWidgets.QMessageBox.question(self.mainWindow, '提示', msg, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel) return reply == QtWidgets.QMessageBox.Yes def getCurrentSelected(self) -> int: """ 获取当前选中的表格单元索引 :return: 前选中的表格单元索引 """ selectedIndex = self.tableView.selectedIndexes() if len(selectedIndex) > 0: return selectedIndex[0].row() return -1 def insertRow(self, index: int) -> None: """ 增加一行空白行 :index: 增加的位置索引 :return: None """ self.model.insertRow(index) def getSubtitle(self) -> str: """ 获取当前编辑的字幕信息 :return: 前编辑的字幕 """ return self.singleText.text() def getSearchText(self) -> str: """ 获取搜索框文本信息 :return: 搜索框文本信息 """ return self.searchText.text() def setVideoText(self, text: str) -> None: """ 设置视频预览区字幕信息 :param text: 字幕信息 :return: None """ self.videoText.setText(text) def setFileName(self, fileName: str) -> None: """ 设置文件名 :param fileName: 文件名 :return: None """ self.filenName.setText(fileName) def windowIsVisible(self) -> bool: """ 当前窗口是否可见,即是否被关闭 :return: 返回当前窗口是否可见,即是否被关闭 """ return self.centralwidget.isVisible() def setSubTileText(self, text: str) -> None: """ 设置字幕编辑框内容 :param text: 字幕 :return: None """ self.singleText.setText(text) self.singleText.home(False) def setSearchText(self, text: str) -> None: """ 设置搜索框内容 :param text: 搜索文字 :return: None """ self.searchText.setText(text) self.searchText.home(False) def getFileName(self) -> str: """ 获取文件名 :return: 文件名 """ return self.filenName.text() def setRowText(self, row: int, text: str) -> None: """ 设置某一行的文案信息 :param row: 行索引 :param text: 文本 :return: """ item = self.model.item(row, 0) if item is not None: item.setText(text) def subtitleHasFocus(self) -> bool: """ 单句字幕编辑框是否有焦点 :return: 单句字幕编辑框是否有焦点 """ return self.singleText.hasFocus() def setGenVideoText(self, text: str) -> None: """ 设置生成视频按钮的文本 :param text: 文本 :return: None """ self.genVideo.setText(text) ================================================ FILE: preprocess.py ================================================ import os import pickle import paddlenlp # 加载tokeniezer from conf import MODELNAME tokenizer = paddlenlp.transformers.GPTChineseTokenizer.from_pretrained(MODELNAME) trainData = [] # 处理所有的公众号文章 for index, path in enumerate(os.listdir('banfoText')): if not path.endswith('.txt'): continue print(index, path) with open(os.path.join('banfoText', path), 'r+', encoding='utf-8') as f: data = f.read() data = tokenizer(text=data, return_token_type_ids=False) data = data['input_ids'] start = -30 lenght = 100 step = 30 if len(data) <= 2 * lenght: continue # 滑动窗口截断获取inputData和label while start + step + 1 < len(data) and start + step + lenght + 1 < len(data): start = start + step input_data = data[start: start + lenght] label = data[start + 1: start + lenght + 1] trainData.append([input_data, label]) trainData.append([data[-lenght-1: -1], data[-lenght:]]) if not os.path.exists('preprocessData'): os.mkdir('preprocessData') with open(os.path.join('preprocessData', 'trainData.pkl'), 'wb') as f: pickle.dump(trainData, f) print(len(trainData)) print('done!') ================================================ FILE: requirements.txt ================================================ moviepy==1.0.3 requests~=2.24.0 numpy==1.21.2 beautifulsoup4==4.10.0 PyQt5==5.15.4 system_hotkey==1.0.3 Flask~=2.0.2 bs4~=0.0.1 Pillow~=8.3.2 piexif~=1.1.3 googletrans~=3.0.0 paddlepaddle-gpu==2.1.3.post110 paddlenlp~=2.1.0 ================================================ FILE: train.py ================================================ import os import pickle import paddle import paddlenlp from paddle.io import Dataset, DataLoader import paddle.nn as nn from conf import MODELNAME class BanfoDataset(Dataset): def __init__(self, data, tokenizer): super().__init__() self.data = data self.tokenizer = tokenizer def __getitem__(self, idx): return paddle.to_tensor(self.data[idx][0], dtype='int64'), paddle.to_tensor(self.data[idx][1], dtype='int64') def __len__(self): return len(self.data) if not os.path.exists('models'): os.mkdir('models') paddle.set_device('gpu') gptModel = paddlenlp.transformers.GPTModel.from_pretrained(MODELNAME) gptModel = paddlenlp.transformers.GPTForPretraining(gptModel) tokenizer = paddlenlp.transformers.GPTChineseTokenizer.from_pretrained(MODELNAME) # 有本地模型存在,则加载本地模型 checkpoint = os.path.join('models', 'model_state.pdparams') if os.path.exists(checkpoint): model_state = paddle.load(checkpoint) gptModel.set_state_dict(model_state) # 设置为评估模型 gptModel.eval() # 测试效果 encodedText = tokenizer(text='前段时间我跟一个老大哥一起吃火锅。大哥的孩子,都上学了', return_token_type_ids=False) ids, _ = gptModel.generate(input_ids=paddle.to_tensor(encodedText['input_ids'], dtype='int64').unsqueeze(0), max_length=16, min_length=1, decode_strategy='sampling') ids = ids[0].numpy().tolist() # 使用tokenizer将生成的id转为文本 text = tokenizer.convert_ids_to_string(ids) print('generation text is {}'.format(text)) # 加载训练数据 with open(os.path.join('preprocessData', 'trainData.pkl'), 'rb') as f: data = pickle.load(f) trainDataLoader = DataLoader(dataset=BanfoDataset(data, tokenizer), batch_size=64, shuffle=True, return_list=True) numEpochs = 100 learningRate = 2e-5 warmupProportion = 0.1 weightDecay = 0.1 maxSteps = (len(trainDataLoader) * numEpochs) lr_scheduler = paddle.optimizer.lr.LambdaDecay(learningRate, lambda currentStep, numWarmupSteps=maxSteps * warmupProportion, numTrainingSteps=maxSteps: float(currentStep) / float(max(1, numWarmupSteps)) if currentStep < numWarmupSteps else max(0.0, float(numTrainingSteps - currentStep) / float(max(1, numTrainingSteps - numWarmupSteps)))) optimizer = paddle.optimizer.AdamW(learning_rate=lr_scheduler, parameters=gptModel.parameters(), weight_decay=weightDecay, grad_clip=nn.ClipGradByGlobalNorm(1.0), apply_decay_param_fun=lambda x: x in [ p.name for n, p in gptModel.named_parameters() if not any(nd in n for nd in ["bias", "norm"]) ]) globalStep = 1 save_steps = 100 criterion = paddle.nn.loss.CrossEntropyLoss() gptModel.train() for epoch in range(numEpochs): for step, batch in enumerate(trainDataLoader, start=1): ids, label = batch logits, _ = gptModel.forward(ids, use_cache=True) loss = criterion(logits, label) loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_gradients() if globalStep % save_steps == 0: print(globalStep, loss.numpy()) gptModel.save_pretrained('models') globalStep += 1 ================================================ FILE: utils.py ================================================ import base64 import hashlib import json import os import random from collections.abc import Iterable from urllib.parse import quote import piexif import requests from PIL import Image from bs4 import BeautifulSoup from config import APIKEY, BAIDUAPPID, BAIDUAPPKEY proxies = None verify = True def getUuid() -> str: """ 生成一个uuid :return: uuid """ return str(random.randint(1, 999999)).zfill(6) def getBaiDuAudio(text: str, filePath: str) -> [str, None]: """ 利用百度语音合成将文字合成语音 :param text: 合成语音的文字 :param filePath: 文件保存路径 :return: 文件路径或者None """ # 生成文件名 md5 = hashlib.md5() md5.update(text.encode('utf-8')) fileName = md5.hexdigest() + '.mp3' fileName = os.path.join(filePath, fileName) # 文件已经存在的话直接返回 if os.path.exists(fileName): return fileName url = 'https://cloud.baidu.com/aidemo' data = 'type=tns&per=4105&spd=8&pit=7&vol=5&aue=6&tex=' + quote(text) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*/*', 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7' } res = requests.post(url, data=data, headers=headers, verify=False) if res.status_code != 200: return None res = json.loads(res.text) if res['msg'] != 'success': return None data = res['data'].replace('data:audio/x-mpeg;base64,', '') if ',' in data: data = data[:data.find(',')] data = base64.b64decode(data) with open(fileName, 'wb') as f: f.write(data) return fileName def decodeBaiduImg(objUrl: str) -> str: """ 百度图片地址解码函数 :param objUrl: 编码的url :return: 解码的url """ res = '' c = ['_z2C$q', '_z&e3B', 'AzdH3F'] d = {'w': 'a', 'k': 'b', 'v': 'c', '1': 'd', 'j': 'e', 'u': 'f', '2': 'g', 'i': 'h', 't': 'i', '3': 'j', 'h': 'k', 's': 'l', '4': 'm', 'g': 'n', '5': 'o', 'r': 'p', 'q': 'q', '6': 'r', 'f': 's', 'p': 't', '7': 'u', 'e': 'v', 'o': 'w', '8': '1', 'd': '2', 'n': '3', '9': '4', 'c': '5', 'm': '6', '0': '7', 'b': '8', 'l': '9', 'a': '0', '_z2C$q': ':', '_z&e3B': '.', 'AzdH3F': '/'} for m in c: objUrl = objUrl.replace(m, d[m]) for char in objUrl: char = d[char] if char in d else char res = res + char return res def getBaiduImgPath(text: str) -> [Iterable, None]: """ 从百度图片接口拉取图片 :param text: 搜索关键字 :return: 图片路径迭代器或者None """ url = 'https://image.baidu.com/search/acjson?tn=resultjson_com&logid=8763701186511659178&ipn=rj&ct=201326592&is=' \ '&fp=result&queryWord={0}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=©right=&word={0}' \ '&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&nojc=&acjsonfr=click&pn=0&rn=30&itg=1' \ '&gsm=3c&1634043752626=' url = url.format(text) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'} res = requests.get(url, headers=headers, verify=False) if res.status_code != 200: return None try: jsonData = json.loads(res.text) except: return None if 'data' not in jsonData: return None data = jsonData['data'] for img in data: imgUrl = '' if 'objURL' in img: imgUrl = decodeBaiduImg(img['objURL']) elif 'middleURL' in img: imgUrl = img['middleURL'] elif 'thumbURL' in img: imgUrl = img['thumbURL'] elif imgUrl == '': return None if 'is_gif' in img and img['is_gif'] == 1: is_gif = 1 else: is_gif = 0 res = requests.get(imgUrl) if res.status_code != 200: continue md5 = hashlib.md5() md5.update(res.content) fileName = md5.hexdigest() + '.gif' if is_gif else md5.hexdigest() + '.png' path = os.path.join('tmp', fileName) with open(path, 'wb') as f: f.write(res.content) yield path def getDoutulaImgPath(text: str) -> [Iterable, None]: """ 从斗图啦表情包接口拉取图片 :param text: 搜索关键字 :return: 图片路径迭代器或者None """ url = 'https://www.doutula.com/search?keyword=' + text headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'} res = requests.get(url, headers=headers) if res.status_code != 200: return None soup = BeautifulSoup(res.text, 'html.parser') randomPics = soup.find_all('a', attrs={'class': 'col-xs-6 col-md-2'}) for pic in randomPics: imgUrl = pic.find('img', attrs={'referrerpolicy': 'no-referrer'})['data-original'] try: res = requests.get(imgUrl) except: return None if res.status_code != 200: continue path = os.path.join('tmp', imgUrl[imgUrl.rfind('/') + 1:]) with open(path, 'wb') as f: f.write(res.content) yield path def resizeImg(width: int, height: int) -> (int, int): """ 重新设置图片大小 :param width: 图片宽度 :param height: 图片高度 :return: (width, height) """ default_width, default_height = 440, 360 if (width < default_width and height < default_height) or (width > default_width and height > default_height): # 如果比例大于1.5,就不强制拉伸,按照宽度进行缩放 if width / height >= 1.5: width, height = default_width, height * default_width / width elif height / width > 1.5: height, width = default_height, width * default_height / height else: # 小于1.5的强制拉伸 width, height = default_width, default_height elif width > default_width and height <= default_height: width, height = default_width, height * default_width / width if height > default_height and width <= default_width: height, width = default_height, width * default_height / height return width, height def convertToRGB(path: str) -> None: """ 如果图片不是RGB模式,则转换成RGB模式,否则生成视频会出错 :param path: 图片路径 :return: None """ # convert to RGB im = Image.open(path) if im.mode != 'RGB': im = im.convert('RGB') # 获取exif是否正常,不正常则添加 try: im.getexif() im.save(path) except: exif_dict = {} exif_dat = piexif.dump(exif_dict) im.save(path, exif=exif_dat) def baiduTranslate(text: str, zhcn2en: bool = True) -> str: """ 将中文翻译成英文 :param text: 中文/英文 :param zhcn2en : 是否为中文转英文, 默认为是 :return: 英文/中文 """ url = 'https://fanyi-api.baidu.com/api/trans/vip/translate' headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = BAIDUAPPID + text + url + BAIDUAPPKEY md5 = hashlib.md5() md5.update(data.encode('utf-8')) if zhcn2en: data = {'appid': BAIDUAPPID, 'q': text, 'from': 'zh', 'to': 'en', 'salt': url, 'sign': md5.hexdigest()} else: data = {'appid': BAIDUAPPID, 'q': text, 'from': 'en', 'to': 'zh', 'salt': url, 'sign': md5.hexdigest()} res = requests.post(url, data=data, headers=headers) if res.status_code != 200: return '' res = json.loads(res.text) if 'trans_result' not in res: return '' result = '' for trans in res['trans_result']: result += trans['dst'] + '。' return result # TODO # 有点儿问题, 翻译的结果为多行的时候解决比较麻烦 def googleTranslate(text: str, zhcn2en: bool = True) -> str: """ 将中文翻译成英文 :param text: 中文/英文 :param zhcn2en : 是否为中文转英文, 默认为是 :return: 英文/中文 """ global proxies global verify text = text.replace('\n', r'\\n').replace('"', r'\\\"') url = 'https://translate.google.cn/_/TranslateWebserverUi/data/batchexecute' if zhcn2en: data = '[[["MkEWBc","[[\\"{}\\",\\"zh-CN\\",\\"en\\",true],[null]]",null,"generic"]]]'.format(text) else: data = '[[["MkEWBc","[[\\"{}\\",\\"en\\",\\"zh-CN\\",true],[null]]",null,"generic"]]]'.format(text) data = quote(data) data = 'f.req=' + data + '&' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'} res = requests.post(url=url, data=data, headers=headers, verify=verify, proxies=proxies) if res.status_code != 200: return '' lIndex = res.text.find('l,[[\\"') rIndex = res.text.find('\\"', lIndex + len('l,[[\\"')) if lIndex != -1 and rIndex != -1: text = res.text[lIndex + len('l,[[\\"'):rIndex] text = text.replace(r'\\n', '\n').replace(r'\\\"', '"') return text return '' def getTips(text: str) -> str: """ 获取指定文本的生成文本信息 :param text: 线索文本 :return: 生成的文本 """ global proxies global verify # 中文 -> 英文 text = baiduTranslate(text) if text == '': return '' # 获取生成文本结果 url = 'https://api.deepai.org/api/text-generator' data = {'text': text} headers = {'api-key': APIKEY} res = requests.post(url, files=data, headers=headers, verify=verify, proxies=proxies) if res.status_code != 200: return '' res = json.loads(res.text) if 'output' not in res: return '' text = res['output'] # 英文 -> 中文 text = baiduTranslate(text, zhcn2en=False).replace('\n\n', '\n') return text def setProxies(switch: bool=False) -> None: """ 是否采用代理 :param switch: 是 :return: None """ global proxies global verify if switch: proxies = {'https': '127.0.0.1:8887', 'http': '127.0.0.1:8887'} verify = False else: proxies = None verify = True