[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# 半佛视频风格生成器\n\n视频地址: [看我如何克隆半佛仙人，批量产出视频！](https://www.bilibili.com/video/BV12v411u7kw)\n## 项目背景\n半佛在2020年凭借众多沙雕表情包视频 + 魔性的文案迅速出圈。正如上一句所说，一个优秀的视频需要两部分组成，优秀的文案以及优秀的视频。那么半佛的成功是否可以复制呢？我认为在一定程度上是可以复制的。那么具体应该如何复制呢？我们尝试分析一下：\n\n### 优秀的文案\n半佛仙人的文案普遍比较nice，直接分析视频的文案似乎有点儿难度。好在半佛仙人还有微信公众号，直接学习微信公众号的写作风格是一个不错的选择，但是需要我们付出比较多的时间成本，并且学习效果不够直观。有没有什么更省事更直观效果更nice的方法呢？有。得益于GPT2模型强大的文本生成能力，我们也可以借助该模型训练一个半佛仙人风格文章生成器。\n### 优秀的视频\n直观上来说视频的生成似乎要简单一些，事实上确实如此。半佛仙人的视频大部分是由相关性不是很强的表情包堆砌起来，我们不可能有大量精力来寻找下载一个个导入视频制作软件并设置字幕。有没有什么自动化的方法？有。搞一个图片搜索接口，不妨我们自定义一个视频制作软件。\n\n**理论存在，实践开始。**\n\n## 思路：\n我们再来详细复习一下思路，理清一下我们要做的每一件事情。\n### 文案生成\n直接生成大篇幅文案似乎不太现实，因为就目前来看，GPT2模型逻辑性不够强，上下文能力也有待提高，雪上加霜的是我们的电脑性能也不太行，只能采用GPT2蒸馏过后的模型，效果进一步下降，因此我们可以做一个文案提示器。当我们撰写文案的时候，轻松一按，即可生成相应的下文提示，这个思路是没有任何问题的。\n1. 爬取半佛仙人微信公众号历史文章\n2. 此处我们思考了一下框架的选择。不是很想在本地训练，目前体验以及部署最快的方案应该属于百度的AI Studio了。正好百度paddlenlp提供了中文GPT2预训练模型，因此我们就利用AI studio对GPT2Chinese预训练模型进行微调。\n3. 数据集预处理。既然要微调自然需要预处理，由于只爬取到800+文章，为了扩大数据量，我们将滑动窗口设置的小一些。\n4. 直接开整训练，数据不是很多的情况下，并不需要训练太久。百度每天8个小时免费GPU，训练几天也就ok了。\n5. 写一个小小的窗口。\n\n### 视频生成\n1. 输入断句后的文案\n2. 将文案根据短句分割，每句作为一条字幕\n3. 根据字幕搜索表情包并选择设置\n4. 利用语音合成手段合成配音\n5. 重复3、4步骤，直到所有的字幕均完成表情包设定、字幕设定、配音设定\n6. 合成视频并加入背景音乐\n7. 导出成品\n\n## 安装\n1. 安装python3.8.3\n2. 安装requirements.txt依赖\n3. 运行`python main.py`\n4. 运行`edit.py`请先按照百度paddlepaddle安装教程安装相应的库\n\n## 使用\n\n### 文案生成\n1. 输入文件名或拖入文件\n2. 输入文案\n3. 按F1或者点击提示获取提示\n4. 导出文案\n5. 需要注意的是，导出文案需手动逐句分割\n\n### 视频生成\n1. 确定文件名，点击设置按钮可以新建工程。\n2. 可以拖入txt格式的文案或者直接拖入软件内，或者直接增加文案。\n3. 点击上一句以及下一句文案，预览区可预览字幕，搜索区可搜索相关图片/表情包。\n4. 预览字幕时，若需要将一句话分为两页，则应用\\n分开。\n5. 所有字幕均设置完毕可进行生成视频。\n6. 软件每5秒保存一次工程文件。崩溃时可重新拖放加载工程文件。工程文件位置：`material/{ProgectName}/*.bfs`\n7. 工程所用到的素材默认会存放至`material/{ProgectName}/audio/`以及`material/{ProgectName}/img/`\n8. 可将工程文件拖放入软件加载上一次的工程内容。需要注意的是加载工程要求素材文件夹必须存在！\n9. 可将txt格式的文案拖入软件！\n10. 可将表情包图片/gif文件拖入软件，用于设置当前字幕的表情包！\n\n## TODO\n- [x] 优化gif显示\n- [x] 表情包尺寸的统一问题\n- [x] 编辑保存防止异常退出工作丢失\n- [x] 支持修改文案\n- [x] 文件名自定义\n- [x] 使用的图片与未使用的图片缓存分开，依据文件名归档\n- [x] 使用过的配音缓存分类归档\n- [x] 支持字幕不设置表情包\n- [x] 修复只修改字幕最后成品无效果的bug\n- [x] 修改单词拼写错误的小问题\n- [x] 支持单条字幕分割成多页, 需要分割请在单条字幕分割的地方加上\\n\n- [ ] 自定义背景音乐\n- [x] 跳转到n条文案\n- [x] 生成视频的过程中主页面卡死问题\n- [x] 生成视频显示进度条\n- [ ] 下拉到底继续加载图片\n- [x] 文案生成\n\n## Reference\n[一键生成半佛仙人视频，表情包之王你也可以！](https://www.bilibili.com/video/BV1oz411e7Jk)\n\n[MoviePy](https://zulko.github.io/moviepy/)\n\n[斗图啦](https://www.doutula.com/article/list/)\n\n[百度图片](https://image.baidu.com/)\n\n[百度在线语音合成](https://cloud.baidu.com/product/speech/tts_online)\n\n[百度飞桨AI studio](https://aistudio.baidu.com/aistudio/index)\n\n[百度飞桨NLP](https://paddlenlp.readthedocs.io/zh/latest/)\n\n[deepai](https://deepai.org/)\n\n## License\n[GNU General Public License v3.0](LICENSE)"
  },
  {
    "path": "banfoTextSpider.py",
    "content": "import json\nimport os.path\nimport re\nfrom collections.abc import Iterable\n\nimport requests\n\nfrom config import BANFOMSGURL, BANFOMSGHEADERS\n\n\ndef getAllMsgUrl(start: int = 0) -> [Iterable, None]:\n    \"\"\"\n    获取半佛仙人公众号文章.\n    :param start: 起始索引\n    :return: None\n    \"\"\"\n    offset = start\n    # 请将下面两个参数换成自己的!抓包公众号历史消息即可.\n    while True:\n        url = BANFOMSGURL.format(offset)\n        headers = BANFOMSGHEADERS\n        ret = requests.get(url, headers=headers)\n        if ret.status_code != 200:\n            return None\n        data = json.loads(ret.text)\n        if 'general_msg_list' not in data:\n            return None\n        can_msg_continue = data['can_msg_continue']\n        data = json.loads(data['general_msg_list'])\n        data = data['list']\n        for msg in data:\n            if 'app_msg_ext_info' not in msg:\n                continue\n            msgUrl = msg['app_msg_ext_info']['content_url']\n            if len(msgUrl) >= 1:\n                yield msgUrl\n        if can_msg_continue == 1:\n            offset += 10\n        else:\n            return None\n\n\ndef getText(msgUrl: str) -> str:\n    \"\"\"\n    获取公众号单条文章的文本记录\n    :param msgUrl:\n    :return:\n    \"\"\"\n    data = requests.get(msgUrl)\n    if data.status_code != 200:\n        return ''\n    pattern = '<p style=\"[^<]*?\">([^(<b)]+?)<|strong[^<]*?>([^<]*?)</strong>|<p>([^<]*?)</p>'\n    matchs = re.findall(pattern, data.text)\n    ret = ''\n    for match in matchs:\n        ret += match[0].strip() + match[1].strip() + match[2].strip()\n    return ret.replace('半佛仙人', '').replace('看一看入口已关闭', '')\n\n\nif __name__ == '__main__':\n    for index, msgUrl in enumerate(getAllMsgUrl(start=0)):\n        if index < 557:\n            if index < 217 or index > 226:\n                continue\n        ret = getText(msgUrl)\n        if ret == '':\n            continue\n        print(index, msgUrl)\n        print(ret)\n        with open(os.path.join('banfoText', '{}.txt'.format(index)), 'w+', encoding='utf-8') as f:\n            f.write(ret)\n    print('done!')\n"
  },
  {
    "path": "conf.py",
    "content": "BackgroundMusic = 'backgroundMusic.mp3'\nDoutulaButton = 0\nBaiduButton = 1\nMODELNAME = 'gpt-cpm-small-cn-distill'\n"
  },
  {
    "path": "edit.py",
    "content": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'edit.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.4\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again.  Do not edit this file unless you know what you are doing.\nimport os\nimport sys\nimport time\n\nfrom PyQt5 import QtCore, QtWidgets\nfrom PyQt5.QtCore import QThread, pyqtSignal, QObject\nfrom system_hotkey import SystemHotkey\n\nfrom generation import getPredictText\nfrom utils import getTips\n\n\nclass getTipsThread(QThread):\n    \"\"\"\n    获取提示线程类\n    \"\"\"\n    signal = pyqtSignal(str)\n\n    def __init__(self, mText: str) -> None:\n        \"\"\"\n        初始化获取提示线程类\n        :param mText: 关键词句\n        \"\"\"\n        super().__init__()\n        self.text = mText\n\n    def __del__(self):\n        self.wait()\n\n    def run(self):\n        \"\"\"\n        文本生成\n        :return: None\n        \"\"\"\n\n        '''\n        # 使用deepai的文本生成服务\n        text = getTips(self.text)\n        self.signal.emit(text)\n        '''\n\n        text = getPredictText(self.text.replace('\\n', ''), length=500)\n        self.signal.emit(text)\n\n\n\nclass Ui_MainWindow(QObject):\n\n    hotkeySign = pyqtSignal()\n\n    def __init__(self):\n        super().__init__()\n        self.subThread = None\n        self.fileName = None\n\n    def setupUi(self, MainWindow):\n        MainWindow.resize(862, 579)\n        self.mainWindow = MainWindow\n        self.centralwidget = QtWidgets.QWidget(MainWindow)\n\n        # 文案输入&编辑框\n        self.writingEdit = QtWidgets.QPlainTextEdit(self.centralwidget)\n        self.writingEdit.setGeometry(QtCore.QRect(10, 10, 431, 501))\n\n        # 给文案提示加个框框\n        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)\n        self.groupBox.setGeometry(QtCore.QRect(450, 10, 401, 501))\n        self.groupBox.setCheckable(False)\n        self.groupBox.setTitle('提示')\n\n        # 文案提示框框\n        self.tipsEdit = QtWidgets.QPlainTextEdit(self.groupBox)\n        self.tipsEdit.setGeometry(QtCore.QRect(10, 20, 381, 471))\n\n        # 文件名\n        self.FileNameLabel = QtWidgets.QLabel(self.centralwidget)\n        self.FileNameLabel.setGeometry(QtCore.QRect(10, 520, 101, 31))\n        self.FileNameLabel.setText('文件路径:')\n        self.fileNameEdit = QtWidgets.QLineEdit(self.centralwidget)\n        self.fileNameEdit.setGeometry(QtCore.QRect(90, 520, 351, 31))\n\n        # 三个按钮水平分布\n        self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget)\n        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(450, 514, 401, 41))\n        self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)\n        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n        self.horizontalLayout.setObjectName('horizontalLayout')\n\n        # 打开\n        self.openButton = QtWidgets.QPushButton(self.horizontalLayoutWidget)\n        self.openButton.setText('打开')\n        self.openButton.clicked.connect(self.openFile)\n        self.horizontalLayout.addWidget(self.openButton)\n\n        # 保存\n        self.saveButton = QtWidgets.QPushButton(self.horizontalLayoutWidget)\n        self.saveButton.setText('保存')\n        self.saveButton.clicked.connect(self.saveFile)\n        self.horizontalLayout.addWidget(self.saveButton)\n\n        # 提示\n        self.tipsButton = QtWidgets.QPushButton(self.horizontalLayoutWidget)\n        self.tipsButton.setText('提示')\n        self.tipsButton.clicked.connect(self.tips)\n        self.horizontalLayout.addWidget(self.tipsButton)\n\n        # 热键\n        self.hotkeySign.connect(self.tips)\n        self.F1Hotkey = SystemHotkey()\n        self.F1Hotkey.register(['f1'], callback=lambda x: self.hotkeyEvent())\n\n        MainWindow.setCentralWidget(self.centralwidget)\n        QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n    def hotkeyEvent(self):\n        self.hotkeySign.emit()\n\n    def msgBox(self, msg: str, hasQuery: bool = False) -> bool:\n        \"\"\"\n        :param msg: 消息\n        :param hasQuery: 是否带询问\n        :return: 如果hasQuery为True,返回值为用户是否点击了确定\n        \"\"\"\n        if not hasQuery:\n            QtWidgets.QMessageBox.information(self.mainWindow, '提示', msg, QtWidgets.QMessageBox.Ok,\n                                              QtWidgets.QMessageBox.Ok)\n            return True\n        reply = QtWidgets.QMessageBox.question(self.mainWindow, '提示', msg,\n                                               QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel,\n                                               QtWidgets.QMessageBox.Cancel)\n        return reply == QtWidgets.QMessageBox.Yes\n\n    def openFile(self) -> None:\n        \"\"\"\n        打开一个文件\n        :return: None\n        \"\"\"\n        fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self.mainWindow, '选择文案', os.path.join(os.getcwd(), 'writing'), 'Text Files (*.txt)')\n        if not os.path.exists(fileName):\n            self.msgBox('未选择文件!')\n            return\n        with open(fileName, 'r+', encoding='UTF-8') as f:\n            data = f.read()\n        self.writingEdit.appendPlainText(data)\n        self.fileName = fileName\n        self.fileNameEdit.setText(fileName)\n\n    def saveFile(self) -> None:\n        \"\"\"\n        保存文件\n        :return: None\n        \"\"\"\n        fileName = self.fileNameEdit.text()\n        if os.path.sep not in fileName:\n            if fileName == '':\n                self.msgBox('请先设置文件名!')\n                return\n            if len(fileName) <= 4:\n                self.msgBox('文件名非法!')\n                return\n            fileName = os.path.join('writing', fileName)\n            if not os.path.exists('writing'):\n                os.mkdir('writing')\n        self.fileName = fileName\n        with open(fileName, 'w+', encoding='UTF-8') as f:\n            f.write(self.writingEdit.toPlainText())\n        self.msgBox('文件已保存在{}'.format(fileName))\n\n    def tips(self) -> None:\n        text = self.writingEdit.toPlainText()\n        if text == '':\n            return\n        self.tipsEdit.setPlainText('')\n        if self.subThread is not None:\n            self.subThread.terminate()\n            while self.subThread.isRunning() and not self.subThread.isFinished():\n                time.sleep(0.1)\n        self.subThread = getTipsThread(self.writingEdit.toPlainText())\n        self.subThread.signal.connect(self.setTips)\n        self.subThread.start()\n\n    def setTips(self, text: str) -> None:\n        \"\"\"\n        设置提示\n        :param text: 提示文本\n        :return: None\n        \"\"\"\n        self.tipsEdit.setPlainText(text)\n\n\nif __name__ == \"__main__\":\n    app = QtWidgets.QApplication(sys.argv)\n    MainWindow = QtWidgets.QMainWindow()\n    ui = Ui_MainWindow()\n    ui.setupUi(MainWindow)\n    MainWindow.show()\n    sys.exit(app.exec_())\n"
  },
  {
    "path": "generation.py",
    "content": "import paddle\nimport paddlenlp\n\nfrom conf import MODELNAME\n\npaddle.set_device('gpu')\ngptModel = paddlenlp.transformers.GPTModel.from_pretrained('models')\ngptModel = paddlenlp.transformers.GPTForPretraining(gptModel)\ngptModel.eval()\ntokenizer = paddlenlp.transformers.GPTChineseTokenizer.from_pretrained(MODELNAME)\n\n\ndef getPredictText(text: str, length: int = 200) -> str:\n    \"\"\"\n    生成半佛风格文本\n    :param text: 前面部分的文本\n    :param length: 生成文本长度\n    :return: 生成的文本\n    \"\"\"\n    encodedText = tokenizer(text=text, return_token_type_ids=False)\n    inputIds = paddle.to_tensor(encodedText['input_ids'], dtype='int64').unsqueeze(0)\n    ids, _ = gptModel.generate(input_ids=inputIds, max_length=length, min_length=32, decode_strategy='sampling')\n    ids = ids[0].numpy().tolist()\n    # 使用tokenizer将生成的id转为文本\n    generatedText = tokenizer.convert_ids_to_string(ids)\n    return generatedText\n\n\ngetPredictText('开始预测模型会先初始化一下, 抵消掉这个时间')\n\n"
  },
  {
    "path": "main.py",
    "content": "import logging\nimport math\nimport os.path\nimport pickle\nimport random\nimport shutil\nimport threading\nimport time\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtCore import QThread, pyqtSignal\nfrom PyQt5.QtGui import QDropEvent, QDragEnterEvent, QStandardItem\n\nimport mainWindow\nfrom PyQt5.QtWidgets import QApplication, QDialog\nfrom moviepy.editor import *\n\nfrom conf import BackgroundMusic, BaiduButton, DoutulaButton\n\nfrom utils import getUuid, getBaiDuAudio, getBaiduImgPath, getDoutulaImgPath, resizeImg, convertToRGB\n\n\nclass genVideoThread(QThread):\n    \"\"\"\n    生成视频线程类\n    \"\"\"\n    signal = pyqtSignal(str)\n\n    def __init__(self, sections: list, materialName: str, fileName: str) -> None:\n        \"\"\"\n        初始化几个参数\n        :param sections: 字幕以及图片信息\n        :param materialName: 素材路径\n        :param fileName: 保存视频名称\n        \"\"\"\n        super().__init__()\n        self.sections = sections\n        self.materialName = materialName\n        self.fileName = fileName\n\n    def __del__(self):\n        self.wait()\n\n    def run(self):\n        screensize = (800, 600)\n        videoClips = []\n        for i, section in enumerate(self.sections):\n\n            imgPath, text = section[0], section[1]\n            if len(text) >= 1:\n                mark = text[-1]\n                if mark == '$':\n                    text = text[:-1]\n            text = text.split(r'\\\\')\n            text = '\\\\'.join([x.replace(r'\\n', '\\n') for x in text])\n            text = text.strip().split('\\n')\n            if imgPath is None:\n                imgPath = 'background.png'\n\n            # gif用到,用于标记当前字幕对应的gif从哪儿开始\n            index = 0\n            print(text, imgPath)\n            if imgPath.endswith('.gif'):\n                # 首先计算一下当前所有语音时间长度\n                clip = VideoFileClip(imgPath)\n                clip = clip.loop()\n            else:\n                convertToRGB(imgPath)\n                clip = ImageClip(imgPath)\n\n            # 设置一下图片/gif大小\n            if mark != '$':\n                width, height = clip.size\n                width, height = resizeImg(width, height)\n                clip = clip.resize((width, height))\n\n\n            # 考虑到每张表情包可能对应多句字幕\n            for txt in text:\n                # 合成语音\n                txtAudio = getBaiDuAudio(txt, os.path.join(self.materialName, 'audio'))\n                if len(txt) < 12:\n                    fontsize = 50\n                else:\n                    fontsize = 40\n                txtClip = TextClip(txt, color='white', font='STKaiti', kerning=5, fontsize=fontsize, align='South')\n                if txtAudio is None:\n                    logging.error('get the audio of {} failed!'.format(txt))\n                    continue\n                txtAudio = AudioFileClip(txtAudio)\n\n                # 表情包视频与字幕融合\n                cvc = CompositeVideoClip([clip.set_position(('center', 'center')).subclip(index, txtAudio.duration),\n                                          txtClip.set_position(('center', 0.85), relative=True)],\n                                         size=screensize)\n                cvc = cvc.subclip(0, txtAudio.duration)\n                index += txtAudio.duration\n                # 添加配音\n                cvc = cvc.set_audio(txtAudio)\n                videoClips.append(cvc)\n            self.signal.emit('进度: {}%'.format(math.ceil((i * 80) / len(self.sections))))\n        finalClip = concatenate_videoclips(videoClips)\n        # 获取原视频声音\n        audio = finalClip.audio\n\n        # 整体背景音乐\n        audioClip = AudioFileClip(BackgroundMusic)\n        if audioClip.duration > finalClip.duration:\n            audioClip = audioClip.subclip(0, audio.duration)\n        elif audioClip.duration < finalClip.duration:\n            audioClip = afx.audio_loop(audioClip, duration=audio.duration)\n        audioClip = afx.volumex(audioClip, factor=0.35)\n        self.signal.emit('进度: {}%'.format(math.ceil(i * 80 / len(self.sections)) + random.randint(5, 15)))\n        # 声音结合起来\n        audio = CompositeAudioClip([audio, audioClip])\n        finalClip = finalClip.set_audio(audio)\n        fileName = os.path.join('out', self.fileName)\n        self.signal.emit('进度: {}'.format('处理完成! 正在写出文件...'))\n        finalClip.write_videofile(fileName, fps=25, codec='mpeg4')\n        self.signal.emit(fileName)\n\n\nclass addImgThread(QThread):\n    \"\"\"\n    获取网络表情包线程类\n    \"\"\"\n    signal = pyqtSignal(str)\n\n    def __init__(self, mText: str, mButton: int) -> None:\n        \"\"\"\n        初始化获取网络表情包线程类\n        :param mText: 搜索关键词\n        :param mButton: 采用哪个搜索引擎\n        \"\"\"\n        super().__init__()\n        self.text = mText\n        self.button = mButton\n\n    def __del__(self):\n        self.wait()\n\n    def run(self):\n        if self.button == BaiduButton:\n            for path in getBaiduImgPath(self.text):\n                self.signal.emit(path)\n\n        if self.button == DoutulaButton:\n            for path in getDoutulaImgPath(self.text):\n                self.signal.emit(path)\n\n\nclass MainDialog(QDialog):\n    def __init__(self, parent=None):\n        super(QDialog, self).__init__(parent)\n\n        # 当前指向的句子\n        self.nowPos = None\n        # 获取表情包线程句柄\n        self.subThread = None\n        # 已经设定好的句子以及表情包,三元组(图片路径, 文案, 时间戳),时间戳一旦生成不再修改,主要用于区分文案并生成对应的图片路径\n        self.sections = []\n        # 接收拖放对象\n        self.setAcceptDrops(True)\n        self.fileName = None\n        self.materialName = None\n\n        # lock of save and read the bfs file\n        self.lock = threading.Lock()\n\n        self.ui = mainWindow.Ui_MainWindow()\n        self.ui.setupUi(self)\n\n        # start save thread\n        self.saveThread = threading.Thread(target=self.save)\n        self.saveThread.start()\n\n    def save(self) -> None:\n        \"\"\"\n        每隔5秒保存一次工程信息\n        :return: None\n        \"\"\"\n        time.sleep(5)\n        # 窗口存在则一直保存\n        while self.ui.windowIsVisible():\n            self.lock.acquire()\n            if len(self.sections) <= 0:\n                self.lock.release()\n                time.sleep(5)\n                continue\n            data = dict()\n            data['nowPos'] = self.nowPos\n            data['sections'] = self.sections\n            data['fileName'] = self.fileName\n            data['materialName'] = self.materialName\n            fileName = os.path.join(self.materialName, self.fileName[:self.fileName.rfind('.')] + '.bfs')\n            with open(fileName, 'wb') as f:\n                pickle.dump(data, f)\n            self.lock.release()\n            time.sleep(5)\n\n    def dragEnterEvent(self, event: QDragEnterEvent) -> None:\n        \"\"\"\n        拖放事件\n        :param event: QDragEnterEvent\n        :return: None\n        \"\"\"\n        if event.mimeData().hasText():\n            event.accept()\n        else:\n            event.ignore()\n\n    def dropEvent(self, event: QDropEvent) -> None:\n        \"\"\"\n        拖放事件,主要处理.bfs工程文件, .txt文案文件, .gif/.png等图片文件\n        :param event: 拖放对象事件\n        :return: None\n        \"\"\"\n        filePathList = event.mimeData().text()\n        filePath = filePathList.split('\\n')[0].replace('file:///', '', 1)\n        # 说明是加载的工程文件\n        if filePath.endswith('.bfs'):\n            self.loadBfs(filePath)\n            return\n\n        # 说明加载的是文案文件\n        if filePath.endswith('.txt'):\n            if self.fileName is None:\n                self.ui.msgBox('请先设置工程目录!')\n                return\n            self.loadText(True, filePath)\n            return\n\n        # 其他情况应该是加载的图片文件,先判断是不是gif/图片\n        if not filePath.endswith('.gif'):\n            # 通过加载文件来判断是否为图片,不是则返回\n            try:\n                ImageClip(filePath)\n            except:\n                return\n        self.loadPic(filePath)\n\n    def loadBfs(self, filePath: str) -> None:\n        \"\"\"\n        加载工程文件\n        :param filePath: 工程文件路径\n        :return: None\n        \"\"\"\n        if len(self.sections) > 0:\n            if not self.ui.msgBox('导入工程文件将清空当前工作内容,可能导致部分内容丢失,是否继续?', True):\n                return\n\n        # 需要在material目录下有对应的文件夹,没有的禁止载入\n        fileName = os.path.basename(filePath).replace('.bfs', '')\n        if not os.path.exists(os.path.join('material', fileName)):\n            self.ui.msgBox('未找到对应的素材文件夹!')\n            return\n\n        with open(filePath, 'rb') as f:\n            data = pickle.load(f)\n\n        self.lock.acquire()\n        self.nowPos = data['nowPos']\n        self.sections = data['sections']\n\n        # 检查资源文件是否都存在\n        for section in self.sections:\n            if section[0] is not None and not os.path.exists(section[0]):\n                self.nowPos = None\n                self.sections = []\n                self.ui.msgBox('对应的素材缺失!')\n                self.lock.release()\n                return\n\n        self.fileName = data['fileName']\n        self.ui.setFileName(self.fileName)\n        self.materialName = data['materialName']\n\n        # 将sections的内容填充到表格\n        self.ui.delAllRow()\n        for section in self.sections:\n            self.ui.addRow(section[1])\n        if self.nowPos is not None:\n            self.ui.setSubTileText(self.sections[self.nowPos][1])\n            self.ui.setSearchText(self.sections[self.nowPos][1])\n\n            imgPath = self.sections[self.nowPos][0]\n            if imgPath is None:\n                self.ui.delVideoImg()\n            else:\n                self.ui.changeVideoImg(imgPath)\n        else:\n            self.ui.delVideoImg()\n        self.lock.release()\n\n    def loadPic(self, imgPath: str) -> None:\n        \"\"\"\n        加载拖放进来的图片文件\n        :param imgPath: 图片文件路径\n        :return: None\n        \"\"\"\n        if self.nowPos is None:\n            # 没有工程内容则忽略该次拖入文件\n            self.ui.msgBox('请先设置字幕内容!')\n            return\n\n        self.ui.changeVideoImg(imgPath)\n\n        imgBaseName = os.path.basename(imgPath)\n        suffix = imgBaseName[imgBaseName.rfind('.') + 1:]\n        uuid = self.sections[self.nowPos][2]\n        newPath = '{}.{}'.format(uuid, suffix)\n        newPath = os.path.join(os.path.join(self.materialName, 'img'), newPath)\n        shutil.copyfile(imgPath, newPath)\n        # 保存图片与字幕信息\n        self.sections[self.nowPos] = [newPath, self.ui.getSubtitle(), uuid]\n        self.ui.setRowText(self.nowPos, self.ui.getSubtitle())\n\n    def setFilename(self) -> None:\n        \"\"\"\n        设置文件名\n        :return: None\n        \"\"\"\n        # 加锁,禁止保存或者载入工程文件\n        self.lock.acquire()\n        fileName = self.ui.getFileName()\n        materialName = os.path.join('material', fileName[:fileName.rfind('.')])\n\n        # 当前工作区没内容,说明是新建的工程,新建的工程的名字不能和之前重复\n        if len(self.sections) <= 0 and os.path.exists(materialName):\n            self.ui.msgBox('文件名已存在,请更换名字或加载之前缓存!')\n            self.lock.release()\n            return\n\n        self.fileName = fileName\n\n        # 文件名并未更改,可能是未修改或者只修改了后缀名,都可以忽略\n        if self.materialName == materialName:\n            self.ui.msgBox('设置工程文件夹成功!')\n            self.lock.release()\n            return\n        # 当前工作区无内容,说明是新建的工程,需要新建文件夹\n        if len(self.sections) <= 0:\n            os.makedirs(os.path.join(materialName, 'audio'))\n            os.makedirs(os.path.join(materialName, 'img'))\n            self.ui.msgBox('新建工程文件夹成功!')\n        else:\n            # 当前工作区有内容,说明工程已经存在,需要对所有数据进行重命名\n            self.changeFileName(self.materialName, materialName)\n            self.ui.msgBox('重命名工程文件夹成功!')\n        self.materialName = materialName\n        self.lock.release()\n\n    def changeFileName(self, oldMaterialName: str, materialName: str) -> None:\n        \"\"\"\n        修改了文件名需要对文件夹等全部进行修改\n        :param oldMaterialName: 旧的素材文件夹名\n        :param materialName: 新的素材文件夹名\n        :return:\n        \"\"\"\n        # 对sections里面包含的图片信息的地址进行修改\n        for section in self.sections:\n            if section[0] is None:\n                continue\n            imgBaseName = os.path.basename(section[0])\n            newPath = os.path.join(os.path.join(materialName, 'img'), imgBaseName)\n            section[0] = newPath\n\n        # 更改文件夹名字\n        os.rename(oldMaterialName, materialName)\n\n    def setSubtitleInfo(self) -> None:\n        \"\"\"\n        设置上一句/下一句对应的字幕以及图片信息\n        :return: None\n        \"\"\"\n        self.ui.setSubTileText(self.sections[self.nowPos][1])\n        self.ui.setSearchText(self.sections[self.nowPos][1])\n        # 如果已经设置好了表情包,显示出来;否则就清空\n        imgPath = self.sections[self.nowPos][0]\n        if imgPath is None:\n            self.ui.delVideoImg()\n        else:\n            self.ui.changeVideoImg(imgPath)\n\n    def last(self) -> None:\n        \"\"\"\n        上一句,加载上一句字幕与图片\n        :return: None\n        \"\"\"\n        if len(self.sections) <= 0:\n            self.ui.msgBox('当前工作区暂无内容!')\n            return\n\n        # 计算当前应该到达的光标\n        if self.nowPos is None:\n            self.nowPos = 1\n        else:\n            # 保存下一句的字幕信息\n            self.sections[self.nowPos][1] = self.ui.getSubtitle()\n            self.ui.setRowText(self.nowPos, self.ui.getSubtitle())\n\n        self.nowPos = self.nowPos - 1 if self.nowPos > 0 else len(self.sections) - 1\n        self.setSubtitleInfo()\n\n    def next(self) -> None:\n        \"\"\"\n        下一句,加载下一句字幕与图片\n        :return: None\n        \"\"\"\n        if len(self.sections) <= 0:\n            self.ui.msgBox('当前工作区暂无内容!')\n            return\n\n        if self.nowPos is None:\n            self.nowPos = -1\n        else:\n            # 保存上一句的字幕信息\n            self.sections[self.nowPos][1] = self.ui.getSubtitle()\n            self.ui.setRowText(self.nowPos, self.ui.getSubtitle())\n\n        self.nowPos = self.nowPos + 1 if self.nowPos < len(self.sections) - 1 else 0\n        self.setSubtitleInfo()\n\n    def changeThePicText(self, text: str) -> None:\n        \"\"\"\n        视频字幕实时更改\n        :param text: 字幕信息\n        :return: None\n        \"\"\"\n        if len(self.sections) <= 0:\n            return\n        self.ui.setVideoText(text)\n        self.sections[self.nowPos][1] = text\n        self.ui.setRowText(self.nowPos, text)\n\n    def previewImg(self, path: str) -> None:\n        \"\"\"\n        将网络表情包加载预览以供选择\n        :param path: 网络表情包路径\n        :return: None\n        \"\"\"\n        self.ui.addImg(path)\n\n    def search(self, button: int) -> None:\n        \"\"\"\n        搜索表情包,button代表了不同的搜索引擎\n        :param button: 来自哪个按钮,代表了不同的搜索引擎\n        :return: None\n        \"\"\"\n        if len(self.sections) <= 0 or self.ui.getSearchText() == '':\n            self.ui.msgBox('工作区暂无内容或未输入搜索文字!')\n            return\n        if self.subThread is not None:\n            self.subThread.terminate()\n            while self.subThread.isRunning() and not self.subThread.isFinished():\n                time.sleep(0.1)\n        # 清空当前的所有表情包图片\n        self.ui.delImg()\n        self.subThread = addImgThread(self.ui.getSearchText(), button)\n        self.subThread.signal.connect(self.previewImg)\n        self.subThread.start()\n\n    def imgClicked(self, index: int) -> None:\n        \"\"\"\n        表情包点击回调函数,将选好的表情包加载到视频预览区\n        :param index: 选好的表情包索引\n        :return: None\n        \"\"\"\n        if len(self.sections) <= 0:\n            self.ui.msgBox('工作区无内容!')\n            return\n        if self.nowPos is None:\n            self.ui.msgBox('暂未选择文案与字幕!')\n            return\n        imgPath = self.ui.getImgPathByIndex(index)\n        self.ui.changeVideoImg(imgPath)\n        # 将表情包复制到material目录\n        imgBaseName = os.path.basename(imgPath)\n        suffix = imgBaseName[imgBaseName.rfind('.') + 1:]\n        uuid = self.sections[self.nowPos][2]\n        newPath = '{}.{}'.format(uuid, suffix)\n        newPath = os.path.join(os.path.join(self.materialName, 'img'), newPath)\n        shutil.copyfile(imgPath, newPath)\n        # 保存图片与字幕信息\n        self.sections[self.nowPos] = [newPath, self.ui.getSubtitle(), uuid]\n        self.ui.setRowText(self.nowPos, self.ui.getSubtitle())\n\n    def genVideo(self) -> None:\n        \"\"\"\n        开始生成视频\n        :return: None\n        \"\"\"\n        if len(self.sections) <= 0:\n            self.ui.msgBox('工作区无内容!')\n            return\n        self.setDisabled(True)\n        self.gvt = genVideoThread(self.sections, self.materialName, self.fileName)\n        self.gvt.signal.connect(self.genVideoFinished)\n        self.gvt.start()\n\n    def genVideoFinished(self, msg: str) -> None:\n        \"\"\"\n        视频生成完成回调函数\n        :param msg: 生成视频传回的信息。主要有两种，第一是进度，第二是输出的视频的路径\n        :return: None\n        \"\"\"\n        if ': ' in msg:\n            self.ui.setGenVideoText(msg)\n            return\n        self.setDisabled(False)\n        self.ui.setGenVideoText('生成视频')\n        self.ui.msgBox('生成完毕!位置:{}'.format(msg))\n\n    def loadText(self, drag=False, fileName: str=None) -> None:\n        \"\"\"\n        文件浏览器回调函数/同时支持拖放导入文案解析\n        :param drag: 是否是拖放导入的\n        :param fileName: 拖放进来的文件名\n        :return: None\n        \"\"\"\n        if self.fileName is None:\n            self.ui.msgBox('请先设置工程目录!')\n            return\n        if len(self.sections) > 0 and not self.ui.msgBox('当前导入会覆盖工作区内容,不可撤销!是否继续?', True):\n            return\n        self.ui.delAllRow()\n        if not drag:\n            fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, '选择文案', os.getcwd(), 'Text Files (*.txt)')\n        if not os.path.exists(fileName):\n            self.ui.msgBox('未选择文件!')\n            return\n        with open(fileName, 'r', encoding='utf-8') as f:\n            data = f.read()\n        self.sections = list()\n        for text in data.split('\\n'):\n            if text == '':\n                continue\n            text = text.strip()\n            self.ui.addRow(text)\n            self.sections.append([None, text, getUuid()])\n        self.ui.msgBox('导入完成!')\n\n    def addFrontText(self) -> None:\n        \"\"\"\n        在当前选中的表格单元前面增加一行空白行\n        :return: None\n        \"\"\"\n        if len(self.sections) <= 0:\n            if self.fileName is not None:\n                index = 0\n            else:\n                self.ui.msgBox('请设置文件名后再添加!')\n                return\n        else:\n            index = self.ui.getCurrentSelected()\n            if index == -1:\n                self.ui.msgBox('未选中表格!')\n                return\n\n        if self.nowPos is not None and self.nowPos >= index:\n            self.nowPos += 1\n\n        self.ui.insertRow(index)\n        self.sections.insert(index, [None, '', getUuid()])\n\n    def addBehindText(self) -> None:\n        \"\"\"\n        在当前选中的表格单元后面增加一行空白行\n        :return: None\n        \"\"\"\n        if len(self.sections) <= 0:\n            if self.fileName is not None:\n                index = -1\n            else:\n                self.ui.msgBox('请设置文件名后再添加!')\n                return\n        else:\n            index = self.ui.getCurrentSelected()\n            if index == -1:\n                self.ui.msgBox('未选中表格!')\n                return\n\n        if self.nowPos is not None and self.nowPos > index:\n            self.nowPos += 1\n\n        self.ui.insertRow(index + 1)\n        self.sections.insert(index + 1, [None, '', getUuid()])\n\n    def delText(self) -> None:\n        \"\"\"\n        删除该行\n        :return: None\n        \"\"\"\n        if len(self.sections) <= 0:\n            self.ui.msgBox('请先创建工程或输入文案!')\n            return\n        index = self.ui.getCurrentSelected()\n        if index == -1:\n            self.ui.msgBox('未选中表格!')\n            return\n\n        # 如果删除了当前预览位置的文案\n        if self.nowPos is not None and self.nowPos == index:\n            # 加载下一句文案\n            self.next()\n\n        # 如果在当前位置之前删除了一个文案,那么当前位置-1\n        if self.nowPos is not None and self.nowPos >= index:\n            self.nowPos -= 1\n\n        self.ui.delRow(index)\n        del self.sections[index]\n\n    def exportText(self) -> None:\n        \"\"\"\n        导出文案内容\n        :return: None\n        \"\"\"\n        if len(self.sections) <= 0:\n            self.ui.msgBox('当前工作区没有内容!')\n            return\n        texts = ''\n        for section in self.sections:\n            texts += section[1] + '\\n'\n\n        path = os.path.join(self.materialName, 'work.txt')\n        with open(path, 'w+') as f:\n            f.write(texts)\n        self.ui.msgBox('导出文案成功!位置:{}'.format(path))\n\n    def tableItemChange(self, item: QStandardItem) -> None:\n        \"\"\"\n        文案内容被修改时,同步到sections\n        :param item: 被修改的表格item\n        :return:\n        \"\"\"\n        if len(self.sections) > item.row():\n            self.sections[item.row()][1] = item.text()\n            # 如果当前单句字幕正好是修改的单元格部分,则修改的内容同步修改到单句字幕编辑处. 需要排除由于单句字幕修改造成的表格修改的情况\n            if self.nowPos is not None and self.nowPos == item.row() and self.ui.getSubtitle() != item.text():\n                self.ui.setSubTileText(item.text())\n                self.ui.setSearchText(item.text())\n\n    def jumpToIndex(self) -> None:\n        \"\"\"\n        跳转到指定的文案\n        :return: None\n        \"\"\"\n        if self.nowPos is not None and self.ui.getCurrentSelected() != -1:\n            # 保存上一句的字幕信息\n            self.sections[self.nowPos][1] = self.ui.getSubtitle()\n            self.ui.setRowText(self.nowPos, self.ui.getSubtitle())\n        self.nowPos = self.ui.getCurrentSelected()\n        self.setSubtitleInfo()\n\n\nif __name__ == '__main__':\n    if os.path.exists('tmp'):\n        shutil.rmtree('tmp')\n        os.mkdir('tmp')\n    if not os.path.exists('out'):\n        os.mkdir('out')\n    myapp = QApplication(sys.argv)\n    myDlg = MainDialog()\n    myDlg.show()\n    sys.exit(myapp.exec_())\n"
  },
  {
    "path": "mainWindow.py",
    "content": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'mainWindow.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.4\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again.  Do not edit this file unless you know what you are doing.\nimport math\nimport os.path\nimport shutil\nimport time\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtGui import QMovie, QStandardItemModel, QStandardItem\nfrom moviepy.video.VideoClip import ImageClip\nfrom moviepy.video.io.VideoFileClip import VideoFileClip\n\nfrom conf import DoutulaButton, BaiduButton\nfrom utils import resizeImg\n\n\nclass clickedButton(QtWidgets.QPushButton):\n    \"\"\"\n    搜索表情包按钮事件,主要可以区分哪个按钮\n    \"\"\"\n    clicked = QtCore.pyqtSignal(int)\n\n    def __init__(self, button, parent=None):\n        super(clickedButton, self).__init__(parent)\n        self.button = button\n\n    def mouseReleaseEvent(self, QMouseEvent):\n        self.clicked.emit(self.button)\n\n\nclass clickedLabel(QtWidgets.QLabel):\n    \"\"\"\n    标签类,主要增加了点击事件,用于图片缓存区,用户点击了图片后可知道点击了哪张图\n    \"\"\"\n    clicked = QtCore.pyqtSignal(int)\n\n    def __init__(self, index: int, parent=None):\n        \"\"\"\n        :param index: 图片索引\n        :param parent:\n        \"\"\"\n        super(clickedLabel, self).__init__(parent)\n        self.index = index\n\n    def mouseReleaseEvent(self, QMouseEvent):\n        self.clicked.emit(self.index)\n\n\nclass Ui_MainWindow(object):\n    def __init__(self):\n        # 所有缓存的图片\n        self.img = []\n        # 当前视频预览区gif\n        self.gif = None\n        # 当前视频预览区图片\n        self.videoImg = None\n\n    def setupUi(self, MainWindow):\n        # 初始设置窗口信息\n        MainWindow.setObjectName('MainWindow')\n        MainWindow.resize(1890, 702)\n        MainWindow.setLayoutDirection(QtCore.Qt.LeftToRight)\n        MainWindow.setWindowTitle('半佛风格视频生成')\n\n        self.mainWindow = MainWindow\n        self.centralwidget = QtWidgets.QWidget(MainWindow)\n\n        # 输入文件名标签\n        self.fileLabel = QtWidgets.QLabel(self.centralwidget)\n        self.fileLabel.setGeometry(QtCore.QRect(10, 23, 121, 16))\n        self.fileLabel.setText('导出视频名称: ')\n\n        # 文件名\n        self.filenName = QtWidgets.QLineEdit(self.centralwidget)\n        self.filenName.setGeometry(QtCore.QRect(140, 16, 361, 31))\n        self.filenName.setText('{}.mp4'.format(int(time.time())))\n\n        # 输入文件名确定按钮\n        self.filenameButton = QtWidgets.QPushButton(self.centralwidget)\n        self.filenameButton.setGeometry(QtCore.QRect(501, 16, 60, 31))\n        self.filenameButton.setText('设置')\n        self.filenameButton.clicked.connect(MainWindow.setFilename)\n\n        # 给输入框加个分组box\n        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)\n        self.groupBox.setGeometry(QtCore.QRect(0, 53, 561, 618))\n        self.groupBox.setTitle('在此输入/编辑文案')\n\n        # 文案以表格的形式展示\n        self.model = QStandardItemModel(0, 0)\n        self.model.itemChanged.connect(MainWindow.tableItemChange)\n        # 设置水平方向四个头标签文本内容\n        self.model.setHorizontalHeaderLabels(['文案&字幕'])\n        self.row = 0\n        self.tableView = QtWidgets.QTableView(self.groupBox)\n        self.tableView.setGeometry(QtCore.QRect(10, 20, 541, 542))\n        self.tableView.setShowGrid(True)\n        self.tableView.setModel(self.model)\n        self.tableView.horizontalHeader().setStretchLastSection(True)\n        self.tableView.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)\n        self.tableView.clicked.connect(MainWindow.jumpToIndex)\n\n        # 打开文案/前增一句/后增一句/删除一句/修改一句/导出文案按钮布局\n        self.tableButtonWidget = QtWidgets.QWidget(self.groupBox)\n        self.tableButtonWidget.setGeometry(QtCore.QRect(10, 561, 541, 55))\n        # 水平分布\n        self.hbox = QtWidgets.QHBoxLayout()\n        self.hbox.setGeometry(QtCore.QRect())\n        self.hbox.setContentsMargins(0, 0, 0, 0)\n        # 打开文案\n        self.openText = QtWidgets.QPushButton()\n        self.openText.setText('打开')\n        self.openText.clicked.connect(MainWindow.loadText)\n        self.hbox.addWidget(self.openText)\n        # 在前面增加一句\n        self.addFrontText = QtWidgets.QPushButton()\n        self.addFrontText.setText('前增一句')\n        self.addFrontText.clicked.connect(MainWindow.addFrontText)\n        self.hbox.addWidget(self.addFrontText)\n        # 在后面增加一句\n        self.addBehindText = QtWidgets.QPushButton()\n        self.addBehindText.setText('后增一句')\n        self.addBehindText.clicked.connect(MainWindow.addBehindText)\n        self.hbox.addWidget(self.addBehindText)\n        # 删除该句\n        self.delText = QtWidgets.QPushButton()\n        self.delText.setText('删除该句')\n        self.delText.clicked.connect(MainWindow.delText)\n        self.hbox.addWidget(self.delText)\n        # 导出文案\n        self.exportText = QtWidgets.QPushButton()\n        self.exportText.setText('导出文案')\n        self.exportText.clicked.connect(MainWindow.exportText)\n        self.hbox.addWidget(self.exportText)\n        self.tableButtonWidget.setLayout(self.hbox)\n\n        # 单句字幕\n        self.singleText = QtWidgets.QLineEdit(self.centralwidget)\n        self.singleText.setGeometry(QtCore.QRect(660, 620, 611, 50))\n        self.singleText.textChanged.connect(MainWindow.changeThePicText)\n\n        # 搜索框文本\n        self.searchText = QtWidgets.QLineEdit(self.centralwidget)\n        self.searchText.setGeometry(QtCore.QRect(1360, 17, 421, 41))\n\n        # 斗图啦/百度搜索按钮\n        self.searchDou = clickedButton(DoutulaButton, self.centralwidget)\n        self.searchDou.setGeometry(QtCore.QRect(1785, 17, 45, 41))\n        self.searchDou.setText('斗图')\n        self.searchDou.clicked.connect(MainWindow.search)\n\n        self.searchBai = clickedButton(BaiduButton, self.centralwidget)\n        self.searchBai.setGeometry(QtCore.QRect(1834, 17, 45, 41))\n        self.searchBai.setText('百度')\n        self.searchBai.clicked.connect(MainWindow.search)\n\n        # 视频背景图\n        self.videoBackgroud = QtWidgets.QLabel(self.centralwidget)\n        self.videoBackgroud.setGeometry(QtCore.QRect(560, 16, 800, 600))\n        self.videoBackgroud.setPixmap(QtGui.QPixmap('background.png'))\n        self.videoBackgroud.setScaledContents(True)\n\n        # 视频字幕\n        self.addSubtitleLayout()\n\n        # 上一句按钮\n        self.last = QtWidgets.QPushButton(self.centralwidget)\n        self.last.setGeometry(QtCore.QRect(560, 620, 101, 51))\n        self.last.setText('上一句')\n        self.last.clicked.connect(MainWindow.last)\n\n        # 下一句按钮\n        self.next = QtWidgets.QPushButton(self.centralwidget)\n        self.next.setGeometry(QtCore.QRect(1270, 620, 91, 51))\n        self.next.setText('下一句')\n        self.next.clicked.connect(MainWindow.next)\n\n        # 生成视频按钮\n        self.genVideo = QtWidgets.QPushButton(self.centralwidget)\n        self.genVideo.setGeometry(QtCore.QRect(1360, 620, 521, 51))\n        self.genVideo.setText('生成视频')\n        self.genVideo.clicked.connect(MainWindow.genVideo)\n\n        # 表情包图片位置布局\n        self.widget = QtWidgets.QWidget(self.centralwidget)\n        self.widget.setGeometry(QtCore.QRect(1349, 48, 540, 579))\n        self.topFiller = QtWidgets.QWidget()\n        self.scroll = QtWidgets.QScrollArea()\n        self.scroll.setWidget(self.topFiller)\n        self.vbox = QtWidgets.QVBoxLayout()\n        self.vbox.addWidget(self.scroll)\n        self.widget.setLayout(self.vbox)\n\n        QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n    def addSubtitleLayout(self) -> None:\n        \"\"\"\n        视频字幕设置布局\n        :return:\n        \"\"\"\n        # 视频字幕\n        self.videoText = QtWidgets.QLabel(self.centralwidget)\n        self.videoText.setGeometry(QtCore.QRect(560, 526, 801, 51))\n        # 视频字幕字体颜色\n        palette = QtGui.QPalette()\n        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n        brush.setStyle(QtCore.Qt.SolidPattern)\n        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)\n        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n        brush.setStyle(QtCore.Qt.SolidPattern)\n        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)\n        brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n        brush.setStyle(QtCore.Qt.SolidPattern)\n        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)\n        self.videoText.setPalette(palette)\n        # 视频字幕字体设置\n        font = QtGui.QFont()\n        font.setFamily('华文楷体')\n        font.setPointSize(20)\n        self.videoText.setFont(font)\n        self.videoText.setTextFormat(QtCore.Qt.PlainText)\n        self.videoText.setScaledContents(False)\n        self.videoText.setAlignment(QtCore.Qt.AlignCenter)\n        self.videoText.setWordWrap(False)\n\n    def delVideoImg(self) -> None:\n        \"\"\"\n        清空视频预览区图片\n        :return: None\n        \"\"\"\n        if self.videoImg is not None:\n            self.videoImg.deleteLater()\n            self.videoImg = None\n        if self.gif is not None:\n            self.gif.deleteLater()\n            self.gif = None\n\n    def getResizedOfVideoImg(self, path) -> (int, int):\n        \"\"\"\n        获取路径图片重新调整过的大小\n        :param path: 图片路径\n        :return: (width, height)\n        \"\"\"\n        try:\n            clip = VideoFileClip(path)\n        except:\n            clip = ImageClip(path)\n        width, height = clip.size\n        return resizeImg(width, height)\n\n    def changeVideoImg(self, path: str) -> None:\n        \"\"\"\n        加载图片到视频预览区\n        :param path: 图片路径\n        :return: None\n        \"\"\"\n        # 如果图片不是在tmp目录保存,则转到tmp目录再加载,不然重命名工程会有问题\n        if not path.startswith('tmp' + os.path.sep):\n            newPath = os.path.join('tmp', os.path.basename(path))\n            if not os.path.exists(newPath):\n                shutil.copyfile(path, newPath)\n            path = newPath\n        self.delVideoImg()\n        self.videoImg = QtWidgets.QLabel(self.centralwidget)\n        wight, height = self.getResizedOfVideoImg(path)\n        self.videoImg.setGeometry(QtCore.QRect(int(960 - wight / 2), int(316 - height / 2), wight, height))\n        self.videoImg.setScaledContents(True)\n        self.gif = QMovie(path)\n        self.videoImg.setMovie(self.gif)\n        self.videoImg.setAlignment(QtCore.Qt.AlignCenter)\n        self.gif.start()\n        self.videoImg.show()\n        self.centralwidget.show()\n\n    def addImg(self, path: str) -> None:\n        \"\"\"\n        给图片缓存区加一张图片\n        :param path: 图片路径\n        :return: None\n        \"\"\"\n        # 计算图片框位置\n        row = math.ceil((len(self.img) + 1) / 3) - 1\n        col = len(self.img) % 3\n\n        img_label = clickedLabel(len(self.img), self.topFiller)\n        img_label.setGeometry(QtCore.QRect(1370, 60, 151, 151))\n        gif = QMovie(path)\n        img_label.setMovie(gif)\n        img_label.setScaledContents(True)\n        gif.start()\n        img_label.move(col * (151 + 10) + 10, row * (151 + 10) + 10)\n        self.img.append((img_label, gif, path))\n        self.topFiller.setMinimumSize(490, (row + 1) * (151 + 10))\n        self.scroll.setWidget(self.topFiller)\n        img_label.clicked.connect(self.mainWindow.imgClicked)\n        img_label.show()\n        self.topFiller.show()\n        self.widget.show()\n\n    def delImg(self) -> None:\n        \"\"\"\n        清空从网络获取的所有的表情包\n        :return: None\n        \"\"\"\n        for imgLabel, gif, _ in self.img:\n            imgLabel.deleteLater()\n            gif.deleteLater()\n        self.img = []\n        self.widget.show()\n\n    def getImgPathByIndex(self, index: int) -> str:\n        \"\"\"\n        通过表情包缓存区的索引获取表情包的实际路径\n        :param index: 表情包缓存区的索引\n        :return: 表情包的实际位置\n        \"\"\"\n        return self.img[index][2]\n\n    def addRow(self, text: str) -> None:\n        \"\"\"\n        向表中添加一行新的数据\n        :param text:\n        :return:\n        \"\"\"\n        item = QStandardItem(text)\n        self.model.setItem(self.row, 0, item)\n        self.row += 1\n\n    def delRow(self, row: int) -> None:\n        \"\"\"\n        删除一行表中的数据\n        :param row: 删除索引\n        :return:\n        \"\"\"\n        self.model.removeRow(row)\n\n    def delAllRow(self) -> None:\n        \"\"\"\n        删除所有行\n        :return:\n        \"\"\"\n        for index in range(self.model.rowCount())[::-1]:\n            self.delRow(index)\n\n    def msgBox(self, msg: str, hasQuery: bool = False) -> bool:\n        \"\"\"\n        :param msg: 消息\n        :param hasQuery: 是否带询问\n        :return: 如果hasQuery为True,返回值为用户是否点击了确定\n        \"\"\"\n        if not hasQuery:\n            QtWidgets.QMessageBox.information(self.mainWindow, '提示', msg, QtWidgets.QMessageBox.Ok,\n                                              QtWidgets.QMessageBox.Ok)\n            return True\n        reply = QtWidgets.QMessageBox.question(self.mainWindow, '提示', msg,\n                                               QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel,\n                                               QtWidgets.QMessageBox.Cancel)\n        return reply == QtWidgets.QMessageBox.Yes\n\n    def getCurrentSelected(self) -> int:\n        \"\"\"\n        获取当前选中的表格单元索引\n        :return: 前选中的表格单元索引\n        \"\"\"\n        selectedIndex = self.tableView.selectedIndexes()\n        if len(selectedIndex) > 0:\n            return selectedIndex[0].row()\n        return -1\n\n    def insertRow(self, index: int) -> None:\n        \"\"\"\n        增加一行空白行\n        :index: 增加的位置索引\n        :return: None\n        \"\"\"\n        self.model.insertRow(index)\n\n    def getSubtitle(self) -> str:\n        \"\"\"\n        获取当前编辑的字幕信息\n        :return: 前编辑的字幕\n        \"\"\"\n        return self.singleText.text()\n\n    def getSearchText(self) -> str:\n        \"\"\"\n        获取搜索框文本信息\n        :return: 搜索框文本信息\n        \"\"\"\n        return self.searchText.text()\n\n    def setVideoText(self, text: str) -> None:\n        \"\"\"\n        设置视频预览区字幕信息\n        :param text: 字幕信息\n        :return: None\n        \"\"\"\n        self.videoText.setText(text)\n\n    def setFileName(self, fileName: str) -> None:\n        \"\"\"\n        设置文件名\n        :param fileName: 文件名\n        :return: None\n        \"\"\"\n        self.filenName.setText(fileName)\n\n    def windowIsVisible(self) -> bool:\n        \"\"\"\n        当前窗口是否可见,即是否被关闭\n        :return: 返回当前窗口是否可见,即是否被关闭\n        \"\"\"\n        return self.centralwidget.isVisible()\n\n    def setSubTileText(self, text: str) -> None:\n        \"\"\"\n        设置字幕编辑框内容\n        :param text: 字幕\n        :return: None\n        \"\"\"\n        self.singleText.setText(text)\n        self.singleText.home(False)\n\n    def setSearchText(self, text: str) -> None:\n        \"\"\"\n        设置搜索框内容\n        :param text: 搜索文字\n        :return: None\n        \"\"\"\n        self.searchText.setText(text)\n        self.searchText.home(False)\n\n    def getFileName(self) -> str:\n        \"\"\"\n        获取文件名\n        :return: 文件名\n        \"\"\"\n        return self.filenName.text()\n\n    def setRowText(self, row: int, text: str) -> None:\n        \"\"\"\n        设置某一行的文案信息\n        :param row: 行索引\n        :param text: 文本\n        :return:\n        \"\"\"\n        item = self.model.item(row, 0)\n        if item is not None:\n            item.setText(text)\n\n    def subtitleHasFocus(self) -> bool:\n        \"\"\"\n        单句字幕编辑框是否有焦点\n        :return: 单句字幕编辑框是否有焦点\n        \"\"\"\n        return self.singleText.hasFocus()\n\n    def setGenVideoText(self, text: str) -> None:\n        \"\"\"\n        设置生成视频按钮的文本\n        :param text: 文本\n        :return: None\n        \"\"\"\n        self.genVideo.setText(text)\n"
  },
  {
    "path": "preprocess.py",
    "content": "import os\nimport pickle\nimport paddlenlp\n\n# 加载tokeniezer\nfrom conf import MODELNAME\n\ntokenizer = paddlenlp.transformers.GPTChineseTokenizer.from_pretrained(MODELNAME)\n\ntrainData = []\n# 处理所有的公众号文章\nfor index, path in enumerate(os.listdir('banfoText')):\n    if not path.endswith('.txt'):\n        continue\n    print(index, path)\n    with open(os.path.join('banfoText', path), 'r+', encoding='utf-8') as f:\n        data = f.read()\n    data = tokenizer(text=data, return_token_type_ids=False)\n    data = data['input_ids']\n    start = -30\n    lenght = 100\n    step = 30\n    if len(data) <= 2 * lenght:\n        continue\n    # 滑动窗口截断获取inputData和label\n    while start + step + 1 < len(data) and start + step + lenght + 1 < len(data):\n        start = start + step\n        input_data = data[start: start + lenght]\n        label = data[start + 1: start + lenght + 1]\n        trainData.append([input_data, label])\n    trainData.append([data[-lenght-1: -1], data[-lenght:]])\n\nif not os.path.exists('preprocessData'):\n    os.mkdir('preprocessData')\nwith open(os.path.join('preprocessData', 'trainData.pkl'), 'wb') as f:\n    pickle.dump(trainData, f)\n\nprint(len(trainData))\nprint('done!')\n"
  },
  {
    "path": "requirements.txt",
    "content": "moviepy==1.0.3\nrequests~=2.24.0\nnumpy==1.21.2\nbeautifulsoup4==4.10.0\nPyQt5==5.15.4\nsystem_hotkey==1.0.3\nFlask~=2.0.2\nbs4~=0.0.1\nPillow~=8.3.2\npiexif~=1.1.3\ngoogletrans~=3.0.0\npaddlepaddle-gpu==2.1.3.post110\npaddlenlp~=2.1.0"
  },
  {
    "path": "train.py",
    "content": "import os\nimport pickle\n\nimport paddle\nimport paddlenlp\nfrom paddle.io import Dataset, DataLoader\nimport paddle.nn as nn\n\nfrom conf import MODELNAME\n\n\nclass BanfoDataset(Dataset):\n    def __init__(self, data, tokenizer):\n        super().__init__()\n        self.data = data\n        self.tokenizer = tokenizer\n\n    def __getitem__(self, idx):\n        return paddle.to_tensor(self.data[idx][0], dtype='int64'), paddle.to_tensor(self.data[idx][1], dtype='int64')\n\n    def __len__(self):\n        return len(self.data)\n\n\nif not os.path.exists('models'):\n    os.mkdir('models')\n\npaddle.set_device('gpu')\n\ngptModel = paddlenlp.transformers.GPTModel.from_pretrained(MODELNAME)\ngptModel = paddlenlp.transformers.GPTForPretraining(gptModel)\ntokenizer = paddlenlp.transformers.GPTChineseTokenizer.from_pretrained(MODELNAME)\n\n# 有本地模型存在，则加载本地模型\ncheckpoint = os.path.join('models', 'model_state.pdparams')\nif os.path.exists(checkpoint):\n    model_state = paddle.load(checkpoint)\n    gptModel.set_state_dict(model_state)\n\n# 设置为评估模型\ngptModel.eval()\n\n# 测试效果\nencodedText = tokenizer(text='前段时间我跟一个老大哥一起吃火锅。大哥的孩子，都上学了', return_token_type_ids=False)\nids, _ = gptModel.generate(input_ids=paddle.to_tensor(encodedText['input_ids'], dtype='int64').unsqueeze(0),\n                           max_length=16, min_length=1, decode_strategy='sampling')\nids = ids[0].numpy().tolist()\n# 使用tokenizer将生成的id转为文本\ntext = tokenizer.convert_ids_to_string(ids)\nprint('generation text is {}'.format(text))\n\n# 加载训练数据\nwith open(os.path.join('preprocessData', 'trainData.pkl'), 'rb') as f:\n    data = pickle.load(f)\n\ntrainDataLoader = DataLoader(dataset=BanfoDataset(data, tokenizer), batch_size=64, shuffle=True, return_list=True)\n\nnumEpochs = 100\nlearningRate = 2e-5\nwarmupProportion = 0.1\nweightDecay = 0.1\n\nmaxSteps = (len(trainDataLoader) * numEpochs)\nlr_scheduler = paddle.optimizer.lr.LambdaDecay(learningRate,\n                                               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))))\n\noptimizer = paddle.optimizer.AdamW(learning_rate=lr_scheduler,\n                                   parameters=gptModel.parameters(),\n                                   weight_decay=weightDecay,\n                                   grad_clip=nn.ClipGradByGlobalNorm(1.0),\n                                   apply_decay_param_fun=lambda x: x in [\n                                       p.name for n, p in gptModel.named_parameters()\n                                       if not any(nd in n for nd in [\"bias\", \"norm\"])\n                                   ])\n\nglobalStep = 1\nsave_steps = 100\ncriterion = paddle.nn.loss.CrossEntropyLoss()\ngptModel.train()\nfor epoch in range(numEpochs):\n    for step, batch in enumerate(trainDataLoader, start=1):\n        ids, label = batch\n        logits, _ = gptModel.forward(ids, use_cache=True)\n        loss = criterion(logits, label)\n        loss.backward()\n        optimizer.step()\n        lr_scheduler.step()\n        optimizer.clear_gradients()\n        if globalStep % save_steps == 0:\n            print(globalStep, loss.numpy())\n            gptModel.save_pretrained('models')\n        globalStep += 1\n"
  },
  {
    "path": "utils.py",
    "content": "import base64\nimport hashlib\nimport json\nimport os\nimport random\nfrom collections.abc import Iterable\nfrom urllib.parse import quote\n\nimport piexif\nimport requests\nfrom PIL import Image\nfrom bs4 import BeautifulSoup\n\nfrom config import APIKEY, BAIDUAPPID, BAIDUAPPKEY\n\nproxies = None\nverify = True\n\n\ndef getUuid() -> str:\n    \"\"\"\n    生成一个uuid\n    :return: uuid\n    \"\"\"\n    return str(random.randint(1, 999999)).zfill(6)\n\n\ndef getBaiDuAudio(text: str, filePath: str) -> [str, None]:\n    \"\"\"\n    利用百度语音合成将文字合成语音\n    :param text: 合成语音的文字\n    :param filePath: 文件保存路径\n    :return: 文件路径或者None\n    \"\"\"\n    # 生成文件名\n    md5 = hashlib.md5()\n    md5.update(text.encode('utf-8'))\n    fileName = md5.hexdigest() + '.mp3'\n    fileName = os.path.join(filePath, fileName)\n    # 文件已经存在的话直接返回\n    if os.path.exists(fileName):\n        return fileName\n\n    url = 'https://cloud.baidu.com/aidemo'\n    data = 'type=tns&per=4105&spd=8&pit=7&vol=5&aue=6&tex=' + quote(text)\n    headers = {\n        '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',\n        'Content-Type': 'application/x-www-form-urlencoded',\n        'Accept': '*/*',\n        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'\n    }\n    res = requests.post(url, data=data, headers=headers, verify=False)\n    if res.status_code != 200:\n        return None\n    res = json.loads(res.text)\n    if res['msg'] != 'success':\n        return None\n    data = res['data'].replace('data:audio/x-mpeg;base64,', '')\n    if ',' in data:\n        data = data[:data.find(',')]\n    data = base64.b64decode(data)\n    with open(fileName, 'wb') as f:\n        f.write(data)\n    return fileName\n\n\ndef decodeBaiduImg(objUrl: str) -> str:\n    \"\"\"\n    百度图片地址解码函数\n    :param objUrl: 编码的url\n    :return: 解码的url\n    \"\"\"\n    res = ''\n    c = ['_z2C$q', '_z&e3B', 'AzdH3F']\n    d = {'w': 'a',\n         'k': 'b',\n         'v': 'c',\n         '1': 'd',\n         'j': 'e',\n         'u': 'f',\n         '2': 'g',\n         'i': 'h',\n         't': 'i',\n         '3': 'j',\n         'h': 'k',\n         's': 'l',\n         '4': 'm',\n         'g': 'n',\n         '5': 'o',\n         'r': 'p',\n         'q': 'q',\n         '6': 'r',\n         'f': 's',\n         'p': 't',\n         '7': 'u',\n         'e': 'v',\n         'o': 'w',\n         '8': '1',\n         'd': '2',\n         'n': '3',\n         '9': '4',\n         'c': '5',\n         'm': '6',\n         '0': '7',\n         'b': '8',\n         'l': '9',\n         'a': '0',\n         '_z2C$q': ':',\n         '_z&e3B': '.',\n         'AzdH3F': '/'}\n    for m in c:\n        objUrl = objUrl.replace(m, d[m])\n    for char in objUrl:\n        char = d[char] if char in d else char\n        res = res + char\n    return res\n\n\ndef getBaiduImgPath(text: str) -> [Iterable, None]:\n    \"\"\"\n    从百度图片接口拉取图片\n    :param text: 搜索关键字\n    :return: 图片路径迭代器或者None\n    \"\"\"\n    url = 'https://image.baidu.com/search/acjson?tn=resultjson_com&logid=8763701186511659178&ipn=rj&ct=201326592&is=' \\\n          '&fp=result&queryWord={0}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=&copyright=&word={0}' \\\n          '&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&nojc=&acjsonfr=click&pn=0&rn=30&itg=1' \\\n          '&gsm=3c&1634043752626='\n    url = url.format(text)\n    headers = {\n        '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',\n        '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',\n        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'}\n    res = requests.get(url, headers=headers, verify=False)\n    if res.status_code != 200:\n        return None\n    try:\n        jsonData = json.loads(res.text)\n    except:\n        return None\n    if 'data' not in jsonData:\n        return None\n    data = jsonData['data']\n    for img in data:\n        imgUrl = ''\n        if 'objURL' in img:\n            imgUrl = decodeBaiduImg(img['objURL'])\n        elif 'middleURL' in img:\n            imgUrl = img['middleURL']\n        elif 'thumbURL' in img:\n            imgUrl = img['thumbURL']\n        elif imgUrl == '':\n            return None\n        if 'is_gif' in img and img['is_gif'] == 1:\n            is_gif = 1\n        else:\n            is_gif = 0\n        res = requests.get(imgUrl)\n        if res.status_code != 200:\n            continue\n        md5 = hashlib.md5()\n        md5.update(res.content)\n        fileName = md5.hexdigest() + '.gif' if is_gif else md5.hexdigest() + '.png'\n        path = os.path.join('tmp', fileName)\n        with open(path, 'wb') as f:\n            f.write(res.content)\n        yield path\n\n\ndef getDoutulaImgPath(text: str) -> [Iterable, None]:\n    \"\"\"\n    从斗图啦表情包接口拉取图片\n    :param text: 搜索关键字\n    :return: 图片路径迭代器或者None\n    \"\"\"\n    url = 'https://www.doutula.com/search?keyword=' + text\n    headers = {\n        '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',\n        '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',\n        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'}\n    res = requests.get(url, headers=headers)\n    if res.status_code != 200:\n        return None\n    soup = BeautifulSoup(res.text, 'html.parser')\n    randomPics = soup.find_all('a', attrs={'class': 'col-xs-6 col-md-2'})\n    for pic in randomPics:\n        imgUrl = pic.find('img', attrs={'referrerpolicy': 'no-referrer'})['data-original']\n        try:\n            res = requests.get(imgUrl)\n        except:\n            return None\n        if res.status_code != 200:\n            continue\n        path = os.path.join('tmp', imgUrl[imgUrl.rfind('/') + 1:])\n        with open(path, 'wb') as f:\n            f.write(res.content)\n        yield path\n\n\ndef resizeImg(width: int, height: int) -> (int, int):\n    \"\"\"\n    重新设置图片大小\n    :param width: 图片宽度\n    :param height: 图片高度\n    :return: (width, height)\n    \"\"\"\n    default_width, default_height = 440, 360\n    if (width < default_width and height < default_height) or (width > default_width and height > default_height):\n        # 如果比例大于1.5,就不强制拉伸,按照宽度进行缩放\n        if width / height >= 1.5:\n            width, height = default_width, height * default_width / width\n        elif height / width > 1.5:\n            height, width = default_height, width * default_height / height\n        else:\n            # 小于1.5的强制拉伸\n            width, height = default_width, default_height\n    elif width > default_width and height <= default_height:\n        width, height = default_width, height * default_width / width\n    if height > default_height and width <= default_width:\n        height, width = default_height, width * default_height / height\n    return width, height\n\n\ndef convertToRGB(path: str) -> None:\n    \"\"\"\n    如果图片不是RGB模式,则转换成RGB模式,否则生成视频会出错\n    :param path: 图片路径\n    :return: None\n    \"\"\"\n    # convert to RGB\n    im = Image.open(path)\n    if im.mode != 'RGB':\n        im = im.convert('RGB')\n\n    # 获取exif是否正常,不正常则添加\n    try:\n        im.getexif()\n        im.save(path)\n    except:\n        exif_dict = {}\n        exif_dat = piexif.dump(exif_dict)\n        im.save(path, exif=exif_dat)\n\n\ndef baiduTranslate(text: str, zhcn2en: bool = True) -> str:\n    \"\"\"\n    将中文翻译成英文\n    :param text: 中文/英文\n    :param zhcn2en : 是否为中文转英文, 默认为是\n    :return: 英文/中文\n    \"\"\"\n    url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'\n    headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n    data = BAIDUAPPID + text + url + BAIDUAPPKEY\n    md5 = hashlib.md5()\n    md5.update(data.encode('utf-8'))\n    if zhcn2en:\n        data = {'appid': BAIDUAPPID, 'q': text, 'from': 'zh', 'to': 'en', 'salt': url, 'sign': md5.hexdigest()}\n    else:\n        data = {'appid': BAIDUAPPID, 'q': text, 'from': 'en', 'to': 'zh', 'salt': url, 'sign': md5.hexdigest()}\n    res = requests.post(url, data=data, headers=headers)\n    if res.status_code != 200:\n        return ''\n    res = json.loads(res.text)\n    if 'trans_result' not in res:\n        return ''\n    result = ''\n    for trans in res['trans_result']:\n        result += trans['dst'] + '。'\n    return result\n\n\n# TODO\n# 有点儿问题, 翻译的结果为多行的时候解决比较麻烦\ndef googleTranslate(text: str, zhcn2en: bool = True) -> str:\n    \"\"\"\n    将中文翻译成英文\n    :param text: 中文/英文\n    :param zhcn2en : 是否为中文转英文, 默认为是\n    :return: 英文/中文\n    \"\"\"\n    global proxies\n    global verify\n    text = text.replace('\\n', r'\\\\n').replace('\"', r'\\\\\\\"')\n    url = 'https://translate.google.cn/_/TranslateWebserverUi/data/batchexecute'\n    if zhcn2en:\n        data = '[[[\"MkEWBc\",\"[[\\\\\"{}\\\\\",\\\\\"zh-CN\\\\\",\\\\\"en\\\\\",true],[null]]\",null,\"generic\"]]]'.format(text)\n    else:\n        data = '[[[\"MkEWBc\",\"[[\\\\\"{}\\\\\",\\\\\"en\\\\\",\\\\\"zh-CN\\\\\",true],[null]]\",null,\"generic\"]]]'.format(text)\n    data = quote(data)\n    data = 'f.req=' + data + '&'\n    headers = {\n        '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',\n        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',\n        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'}\n    res = requests.post(url=url, data=data, headers=headers, verify=verify, proxies=proxies)\n    if res.status_code != 200:\n        return ''\n    lIndex = res.text.find('l,[[\\\\\"')\n    rIndex = res.text.find('\\\\\"', lIndex + len('l,[[\\\\\"'))\n    if lIndex != -1 and rIndex != -1:\n        text = res.text[lIndex + len('l,[[\\\\\"'):rIndex]\n        text = text.replace(r'\\\\n', '\\n').replace(r'\\\\\\\"', '\"')\n        return text\n    return ''\n\n\ndef getTips(text: str) -> str:\n    \"\"\"\n    获取指定文本的生成文本信息\n    :param text: 线索文本\n    :return: 生成的文本\n    \"\"\"\n    global proxies\n    global verify\n    # 中文 -> 英文\n    text = baiduTranslate(text)\n    if text == '':\n        return ''\n    # 获取生成文本结果\n    url = 'https://api.deepai.org/api/text-generator'\n    data = {'text': text}\n    headers = {'api-key': APIKEY}\n    res = requests.post(url, files=data, headers=headers, verify=verify, proxies=proxies)\n    if res.status_code != 200:\n        return ''\n    res = json.loads(res.text)\n    if 'output' not in res:\n        return ''\n    text = res['output']\n    # 英文 -> 中文\n    text = baiduTranslate(text, zhcn2en=False).replace('\\n\\n', '\\n')\n    return text\n\n\ndef setProxies(switch: bool=False) -> None:\n    \"\"\"\n    是否采用代理\n    :param switch: 是\n    :return: None\n    \"\"\"\n    global proxies\n    global verify\n    if switch:\n        proxies = {'https': '127.0.0.1:8887',\n                   'http': '127.0.0.1:8887'}\n        verify = False\n    else:\n        proxies = None\n        verify = True\n"
  }
]