[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\n#github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]\n#patreon: # Replace with a single Patreon username\n#open_collective: # Replace with a single Open Collective username\n#ko_fi: # Replace with a single Ko-fi username\n#tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\n#community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\n#liberapay: # Replace with a single Liberapay username\n#issuehunt: # Replace with a single IssueHunt username\n#otechie: # Replace with a single Otechie username\n#lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry\ncustom: ['https://www.buymeacoffee.com/a2569875']\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n    \"python.envFile\": \"${workspaceFolder}/.env\",\n    \"python.defaultInterpreterPath\": \"${workspaceFolder}/../../sd.webui/webui/venv/Scripts/\"\n}"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n                       \nCopyright (c) 2023 a2569875/Chang Yu-Fan(張宇帆) – a2569875@gmail.com ; and opparco.\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 Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\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,\nour General Public Licenses are 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.\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  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\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 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 work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be 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 Affero 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 Affero 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 Affero 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 Affero General Public License as published\n    by 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 Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\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 AGPL, see\n<https://www.gnu.org/licenses/>.\n\n===================================================================\n\nThe Original is MIT License\nThis program was developed based on the opparco's original version\n\nCopyright (c) 2023 opparco\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.ja.md",
    "content": "[![Python](https://img.shields.io/badge/Python-%E2%89%A73.10-blue)](https://www.python.org/downloads/)\n[![License](https://img.shields.io/github/license/a2569875/stable-diffusion-webui-composable-lora)](https://github.com/a2569875/stable-diffusion-webui-composable-lora/blob/main/LICENSE)\n# Composable LoRA/LyCORIS with steps\nこの拡張機能は、内部のforward LoRAプロセスを置き換え、同時にLoCon、LyCORISをサポートします。\n\nこの拡張機能はComposable LoRAのフォークです。\n\n[![buy me a coffee](readme/Artboard.svg)](https://www.buymeacoffee.com/a2569875 \"buy me a coffee\")\n\n[![stable-diffusion-webui-composable-lycoris](https://res.cloudinary.com/marcomontalbano/image/upload/v1683643967/video_to_markdown/images/youtube--QS9yjSMySuY-c05b58ac6eb4c4700831b2b3070cd403.jpg)](https://www.youtube.com/watch?v=QS9yjSMySuY \"stable-diffusion-webui-composable-lycoris\")\n\n### 言語\n* [英語](README.md) (グーグル翻訳)\n* [台湾中国語](README.zh-tw.md)  \n* [簡体字中国語](README.zh-cn.md) (ウィキペディア 従来および簡略化された変換システム)\n\n## インストール\n注意: このバージョンのComposable LoRAには、元のComposable LoRAのすべての機能が含まれています。1つ選んでインストールするだけです。\n\nこの拡張機能は、元のバージョンのComposable LoRA拡張機能と同時に使用できません。インストールする前に、`webui\\extensions\\`フォルダー内の`stable-diffusion-webui-composable-lora`フォルダーを削除する必要があります。\n\n次に、WebUIの\\[Extensions\\] -> \\[Install from URL\\]で以下のURLを入力します。\n```\nhttps://github.com/a2569875/stable-diffusion-webui-composable-lora.git\n```\nインストールして再起動します。\n\n## デモ\nここでは2つのLoRA（1つはLoHA、もう1つはLoCon）を紹介します。 \n* [`<lora:roukin8_loha:0.8>`](https://civitai.com/models/17336/roukin8-character-lohaloconfullckpt-8) に対応するトリガーワード： `yamanomitsuha`\n* `<lora:dia_viekone_locon:0.8>` に対応するトリガーワード： `dia_viekone_\\(ansatsu_kizoku\\)`\n\n[Latent Couple extension](https://github.com/opparco/stable-diffusion-webui-two-shot)と組み合わせます。\n\n以下はその効果です。\n![](readme/fig11.png)\n\n以下のことが分かります。\n- `<lora:roukin8_loha:0.8>`を`yamanomitsuha`と組み合わせ、そして`<lora:dia_viekone_locon:0.8>`を`dia_viekone_\\(ansatsu_kizoku\\)`と組み合わせることで、対応するキャラクターを描画できます。\n- モデルのトリガーワードが互いに交換され、一致しなくなった場合、2つのキャラクターは描画できません。これは`<lora:roukin8_loha:0.8>`が画像の左側のブロックにのみ制限されているため、そして`<lora:dia_viekone_locon:0.8>`が画像の右側のブロックにのみ制限されているためです。したがって、このアルゴリズムは有効です。\n\n画像のヒントの文法には[sd-webui-prompt-highlight](https://github.com/a2569875/sd-webui-prompt-highlight)プラグインが使用されています。\n\nこのテストは2023年5月14日に行われ、使用されたStable Diffusion WebUIのバージョンは[v1.2 (89f9faa)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/89f9faa63388756314e8a1d96cf86bf5e0663045)です。\n\n(Note: You should enable \\[`Lora: use old method that takes longer when you have multiple Loras active and produces same results as kohya-ss/sd-webui-additional-networks extension`\\] in setting page.)\n\n2023年7月25日、Stable Diffusion WebUIバージョン[v1.5.0 (a3ddf46)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/a3ddf464a2ed24c999f67ddfef7969f8291567be)を使用して、もう一つのテストが行われました。私自身が訓練したヒヨリのLoConモデルと、私自身が訓練したディア・ヴィコーネのLoConモデルの両方を使用しました。\n![](readme/fig13.png)\n\n## 機能\n### Composable-Diffusionと互換性がある\nLoRAの挿入箇所を`AND`構文と関連付け、LoRAの影響範囲を特定のサブプロンプト内に限定します（特定の`AND...AND`ブロック内）。\n\n### ステップに基づく可組合性\n形式`[A:B:N]`のプロンプトにLoRAを配置し、LoRAの影響範囲を特定のグラフィックステップに制限します。\n![](readme/fig9.png)\n\n### LoRA重み制御\n`[A #xxx]`構文を追加して、LoRAの各グラフィックステップでの重みを制御できます。\n現在、サポートされているものは以下のとおりです。\n* `decrease`\n     - LoRAの有効なステップ数で徐々に重みを減少させ、0になります\n* `increment`\n     - LoRAの有効なステップ数で0から重みを徐々に増加させます\n* `cmd(...)`\n     - カスタムの重み制御コマンドで、主にPython構文を使用します。\n         * 使用可能なパラメータ\n             + `weight`\n                 * 現在のLoRA重み\n             + `life`\n                 * 0-1の数字で、現在のLoRAのライフサイクルを表します。開始ステップ数にある場合は0であり、このLoRAが最後に適用されるステップ数にある場合は1です。\n             + `step`\n                 * 現在のステップ数\n             + `steps`\n                 * 全ステップ数\n             + `lora`\n                 * 現在のLoRAオブジェクト\n             + `lora_module`\n                 * 現在のLoRA作用層オブジェクト\n             + `lora_type`\n                 * 現在のLoRAのロードされた種類で、`lora`または`lyco`のいずれかです。\n             + `lora_name`\n                 * 現在のLoRAの名前\n             + `lora_count`\n                 * すべてのLoRAの数\n             + `block_lora_count`\n                 * 作用中の`AND...AND`ブロック内のLoRAの数\n             + `is_negative`\n                 * 反転提示語であるかどうか\n             + `layer_name`\n                 * 現在の作用層の名前。これを使用して、[LoRA Block Weight](https://github.com/hako-mikan/sd-webui-lora-block-weight)の効果をシミュレートできます。\n             + `current_prompt`\n                 * 作用中の`AND...AND`ブロック内のプロンプト\n             + `sd_processing`\n                 * sd画像の生成パラメータ\n             + `enable_prepare_step`\n                 * (出力用パラメータ) Trueに設定すると、この重みがtransformer text model encoder層に適用されます。 step == -1の場合は、現在transformer text model encoder層にいます。\n         * 使用可能な関数は以下の通りです\n             + `warmup(x)`\n                 * xは0から1までの数値で、総ステップ数に対して、xの比率以下のステップでは関数値が0から1に徐々に上昇し、x以降は1になります。\n             + `cooldown(x)`\n                 * xは0から1までの数値で、総ステップ数に対して、xの比率以上のステップでは関数値が1から0に徐々に減少し、0になります。\n             + sin, cos, tan, asin, acos, atan\n                 * すべてのステップを周期とする三角関数です。sin、cosの値は0から1に変更されます。\n             + sinr, cosr, tanr, asinr, acosr, atanr\n                 * 弧度単位の周期2*piの三角関数です。\n             + abs, ceil, floor, trunc, fmod, gcd, lcm, perm, comb, gamma, sqrt, cbrt, exp, pow, log, log2, log10\n                 * Pythonのmath関数ライブラリと同じ関数です。\n例 :\n* `[<lora:A:1>::10]`\n     - 名前がAのLoRAを使用して、10ステップで停止します。\n       ![](readme/fig1.png)\n* `[<lora:A:1>:<lora:B:1>:10]`\n     - 名前がAのLoRAを、10ステップまで使用し、10ステップから名前がBのLoRAを使用します。\n       ![](readme/fig2.png)\n* `[<lora:A:1>:10]`\n     - 10ステップから名前がAのLoRAを使用します。\n* `[<lora:A:1>:0.5]`\n     - 50％のステップから名前がAのLoRAを使用します。\n* `[[<lora:A:1>::25]:10]`\n     - 10ステップから名前がAのLoRAを使用し、25ステップで使用を停止します。\n       ![](readme/fig3.png)\n* `[<lora:A:1> #increment:10]`\n     - 名前がAのLoRAを使用する期間中に重みを0から線形に増加させ、設定された重みに到達します。そして、10ステップからこのLoRAを使用します。\n       ![](readme/fig4.png)\n* `[<lora:A:1> #decrease:10]`\n     - 名前がAのLoRAを使用する期間中に重みを1から線形に減少させ、0に到達します。そして、10ステップからこのLoRAを使用します。\n       ![](readme/fig5.png)\n* `[<lora:A:1> #cmd\\(warmup\\(0.5\\)\\):10]`\n     - 名前がAのLoRAを使用する期間中、重みはウォームアップ定数であり、0からこのLoRAのライフサイクルの50％に到達するまで線形に増加します。そして、10ステップからこのLoRAを使用します。\n     - ![](readme/fig6.png)\n* `[<lora:A:1> #cmd\\(sin\\(life\\)\\):20]`\n     - 名前がAのLoRAを使用する期間中、重みは正弦波であり、10ステップからこのLoRAを使用します。\n       ![](readme/fig7.png)\n\nすべての生成された画像:\n![](readme/fig8.png)\n\n### 反向トークンに対する影響の消去\n内蔵のLoRAを使用する場合、反転トークンは常にLoRAの影響を受けます。これは通常、出力に負の影響を与えます。この拡張機能は、負の影響を排除するオプションを提供します。\n\n## 使用方法\n### 有効化 (Enabled)\nこのオプションをオンにすると、Composable LoRAの機能を使用できるようになります。\n\n### Composable LoRA with step\n特定のステップでLoRAを有効または無効にする機能を使用するには、このオプションを選択する必要があります。\n\n### Use Lora in uc text model encoder\n言語モデルエンコーダー（text model encoder）の逆提示語部分でLoRAを使用します。\nこのオプションをオフにすると、より良い出力が期待できます。\n\n### Use Lora in uc diffusion model\n拡散モデル（diffusion model）またはデノイザー（denoiser）の逆提示語部分でLoRAを使用します。\nこのオプションをオフにすると、より良い出力が期待できます。\n\n### plot the LoRA weight in all steps\n\\[Composable LoRA with step\\]が選択されている場合、LoRAの重みが各ステップでどのように変化するかを観察するために、このオプションを選択できます。\n\n## 互換性\n`--always-batch-cond-uncond`は`--medvram`または`--lowvram`と一緒に使用する必要があります。\n\n## 更新ログ\n### 2023-04-02\n* LoCon、LyCORISサポートを追加\n* 不具合を修正：IndexError: list index out of range\n### 2023-04-08\n* 複数の異なるANDブロックで同じLoRAを使用できるようにする\n  ![](readme/changelog_2023-04-08.png)\n### 2023-04-13\n* 2023-04-08のバージョンでpull requestを提出\n### 2023-04-19\n* pytorch 2.0を使用する場合に拡張がロードされない問題を修正\n* 不具合を修正: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda and cpu! (when checking argument for argument mat2 in method wrapper_CUDA_mm)\n### 2023-04-20\n* 特定のステップでLoRAを有効または無効にする機能を実装\n* LoCon、LyCORISの拡張プログラムを参考にし、異なるANDブロックおよびステップでのLoRAの有効化/無効化アルゴリズムを改善\n### 2023-04-21\n* 異なるステップ数でのLoRAの重みを制御する方法の実装 `[A #xxx]`\n* 異なるステップ数でのLoRAの重み変化を示すグラフの作成\n### 2023-04-22\n* 不具合を修正: AttributeError: 'Options' object has no attribute 'lora_apply_to_outputs'\n* 不具合を修正: RuntimeError: \"addmm_impl_cpu_\" not implemented for 'Half'\n\n## 特別な感謝\n*  [opparco: Composable LoRAの元の作者である](https://github.com/opparco)、[Composable LoRA](https://github.com/opparco/stable-diffusion-webui-composable-lora)\n*  [JackEllieのStable-Siffusionコミュニティチーム](https://discord.gg/TM5d89YNwA) 、 [YouTubeチャンネル](https://www.youtube.com/@JackEllie)\n*  [中文ウィキペディアのコミュニティチーム](https://discord.gg/77n7vnu)\n\n<p align=\"center\"><img src=\"https://count.getloli.com/get/@a2569875-stable-diffusion-webui-composable-lora.github\" alt=\"a2569875/stable-diffusion-webui-composable-lora\"></p>"
  },
  {
    "path": "README.md",
    "content": "[![Python](https://img.shields.io/badge/Python-%E2%89%A73.10-blue)](https://www.python.org/downloads/)\n[![License](https://img.shields.io/github/license/a2569875/stable-diffusion-webui-composable-lora)](https://github.com/a2569875/stable-diffusion-webui-composable-lora/blob/main/LICENSE)\n# Composable LoRA/LyCORIS with steps\nThis extension replaces the built-in LoRA forward procedure and provides support for LoCon and LyCORIS.\n\nThis extension is forked from the Composable LoRA extension.\n\n[![buy me a coffee](readme/Artboard.svg)](https://www.buymeacoffee.com/a2569875 \"buy me a coffee\")\n\n[![stable-diffusion-webui-composable-lycoris](https://res.cloudinary.com/marcomontalbano/image/upload/v1683643967/video_to_markdown/images/youtube--QS9yjSMySuY-c05b58ac6eb4c4700831b2b3070cd403.jpg)](https://www.youtube.com/watch?v=QS9yjSMySuY \"stable-diffusion-webui-composable-lycoris\")\n\n### Language\n* [繁體中文](README.zh-tw.md)  \n* [简体中文](README.zh-cn.md) (Wikipedia zh converter)\n* [日本語](README.ja.md) (ChatGPT)\n\n## Installation\nNote: This version of Composable LoRA already includes all the features of the original version of Composable LoRA. You only need to select one to install.\n\nThis extension cannot be used simultaneously with the original version of the Composable LoRA extension. Before installation, you must first delete the `stable-diffusion-webui-composable-lora` folder of the original version of the Composable LoRA extension in the `webui\\extensions\\` directory.\n\nNext, go to \\[Extension\\] -> \\[Install from URL\\] in the webui and enter the following URL:\n```\nhttps://github.com/a2569875/stable-diffusion-webui-composable-lora.git\n```\nInstall and restart to complete the process.\n\n## Demo\nHere we demonstrate two LoRAs (one LoHA and one LoCon), where\n* [`<lora:roukin8_loha:0.8>`](https://civitai.com/models/17336/roukin8-character-lohaloconfullckpt-8) corresponds to the trigger word `yamanomitsuha`\n* `<lora:dia_viekone_locon:0.8>` corresponds to the trigger word `dia_viekone_\\(ansatsu_kizoku\\)`\n\nWe use the [Latent Couple extension](https://github.com/opparco/stable-diffusion-webui-two-shot) for generating the images.\n\nThe results are shown below:\n![](readme/fig11.png)\n\nIt can be observed that:\n- The combination of `<lora:roukin8_loha:0.8>` with `yamanomitsuha`, and `<lora:dia_viekone_locon:0.8>` with `dia_viekone_\\(ansatsu_kizoku\\)` can successfully generate the corresponding characters.\n- When the trigger words are swapped, causing a mismatch, both characters cannot be generated successfully. This demonstrates that `<lora:roukin8_loha:0.8>` is restricted to the left half of the image, while `<lora:dia_viekone_locon:0.8>` is restricted to the right half of the image. Therefore, the algorithm is effective.\n\nThe highlighting of the prompt words on the image is done using the [sd-webui-prompt-highlight](https://github.com/a2569875/sd-webui-prompt-highlight) plugin.\n\nThis test was conducted on May 14, 2023, using Stable Diffusion WebUI version [v1.2 (89f9faa)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/89f9faa63388756314e8a1d96cf86bf5e0663045).\n\nAnother test was conducted on July 25, 2023, using Stable Diffusion WebUI version [v1.5.0 (a3ddf46)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/a3ddf464a2ed24c999f67ddfef7969f8291567be). Using hiyori \\(princess_connect!\\) and dia viekone locon model that I trained myself. \n![](readme/fig13.png)\n\n## Features\n### Compatible with Composable-Diffusion\nBy associating LoRA's insertion position in the prompt with `AND` syntax, LoRA's scope of influence is limited to a specific subprompt.\n\n### Composable with step\nBy placing LoRA within a prompt in the form of `[A:B:N]`, the scope of LoRA's effect is limited to specific drawing steps.\n![](readme/fig9.png)\n\n### LoRA weight controller\nAdded a syntax `[A #xxx]` to control the weight of LoRA at each drawing step. \n\nYou can replace the `#` symbol with `\\u0023`, if `#` didn't work.\n\nCurrently supported options are:\n* `decrease`\n     - Gradually decrease weight within the effective steps of LoRA until 0.\n* `increment`\n     - Gradually increase weight from 0 within the effective steps of LoRA.\n* `cmd(...)`\n     - A customizable weight control command, mainly using Python syntax.\n         * Available parameters\n             + `weight`\n                 * The current weight of LoRA.\n             + `life`\n                 * A number between 0-1, indicating the current life cycle of LoRA. It is 0 when it is at the starting step and 1 when it is at the final step of this LoRA's effect.\n             + `step`\n                 * The current step number.\n             + `steps`\n                 * The total number of steps.\n             + `lora`\n                 * The current LoRA object.\n             + `lora_module`\n                 * The current LoRA working layer object.\n             + `lora_type`\n                 * The type of LoRA being loaded, which may be `lora` or `lyco`.\n             + `lora_name`\n                 * The name of the current LoRA.\n             + `lora_count`\n                 * The number of all LoRAs.\n             + `block_lora_count`\n                 * The number of LoRAs in the `AND...AND` block currently being used.\n             + `is_negative`\n                 * Whether it is a negative prompt.\n             + `layer_name`\n                 * The name of the current working layer. You can use this to determine and simulate the effect of [LoRA Block Weight](https://github.com/hako-mikan/sd-webui-lora-block-weight).\n             + `current_prompt`\n                 * The prompt currently being used in the `AND...AND` block.\n             + `sd_processing`\n                 * Parameters for generating the SD image.\n             + `enable_prepare_step`\n                 * (Output parameter) If set to True, it means that this weight will be applied to the transformer text model encoder layer. If step == -1, it means that the current layer is in the transformer text model encoder layer.\n         * Available functions\n             + `warmup(x)`\n                 * x is a number between 0-1, representing a warmup constant. Calculated based on the total number of steps, the function value gradually increases from 0 to 1 until x is reached.\n             + `cooldown(x)`\n                 * x is a number between 0-1, representing a cooldown constant. Calculated based on the total number of steps, the function value gradually decreases from 1 to 0 after x.\n             + sin, cos, tan, asin, acos, atan\n                 * Trigonometric functions with all steps as the period. The values of sin and cos are expected to be between 0 and 1.\n             + sinr, cosr, tanr, asinr, acosr, atanr\n                 * Trigonometric functions in radians, with a period of 2π.\n             + abs, ceil, floor, trunc, fmod, gcd, lcm, perm, comb, gamma, sqrt, cbrt, exp, pow, log, log2, log10\n                 * Functions in the math library of Python.\nExample :\n* `[<lora:A:1>::10]`\n     - Use LoRA named A until step 10.\n       ![](readme/fig1.png)\n* `[<lora:A:1>:<lora:B:1>:10]`\n     - Use LoRA named A until step 10, then switch to LoRA named B.\n       ![](readme/fig2.png)\n* `[<lora:A:1>:10]`\n     - Start using LoRA named A from step 10.\n* `[<lora:A:1>:0.5]`\n     - Start using LoRA named A from 50% of the steps.\n* `[[<lora:A:1>::25]:10]`\n     - Start using LoRA named A from step 10 until step 25.\n       ![](readme/fig3.png)\n* `[<lora:A:1> #increment:10]`\n     - During the usage of LoRA named A, increment the weight linearly from 0 to the specified weight, starting from step 10.\n       ![](readme/fig4.png)\n* `[<lora:A:1> #decrease:10]`\n     - During the usage of LoRA named A, decrease the weight linearly from 1 to 0, starting from step 10.\n       ![](readme/fig5.png)\n* `[<lora:A:1> #cmd\\(warmup\\(0.5\\)\\):10]`\n     - During the usage of LoRA named A, set the weight to the warm-up constant and increase it linearly from 0 to the specified weight until 50% of the LoRA lifecycle is reached, starting from step 10.\n     - ![](readme/fig6.png)\n* `[<lora:A:1> #cmd\\(sin\\(life\\)\\):10]`\n     - During the usage of LoRA named A, set the weight to a sine wave, starting from step 10.\n       ![](readme/fig7.png)\n```python\n[<lora:A:1> #cmd\\(\ndef my_func\\(\\)\\:\n    return sin\\(life\\)\nmy_func\\(\\)\n\\):10]\n```\n- same as `[<lora:A:1> #cmd\\(sin\\(life\\)\\):10]`, but using function syntax.\n\nAll the image:\n![](readme/fig8.png)\n\n* Note : \n   - Try `[<lora:A:1> \\u0023cmd\\(sin\\(life\\)\\):10]` if `[<lora:A:1> #cmd\\(sin\\(life\\)\\):10]` doesn't work.\n   - Try `[<lora:A:1> \\u0023increment:10]` if `[<lora:A:1> #increment:10]` doesn't work.\n\n\n### Eliminate the impact on negative prompts\nWith the built-in LoRA, negative prompts are always affected by LoRA. This often has a negative impact on the output.\nSo this extension offers options to eliminate the negative effects.\n\n## How to use\n### Enabled\nWhen checked, Composable LoRA is enabled.\n\n### Composable LoRA with step\nCheck this option to enable the feature of turning on or off LoRAs at specific steps.\n\n### Use Lora in uc text model encoder\nEnable LoRA for uncondition (negative prompt) text model encoder.\nWith this disabled, you can expect better output.\n\n### Use Lora in uc diffusion model\nEnable LoRA for uncondition (negative prompt) diffusion model (denoiser).\nWith this disabled, you can expect better output.\n\n### plot the LoRA weight in all steps\nIf \"Composable LoRA with step\" is enabled, you can select this option to generate a chart that shows the relationship between LoRA weight and the number of steps after the drawing is completed. This allows you to observe the variation of LoRA weight at each step.\n\n### Other\n* If the image you generated becomes like this:\n  ![](readme/fig10.png)\n  try the following steps to solve it:\n  1. Disable Composable LoRA first\n  2. Temporarily remove all LoRA from your prompt\n  3. Randomly generate a image\n  4. If the image of the habitat is normal, enable Composable LoRA again\n  5. Add the LoRA you just removed back to the prompt\n  6. It should be able to generate pictures normally\n\n## Compatibilities\n`--always-batch-cond-uncond` must be enabled  with `--medvram` or `--lowvram`\n\n## Changelog\n### 2023-04-02\n* Added support for LoCon and LyCORIS\n* Fixed error: IndexError: list index out of range\n### 2023-04-08\n* Allow using the same LoRA in multiple AND blocks\n  ![](readme/changelog_2023-04-08.png)\n### 2023-04-13\n* Submitted pull request for the 2023-04-08 version\n### 2023-04-19\n* Fixed loading extension failure issue when using pytorch 2.0\n* Fixed error: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda and cpu! (when checking argument for argument mat2 in method wrapper_CUDA_mm)\n### 2023-04-20\n* Implemented the function of enabling or disabling LoRA at specific steps\n* Improved the algorithm for enabling or disabling LoRA in different AND blocks and steps, by referring to the code of LoCon and LyCORIS extensions\n### 2023-04-21\n* Implemented the method to control different weights of LoRA at different steps (`[A #xxx]`)\n* Plotted a chart of LoRA weight changes at different steps\n### 2023-04-22\n* Fixed error: AttributeError: 'Options' object has no attribute 'lora_apply_to_outputs'\n* Fixed error: RuntimeError: \"addmm_impl_cpu_\" not implemented for 'Half'\n### 2023-04-23\n* Fixed the problem that sometimes LoRA cannot be removed after being added\n### 2023-04-25\n* Add support for `<lyco:MODEL>` syntax.\n\n## Acknowledgements\n*  [opparco, Composable LoRA original author](https://github.com/opparco)、[Composable LoRA](https://github.com/opparco/stable-diffusion-webui-composable-lora)\n*  [JackEllie's Stable-Siffusion community team](https://discord.gg/TM5d89YNwA) 、 [Youtube channel](https://www.youtube.com/@JackEllie)\n*  [Chinese Wikipedia community team](https://discord.gg/77n7vnu)\n\n<p align=\"center\"><img src=\"https://count.getloli.com/get/@a2569875-stable-diffusion-webui-composable-lora.github\" alt=\"a2569875/stable-diffusion-webui-composable-lora\"></p>"
  },
  {
    "path": "README.zh-cn.md",
    "content": "[![Python](https://img.shields.io/badge/Python-%E2%89%A73.10-blue)](https://www.python.org/downloads/)\n[![License](https://img.shields.io/github/license/a2569875/stable-diffusion-webui-composable-lora)](https://github.com/a2569875/stable-diffusion-webui-composable-lora/blob/main/LICENSE)\n# Composable LoRA/LyCORIS with steps\n这个扩展取代了内置的 forward LoRA 过程，同时提供对LoCon、LyCORIS的支持。\n\n本扩展Fork自Composable LoRA扩展\n\n[![buy me a coffee](readme/Artboard.svg)](https://www.buymeacoffee.com/a2569875 \"buy me a coffee\")\n\n[![stable-diffusion-webui-composable-lycoris](https://res.cloudinary.com/marcomontalbano/image/upload/v1683643967/video_to_markdown/images/youtube--QS9yjSMySuY-c05b58ac6eb4c4700831b2b3070cd403.jpg)](https://www.youtube.com/watch?v=QS9yjSMySuY \"stable-diffusion-webui-composable-lycoris\")\n\n### 语言\n* [繁体中文](README.zh-tw.md)  \n* [英语](README.md) (google translate)\n* [日语](README.ja.md) (ChatGPT)\n\n## 安装\n注意 : 这个版本的Composable LoRA已经包含了原版Composable LoRA的所有功能，只要选一个安装就好。\n\n此扩展不能与原始版本的Composable LoRA扩展同时使用，安装前必须先删除原始版本的Composable LoRA扩展。请先到`webui\\extensions\\`文件夹下删除`stable-diffusion-webui-composable-lora`文件夹\n\n接下来到webui的\\[扩展\\] -> \\[从网址安装\\]输入以下网址:\n```\nhttps://github.com/a2569875/stable-diffusion-webui-composable-lora.git\n```\n安装并重启即可\n\n## 演示\n这里示范两个LoRA (分别为LoHA和LoCon) ，其中\n* [`<lora:roukin8_loha:0.8>`](https://civitai.com/models/17336/roukin8-character-lohaloconfullckpt-8) 对应的触发词: `yamanomitsuha`\n* `<lora:dia_viekone_locon:0.8>` 对应的触发词: `dia_viekone_\\(ansatsu_kizoku\\)`\n\n并搭配[Latent Couple extension](https://github.com/opparco/stable-diffusion-webui-two-shot)\n\n效果如下:\n![](readme/fig11.png)\n可以看到:\n- 当我`<lora:roukin8_loha:0.8>`搭配`yamanomitsuha`，以及`<lora:dia_viekone_locon:0.8>`搭配`dia_viekone_\\(ansatsu_kizoku\\)`的组合可以顺利画出对应角色；\n- 当模型触发词互相交换而导致不匹配时，两个角色都无法顺利画出，可见`<lora:roukin8_loha:0.8>`被限制在只作用于图片的左半边区块、而`<lora:dia_viekone_locon:0.8>`被限制在只作用于图片的右半边区块，因此这个算法是有效的。\n\n图片上的提示词语法使用[sd-webui-prompt-highlight](https://github.com/a2569875/sd-webui-prompt-highlight)插件進行上色。\n\n本次测试于2023年5月14日完成，使用Stable Diffusion WebUI版本为[v1.2 (89f9faa)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/89f9faa63388756314e8a1d96cf86bf5e0663045)\n\n(Note: You should enable \\[`Lora: use old method that takes longer when you have multiple Loras active and produces same results as kohya-ss/sd-webui-additional-networks extension`\\] in setting page.)\n\n另一次测试于2023年7月25日完成，使用Stable Diffusion WebUI版本为[v1.5.0 (a3ddf46)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/a3ddf464a2ed24c999f67ddfef7969f8291567be)。 测试中使用了自行训练的春咲日和莉和蒂雅·维科尼LoCon模型模型。\n![](readme/fig13.png)\n\n## 功能\n### 与 Composable-Diffusion 兼容\n将 LoRA 在提示词中的插入位置与`AND`语法相关系，让 LoRA 的影响范围限制在特定的子提示词中 (特定 AND...AND区块中)。\n\n### 在步骤数上的 Composable\n使 LoRA 支持放置在形如`[A:B:N]`的提示词语法中，让 LoRA 的影响范围限制在特定的绘图步骤上。\n![](readme/fig9.png)\n\n### LoRA 权重控制\n添加了一个语法`[A #xxx]`可以用来控制LoRA在每个绘图步骤的权重\n\n如果 `#` 不起作用，您可以将 `#` 符号替换为 `\\u0023`。 \n\n目前支持的有:\n* `decrease`\n     - 在LoRA的有效步骤数内逐渐递减权重直到0\n* `increment`\n     - 在LoRA的有效步骤数内从0开始逐渐递增权重\n* `cmd(...)`\n     - 自定义的权重控制指令，主要以python语法为主\n         * 可用参数\n             + `weight`\n                 * 当前的LoRA权重\n             + `life`\n                 * 0-1之间的数字，表示目前LoRA的生命周期。位于起始步骤数时为0，位于此LoRA最终作用的步骤数时为1\n             + `step`\n                 * 目前的步骤数\n             + `steps`\n                 * 总共的步骤数\n             + `lora`\n                 * 目前的LoRA物件\n             + `lora_module`\n                 * 目前的LoRA作用层物件\n             + `lora_type`\n                 * 目前的LoRA载入的种类，可能是`lora`或`lyco`\n             + `lora_name`\n                 * 目前的LoRA名称\n             + `lora_count`\n                 * 所有LoRA的数量\n             + `block_lora_count`\n                 * 作用中的`AND...AND`区块内LoRA的数量\n             + `is_negative`\n                 * 是否为反向提示词\n             + `layer_name`\n                 * 目前作用层名称。你可以用这来来判断并模拟[LoRA Block Weight](https://github.com/hako-mikan/sd-webui-lora-block-weight)的效果\n             + `current_prompt`\n                 * 作用中的`AND...AND`区块内的提示词\n             + `sd_processing`\n                 * sd图片生成的参数\n             + `enable_prepare_step`\n                 * (输出用参数) 如果设为True，则代表此权重会做用到transformer text model encoder层。如过step==-1代表目前在transformer text model encoder层。\n         * 可用函数\n             + `warmup(x)`\n                 * x为0-1之间的数字，表示一个预热的常数，以总步数计算，在低于x比例的步数时，函数值从0逐渐递增，直到x之后为1\n             + `cooldown(x)`\n                 * x为0-1之间的数字，表示一个冷却的常数，以总步数计算，在高于x比例的步数时，函数值从1逐渐递减，直到0\n             + sin, cos, tan, asin, acos, atan\n                 * 以所有步数为周期的三角函数。其中sin, cos的值预被改成0到1之间\n             + sinr, cosr, tanr, asinr, acosr, atanr\n                 * 以弧度为单位的三角函数，周期 2*pi。\n             + abs, ceil, floor, trunc, fmod, gcd, lcm, perm, comb, gamma, sqrt, cbrt, exp, pow, log, log2, log10\n                 * 同python的math函数库中的函数\n示例 :\n* `[<lora:A:1>::10]`\n     - 使用名为A的LoRA到第10步停止\n       ![](readme/fig1.png)\n* `[<lora:A:1>:<lora:B:1>:10]`\n     - 使用名为A的LoRA到第10步为止，从第10步开始换用名为B的LoRA\n       ![](readme/fig2.png)\n* `[<lora:A:1>:10]`\n     - 从第10步才开始使用名为A的LoRA\n* `[<lora:A:1>:0.5]`\n     - 从50%的步数才开始使用名为A的LoRA\n* `[[<lora:A:1>::25]:10]`\n     - 从第10步才开始使用名为A的LoRA，并且到第25步停止使用\n       ![](readme/fig3.png)\n* `[<lora:A:1> #increment:10]`\n     - 在名为A的LoRA使用期间，权重从0开始线性递增直到设置的权重，且从第10步才开始使用此LoRA\n       ![](readme/fig4.png)\n* `[<lora:A:1> #decrease:10]`\n     - 在名为A的LoRA使用期间，权重从1开始线性递减直到0，且从第10步才开始使用此LoRA\n       ![](readme/fig5.png)\n* `[<lora:A:1> #cmd\\(warmup\\(0.5\\)\\):10]`\n     - 在名为A的LoRA使用期间，权重为预热的常数，从0开始递增直到50%的此LoRA生命周期达到设置的权重，且从第10步才开始使用此LoRA\n     - ![](readme/fig6.png)\n* `[<lora:A:1> #cmd\\(sin\\(life\\)\\):20]`\n     - 在名为A的LoRA使用期间，权重为正弦波，且从第10步才开始使用此LoRA\n       ![](readme/fig7.png)\n```python\n[<lora:A:1> #cmd\\(\ndef my_func\\(\\)\\:\n    return sin\\(life\\)\nmy_func\\(\\)\n\\):10]\n```\n- 与`[<lora:A:1> #cmd\\(sin\\(life\\)\\):10]`相同，但用了函数语法 \n\n所有生成的图像 :\n![](readme/fig8.png)\n\n* 提示 :\n   - 如果`[<lora:A:1> #cmd\\(sin\\(life\\)\\):10]`无效的话，试试`[<lora:A:1> \\u0023cmd\\(sin\\(life\\)\\):10]`。\n   - 如果`[<lora:A:1> #increment:10]`无效的话，试试`[<lora:A:1> \\u0023increment:10]` \n\n### 消除对反向提示词的影响\n使用内置的 LoRA 时，反向提示词总是受到 LoRA 的影响。 这通常会对输出产生负面影响。\n而此扩展程序提供了消除负面影响的选项。\n\n## 使用方法\n### 激活 (Enabled)\n勾选此选项之后才能使用Composable LoRA的功能。\n\n### Composable LoRA with step\n勾选此选项之后才能使用在特定步数上激活或不激活LoRA的功能。\n\n### 在反向提示词的语言模型编码器上使用LoRA (Use Lora in uc text model encoder)\n在语言模型编码器(text model encoder)的反向提示词部分使用LoRA。\n关闭此选项后，您可以期待更好的输出。\n\n### 在反向提示词的扩散模型上上使用LoRA (Use Lora in uc diffusion model)\n在扩散模型(diffusion model)或称降噪器(denoiser)的反向提示词部分使用LoRA。\n关闭此选项后，您可以期待更好的输出。\n\n### 绘制LoRA权重与步数关系的图表 (plot the LoRA weight in all steps)\n如果有勾选\\[Composable LoRA with step\\]，可以勾选此选项来观察LoRA权重在每个步骤数上的变化\n\n### 其他\n* 如果你产生的图片崩成这样:\n  ![](readme/fig10.png)\n  可尝试以下步骤解决:\n  1. 先关闭Composable LoRA \n  2. 从你的提示词中暂时移除所有LoRA\n  3. 随便生成一张图片\n  4. 如果产生的图片是正常的，再次开启Composable LoRA\n  5. 再把刚才移除的LoRA加回去提示词中 (注意，要先开启Composable LoRA再加入LoRA语法)\n  6. 应该就能正常产生图片了 \n\n## 兼容性\n`--always-batch-cond-uncond`必须与`--medvram`或`--lowvram`一起使用\n\n## 更新日志\n### 2023-04-02\n* 新增LoCon、LyCORIS支持\n* 修正: IndexError: list index out of range\n### 2023-04-08\n* 允许在多个不同AND区块使用同一个LoRA\n  ![](readme/changelog_2023-04-08.png)\n### 2023-04-13\n* 2023-04-08的版本提交pull request\n### 2023-04-19\n* 修正使用 pytorch 2.0 时，扩展加载失败的问题\n* 修正: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda and cpu! (when checking argument for argument mat2 in method wrapper_CUDA_mm)\n### 2023-04-20\n* 实现控制LoRA在指定步数激活与不激活的功能\n* 参考LoCon、LyCORIS扩展的代码，改善LoRA在不同AND区块与步数激活与不激活的算法\n### 2023-04-21\n* 实现控制LoRA在不同步骤数能有不同权重的方法`[A #xxx]`\n* 绘制LoRA权重在不同步骤数之变化的图表\n### 2023-04-22\n* 修正: AttributeError: 'Options' object has no attribute 'lora_apply_to_outputs'\n* 修正: RuntimeError: \"addmm_impl_cpu_\" not implemented for 'Half'\n### 2023-04-23\n* 修正有时候LoRA加上去后会无法移除的问题 (症状 : 崩图。) \n### 2023-04-25\n* 加入对`<lyco:MODEL>`语法的支持。\n\n## 铭谢\n*  [Composable LoRA原始作者opparco](https://github.com/opparco)、[Composable LoRA](https://github.com/opparco/stable-diffusion-webui-composable-lora)\n*  [JackEllie的Stable-Siffusion的社群团队](https://discord.gg/TM5d89YNwA) 、 [Youtube频道](https://www.youtube.com/@JackEllie)\n*  [中文维基百科的社群团队](https://discord.gg/77n7vnu)\n\n<p align=\"center\"><img src=\"https://count.getloli.com/get/@a2569875-stable-diffusion-webui-composable-lora.github\" alt=\"a2569875/stable-diffusion-webui-composable-lora\"></p>"
  },
  {
    "path": "README.zh-tw.md",
    "content": "[![Python](https://img.shields.io/badge/Python-%E2%89%A73.10-blue)](https://www.python.org/downloads/)\n[![License](https://img.shields.io/github/license/a2569875/stable-diffusion-webui-composable-lora)](https://github.com/a2569875/stable-diffusion-webui-composable-lora/blob/main/LICENSE)\n# Composable LoRA/LyCORIS with steps\n這個擴展取代了內置的 forward LoRA 過程，同時提供對LoCon、LyCORIS的支援。\n\n本擴展Fork自Composable LoRA擴展\n\n[![buy me a coffee](readme/Artboard.svg)](https://www.buymeacoffee.com/a2569875 \"buy me a coffee\")\n\n[![stable-diffusion-webui-composable-lycoris](https://res.cloudinary.com/marcomontalbano/image/upload/v1683643967/video_to_markdown/images/youtube--QS9yjSMySuY-c05b58ac6eb4c4700831b2b3070cd403.jpg)](https://www.youtube.com/watch?v=QS9yjSMySuY \"stable-diffusion-webui-composable-lycoris\")\n\n### 語言\n* [英文](README.md) (google翻譯)\n* [简体中文](README.zh-cn.md) (維基百科繁簡轉換系統)\n* [日文](README.ja.md) (ChatGPT翻譯)\n\n## 安裝\n注意 : 這個版本的Composable LoRA已經包含了原版Composable LoRA的所有功能，只要選一個安裝就好。\n\n此擴展不能與原始版本的Composable LoRA擴展同時使用，安裝前必須先刪除原始版本的Composable LoRA擴展。請先到`webui\\extensions\\`資料夾下刪除`stable-diffusion-webui-composable-lora`資料夾\n\n接下來到webui的\\[擴充功能\\] -> \\[從網址安裝\\]輸入以下網址:\n```\nhttps://github.com/a2569875/stable-diffusion-webui-composable-lora.git\n```\n安裝並重新啟動即可\n\n## 演示\n這裡示範兩個LoRA (分別為LoHA和LoCon)，其中\n* [`<lora:roukin8_loha:0.8>`](https://civitai.com/models/17336/roukin8-character-lohaloconfullckpt-8) 對應的觸發詞: `yamanomitsuha`\n* `<lora:dia_viekone_locon:0.8>` 對應的觸發詞: `dia_viekone_\\(ansatsu_kizoku\\)`\n\n並搭配[Latent Couple extension](https://github.com/opparco/stable-diffusion-webui-two-shot)\n\n效果如下:\n![](readme/fig11.png)\n可以看到:\n- 當我`<lora:roukin8_loha:0.8>`搭配`yamanomitsuha`，以及`<lora:dia_viekone_locon:0.8>`搭配`dia_viekone_\\(ansatsu_kizoku\\)`的組合可以順利畫出對應角色；\n- 當模型觸發詞互相交換而導致不匹配時，兩個角色都無法順利畫出，可見`<lora:roukin8_loha:0.8>`被限制在只作用於圖片的左半邊區塊、而`<lora:dia_viekone_locon:0.8>`被限制在只作用於圖片的右半邊區塊，因此這個演算法是有效的。\n\n圖片上的提示詞語法使用[sd-webui-prompt-highlight](https://github.com/a2569875/sd-webui-prompt-highlight)插件進行上色。\n\n本次測試於2023年5月14日完成，使用Stable Diffusion WebUI版本為[v1.2 (89f9faa)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/89f9faa63388756314e8a1d96cf86bf5e0663045)\n\n另一次測試於2023年7月25日完成，使用Stable Diffusion WebUI版本為[v1.5.0 (a3ddf46)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/a3ddf464a2ed24c999f67ddfef7969f8291567be)。 測試中使用了自行訓練的《世界頂尖的暗殺者轉生為異世界貴族》蒂雅·維科尼和《公主連結》日和LoCon模型。\n![](readme/fig13.png)\n\n## 功能\n### 與 Composable-Diffusion 相容\n將 LoRA 在提示詞中的插入位置與`AND`語法相關聯，讓 LoRA 的影響範圍限制在特定的子提示詞中 (特定 AND...AND區塊中)。\n\n### 在步驟數上的 Composable\n使 LoRA 支援放置在形如`[A:B:N]`的提示詞語法中，讓 LoRA 的影響範圍限制在特定的繪圖步驟上。\n![](readme/fig9.png)\n\n### LoRA 權重控制\n添加了一個語法`[A #xxx]`可以用來控制LoRA在每個繪圖步驟的權重\n\n如果 `#` 不起作用，您可以將 `#` 符號替換為 `\\u0023`。\n\n目前支援的有:\n* `decrease`\n     - 在LoRA的有效步驟數內逐漸遞減權重直到0\n* `increment`\n     - 在LoRA的有效步驟數內從0開始逐漸遞增權重\n* `cmd(...)`\n     - 自定義的權重控制指令，主要以python語法為主\n         * 可用參數\n             + `weight`\n                 * 當前的LoRA權重\n             + `life`\n                 * 0-1之間的數字，表示目前LoRA的生命週期。位於起始步驟數時為0，位於此LoRA最終作用的步驟數時為1\n             + `step`\n                 * 目前的步驟數\n             + `steps`\n                 * 總共的步驟數\n             + `lora`\n                 * 目前的LoRA物件\n             + `lora_module`\n                 * 目前的LoRA作用層物件\n             + `lora_type`\n                 * 目前的LoRA載入的種類，可能是`lora`或`lyco`\n             + `lora_name`\n                 * 目前的LoRA名稱\n             + `lora_count`\n                 * 所有LoRA的數量\n             + `block_lora_count`\n                 * 作用中的`AND...AND`區塊內LoRA的數量\n             + `is_negative`\n                 * 是否為反向提示詞\n             + `layer_name`\n                 * 目前作用層名稱。你可以用這來來判斷並模擬[LoRA Block Weight](https://github.com/hako-mikan/sd-webui-lora-block-weight)的效果\n             + `current_prompt`\n                 * 作用中的`AND...AND`區塊內的提示詞\n             + `sd_processing`\n                 * sd圖片生成的參數\n             + `enable_prepare_step`\n                 * (輸出用參數) 如果設為True，則代表此權重會做用到transformer text model encoder層。如過step==-1代表目前在transformer text model encoder層。\n         * 可用函數\n             + `warmup(x)`\n                 * x為0-1之間的數字，表示一個預熱的常數，以總步數計算，在低於x比例的步數時，函數值從0逐漸遞增，直到x之後為1\n             + `cooldown(x)`\n                 * x為0-1之間的數字，表示一個冷卻的常數，以總步數計算，在高於x比例的步數時，函數值從1逐漸遞減，直到0\n             + sin, cos, tan, asin, acos, atan\n                 * 以所有步數為週期的三角函數。其中sin, cos的值預被改成0到1之間\n             + sinr, cosr, tanr, asinr, acosr, atanr\n                 * 以弧度為單位的三角函數，週期 2*pi。\n             + abs, ceil, floor, trunc, fmod, gcd, lcm, perm, comb, gamma, sqrt, cbrt, exp, pow, log, log2, log10\n                 * 同python的math函數庫中的函數\n範例 :\n* `[<lora:A:1>::10]`\n     - 使用名為A的LoRA到第10步停止\n       ![](readme/fig1.png)\n* `[<lora:A:1>:<lora:B:1>:10]`\n     - 使用名為A的LoRA到第10步為止，從第10步開始換用名為B的LoRA\n       ![](readme/fig2.png)\n* `[<lora:A:1>:10]`\n     - 從第10步才開始使用名為A的LoRA\n* `[<lora:A:1>:0.5]`\n     - 從50%的步數才開始使用名為A的LoRA\n* `[[<lora:A:1>::25]:10]`\n     - 從第10步才開始使用名為A的LoRA，並且到第25步停止使用\n       ![](readme/fig3.png)\n* `[<lora:A:1> #increment:10]`\n     - 在名為A的LoRA使用期間，權重從0開始線性遞增直到設定的權重，且從第10步才開始使用此LoRA\n       ![](readme/fig4.png)\n* `[<lora:A:1> #decrease:10]`\n     - 在名為A的LoRA使用期間，權重從1開始線性遞減直到0，且從第10步才開始使用此LoRA\n       ![](readme/fig5.png)\n* `[<lora:A:1> #cmd\\(warmup\\(0.5\\)\\):10]`\n     - 在名為A的LoRA使用期間，權重為預熱的常數，從0開始遞增直到50%的此LoRA生命週期達到設定的權重，且從第10步才開始使用此LoRA\n     - ![](readme/fig6.png)\n* `[<lora:A:1> #cmd\\(sin\\(life\\)\\):20]`\n     - 在名為A的LoRA使用期間，權重為正弦波，且從第10步才開始使用此LoRA\n       ![](readme/fig7.png)\n```python\n[<lora:A:1> #cmd\\(\ndef my_func\\(\\)\\:\n    return sin\\(life\\)\nmy_func\\(\\)\n\\):10]\n```\n- 與`[<lora:A:1> #cmd\\(sin\\(life\\)\\):10]`相同，但用了函數語法\n\n所有生成的圖像 :\n![](readme/fig8.png)\n\n* 提示 :\n   - 如果`[<lora:A:1> #cmd\\(sin\\(life\\)\\):10]`沒有作用的話，試試`[<lora:A:1> \\u0023cmd\\(sin\\(life\\)\\):10]`。\n   - 如果`[<lora:A:1> #increment:10]`沒有作用的話，試試`[<lora:A:1> \\u0023increment:10]` 。\n\n### 消除對反向提示詞的影響\n使用內建的 LoRA 時，反向提示詞總是受到 LoRA 的影響。 這通常會對輸出產生負面影響。\n而此擴展程序提供了消除負面影響的選項。\n\n## 使用方法\n### 啟用 (Enabled)\n勾選此選項之後才能使用Composable LoRA的功能。\n\n### Composable LoRA with step\n勾選此選項之後才能使用在特定步數上啟用或不啟用LoRA的功能。\n\n### 在反向提示詞的語言模型編碼器上使用LoRA (Use Lora in uc text model encoder)\n在語言模型編碼器(text model encoder)的反向提示詞部分使用LoRA。\n關閉此選項後，您可以期待更好的輸出。\n\n### 在反向提示詞的擴散模型上上使用LoRA (Use Lora in uc diffusion model)\n在擴散模型(diffusion model)或稱降噪器(denoiser)的反向提示詞部分使用LoRA。\n關閉此選項後，您可以期待更好的輸出。\n\n### 繪製LoRA權重與步數關聯的圖表 (plot the LoRA weight in all steps)\n如果有勾選\\[Composable LoRA with step\\]，可以勾選此選項來觀察LoRA權重在每個步驟數上的變化\n\n### 其他\n* 如果你產生的圖片崩成這樣:\n  ![](readme/fig10.png)\n  可嘗試以下步驟解決:\n  1. 先關閉Composable LoRA\n  2. 從你的提示詞中暫時移除所有LoRA\n  3. 隨便生成一張圖片\n  4. 如果產生的圖片是正常的，再次開啟Composable LoRA\n  5. 再把剛才移除的LoRA加回去提示詞中 (注意，要先開啟Composable LoRA再加入LoRA語法)\n  6. 應該就能正常產生圖片了\n\n## 相容性\n`--always-batch-cond-uncond`必須與`--medvram`或`--lowvram`一起使用\n\n## 更新日誌\n### 2023-04-02\n* 新增LoCon、LyCORIS支援\n* 修正: IndexError: list index out of range\n### 2023-04-08\n* 允許在多個不同AND區塊使用同一個LoRA\n  ![](readme/changelog_2023-04-08.png)\n### 2023-04-13\n* 2023-04-08的版本提交pull request\n### 2023-04-19\n* 修正使用 pytorch 2.0 時，擴展載入失敗的問題\n* 修正: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda and cpu! (when checking argument for argument mat2 in method wrapper_CUDA_mm)\n### 2023-04-20\n* 實作控制LoRA在指定步數啟用與不啟用的功能\n* 參考LoCon、LyCORIS擴展的程式碼，改善LoRA在不同AND區塊與步數啟用與不啟用的演算法\n### 2023-04-21\n* 實作控制LoRA在不同步驟數能有不同權重的方法`[A #xxx]`\n* 繪製LoRA權重在不同步驟數之變化的圖表\n### 2023-04-22\n* 修正: AttributeError: 'Options' object has no attribute 'lora_apply_to_outputs'\n* 修正: RuntimeError: \"addmm_impl_cpu_\" not implemented for 'Half'\n### 2023-04-23\n* 修正有時候LoRA加上去後會無法移除的問題 (症狀 : 崩圖。)\n### 2023-04-25\n* 加入對`<lyco:MODEL>`語法的支援。\n\n## 銘謝\n*  [Composable LoRA原始作者opparco](https://github.com/opparco)、[Composable LoRA](https://github.com/opparco/stable-diffusion-webui-composable-lora)\n*  [JackEllie的Stable-Siffusion的社群團隊](https://discord.gg/TM5d89YNwA) 、 [Youtube頻道](https://www.youtube.com/@JackEllie)\n*  [中文維基百科的社群團隊](https://discord.gg/77n7vnu)\n\n<p align=\"center\"><img src=\"https://count.getloli.com/get/@a2569875-stable-diffusion-webui-composable-lora.github\" alt=\"a2569875/stable-diffusion-webui-composable-lora\"></p>\n"
  },
  {
    "path": "composable_lora.py",
    "content": "from typing import List, Dict, Optional, Union\nimport re\nimport torch\nimport composable_lora_step\nimport composable_lycoris\nimport plot_helper\nimport lora_ext\nfrom modules import extra_networks, devices\n\ndef lora_forward(compvis_module: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.MultiheadAttention], input, res):\n    global text_model_encoder_counter\n    global diffusion_model_counter\n    global step_counter\n    global should_print\n    global first_log_drawing\n    global drawing_lora_first_index\n\n    import lora\n\n    if composable_lycoris.has_webui_lycoris:\n        import lycoris\n        if len(lycoris.loaded_lycos) > 0 and not first_log_drawing:\n            print(\"Found LyCORIS models, Using Composable LyCORIS.\")\n\n    if not first_log_drawing:\n        first_log_drawing = True\n        if enabled:\n            print(\"Composable LoRA load successful.\")\n        if opt_plot_lora_weight:\n            log_lora()\n            drawing_lora_first_index = drawing_data[0]\n\n    if len(lora_ext.get_loaded_lora()) == 0:\n        return res\n    \n    if hasattr(devices, \"cond_cast_unet\"):\n        input = devices.cond_cast_unet(input)\n\n    lora_layer_name_loading : Optional[str] = getattr(compvis_module, 'lora_layer_name', None)\n    if lora_layer_name_loading is None:\n        lora_layer_name_loading = getattr(compvis_module, 'network_layer_name', None)\n    if lora_layer_name_loading is None:\n        return res\n    #let it type is actually a string\n    lora_layer_name : str = str(lora_layer_name_loading)\n    del lora_layer_name_loading\n\n    lora_loaded_loras = lora_ext.get_loaded_lora()\n    num_loras = len(lora_loaded_loras)\n    if composable_lycoris.has_webui_lycoris:\n        num_loras += len(lycoris.loaded_lycos)\n\n    if text_model_encoder_counter == -1:\n        text_model_encoder_counter = len(prompt_loras) * num_loras\n\n    tmp_check_loras = [] #store which lora are already apply\n    tmp_check_loras.clear()\n\n    for m_lora in lora_loaded_loras:\n        module = m_lora.modules.get(lora_layer_name, None)\n        if module is None:\n            #fix the lyCORIS issue\n            composable_lycoris.check_lycoris_end_layer(lora_layer_name, res, num_loras)\n            continue\n\n        current_lora = composable_lycoris.normalize_lora_name(m_lora.name)\n        lora_already_used = False\n        if current_lora in tmp_check_loras:\n            lora_already_used = True\n        #store the applied lora into list\n        tmp_check_loras.append(current_lora)\n        if lora_already_used:\n            composable_lycoris.check_lycoris_end_layer(lora_layer_name, res, num_loras)\n            continue\n        \n        #support for lyCORIS\n        patch = composable_lycoris.get_lora_patch(module, input, res, lora_layer_name)\n        alpha = composable_lycoris.get_lora_alpha(module, 1.0)\n        num_prompts = len(prompt_loras)\n\n        # print(f\"lora.name={m_lora.name} lora.mul={m_lora.multiplier} alpha={alpha} pat.shape={patch.shape}\")\n        res = apply_composable_lora(lora_layer_name, m_lora, module, \"lora\", patch, alpha, res, num_loras, num_prompts)\n    return res\n\nre_AND = re.compile(r\"\\bAND\\b\")\n\ndef load_prompt_loras(prompt: str):\n    global is_single_block\n    global full_controllers\n    global first_log_drawing\n    global full_prompt\n    prompt_loras.clear()\n    prompt_blocks.clear()\n    lora_controllers.clear()\n    drawing_data.clear()\n    full_controllers.clear()\n    drawing_lora_names.clear()\n    cache_layer_list.clear()\n    #load AND...AND block\n    subprompts = re_AND.split(prompt)\n    full_prompt = prompt\n    tmp_prompt_loras = []\n    tmp_prompt_blocks = []\n    for i, subprompt in enumerate(subprompts):\n        loras = {}\n        _, extra_network_data = extra_networks.parse_prompt(subprompt)\n        for m_type in ['lora', 'lyco']:\n            if m_type in extra_network_data.keys():\n                for params in extra_network_data[m_type]:\n                    name = params.items[0]\n                    multiplier = float(params.items[1]) if len(params.items) > 1 else 1.0\n                    loras[f\"{m_type}:{name}\"] = multiplier\n\n        tmp_prompt_loras.append(loras)\n        tmp_prompt_blocks.append(subprompt)\n    is_single_block = (len(tmp_prompt_loras) == 1)\n\n    #load [A:B:N] syntax\n    if opt_composable_with_step:\n        print(\"Loading LoRA step controller...\")\n    tmp_lora_controllers = composable_lora_step.parse_step_rendering_syntax(prompt)\n\n    #for batches > 1\n    prompt_loras.extend(tmp_prompt_loras * num_batches)\n    lora_controllers.extend(tmp_lora_controllers * num_batches)\n    prompt_blocks.extend(tmp_prompt_blocks * num_batches)\n\n    for controller_it in tmp_lora_controllers:\n        full_controllers += controller_it\n    first_log_drawing = False\n\ndef reset_counters():\n    global text_model_encoder_counter\n    global diffusion_model_counter\n    global step_counter\n    global should_print\n\n    # reset counter to uc head\n    text_model_encoder_counter = -1\n    diffusion_model_counter = 0\n    step_counter += 1\n    should_print = True\n    \ndef reset_step_counters():\n    global step_counter\n    global should_print\n\n    should_print = True\n    step_counter = 0\n\ndef add_step_counters(): \n    global step_counter\n    global should_print\n\n    should_print = True\n    step_counter += 1\n\n    reset_flag = False\n    if step_counter == num_steps + 1:\n        if not opt_hires_step_as_global:\n            step_counter = 0\n            reset_flag = True\n    elif step_counter > num_steps + num_hires_steps:\n        step_counter = 0\n        reset_flag = True\n    if not reset_flag:\n        if opt_plot_lora_weight:\n            log_lora()\n\ndef log_lora():\n    import lora\n    loaded_loras = lora_ext.get_loaded_lora()\n    loaded_lycos = []\n    if composable_lycoris.has_webui_lycoris:\n        import lycoris\n        loaded_lycos = lycoris.loaded_lycos\n\n    tmp_data : List[float] = []\n    if len(loaded_loras) + len(loaded_lycos) <= 0:\n        tmp_data = [0.0]\n        if len(drawing_lora_names) <= 0:\n            drawing_lora_names.append(\"LoRA Model Not Found.\")\n    for m_type in [(\"lora\", loaded_loras), (\"lyco\", loaded_lycos)]:\n        for m_lora in m_type[1]:\n            m_lora_name = composable_lycoris.normalize_lora_name(m_lora.name)\n            custom_scope = {}\n            if opt_composable_with_step:\n                custom_scope = {\n                    \"is_negative\": False,\n                    \"lora\": m_lora,\n                    \"lora_module\": None,\n                    \"lora_type\": m_type[0],\n                    \"lora_name\": m_lora_name,\n                    \"lora_count\": len(loaded_loras) + len(loaded_lycos),\n                    \"block_lora_count\": len(loaded_loras) + len(loaded_lycos),\n                    \"layer_name\": \"ploting\",\n                    \"current_prompt\": full_prompt,\n                    \"sd_processing\": sd_processing\n                }\n            current_lora = f\"{m_type[0]}:{m_lora_name}\"\n            multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, \"lora_layer_name\")\n            if opt_composable_with_step:\n                multiplier = composable_lora_step.check_lora_weight(full_controllers, current_lora, step_counter, num_steps, custom_scope)\n            index = -1\n            if current_lora in drawing_lora_names:\n                index = drawing_lora_names.index(current_lora)\n            else:\n                index = len(drawing_lora_names)\n                drawing_lora_names.append(current_lora)\n            if index >= len(tmp_data):\n                for i in range(len(tmp_data), index):\n                    tmp_data.append(0.0)\n                tmp_data.append(multiplier)\n            else:\n                tmp_data[index] = multiplier\n    drawing_data.append(tmp_data)\n\ndef plot_lora():\n    \"\"\"Plot the LoRA weight chart\"\"\"\n    max_size = -1\n    if len(drawing_data) < num_steps:\n        item = drawing_data[len(drawing_data) - 1] if len(drawing_data) > 0 else [0.0]\n        drawing_data.extend([item]*(num_steps - len(drawing_data)))\n    drawing_data.insert(0, drawing_lora_first_index)\n    for datalist in drawing_data:\n        datalist_len = len(datalist)\n        if datalist_len > max_size:\n            max_size = datalist_len\n    for i, datalist in enumerate(drawing_data):\n        datalist_len = len(datalist)\n        if datalist_len < max_size:\n            drawing_data[i].extend([0.0]*(max_size - datalist_len))\n    return plot_helper.plot_lora_weight(drawing_data, drawing_lora_names)\n\ndef lora_backup_weights(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.MultiheadAttention]):\n    lora_layer_name = getattr(self, 'lora_layer_name', None)\n    if lora_layer_name is None:\n        return\n    import lora\n\n    weights_backup = getattr(self, \"composable_lora_weights_backup\", None)\n    if weights_backup is None:\n        if isinstance(self, torch.nn.MultiheadAttention):\n            weights_backup = (self.in_proj_weight.to(devices.cpu, copy=True), self.out_proj.weight.to(devices.cpu, copy=True))\n        else:\n            weights_backup = self.weight.to(devices.cpu, copy=True)\n\n        self.composable_lora_weights_backup = weights_backup\n        self.lora_weights_backup = weights_backup\n\ndef clear_cache_lora(compvis_module : Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.MultiheadAttention], force_clear : bool):\n    lora_layer_name = getattr(compvis_module, 'lora_layer_name', 'unknown layer')\n    if lora_layer_name in cache_layer_list:\n        return\n    cache_layer_list.append(lora_layer_name)\n    lyco_weights_backup = getattr(compvis_module, \"lyco_weights_backup\", None)\n    lora_weights_backup = getattr(compvis_module, \"lora_weights_backup\", None)\n    composable_lora_weights_backup = getattr(compvis_module, \"composable_lora_weights_backup\", None)\n    if enabled or force_clear:\n        if composable_lora_weights_backup is not None:\n            if isinstance(compvis_module, torch.nn.MultiheadAttention):\n                compvis_module.in_proj_weight.copy_(composable_lora_weights_backup[0])\n                compvis_module.out_proj.weight.copy_(composable_lora_weights_backup[1])\n            else:\n                compvis_module.weight.copy_(composable_lora_weights_backup)\n        else:\n            if lyco_weights_backup is not None:\n                if isinstance(compvis_module, torch.nn.MultiheadAttention):\n                    compvis_module.in_proj_weight.copy_(lyco_weights_backup[0])\n                    compvis_module.out_proj.weight.copy_(lyco_weights_backup[1])\n                    lora_weights_backup = (\n                        lyco_weights_backup[0].to(devices.cpu, copy=True), \n                        lyco_weights_backup[1].to(devices.cpu, copy=True)\n                    )\n                else:\n                    compvis_module.weight.copy_(lyco_weights_backup)\n                    lora_weights_backup = lyco_weights_backup.to(devices.cpu, copy=True)\n                setattr(compvis_module, \"lora_weights_backup\", lora_weights_backup)\n            elif lora_weights_backup is not None:\n                if isinstance(compvis_module, torch.nn.MultiheadAttention):\n                    compvis_module.in_proj_weight.copy_(lora_weights_backup[0])\n                    compvis_module.out_proj.weight.copy_(lora_weights_backup[1])\n                else:\n                    compvis_module.weight.copy_(lora_weights_backup)\n            setattr(compvis_module, \"lora_current_names\", ())\n            setattr(compvis_module, \"lyco_current_names\", ())\n    else:\n        if (composable_lora_weights_backup is not None) and composable_lycoris.has_webui_lycoris:\n            if isinstance(compvis_module, torch.nn.MultiheadAttention):\n                compvis_module.in_proj_weight.copy_(composable_lora_weights_backup[0])\n                compvis_module.out_proj.weight.copy_(composable_lora_weights_backup[1])\n            else:\n                compvis_module.weight.copy_(composable_lora_weights_backup)\n\ndef apply_composable_lora(lora_layer_name, m_lora, module, m_type: str, patch, alpha, res, num_loras, num_prompts):\n    global text_model_encoder_counter\n    global diffusion_model_counter\n    global step_counter\n\n    custom_scope = {}\n    if opt_composable_with_step:\n        custom_scope = {\n            \"is_negative\": False,\n            \"lora\": m_lora,\n            \"lora_module\": module,\n            \"lora_type\": m_type,\n            \"lora_name\": composable_lycoris.normalize_lora_name(m_lora.name),\n            \"lora_count\": num_loras,\n            \"block_lora_count\": 0,\n            \"layer_name\": lora_layer_name,\n            \"current_prompt\": \"\",\n            \"sd_processing\": sd_processing\n        }\n\n    m_lora_name = f\"{m_type}:{composable_lycoris.normalize_lora_name(m_lora.name)}\"\n    # print(f\"lora.name={m_lora.name} lora.mul={m_lora.multiplier} alpha={alpha} pat.shape={patch.shape}\")\n    if enabled:\n        if lora_layer_name.startswith(\"transformer_\"):  # \"transformer_text_model_encoder_\"\n            #\n            if 0 <= text_model_encoder_counter // num_loras < len(prompt_loras):\n                # c\n                prompt_block_id = text_model_encoder_counter // num_loras\n                loras = prompt_loras[prompt_block_id]\n                multiplier = loras.get(m_lora_name, 0.0)\n                if opt_composable_with_step:\n                    custom_scope[\"current_prompt\"] = prompt_blocks[prompt_block_id]\n                    custom_scope[\"block_lora_count\"] = len(loras)\n                    lora_controller = lora_controllers[prompt_block_id]\n                    multiplier = composable_lora_step.check_lora_weight(lora_controller, m_lora_name, -1, num_steps, custom_scope)\n                if multiplier != 0.0:\n                    multiplier *= composable_lycoris.lycoris_get_multiplier_normalized(m_lora, lora_layer_name)\n                    # print(f\"c #{text_model_encoder_counter // num_loras} lora.name={m_lora_name} mul={multiplier}  lora_layer_name={lora_layer_name}\")\n                    res = composable_lycoris.composable_forward(module, patch, alpha, multiplier, res)\n            else:\n                # uc\n                multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, lora_layer_name)\n                if (opt_uc_text_model_encoder or (is_single_block and (not opt_single_no_uc))) and multiplier != 0.0:\n                    # print(f\"uc #{text_model_encoder_counter // num_loras} lora.name={m_lora_name} lora.mul={multiplier}  lora_layer_name={lora_layer_name}\")\n                    custom_scope[\"current_prompt\"] = negative_prompt\n                    custom_scope[\"is_negative\"] = True\n                    res = composable_lycoris.composable_forward(module, patch, alpha, multiplier, res)\n\n            composable_lycoris.check_lycoris_end_layer(lora_layer_name, res, num_loras)\n\n        elif lora_layer_name.startswith(\"diffusion_model_\"):  # \"diffusion_model_\"\n\n            if res.shape[0] == num_batches * num_prompts + num_batches:\n                # tensor.shape[1] == uncond.shape[1]\n                tensor_off = 0\n                uncond_off = num_batches * num_prompts\n                for b in range(num_batches):\n                    # c\n                    for p, loras in enumerate(prompt_loras):\n                        multiplier = loras.get(m_lora_name, 0.0)\n                        if opt_composable_with_step:\n                            prompt_block_id = p\n                            custom_scope[\"current_prompt\"] = prompt_blocks[prompt_block_id]\n                            custom_scope[\"block_lora_count\"] = len(loras)\n                            lora_controller = lora_controllers[prompt_block_id]\n                            multiplier = composable_lora_step.check_lora_weight(lora_controller, m_lora_name, step_counter, num_steps, custom_scope)\n                        if multiplier != 0.0:\n                            multiplier *= composable_lycoris.lycoris_get_multiplier_normalized(m_lora, lora_layer_name)\n                            # print(f\"tensor #{b}.{p} lora.name={m_lora_name} mul={multiplier} lora_layer_name={lora_layer_name}\")\n                            res[tensor_off] = composable_lycoris.composable_forward(module, patch[tensor_off], alpha, multiplier, res[tensor_off])\n                        tensor_off += 1\n\n                    # uc\n                    multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, lora_layer_name)\n                    if (opt_uc_diffusion_model or (is_single_block and (not opt_single_no_uc))) and multiplier != 0.0:\n                        # print(f\"uncond lora.name={m_lora_name} lora.mul={m_lora.multiplier} lora_layer_name={lora_layer_name}\")\n                        if is_single_block and opt_composable_with_step:\n                            custom_scope[\"current_prompt\"] = negative_prompt\n                            custom_scope[\"is_negative\"] = True\n                            multiplier = composable_lora_step.check_lora_weight(full_controllers, m_lora_name, step_counter, num_steps, custom_scope)\n                            multiplier *= composable_lycoris.lycoris_get_multiplier_normalized(m_lora, lora_layer_name)\n                        res[uncond_off] = composable_lycoris.composable_forward(module, patch[uncond_off], alpha, multiplier, res[uncond_off])\n                    \n                    uncond_off += 1\n            else:\n                # tensor.shape[1] != uncond.shape[1]\n                cur_num_prompts = res.shape[0]\n                base = (diffusion_model_counter // cur_num_prompts) // num_loras * cur_num_prompts\n                prompt_len = len(prompt_loras)\n                if 0 <= base < len(prompt_loras):\n                    # c\n                    for off in range(cur_num_prompts):\n                        if base + off < prompt_len:\n                            loras = prompt_loras[base + off]\n                            multiplier = loras.get(m_lora_name, 0.0)\n                            if opt_composable_with_step:\n                                prompt_block_id = base + off\n                                custom_scope[\"current_prompt\"] = prompt_blocks[prompt_block_id]\n                                custom_scope[\"block_lora_count\"] = len(loras)\n                                lora_controller = lora_controllers[prompt_block_id]\n                                multiplier = composable_lora_step.check_lora_weight(lora_controller, m_lora_name, step_counter, num_steps, custom_scope)\n                            if multiplier != 0.0:\n                                multiplier *= composable_lycoris.lycoris_get_multiplier_normalized(m_lora, lora_layer_name)\n                                # print(f\"c #{base + off} lora.name={m_lora_name} mul={multiplier} lora_layer_name={lora_layer_name}\")\n                                res[off] = composable_lycoris.composable_forward(module, patch[off], alpha, multiplier, res[off])\n                else:\n                    # uc\n                    multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, lora_layer_name)\n                    if (opt_uc_diffusion_model or (is_single_block and (not opt_single_no_uc))) and multiplier != 0.0:\n                        # print(f\"uc {lora_layer_name} lora.name={m_lora_name} lora.mul={m_lora.multiplier}\")\n                        if is_single_block and opt_composable_with_step:\n                            custom_scope[\"current_prompt\"] = negative_prompt\n                            custom_scope[\"is_negative\"] = True\n                            multiplier = composable_lora_step.check_lora_weight(full_controllers, m_lora_name, step_counter, num_steps, custom_scope)\n                            multiplier *= composable_lycoris.lycoris_get_multiplier_normalized(m_lora, lora_layer_name)\n                        res = composable_lycoris.composable_forward(module, patch, alpha, multiplier, res)\n\n            composable_lycoris.check_lycoris_end_layer(lora_layer_name, res, num_loras)\n        else:\n            # default\n            multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, lora_layer_name)\n            if multiplier != 0.0:\n                # print(f\"default {lora_layer_name} lora.name={m_lora_name} lora.mul={m_lora.multiplier}\")\n                res = composable_lycoris.composable_forward(module, patch, alpha, multiplier, res)\n            composable_lycoris.check_lycoris_end_layer(lora_layer_name, res, num_loras)\n    else:\n        # default\n        multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, lora_layer_name)\n        if multiplier != 0.0:\n            # print(f\"DEFAULT {lora_layer_name} lora.name={m_lora_name} lora.mul={m_lora.multiplier}\")\n            res = composable_lycoris.composable_forward(module, patch, alpha, multiplier, res)\n    return res\n\ndef lora_Linear_forward(self, input):\n    if composable_lycoris.has_webui_lycoris:\n        lora_backup_weights(self)\n        if not enabled:\n            import lycoris\n            import lora\n            lyco_count = len(lycoris.loaded_lycos)\n            old_lyco_count = getattr(self, \"old_lyco_count\", 0)\n            if old_lyco_count > 0 and lyco_count <= 0:\n                clear_cache_lora(self, True)\n            self.old_lyco_count = lyco_count\n            lora_ext.load_lora_ext()\n            torch.nn.Linear_forward_before_lyco = lora_ext.lora_Linear_forward\n            torch.nn.Linear_forward_before_network = Linear_forward_before_clora\n            #if lyco_count <= 0:\n            #    return lora_ext.lora_Linear_forward(self, input)\n            if 'lyco_notfound' in locals() or 'lyco_notfound' in globals():\n                if lyco_notfound:\n                    backup_Linear_forward = torch.nn.Linear_forward_before_lora\n                    torch.nn.Linear_forward_before_lora = Linear_forward_before_clora\n                    result = lycoris.lyco_Linear_forward(self, input)\n                    torch.nn.Linear_forward_before_lora = backup_Linear_forward\n                    return result\n            return lycoris.lyco_Linear_forward(self, input)\n    if lora_ext.is_sd_1_5:\n        import networks\n        networks.network_restore_weights_from_backup(self)\n        networks.network_reset_cached_weight(self)\n    else:\n        clear_cache_lora(self, False)\n    if (not self.weight.is_cuda) and input.is_cuda: #if variables not on the same device (between cpu and gpu)\n        self_weight_cuda = self.weight.to(device=devices.device) #pass to GPU\n        to_del = self.weight\n        self.weight = None                    #delete CPU variable\n        del to_del\n        del self.weight                       #avoid pytorch 2.0 throwing exception\n        self.weight = self_weight_cuda        #load GPU data to self.weight\n    res = torch.nn.Linear_forward_before_lora(self, input)\n    res = lora_forward(self, input, res)\n    if composable_lycoris.has_webui_lycoris:\n        res = composable_lycoris.lycoris_forward(self, input, res)\n    return res\n\ndef lora_Conv2d_forward(self, input):\n    if composable_lycoris.has_webui_lycoris:\n        lora_backup_weights(self)\n        if not enabled:\n            import lycoris\n            import lora\n            lyco_count = len(lycoris.loaded_lycos)\n            old_lyco_count = getattr(self, \"old_lyco_count\", 0)\n            if old_lyco_count > 0 and lyco_count <= 0:\n                clear_cache_lora(self, True)\n            self.old_lyco_count = lyco_count\n            lora_ext.load_lora_ext()\n            torch.nn.Conv2d_forward_before_lyco = lora_ext.lora_Conv2d_forward\n            torch.nn.Conv2d_forward_before_network = Conv2d_forward_before_clora\n            #if lyco_count <= 0:\n            #    return lora_ext.lora_Conv2d_forward(self, input)\n            if 'lyco_notfound' in locals() or 'lyco_notfound' in globals():\n                if lyco_notfound:\n                    backup_Conv2d_forward = torch.nn.Conv2d_forward_before_lora\n                    torch.nn.Conv2d_forward_before_lora = Conv2d_forward_before_clora\n                    result = lycoris.lyco_Conv2d_forward(self, input)\n                    torch.nn.Conv2d_forward_before_lora = backup_Conv2d_forward\n                    return result\n\n            return lycoris.lyco_Conv2d_forward(self, input)\n    if lora_ext.is_sd_1_5:\n        import networks\n        networks.network_restore_weights_from_backup(self)\n        networks.network_reset_cached_weight(self)\n    else:\n        clear_cache_lora(self, False)\n    if (not self.weight.is_cuda) and input.is_cuda:\n        self_weight_cuda = self.weight.to(device=devices.device)\n        to_del = self.weight\n        self.weight = None\n        del to_del\n        del self.weight #avoid \"cannot assign XXX as parameter YYY (torch.nn.Parameter or None expected)\"\n        self.weight = self_weight_cuda\n    res = torch.nn.Conv2d_forward_before_lora(self, input)\n    res = lora_forward(self, input, res)\n    if composable_lycoris.has_webui_lycoris:\n        res = composable_lycoris.lycoris_forward(self, input, res)\n    return res\n\ndef lora_MultiheadAttention_forward(self, input):\n    if composable_lycoris.has_webui_lycoris:\n        lora_backup_weights(self)\n        if not enabled:\n            import lycoris\n            import lora\n            lyco_count = len(lycoris.loaded_lycos)\n            old_lyco_count = getattr(self, \"old_lyco_count\", 0)\n            if old_lyco_count > 0 and lyco_count <= 0:\n                clear_cache_lora(self, True)\n            self.old_lyco_count = lyco_count\n            lora_ext.load_lora_ext()\n            torch.nn.MultiheadAttention_forward_before_lyco = lora_ext.lora_MultiheadAttention_forward\n            torch.nn.MultiheadAttention_forward_before_network = MultiheadAttention_forward_before_clora\n\n            #if lyco_count <= 0:\n            #    return lora_ext.lora_MultiheadAttention_forward(self, input)\n            if 'lyco_notfound' in locals() or 'lyco_notfound' in globals():\n                if lyco_notfound:\n                    backup_MultiheadAttention_forward = torch.nn.MultiheadAttention_forward_before_lora\n                    torch.nn.MultiheadAttention_forward_before_lora = MultiheadAttention_forward_before_clora\n                    result = lycoris.lyco_MultiheadAttention_forward(self, input)\n                    torch.nn.MultiheadAttention_forward_before_lora = backup_MultiheadAttention_forward\n                    return result\n\n            return lycoris.lyco_MultiheadAttention_forward(self, input)\n    if lora_ext.is_sd_1_5:\n        import networks\n        networks.network_restore_weights_from_backup(self)\n        networks.network_reset_cached_weight(self)\n    else:\n        clear_cache_lora(self, False)\n    if (not self.weight.is_cuda) and input.is_cuda:\n        self_weight_cuda = self.weight.to(device=devices.device)\n        to_del = self.weight\n        self.weight = None\n        del to_del\n        del self.weight #avoid \"cannot assign XXX as parameter YYY (torch.nn.Parameter or None expected)\"\n        self.weight = self_weight_cuda\n    res = torch.nn.MultiheadAttention_forward_before_lora(self, input)\n    res = lora_forward(self, input, res)\n    if composable_lycoris.has_webui_lycoris:\n        res = composable_lycoris.lycoris_forward(self, input, res)\n    return res\n\ndef noop():\n    pass\n\ndef should_reload():\n    #pytorch 2.0 should reload\n    match = re.search(r\"\\d+(\\.\\d+)?\",str(torch.__version__)) \n    if not match:\n        return True\n    ver = float(match.group(0))\n    return ver >= 2.0\n\nenabled : bool = False\nopt_composable_with_step : bool = False\nopt_uc_text_model_encoder : bool = False\nopt_uc_diffusion_model : bool = False\nopt_plot_lora_weight : bool = False\nopt_single_no_uc : bool = False\nopt_hires_step_as_global : bool = False\nverbose : bool = True\n\nsd_processing = None\nfull_prompt: str = \"\"\nnegative_prompt: str = \"\"\ndrawing_lora_names : List[str] = []\ndrawing_data : List[List[float]] = []\ndrawing_lora_first_index : List[float] = []\nfirst_log_drawing : bool = False\n\nis_single_block : bool = False\nnum_batches: int = 0\nnum_steps: int = 20\nnum_hires_steps: int = 20\nprompt_loras: List[Dict[str, float]] = []\ntext_model_encoder_counter: int = -1\ndiffusion_model_counter: int = 0\nstep_counter: int = 0\ncache_layer_list : List[str] = []\n\nshould_print : bool = True\nprompt_blocks: List[str] = []\nlora_controllers: List[List[composable_lora_step.LoRA_Controller_Base]] = []\nfull_controllers: List[composable_lora_step.LoRA_Controller_Base] = []\n"
  },
  {
    "path": "composable_lora_function_handler.py",
    "content": "import torch\nimport composable_lora\nimport composable_lycoris\n\ndef on_enable():\n    #backup original forward methods\n    composable_lora.backup_lora_Linear_forward = torch.nn.Linear.forward\n    composable_lora.backup_lora_Conv2d_forward = torch.nn.Conv2d.forward\n    composable_lora.backup_lora_MultiheadAttention_forward = torch.nn.MultiheadAttention.forward\n\n    if hasattr(torch.nn, 'Linear_forward_before_lyco'):\n        #if a1111-sd-webui-lycoris installed, backup it's forward methods\n        import lycoris\n        composable_lycoris.has_webui_lycoris = True\n        if hasattr(torch.nn, 'Linear_forward_before_lyco'):\n            composable_lycoris.backup_Linear_forward_before_lyco = torch.nn.Linear_forward_before_lyco\n        if hasattr(torch.nn, 'Linear_load_state_dict_before_lyco'):\n            composable_lycoris.backup_Linear_load_state_dict_before_lyco = torch.nn.Linear_load_state_dict_before_lyco\n        if hasattr(torch.nn, 'Conv2d_forward_before_lyco'):\n            composable_lycoris.backup_Conv2d_forward_before_lyco = torch.nn.Conv2d_forward_before_lyco\n        if hasattr(torch.nn, 'Conv2d_load_state_dict_before_lyco'):\n            composable_lycoris.backup_Conv2d_load_state_dict_before_lyco = torch.nn.Conv2d_load_state_dict_before_lyco\n        if hasattr(torch.nn, 'MultiheadAttention_forward_before_lyco'):\n            composable_lycoris.backup_MultiheadAttention_forward_before_lyco = torch.nn.MultiheadAttention_forward_before_lyco\n        if hasattr(torch.nn, 'MultiheadAttention_load_state_dict_before_lyco'):\n            composable_lycoris.backup_MultiheadAttention_load_state_dict_before_lyco = torch.nn.MultiheadAttention_load_state_dict_before_lyco\n        if hasattr(composable_lora, 'lyco_notfound'):\n            if composable_lora.lyco_notfound:\n                torch.nn.Linear_forward_before_lyco = composable_lora.Linear_forward_before_clora\n                torch.nn.Conv2d_forward_before_lyco = composable_lora.Conv2d_forward_before_clora\n                torch.nn.MultiheadAttention_forward_before_lyco = composable_lora.MultiheadAttention_forward_before_clora\n        torch.nn.Linear.forward = composable_lora.lora_Linear_forward\n        torch.nn.Conv2d.forward = composable_lora.lora_Conv2d_forward\n        torch.nn.MultiheadAttention.forward = lycoris.lyco_MultiheadAttention_forward\n        torch.nn.MultiheadAttention._load_from_state_dict = lycoris.lyco_MultiheadAttention_load_state_dict\n    else:\n        composable_lycoris.has_webui_lycoris = False\n\n    if (composable_lora.should_reload() or (torch.nn.Linear.forward != composable_lora.lora_Linear_forward)):\n        if composable_lora.enabled:\n            torch.nn.Linear.forward = composable_lora.lora_Linear_forward\n            torch.nn.Conv2d.forward = composable_lora.lora_Conv2d_forward\n\ndef on_disable():\n    torch.nn.Linear.forward = composable_lora.backup_lora_Linear_forward\n    torch.nn.Conv2d.forward = composable_lora.backup_lora_Conv2d_forward\n    torch.nn.MultiheadAttention.forward = composable_lora.backup_lora_MultiheadAttention_forward\n    if hasattr(torch.nn, 'Linear_forward_before_lyco'):\n        composable_lycoris.has_webui_lycoris = True\n        if hasattr(composable_lycoris, 'backup_Linear_forward_before_lyco'):\n            torch.nn.Linear_forward_before_lyco = composable_lycoris.backup_Linear_forward_before_lyco\n        if hasattr(composable_lycoris, 'backup_Linear_load_state_dict_before_lyco'):\n            torch.nn.Linear_load_state_dict_before_lyco = composable_lycoris.backup_Linear_load_state_dict_before_lyco\n        if hasattr(composable_lycoris, 'backup_Conv2d_forward_before_lyco'):\n            torch.nn.Conv2d_forward_before_lyco = composable_lycoris.backup_Conv2d_forward_before_lyco\n        if hasattr(composable_lycoris, 'backup_Conv2d_load_state_dict_before_lyco'):\n            torch.nn.Conv2d_load_state_dict_before_lyco = composable_lycoris.backup_Conv2d_load_state_dict_before_lyco\n        if hasattr(composable_lycoris, 'backup_MultiheadAttention_forward_before_lyco'):\n            torch.nn.MultiheadAttention_forward_before_lyco = composable_lycoris.backup_MultiheadAttention_forward_before_lyco\n        if hasattr(composable_lycoris, 'backup_MultiheadAttention_load_state_dict_before_lyco'):\n            torch.nn.MultiheadAttention_load_state_dict_before_lyco = composable_lycoris.backup_MultiheadAttention_load_state_dict_before_lyco\n    else:\n        composable_lycoris.has_webui_lycoris = False"
  },
  {
    "path": "composable_lora_step.py",
    "content": "from typing import List, Union\nimport re\nimport ast\nimport copy\nimport json\nimport math\nimport sys\nimport traceback\nimport random\n\nfrom modules import extra_networks\n\nre_AND = re.compile(r\"\\bAND\\b\")\n\nclass Runable:\n    \"\"\"\n    like exec() but can return values\n    https://stackoverflow.com/a/52361938/5862977\n    \"\"\"\n    def __init__(self, code : str, code_name : str = \"<prompt>\"):\n        self.code = code\n        self.code_name = code_name\n        self.compiled = False\n        try:\n            self.compile_self()\n        except Exception:\n            pass\n\n    def compile_self(self):\n        self.code_ast = ast.parse(self.code, self.code_name)\n        self.init_ast = copy.deepcopy(self.code_ast)\n        self.init_ast.body = self.code_ast.body[:-1]\n\n        self.last_ast = copy.deepcopy(self.code_ast)\n        self.last_ast.body = self.code_ast.body[-1:]\n\n        self.full_bin = compile(self.code_ast, self.code_name, \"exec\")\n        self.start_bin = compile(self.init_ast, self.code_name, \"exec\")\n        if type(self.last_ast.body[0]) == ast.Expr:\n            self.run_bin = compile(self.convertExpr2Expression(self.last_ast.body[0]), self.code_name, \"eval\")\n        else:\n            self.end_bin = compile(self.last_ast, self.code_name, \"exec\")\n\n        self.compiled = True\n\n    def convertExpr2Expression(self, expr : ast.Expr):\n        expr.lineno = 0\n        expr.col_offset = 0\n        result = ast.Expression(expr.value, lineno=0, col_offset = 0)\n\n        return result\n\n    def run(self, module):\n        if not self.compiled:\n            self.compile_self()\n        if len(self.init_ast.body) > 0:\n            exec(self.start_bin, module.__dict__)\n        if type(self.last_ast.body[0]) == ast.Expr:\n            return eval(self.run_bin, module.__dict__)\n        else:\n            exec(self.end_bin, module.__dict__)\n\nclass LoRA_data:\n    def __init__(self, name : str, weight : float):\n        self.name = name\n        self.weight = weight\n    def __repr__(self):\n        return f\"LoRA:{self.name}:{self.weight}\"\n    def __str__(self):\n        return f\"LoRA:{self.name}:{self.weight}\"\n\nclass LoRA_Weight_CMD:\n    def getWeight(self, weight : float, progress: float, step : int, all_step : int, custom_scope):\n        return weight\n\nclass LoRA_Weight_decrement(LoRA_Weight_CMD):\n    def getWeight(self, weight : float, progress: float, step : int, all_step : int, custom_scope):\n        return weight * (1 - progress)\n\nclass LoRA_Weight_increment(LoRA_Weight_CMD):\n    def getWeight(self, weight : float, progress: float, step : int, all_step : int, custom_scope):\n        return weight * progress\n\ndef raise_(ex):\n    raise ex\ndef not_allow(name):\n    return lambda: raise_(Exception(f'function {name} is not allow in LoRA Controller'))\n\nLoRA_Weight_eval_scope = {\n    \"abs\": abs,\n    \"ceil\": math.ceil, \"floor\": math.floor, \"trunc\": math.trunc,\n    \"fmod\": math.fmod,\n    \"gcd\": math.gcd, \"lcm\": math.lcm,\n    \"perm\": math.perm, \"comb\": math.comb, \"gamma\": math.gamma,\n    \"sqrt\": math.sqrt, \"cbrt\": lambda x: pow(x, 1.0 / 3.0),\n    \"exp\": math.exp, \"pow\": math.pow,\n    \"log\": math.log, \"ln\": math.log, \"log2\": math.log2, \"log10\": math.log10,\n    \"clamp\": lambda x: 1.0 if x > 1 else (0.0 if x < 0 else x),\n    \"asin\": lambda x: (math.acos(1.0 - x * 2.0) + 2.0 * math.pi) / (2.0 * math.pi),\n    \"acos\": lambda x: (math.acos(x * 2.0 - 1.0) + 2.0 * math.pi) / (2.0 * math.pi),\n    \"atan\": lambda x: (math.atan(x) + math.pi) / (2.0 * math.pi),\n    \"sin\": lambda x: (math.sin(x * 2.0 * math.pi - (math.pi / 2.0)) + 1.0) / 2.0,\n    \"cos\": lambda x: (math.sin(x * 2.0 * math.pi + (math.pi / 2.0)) + 1.0) / 2.0,\n    \"tan\": lambda x: math.tan(x * 2.0 * math.pi),\n    \"sinr\": math.sin, \"cosr\": math.cos, \"tanr\": math.tan,\n    \"asinr\": math.asin, \"acosr\": math.acos, \"atanr\": math.atan,\n    \"sinh\": math.sinh, \"cosh\": math.cosh, \"tanh\": math.tanh,\n    \"asinh\": math.asinh, \"acosh\": math.acosh, \"atanh\": math.atanh,\n    \"abssin\": lambda x: abs(math.sin(x * 2 * math.pi)),\n    \"abscos\": lambda x: abs(math.cos(x * 2 * math.pi)),\n    \"random\": random.random,\n    \"pi\": math.pi, \"nan\": math.nan, \"inf\": math.inf,\n    #not allow functions\n    \"eval\": not_allow(\"eval\"),\n    \"exec\": not_allow(\"exec\"),\n    \"compile\": not_allow(\"compile\"),\n    \"breakpoint\": not_allow(\"breakpoint\"),\n    \"__import__\": not_allow(\"__import__\")\n}\n\nclass LoRA_Weight_eval(LoRA_Weight_CMD):\n    def __init__(self, command : str, code_name : str = \"<prompt>\"):\n        self.command = command\n        self.is_error = False\n        from types import ModuleType\n        self.module = ModuleType(\"module_in_prompt\")\n        self.module.__dict__.update(globals())\n        self.module.__dict__.update(LoRA_Weight_eval_scope)\n        self.bin = Runable(self.command, code_name)\n\n    def getWeight(self, weight : float, progress: float, step : int, all_step : int, custom_scope):\n\n        result = None\n        #setup local variables\n        LoRA_Weight_eval_scope[\"enable_prepare_step\"] = False\n        LoRA_Weight_eval_scope[\"weight\"] = weight\n        LoRA_Weight_eval_scope[\"life\"] = progress if step != -1 else 0\n        LoRA_Weight_eval_scope[\"step\"] = step\n        LoRA_Weight_eval_scope[\"steps\"] = all_step\n        LoRA_Weight_eval_scope[\"warmup\"] = lambda x: progress / x if progress < x else 1.0\n        LoRA_Weight_eval_scope[\"cooldown\"] = lambda x: (1 - progress) / (1 - x) if progress > x else 1.0\n        self.module.__dict__.update(globals())\n        self.module.__dict__.update(LoRA_Weight_eval_scope)\n        self.module.__dict__.update(custom_scope)\n        try:\n            result = self.bin.run(self.module)\n            try:\n                result = float(result) * weight\n            except Exception:\n                raise Exception(\\\n                    f\"LoRA Controller command result must be a numble, but got {type(result)}\")\n            if math.isnan(result):\n                raise Exception(\\\n                    f\"Can not apply a NaN weight to LoRA.\")\n            if math.isinf(result):\n                raise Exception(\\\n                    f\"Can not apply a infinity weight to LoRA.\")\n        except:\n            if not self.is_error:\n                print(f\"CommandError: {self.command}\")\n                traceback.print_exception(*sys.exc_info())\n                self.is_error = True\n            return weight\n        if step == -1 and not self.module.__dict__[\"enable_prepare_step\"]:\n            return weight\n\n        return result\n    def __repr__(self):\n        return f\"LoRA_Weight_eval:{self.command}\"\n    def __str__(self):\n        return f\"LoRA_Weight_eval:{self.command}\"\n\nclass LoRA_Controller_Base:\n    def __init__(self):\n        self.base_weight = 1.0\n        self.Weight_Controller = LoRA_Weight_CMD()\n    def getWeight(self, weight : float, progress: float, step : int, all_step : int, custom_scope):\n        result = self.Weight_Controller.getWeight(weight, progress, step, all_step, custom_scope)\n        if step == -1:\n            if not isinstance(self.Weight_Controller, LoRA_Weight_eval):\n                return weight\n        return result\n    def test(self, test_lora : str, step : int, all_step : int, custom_scope):\n        return self.base_weight\n\n#normal lora\nclass LoRA_Controller(LoRA_Controller_Base):\n    def __init__(self, name : str, weight : float):\n        super().__init__()\n        self.name = name\n        self.weight = float(weight)\n    def test(self, test_lora : str, step : int, all_step : int, custom_scope):\n        if test_lora == self.name:\n            return self.getWeight(self.weight, float(step) / float(all_step), step, all_step, custom_scope)\n        return 0.0\n    def __repr__(self):\n        return f\"LoRA_Controller:{self.name}[weight={self.weight}]\"\n    def __str__(self):\n        return f\"LoRA_Controller:{self.name}[weight={self.weight}]\"\n\n#lora with start and end\nclass LoRA_StartEnd_Controller(LoRA_Controller_Base):\n    def __init__(self, name : str, weight : float, start : Union[float, int], end : Union[float, int]):\n        super().__init__()\n        self.name = name\n        self.weight = float(weight)\n        self.start = float(start)\n        self.end = float(end)\n    def test(self, test_lora : str, step : int, all_step : int, custom_scope):\n        if test_lora == self.name:\n            if step == -1:\n                return self.getWeight(self.weight, -1, step, all_step, custom_scope)\n            start = self.start\n            end = self.end\n            if start < 1:\n                start = self.start * all_step\n            if end < 1:\n                end = self.end * all_step\n            if end < 0:\n                end = all_step\n            if (step >= start) and (step <= end):\n                return self.getWeight(self.weight, float(step - start) / float(end - start), step, all_step, custom_scope)\n        return 0.0\n    def __repr__(self):\n        return f\"LoRA_StartEnd_Controller:{self.name}[weight={self.weight},start at={self.start},end at={self.end}]\"\n    def __str__(self):\n        return f\"LoRA_StartEnd_Controller:{self.name}[weight={self.weight},start at={self.start},end at={self.end}]\"\n\n#switch lora\nclass LoRA_Switcher_Controller(LoRA_Controller_Base):\n    def __init__(self, lora_dist : List[LoRA_data], start : Union[float, int], end : Union[float, int]):\n        super().__init__()\n        self.lora_dist = lora_dist\n        the_list : List[str] = []\n        self.lora_list = the_list\n        self.start = float(start)\n        self.end = float(end)\n        for lora_item in self.lora_dist:\n            self.lora_list.append(lora_item.name)\n    def test(self, test_lora : str, step : int, all_step : int, custom_scope):\n        lora_count = len(self.lora_dist)\n        if step == -1 and test_lora in self.lora_list:\n            return self.getWeight(self.lora_dist[self.lora_list.index(test_lora)].weight, -1, step, all_step, custom_scope)\n        if test_lora == self.lora_list[step % lora_count]:\n            start = self.start\n            end = self.end\n            if start < 1:\n                start = self.start * all_step\n            if end < 1:\n                end = self.end * all_step\n            if end < 0:\n                end = all_step\n            if (step >= start) and (step <= end):\n                return self.getWeight(self.lora_dist[step % lora_count].weight, float(step - start) / float(end - start), step, all_step, custom_scope)\n        return 0.0\n    def __repr__(self):\n        return f\"LoRA_Switcher_Controller:{self.lora_dist}[start at={self.start},end at={self.end}]\"\n    def __str__(self):\n        return f\"LoRA_Switcher_Controller:{self.lora_dist}[start at={self.start},end at={self.end}]\"\n\n\ndef parse_step_rendering_syntax(prompt: str):\n    lora_controllers : List[List[LoRA_Controller_Base]] = []\n    subprompts = re_AND.split(escape_prompt(prompt))\n    for i, subprompt in enumerate(subprompts):\n        tmp_lora_controllers: List[LoRA_Controller_Base] = []\n        step_rendering_list, pure_loratext = get_all_step_rendering_in_prompt(subprompt)\n        for item in step_rendering_list:\n            tmp_lora_controllers += get_LoRA_Controllers(item)\n        lora_list = get_lora_list(pure_loratext)\n        for lora_item in lora_list:\n            tmp_lora_controllers.append(LoRA_Controller(lora_item.name, lora_item.weight))\n        lora_controllers.append(tmp_lora_controllers)\n    return lora_controllers\n\ndef check_lora_weight(controllers : List[LoRA_Controller_Base], test_lora : str, step : int, all_step : int, custom_scope):\n    result_weight = 0.0\n    for controller in controllers:\n        calc_weight = controller.test(test_lora, step, all_step, custom_scope)\n        if abs(calc_weight) > abs(result_weight):\n            result_weight = calc_weight\n    return result_weight\n\ndef get_lora_list(prompt: str):\n    result : List[LoRA_data] = []\n    _, extra_network_data = extra_networks.parse_prompt(prompt)\n    for m_type in ['lora', 'lyco']:\n        if m_type in extra_network_data.keys():\n            for params in extra_network_data[m_type]:\n                name = params.items[0]\n                multiplier = float(params.items[1]) if len(params.items) > 1 else 1.0\n                result.append(LoRA_data(f\"{m_type}:{name}\", multiplier))\n\n    if len(result) <= 0:\n        result.append(LoRA_data(\"\", 0.0))\n\n    return result\n\ndef get_or_list(prompt: str):\n    return prompt.split(\"|\")\n\nre_start_end = re.compile(r\"\\[\\s*\\[\\s*([^\\:\\]]+)\\:\\s*\\:([^\\]]+)\\]\\s*\\:\\s*([^\\]]+)\\]\")\nre_strat_at = re.compile(r\"\\[\\s*([^\\:\\]]+)\\:\\s*([0-9\\.]+)\\s*\\]\")\nre_bucket_inside = re.compile(r\"\\[([^\\]]+)\\]\")\nre_extra_net = re.compile(r\"<([^>]+):([^>]+)>\")\nre_python_escape = re.compile(r\"\\$\\$PYTHON_OBJ\\$\\$(\\d+)\\^\")\nre_python_escape_x = re.compile(r\"\\$\\$PYTHON_OBJX?\\$\\$(\\d+)\\^\")\nre_sd_step_render = re.compile(r\"\\[[^\\[\\]]+\\]\")\nre_super_cmd = re.compile(r\"(\\\\u0023|#)([^:#\\[\\]]+)\")\nre_escape_char = re.compile(r\"\\\\([\\[\\]\\:\\\\])\")\n\ndef escape_prompt(prompt : str):\n    def preprossing_escape(match_pt : re.Match):\n        input_str = str(match_pt.group(1))\n        if input_str == '[':\n            return '\\\\u005B'\n        elif input_str == ']':\n            return '\\\\u005D'\n        elif input_str == ':':\n            return '\\\\u003A'\n        elif input_str == '\\\\':\n            return '\\\\u005C'\n        return str(match_pt.group(0))\n    return re.sub(re_escape_char, preprossing_escape, prompt)\n\nclass MySearchResult:\n    def __init__(self):\n        group : List[str] = []\n        self.group = group\n\ndef extra_net_split(input_str : str, pattern : str):\n    result : List[str] = []\n    extra_net_list : List[str] = []\n    escape_obj_list : List[str] = []\n    def preprossing_escape(match_pt : re.Match):\n        escape_obj_list.append(str(match_pt.group(0)))\n        return f\"$$PYTHON_OBJX$${len(escape_obj_list)-1}^\"\n    def preprossing_extra_net(match_pt : re.Match):\n        extra_net_list.append(str(match_pt.group(0)))\n        return f\"$$PYTHON_OBJ$${len(extra_net_list)-1}^\"\n    def unstrip_extra_net_pattern(match_pt : re.Match):\n        input_str = str(match_pt.group(0))\n        try:\n            index = int(match_pt.group(1))\n            return extra_net_list[index]\n        except Exception:\n            return input_str\n    def unstrip_text_pattern_obj(match_pt : re.Match):\n        input_str = str(match_pt.group(0))\n        try:\n            index = int(match_pt.group(1))\n            return escape_obj_list[index]\n        except Exception:\n            return input_str\n    txt : str = input_str\n    txt = re.sub(re_python_escape_x, preprossing_escape, txt)\n    txt = re.sub(re_extra_net, preprossing_extra_net, txt)\n    pre_result = txt.split(pattern)\n    for i in range(len(pre_result)):\n        try:\n            cur_pattern = str(pre_result[i])\n            cur_result = re.sub(re_python_escape, unstrip_extra_net_pattern, cur_pattern)\n            cur_result = re.sub(re_python_escape_x, unstrip_text_pattern_obj, cur_result)\n            result.append(cur_result)\n        except Exception as ex:\n            break\n    if len(result) <= 0:\n        return [input_str]\n    return result\n\ndef extra_net_re_search(pattern : Union[str, re.Pattern[str]], input_str : str):\n    result = MySearchResult()\n    extra_net_list : List[str] = []\n    escape_obj_list : List[str] = []\n    def preprossing_escape(match_pt : re.Match):\n        escape_obj_list.append(str(match_pt.group(0)))\n        return f\"$$PYTHON_OBJX$${len(escape_obj_list)-1}^\"\n    def preprossing_extra_net(match_pt : re.Match):\n        extra_net_list.append(str(match_pt.group(0)))\n        return f\"$$PYTHON_OBJ$${len(extra_net_list)-1}^\"\n    def unstrip_extra_net_pattern(match_pt : re.Match):\n        input_str = str(match_pt.group(0))\n        try:\n            index = int(match_pt.group(1))\n            return extra_net_list[index]\n        except Exception:\n            return input_str\n    def unstrip_text_pattern_obj(match_pt : re.Match):\n        input_str = str(match_pt.group(0))\n        try:\n            index = int(match_pt.group(1))\n            return escape_obj_list[index]\n        except Exception:\n            return input_str\n    txt : str = input_str\n    txt = re.sub(re_python_escape_x, preprossing_escape, txt)\n    txt = re.sub(re_extra_net, preprossing_extra_net, txt)\n    pre_result = re.search(pattern, txt)\n    for i in range(1000):\n        try:\n            cur_pattern = str(pre_result.group(i))\n            cur_result = re.sub(re_python_escape, unstrip_extra_net_pattern, cur_pattern)\n            cur_result = re.sub(re_python_escape_x, unstrip_text_pattern_obj, cur_result)\n            result.group.append(cur_result)\n        except Exception as ex:\n            break\n    if len(result.group) <= 0:\n        return None\n    return result\n\ndef unescape_string(input_string : str):\n    result = ''\n    unicode_list = ['u','x']\n    \n    i = 0 #for(var i=0; i<input_string.length; ++i)\n    while i < len(input_string):\n        current_char = input_string[i]\n        if current_char == '\\\\':\n            i += 1\n            if i >= len(input_string):\n                break\n            string_body = input_string[i]\n            if(string_body.lower() in unicode_list):\n                result += f\"{current_char}{string_body}\"\n            else:\n                char_added = False\n                try:\n                    unescaped = json.loads(f\"\\\"{current_char}{string_body}\\\"\")\n                    if unescaped:\n                        result += unescaped\n                        char_added = True\n                except Exception:\n                    pass\n                if not char_added:\n                    result += string_body\n        else:\n            result += current_char\n        i += 1\n    return str(json.loads(json.dumps(result, indent=4).replace(\"\\\\\\\\\", \"\\\\\")))\n    \n\ndef get_LoRA_Controllers(prompt: str):\n    result = extra_net_re_search(re_start_end, prompt)\n    super_cmd = re.search(re_super_cmd, prompt)\n    Weight_Controller = LoRA_Weight_CMD()\n    if super_cmd:\n        super_cmd_text = unescape_string(super_cmd.group(2)).strip()\n        if super_cmd_text.startswith(\"cmd(\"):\n            Weight_Controller = LoRA_Weight_eval(super_cmd_text[4:-1], f\"<prompt>, at {re.sub(re_super_cmd, '', prompt)}\")\n        elif super_cmd_text.startswith(\"decrease\"):\n            Weight_Controller = LoRA_Weight_decrement()\n        elif super_cmd_text.startswith(\"increment\"):\n            Weight_Controller = LoRA_Weight_increment()\n    def set_Weight_Controller(controller_list : list[LoRA_Controller_Base], the_controller : LoRA_Weight_CMD):\n        for i, the_item in enumerate(controller_list):\n            controller_list[i].Weight_Controller = the_controller\n        return controller_list\n    result_list: List[LoRA_Controller_Base] = []\n    if result:\n        or_list = get_or_list(result.group[1])\n        if len(or_list) == 1: #LoRA with start and end\n            lora_list = get_lora_list(or_list[0])\n            for lora_item in lora_list:\n                try:\n                    result_list.append(LoRA_StartEnd_Controller(lora_item.name, lora_item.weight, float(result.group[3]), float(result.group[2])))\n                except Exception:\n                    continue\n            return set_Weight_Controller(result_list, Weight_Controller)\n        lora_lists : List[List[LoRA_data]] = []\n        max_len = -1\n        for or_block in or_list: #or \n            lora_list = get_lora_list(or_block)\n            lora_list_len = len(lora_list)\n            if lora_list_len > max_len:\n                max_len = lora_list_len\n            lora_lists.append(lora_list)\n        if max_len > 0:\n            for i in range(max_len):\n                tmp_lora_list : List[LoRA_data] = []\n                for it_lora_list in lora_lists:\n                    tmp_lora = LoRA_data(\"\", 0.0)\n                    if i < len(it_lora_list):\n                        tmp_lora = it_lora_list[i]\n                    tmp_lora_list.append(tmp_lora)\n                result_list.append(LoRA_Switcher_Controller(tmp_lora_list, float(result.group[3]), float(result.group[2])))\n        return set_Weight_Controller(result_list, Weight_Controller)\n    result = extra_net_re_search(re_strat_at, prompt)\n    if result:\n        or_list = get_or_list(result.group[1])\n        if len(or_list) == 1: #LoRA with start and end\n            lora_list = get_lora_list(or_list[0])\n            for lora_item in lora_list:\n                try:\n                    result_list.append(LoRA_StartEnd_Controller(lora_item.name, lora_item.weight, float(result.group[2]), -1.0))\n                except Exception:\n                    continue\n            return set_Weight_Controller(result_list, Weight_Controller)\n        lora_lists : List[List[LoRA_data]] = []\n        max_len = -1\n        for or_block in or_list: #or \n            lora_list = get_lora_list(or_block)\n            lora_list_len = len(lora_list)\n            if lora_list_len > max_len:\n                max_len = lora_list_len\n            lora_lists.append(lora_list)\n        if max_len > 0:\n            for i in range(max_len):\n                tmp_lora_list : List[LoRA_data] = []\n                for it_lora_list in lora_lists:\n                    tmp_lora = LoRA_data(\"\", 0.0)\n                    if i < len(it_lora_list):\n                        tmp_lora = it_lora_list[i]\n                    tmp_lora_list.append(tmp_lora)\n                result_list.append(LoRA_Switcher_Controller(tmp_lora_list, float(result.group[2]), -1.0))\n        return set_Weight_Controller(result_list, Weight_Controller)\n    result = extra_net_re_search(re_bucket_inside, prompt)\n    if result:\n        bucket_inside = result.group[1]\n        split_by_colon = extra_net_split(bucket_inside,\":\")\n        if len(split_by_colon) == 1 and ((\"|\" in bucket_inside) or (\"#\" in bucket_inside)):\n            split_by_colon.append('')\n            split_by_colon.append('-1')\n        if len(split_by_colon) > 2:\n            should_pass = False\n            or_list = get_or_list(split_by_colon[0])\n            if len(or_list) == 1: #LoRA with start and end\n                lora_list = get_lora_list(or_list[0])\n                for lora_item in lora_list:\n                    try:\n                        result_list.append(LoRA_StartEnd_Controller(lora_item.name, lora_item.weight, 0.0, float(split_by_colon[2])))\n                    except Exception:\n                        continue\n                should_pass = True\n            if not should_pass:\n                lora_lists : List[List[LoRA_data]] = []\n                max_len = -1\n                for or_block in or_list: #or \n                    lora_list = get_lora_list(or_block)\n                    lora_list_len = len(lora_list)\n                    if lora_list_len > max_len:\n                        max_len = lora_list_len\n                    lora_lists.append(lora_list)\n                if max_len > 0:\n                    for i in range(max_len):\n                        tmp_lora_list : List[LoRA_data] = []\n                        for it_lora_list in lora_lists:\n                            tmp_lora = LoRA_data(\"\", 0.0)\n                            if i < len(it_lora_list):\n                                tmp_lora = it_lora_list[i]\n                            tmp_lora_list.append(tmp_lora)\n                        result_list.append(LoRA_Switcher_Controller(tmp_lora_list, 0.0, float(split_by_colon[2])))\n            should_pass = False\n            or_list = get_or_list(split_by_colon[1])\n            if len(or_list) == 1: #LoRA with start and end\n                lora_list = get_lora_list(or_list[0])\n                for lora_item in lora_list:\n                    try:\n                        result_list.append(LoRA_StartEnd_Controller(lora_item.name, lora_item.weight, float(split_by_colon[2]), -1.0))\n                    except Exception:\n                        continue\n                should_pass = True\n            if not should_pass:\n                lora_lists : List[List[LoRA_data]] = []\n                max_len = -1\n                for or_block in or_list: #or \n                    lora_list = get_lora_list(or_block)\n                    lora_list_len = len(lora_list)\n                    if lora_list_len > max_len:\n                        max_len = lora_list_len\n                    lora_lists.append(lora_list)\n                if max_len > 0:\n                    for i in range(max_len):\n                        tmp_lora_list : List[LoRA_data] = []\n                        for it_lora_list in lora_lists:\n                            tmp_lora = LoRA_data(\"\", 0.0)\n                            if i < len(it_lora_list):\n                                tmp_lora = it_lora_list[i]\n                            tmp_lora_list.append(tmp_lora)\n                        result_list.append(LoRA_Switcher_Controller(tmp_lora_list, float(split_by_colon[2]), -1.0))\n            return set_Weight_Controller(result_list, Weight_Controller)\n    return set_Weight_Controller(result_list, Weight_Controller)\n\ndef get_all_step_rendering_in_prompt(input_prompt : str):\n    read_rendering_item_list : List[str] = []\n    escape_obj_list : List[str] = []\n    rendering_item_list : List[str] = []\n    def preprossing_step_rendering_item(match_pt : re.Match):\n        read_rendering_item_list.append(str(match_pt.group(0)))\n        return f\"$$PYTHON_OBJ$${len(read_rendering_item_list)-1}^\"\n    def preprossing_step_rendering_text(match_pt : re.Match):\n        escape_obj_list.append(str(match_pt.group(0)))\n        return f\"$$PYTHON_OBJX$${len(escape_obj_list)-1}^\"\n    def load_step_rendering_item(match_pt : re.Match):\n        input_str = str(match_pt.group(0))\n        rendering_item_list.append(input_str)\n        return input_str\n    def unstrip_rendering_text_pattern(match_pt : re.Match):\n        input_str = str(match_pt.group(0))\n        try:\n            index = int(match_pt.group(1))\n            return read_rendering_item_list[index]\n        except Exception:\n            return input_str\n    def unstrip_rendering_text_pattern_obj(match_pt : re.Match):\n        input_str = str(match_pt.group(0))\n        try:\n            index = int(match_pt.group(1))\n            return escape_obj_list[index]\n        except Exception:\n            return input_str\n    def unstrip_rendering_text(input_str : str):\n        old_result : str = \"None\"\n        result : str = input_str\n        while old_result != result:\n            old_result = result\n            result = re.sub(re_python_escape, unstrip_rendering_text_pattern, result)\n        old_result = \"None\"\n        while old_result != result:\n            old_result = result\n            result = re.sub(re_python_escape_x, unstrip_rendering_text_pattern_obj, result)\n        return result\n    txt : str = input_prompt\n    txt = re.sub(re_python_escape_x, preprossing_step_rendering_text, txt)\n    old_txt : str = \"None\"\n    while old_txt != txt:\n        old_txt = txt\n        txt = re.sub(re_sd_step_render, preprossing_step_rendering_item, txt)\n    re.sub(re_python_escape, load_step_rendering_item, txt)\n    for i, the_item in enumerate(rendering_item_list):\n        rendering_item_list[i] = unstrip_rendering_text(the_item)\n    return rendering_item_list, txt\n"
  },
  {
    "path": "composable_lycoris.py",
    "content": "from typing import Optional, Union\nimport re\nimport torch\nimport lora_ext\nfrom modules import shared, devices\n\n#support for <lyco:MODEL> \ndef lycoris_forward(compvis_module: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.MultiheadAttention], input, res):\n    import composable_lora as lora_controller\n    import lora\n    import lycoris\n    if len(lycoris.loaded_lycos) == 0:\n        return res\n    \n    if hasattr(devices, \"cond_cast_unet\"):\n        input = devices.cond_cast_unet(input)\n\n    lycoris_layer_name_loading : Optional[str] = getattr(compvis_module, 'lyco_layer_name', None)\n    if lycoris_layer_name_loading is None:\n        return res\n    #let it type is actually a string\n    lycoris_layer_name : str = str(lycoris_layer_name_loading)\n    del lycoris_layer_name_loading\n\n    sd_module = shared.sd_model.lora_layer_mapping.get(lycoris_layer_name, None)\n    num_loras = len(lora_ext.get_loaded_lora()) + len(lycoris.loaded_lycos)\n\n    if lora_controller.text_model_encoder_counter == -1:\n        lora_controller.text_model_encoder_counter = len(lora_controller.prompt_loras) * num_loras\n\n    tmp_check_loras = [] #store which lora are already apply\n    tmp_check_loras.clear()\n\n    for m_lycoris in lycoris.loaded_lycos:\n        module = m_lycoris.modules.get(lycoris_layer_name, None)\n        if module is None:\n            #fix the lyCORIS issue\n            check_lycoris_end_layer(lycoris_layer_name, res, num_loras)\n            continue\n\n        current_lora = normalize_lora_name(m_lycoris.name)\n        lora_already_used = False\n        if current_lora in tmp_check_loras:\n            lora_already_used = True\n        #store the applied lora into list\n        tmp_check_loras.append(current_lora)\n        if lora_already_used:\n            check_lycoris_end_layer(lycoris_layer_name, res, num_loras)\n            continue\n\n        converted_module = convert_lycoris(module, sd_module)\n        if converted_module is None:\n            check_lycoris_end_layer(lycoris_layer_name, res, num_loras)\n            continue\n        \n        patch = get_lora_patch(converted_module, input, res, lycoris_layer_name)\n        alpha = get_lora_alpha(converted_module, 1.0)\n        num_prompts = len(lora_controller.prompt_loras)\n\n        # print(f\"lora.name={m_lora.name} lora.mul={m_lora.multiplier} alpha={alpha} pat.shape={patch.shape}\")\n        res = lora_controller.apply_composable_lora(lycoris_layer_name, m_lycoris, converted_module, \"lyco\", patch, alpha, res, num_loras, num_prompts)\n\n    return res\n\ndef composable_forward(module, patch, alpha, multiplier, res):\n    if hasattr(module, 'composable_forward'):\n        return module.composable_forward(patch, alpha, multiplier, res)\n    return res + multiplier * alpha * patch\n\nre_lora_block_weight = re.compile(r\"[_\\s]*added[_\\s]*by[_\\s]*lora[_\\s]*block[_\\s]*weight[_\\s]*.*$\")\n\ndef normalize_lora_name(lora_name):\n    result = re.sub(r\"[_\\s]*added[_\\s]*by[_\\s]*lora[_\\s]*block[_\\s]*weight[_\\s]*.*$\", \"\", lora_name)\n    return result\n\ndef get_lora_inference(module, input):\n    if hasattr(module, 'inference'): #support for lyCORIS\n        return module.inference(input)\n    elif hasattr(module, 'up'):     #LoRA\n        if hasattr(module.up, \"to\"):\n            module.up.to(device=devices.device)\n        if hasattr(module.down, \"to\"):\n            module.down.to(device=devices.device)\n        return module.up(module.down(input))\n    else:\n        return None\n\ndef get_lora_patch(module, input, res, lora_layer_name):\n    if is_loha(module):\n        if input.is_cuda: #if is cuda, pass to cuda; otherwise do nothing\n            pass_loha_to_gpu(module)\n    if getattr(shared.opts, \"lora_apply_to_outputs\", False) and res.shape == input.shape:\n        inference = get_lora_inference(module, res)\n        if inference is not None: \n            return inference\n        else:\n            converted_module = convert_lycoris(module, shared.sd_model.lora_layer_mapping.get(lora_layer_name, None))\n            if converted_module is not None:\n                return get_lora_inference(converted_module, res)\n            else:\n                raise NotImplementedError(\n                    \"Your settings, extensions or models are not compatible with each other.\"\n                )\n    else:\n        inference = get_lora_inference(module, input)\n        if inference is not None: \n            return inference\n        else:\n            if hasattr(shared.sd_model, \"network_layer_mapping\"):\n                converted_module = convert_lycoris(module, shared.sd_model.network_layer_mapping.get(lora_layer_name, None))\n            else:\n                converted_module = convert_lycoris(module, shared.sd_model.lora_layer_mapping.get(lora_layer_name, None))\n            if converted_module is not None:\n                return get_lora_inference(converted_module, input)\n            else:\n                raise NotImplementedError(\n                    \"Your settings, extensions or models are not compatible with each other.\"\n                )\n        \ndef get_lora_alpha(module, default_val):\n    if hasattr(module, 'up'):\n        return (module.alpha / module.up.weight.shape[1] if module.alpha else default_val)\n    elif hasattr(module, 'dim'): #support for lyCORIS\n        return (module.alpha / module.dim if module.alpha else default_val)\n    else:\n        return default_val\n    \ndef check_lycoris_end_layer(lora_layer_name: str, res, num_loras):\n    if lora_layer_name.endswith(\"_11_mlp_fc2\") or lora_layer_name.endswith(\"_11_1_proj_out\"):\n        import composable_lora as lora_controller\n        if lora_layer_name.endswith(\"_11_mlp_fc2\"):  # lyCORIS maybe doesn't has _11_mlp_fc2 layer\n            lora_controller.text_model_encoder_counter += 1\n            if lora_controller.text_model_encoder_counter == (len(lora_controller.prompt_loras) + lora_controller.num_batches) * num_loras:\n                lora_controller.text_model_encoder_counter = 0\n        if lora_layer_name.endswith(\"_11_1_proj_out\"):  # lyCORIS maybe doesn't has _11_1_proj_out layer\n            lora_controller.diffusion_model_counter += res.shape[0]\n            if lora_controller.diffusion_model_counter >= (len(lora_controller.prompt_loras) + lora_controller.num_batches) * num_loras:\n                lora_controller.diffusion_model_counter = 0\n                lora_controller.add_step_counters()\n\ndef lycoris_get_multiplier(lycoris_model, lora_layer_name):\n    multiplier = 1.0\n    if hasattr(lycoris_model, 'te_multiplier'):\n        multiplier = (\n            lycoris_model.te_multiplier if 'transformer' in lora_layer_name[:20] \n            else lycoris_model.unet_multiplier\n        )\n    elif hasattr(lycoris_model, 'multiplier'):\n        multiplier = getattr(lycoris_model, 'multiplier', 1.0)\n    return multiplier\n\ndef lycoris_get_multiplier_normalized(lycoris_model, lora_layer_name):\n    multiplier = 1.0\n    if hasattr(lycoris_model, 'te_multiplier'):\n        te_multiplier = 1.0\n        unet_multiplier = lycoris_model.unet_multiplier / lycoris_model.te_multiplier\n        multiplier = (\n            te_multiplier if 'transformer' in lora_layer_name[:20] \n            else unet_multiplier\n        )\n    return multiplier\n\nclass FakeModule(torch.nn.Module):\n    def __init__(self, weight, func):\n        super().__init__()\n        self.weight = weight\n        self.func = func\n    \n    def forward(self, x):\n        return self.func(x)\n\nclass FullModule:\n    def __init__(self):\n        self.weight = None\n        self.alpha = None\n        self.op = None\n        self.extra_args = {}\n        self.shape = None\n        self.up = None\n    \n    def down(self, x):\n        return x\n    \n    def inference(self, x):\n        return self.op(x, self.weight, **self.extra_args)\n\nclass IA3Module:\n    def __init__(self):\n        self.w = None\n        self.alpha = None\n        self.on_input = None\n        self.shape = None\n        self.op = None\n        self.extra_args = {}\n\n    def down(self, x):\n        return x\n    \n    def inference(self, x):\n        return self.op(x, self.w, **self.extra_args)\n    \n    def composable_forward(self, patch, alpha, multiplier, res):\n        patch = patch.to(res.dtype)\n        return res * (1 + patch * alpha * multiplier)\n\nclass LoraUpDownModule:\n    def __init__(self):\n        self.up_model = None\n        self.mid_model = None\n        self.down_model = None\n        self.alpha = None\n        self.dim = None\n        self.op = None\n        self.extra_args = {}\n        self.shape = None\n        self.bias = None\n        self.up = None\n    \n    def down(self, x):\n        return x\n    \n    def inference(self, x):\n        if hasattr(self, 'bias') and isinstance(self.bias, torch.Tensor):\n            out_dim = self.up_model.weight.size(0)\n            rank = self.down_model.weight.size(0)\n            rebuild_weight = (\n                self.up_model.weight.reshape(out_dim, -1) @ self.down_model.weight.reshape(rank, -1)\n                + self.bias\n            ).reshape(self.shape)\n            return self.op(\n                x, rebuild_weight,\n                bias=None,\n                **self.extra_args\n            )\n        else:\n            if self.mid_model is None:\n                return self.up_model(self.down_model(x))\n            else:\n                return self.up_model(self.mid_model(self.down_model(x)))\n\ndef make_weight_cp(t, wa, wb):\n    temp = torch.einsum('i j k l, j r -> i r k l', t, wb)\n    return torch.einsum('i j k l, i r -> r j k l', temp, wa)\n\nclass LoraHadaModule:\n    def __init__(self):\n        self.t1 = None\n        self.w1a = None\n        self.w1b = None\n        self.t2 = None\n        self.w2a = None\n        self.w2b = None\n        self.alpha = None\n        self.dim = None\n        self.op = None\n        self.extra_args = {}\n        self.shape = None\n        self.bias = None\n        self.up = None\n    \n    def down(self, x):\n        return x\n    \n    def inference(self, x):\n        if hasattr(self, 'bias') and isinstance(self.bias, torch.Tensor):\n            bias = self.bias\n        else:\n            bias = 0\n        \n        if self.t1 is None:\n            return self.op(\n                x,\n                ((self.w1a @ self.w1b) * (self.w2a @ self.w2b) + bias).view(self.shape),\n                bias=None,\n                **self.extra_args\n            )\n        else:\n            return self.op(\n                x,\n                (make_weight_cp(self.t1, self.w1a, self.w1b) \n                 * make_weight_cp(self.t2, self.w2a, self.w2b) + bias).view(self.shape),\n                bias=None,\n                **self.extra_args\n            )\n\ndef make_kron(orig_shape, w1, w2):\n    if len(w2.shape) == 4:\n        w1 = w1.unsqueeze(2).unsqueeze(2)\n    w2 = w2.contiguous()\n    return torch.kron(w1, w2).reshape(orig_shape)\n\nclass LoraKronModule:\n    def __init__(self):\n        self.w1 = None\n        self.w1a = None\n        self.w1b = None\n        self.w2 = None\n        self.t2 = None\n        self.w2a = None\n        self.w2b = None\n        self._alpha = None\n        self.dim = None\n        self.op = None\n        self.extra_args = {}\n        self.shape = None\n        self.bias = None\n        self.up = None\n    \n    @property\n    def alpha(self):\n        if self.w1a is None and self.w2a is None:\n            return None\n        else:\n            return self._alpha\n    \n    @alpha.setter\n    def alpha(self, x):\n        self._alpha = x\n    \n    def down(self, x):\n        return x\n    \n    def inference(self, x):\n        if hasattr(self, 'bias') and isinstance(self.bias, torch.Tensor):\n            bias = self.bias\n        else:\n            bias = 0\n        \n        if self.t2 is None:\n            return self.op(\n                x,\n                (torch.kron(self.w1, self.w2a@self.w2b) + bias).view(self.shape),\n                **self.extra_args\n            )\n        else:\n            # will raise NotImplemented Error\n            return self.op(\n                x,\n                (torch.kron(self.w1, make_weight_cp(self.t2, self.w2a, self.w2b)) + bias).view(self.shape),\n                **self.extra_args\n            )\n\ndef convert_lycoris(lycoris_module, sd_module):\n    result_module = getattr(lycoris_module, 'lyco_converted_lora_module', None)\n    if result_module is not None:\n        return result_module\n    if lycoris_module.__class__.__name__ == \"LycoUpDownModule\" or lycoris_module.__class__.__name__ == \"LoraUpDownModule\"\\\n    or lycoris_module.__class__.__name__ == \"NetworkModuleLora\":\n        result_module = LoraUpDownModule()\n        if (type(sd_module) == torch.nn.Linear\n            or type(sd_module) == torch.nn.modules.linear.NonDynamicallyQuantizableLinear\n            or type(sd_module) == torch.nn.MultiheadAttention):\n            result_module.op = torch.nn.functional.linear\n        elif type(sd_module) == torch.nn.Conv2d:\n            result_module.op = torch.nn.functional.conv2d\n            result_module.extra_args = {\n                'stride': sd_module.stride,\n                'padding': sd_module.padding\n            }\n        else:\n            return None\n        result_module.up_model = lycoris_module.up_model\n        result_module.mid_model = lycoris_module.mid_model\n        result_module.down_model = lycoris_module.down_model\n        result_module.alpha = lycoris_module.alpha\n        result_module.dim = lycoris_module.dim \n        result_module.shape = lycoris_module.shape\n        result_module.bias = lycoris_module.bias\n        result_module.up = FakeModule(\n            result_module.up_model.weight,\n            result_module.inference\n        )\n    elif lycoris_module.__class__.__name__ == \"FullModule\" or lycoris_module.__class__.__name__ == \"NetworkModuleFull\":\n        result_module = FullModule()\n        result_module.weight = lycoris_module.weight.to(device=devices.device, dtype=devices.dtype)\n        result_module.alpha = lycoris_module.alpha\n        result_module.shape = lycoris_module.shape\n        result_module.up = FakeModule(\n            result_module.weight,\n            result_module.inference\n        )\n        if len(result_module.weight.shape)==2:\n            result_module.op = torch.nn.functional.linear\n            result_module.extra_args = {\n                'bias': None\n            }\n        else:\n            result_module.op = torch.nn.functional.conv2d\n            result_module.extra_args = {\n                'stride': sd_module.stride,\n                'padding': sd_module.padding,\n                'bias': None\n            }\n        setattr(lycoris_module, \"lyco_converted_lora_module\", result_module)\n        return result_module\n    elif lycoris_module.__class__.__name__ == \"IA3Module\" or lycoris_module.__class__.__name__ == \"NetworkModuleIa3\":\n        result_module = IA3Module()\n        result_module.w = lycoris_module.w\n        result_module.alpha = lycoris_module.alpha\n        result_module.on_input = lycoris_module.on_input\n        if hasattr(sd_module, 'weight'):\n            result_module.shape = sd_module.weight.shape\n        if (type(sd_module) == torch.nn.Linear\n            or type(sd_module) == torch.nn.modules.linear.NonDynamicallyQuantizableLinear\n            or type(sd_module) == torch.nn.MultiheadAttention):\n            result_module.op = torch.nn.functional.linear\n        elif type(sd_module) == torch.nn.Conv2d:\n            result_module.op = torch.nn.functional.conv2d\n    elif lycoris_module.__class__.__name__ == \"LycoHadaModule\" or lycoris_module.__class__.__name__ == \"LoraHadaModule\"\\\n          or lycoris_module.__class__.__name__ == \"NetworkModuleHada\":\n        result_module = LoraHadaModule()\n        result_module.t1 = lycoris_module.t1\n        result_module.w1a = lycoris_module.w1a\n        result_module.w1b = lycoris_module.w1b\n        result_module.t2 = lycoris_module.t2\n        result_module.w2a = lycoris_module.w2a\n        result_module.w2b = lycoris_module.w2b\n        result_module.alpha = lycoris_module.alpha\n        result_module.dim = lycoris_module.dim\n        result_module.shape = lycoris_module.shape\n        result_module.bias = lycoris_module.bias\n        result_module.up = FakeModule(\n            result_module.t1 if result_module.t1 is not None else result_module.w1a,\n            result_module.inference\n        )\n        if (type(sd_module) == torch.nn.Linear\n            or type(sd_module) == torch.nn.modules.linear.NonDynamicallyQuantizableLinear\n            or type(sd_module) == torch.nn.MultiheadAttention):\n            result_module.op = torch.nn.functional.linear\n        elif type(sd_module) == torch.nn.Conv2d:\n            result_module.op = torch.nn.functional.conv2d\n            result_module.extra_args = {\n                'stride': sd_module.stride,\n                'padding': sd_module.padding\n            }\n    elif lycoris_module.__class__.__name__ == \"LycoKronModule\" or lycoris_module.__class__.__name__ == \"LoraKronModule\"\\\n          or lycoris_module.__class__.__name__ == \"NetworkModuleLokr\" :\n        result_module = LoraKronModule()\n        result_module.w1 = lycoris_module.w1\n        result_module.w1a = lycoris_module.w1a\n        result_module.w1b = lycoris_module.w1b\n        result_module.w2 = lycoris_module.w2\n        result_module.t2 = lycoris_module.t2\n        result_module.w2a = lycoris_module.w2a\n        result_module.w2b = lycoris_module.w2b\n        result_module._alpha = lycoris_module._alpha\n        result_module.dim = lycoris_module.dim\n        result_module.shape = lycoris_module.shape\n        result_module.bias = lycoris_module.bias\n        result_module.up = FakeModule(\n            result_module.w1a if result_module.w1a is not None else result_module.w2a,\n            result_module.inference\n        )\n        if (any(isinstance(sd_module, torch_layer) for torch_layer in \n                [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear, torch.nn.MultiheadAttention])):\n            result_module.op = torch.nn.functional.linear\n        elif isinstance(sd_module, torch.nn.Conv2d):\n            result_module.op = torch.nn.functional.conv2d\n            result_module.extra_args = {\n                'stride': sd_module.stride,\n                'padding': sd_module.padding\n            }\n    if result_module is not None:\n        setattr(lycoris_module, \"lyco_converted_lora_module\", result_module)\n        return result_module\n    return None\n\ndef is_loha(m_lora):\n    return hasattr(m_lora, 'w1a') or hasattr(m_lora, 'w1b') or hasattr(m_lora, 'w2a') or hasattr(m_lora, 'w2b')\n\ndef pass_loha_to_gpu(m_loha):\n    if hasattr(m_loha, 'bias'):\n        if isinstance(m_loha.bias, torch.Tensor):\n            if not m_loha.bias.is_cuda:\n                to_cuda = m_loha.bias.to(device=devices.device)\n                to_del = m_loha.bias\n                m_loha.bias = None\n                del to_del\n                del m_loha.bias\n                m_loha.bias = to_cuda\n    if hasattr(m_loha, 't1'):\n        if isinstance(m_loha.t1, torch.Tensor):\n            if not m_loha.t1.is_cuda:\n                to_cuda = m_loha.t1.to(device=devices.device)\n                to_del = m_loha.t1\n                m_loha.t1 = None\n                del to_del\n                del m_loha.t1\n                m_loha.t1 = to_cuda\n    if hasattr(m_loha, 't2'):\n        if isinstance(m_loha.t2, torch.Tensor):\n            if not m_loha.t2.is_cuda:\n                to_cuda = m_loha.t2.to(device=devices.device)\n                to_del = m_loha.t2\n                m_loha.t2 = None\n                del to_del\n                del m_loha.t2\n                m_loha.t2 = to_cuda\n    if hasattr(m_loha, 'w'):\n        if isinstance(m_loha.w, torch.Tensor):\n            if not m_loha.w.is_cuda:\n                to_cuda = m_loha.w.to(device=devices.device)\n                to_del = m_loha.w\n                m_loha.w = None\n                del to_del\n                del m_loha.w\n                m_loha.w = to_cuda\n    if hasattr(m_loha, 'w1'):\n        if isinstance(m_loha.w1, torch.Tensor):\n            if not m_loha.w1.is_cuda:\n                to_cuda = m_loha.w1.to(device=devices.device)\n                to_del = m_loha.w1\n                m_loha.w1 = None\n                del to_del\n                del m_loha.w1\n                m_loha.w1 = to_cuda\n    if hasattr(m_loha, 'w1a'):\n        if isinstance(m_loha.w1a, torch.Tensor):\n            if not m_loha.w1a.is_cuda:\n                to_cuda = m_loha.w1a.to(device=devices.device)\n                to_del = m_loha.w1a\n                m_loha.w1a = None\n                del to_del\n                del m_loha.w1a\n                m_loha.w1a = to_cuda\n    if hasattr(m_loha, 'w1b'):\n        if isinstance(m_loha.w1b, torch.Tensor):\n            if not m_loha.w1b.is_cuda:\n                to_cuda = m_loha.w1b.to(device=devices.device)\n                to_del = m_loha.w1b\n                m_loha.w1b = None\n                del to_del\n                del m_loha.w1b\n                m_loha.w1b = to_cuda\n    if hasattr(m_loha, 'w2'):\n        if isinstance(m_loha.w2, torch.Tensor):\n            if not m_loha.w2.is_cuda:\n                to_cuda = m_loha.w2.to(device=devices.device)\n                to_del = m_loha.w2\n                m_loha.w2 = None\n                del to_del\n                del m_loha.w2\n                m_loha.w2 = to_cuda\n    if hasattr(m_loha, 'w2a'):\n        if isinstance(m_loha.w2a, torch.Tensor):\n            if not m_loha.w2a.is_cuda:\n                to_cuda = m_loha.w2a.to(device=devices.device)\n                to_del = m_loha.w2a\n                m_loha.w2a = None\n                del to_del\n                del m_loha.w2a\n                m_loha.w2a = to_cuda\n    if hasattr(m_loha, 'w2b'):\n        if isinstance(m_loha.w2b, torch.Tensor):\n            if not m_loha.w2b.is_cuda:\n                to_cuda = m_loha.w2b.to(device=devices.device)\n                to_del = m_loha.w2b\n                m_loha.w2b = None\n                del to_del\n                del m_loha.w2b\n                m_loha.w2b = to_cuda\n\nhas_webui_lycoris : bool = False"
  },
  {
    "path": "lora_ext.py",
    "content": "lora_Linear_forward = None\nlora_Linear_load_state_dict = None\nlora_Conv2d_forward = None\nlora_Conv2d_load_state_dict = None\nlora_MultiheadAttention_forward = None\nlora_MultiheadAttention_load_state_dict = None\nis_sd_1_5 = False\ndef get_loaded_lora():\n    global is_sd_1_5\n    if lora_Linear_forward is None:\n        load_lora_ext()\n    import lora\n    try:\n        import networks\n        is_sd_1_5 = True\n    except ImportError:\n        pass\n    if is_sd_1_5:\n        return networks.loaded_networks\n    return lora.loaded_loras\n\ndef load_lora_ext():\n    global is_sd_1_5\n    global lora_Linear_forward\n    global lora_Linear_load_state_dict\n    global lora_Conv2d_forward\n    global lora_Conv2d_load_state_dict\n    global lora_MultiheadAttention_forward\n    global lora_MultiheadAttention_load_state_dict\n    if lora_Linear_forward is not None:\n        return\n    import lora\n    is_sd_1_5 = False\n    try:\n        import networks\n        is_sd_1_5 = True\n    except ImportError:\n        pass\n    if is_sd_1_5:\n        if hasattr(networks, \"network_Linear_forward\"):\n            lora_Linear_forward = networks.network_Linear_forward\n        if hasattr(networks, \"network_Linear_load_state_dict\"):\n            lora_Linear_load_state_dict = networks.network_Linear_load_state_dict\n        if hasattr(networks, \"network_Conv2d_forward\"):\n            lora_Conv2d_forward = networks.network_Conv2d_forward\n        if hasattr(networks, \"network_Conv2d_load_state_dict\"):\n            lora_Conv2d_load_state_dict = networks.network_Conv2d_load_state_dict\n        if hasattr(networks, \"network_MultiheadAttention_forward\"):\n            lora_MultiheadAttention_forward = networks.network_MultiheadAttention_forward\n        if hasattr(networks, \"network_MultiheadAttention_load_state_dict\"):\n            lora_MultiheadAttention_load_state_dict = networks.network_MultiheadAttention_load_state_dict\n    else:\n        if hasattr(lora, \"network_Linear_forward\"):\n            lora_Linear_forward = lora.lora_Linear_forward\n        if hasattr(lora, \"network_Linear_load_state_dict\"):\n            lora_Linear_load_state_dict = lora.lora_Linear_load_state_dict\n        if hasattr(lora, \"network_Conv2d_forward\"):\n            lora_Conv2d_forward = lora.lora_Conv2d_forward\n        if hasattr(lora, \"network_Conv2d_load_state_dict\"):\n            lora_Conv2d_load_state_dict = lora.lora_Conv2d_load_state_dict\n        if hasattr(lora, \"network_MultiheadAttention_forward\"):\n            lora_MultiheadAttention_forward = lora.lora_MultiheadAttention_forward\n        if hasattr(lora, \"network_MultiheadAttention_load_state_dict\"):\n            lora_MultiheadAttention_load_state_dict = lora.lora_MultiheadAttention_load_state_dict\n"
  },
  {
    "path": "plot_helper.py",
    "content": "from dataclasses import dataclass\nfrom typing import List\nimport io\nimport matplotlib\nmatplotlib.use('Agg')\nimport pandas as pd\nfrom pandas.plotting._matplotlib.style import get_standard_colors\nfrom PIL import Image\n\n@dataclass\nclass YAxis:\n    name: str\n    columns: List[str]\n\n@dataclass\nclass PlotDefinition:\n    title: str\n    x_axis: str\n    y_axis: List[YAxis]\n\ndef plot_lora_weight(lora_weights, lora_names):\n    data = pd.DataFrame(lora_weights, columns=lora_names)\n    ax = data.plot()\n    ax.set_xlabel(\"Steps\")\n    ax.set_ylabel(\"LoRA weight\")\n    ax.set_title(\"LoRA weight in all steps\")\n    ax.legend(loc=0)\n    result_image = fig2img(ax)\n    matplotlib.pyplot.close(ax.figure)\n    del ax # RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`). Consider using `matplotlib.pyplot.close()`.\n    return result_image\n\ndef fig2img(fig):\n    buf = io.BytesIO()\n    fig.figure.savefig(buf)\n    buf.seek(0)\n    img = Image.open(buf)\n    return img\n\n\ndef plot_graph(\n        data: pd.DataFrame,\n        plot_definition: PlotDefinition,\n        spacing: float = 0.1,\n):\n    colors = get_standard_colors(num_colors=(len(plot_definition.y_axis) + 7))\n    loss_color = colors[0]\n    avg_colors = colors[1:]\n    for i, yi in enumerate(plot_definition.y_axis):\n        if i == 0:\n            ax = data.plot(\n                x=plot_definition.x_axis,\n                y=yi.columns,\n                title=plot_definition.title,\n                color=[loss_color] * len(yi.columns)\n            )\n            ax.set_ylabel(ylabel=yi.name)\n\n        else:\n            # Multiple y-axes\n            ax_new = ax.twinx()\n            ax_new.spines[\"right\"].set_position((\"axes\", 1 + spacing * (i - 1)))\n            data.plot(\n                ax=ax_new,\n                x=plot_definition.x_axis,\n                y=yi.columns,\n                color=[avg_colors[yl] for yl in range(len(yi.columns))]\n            )\n            ax_new.set_ylabel(ylabel=yi.name)\n\n    ax.legend(loc=0)\n\n    return ax"
  },
  {
    "path": "scripts/composable_lora_script.py",
    "content": "#\n# Composable-Diffusion with Lora\n#\nimport torch\nimport gradio as gr\n\nimport composable_lora\nimport composable_lora_function_handler\nimport lora_ext\nimport modules.scripts as scripts\nfrom modules import script_callbacks\nfrom modules.processing import StableDiffusionProcessing\n\ndef unload():\n    torch.nn.Linear.forward = torch.nn.Linear_forward_before_lora\n    torch.nn.Conv2d.forward = torch.nn.Conv2d_forward_before_lora\n    torch.nn.MultiheadAttention.forward = torch.nn.MultiheadAttention_forward_before_lora\n\nif not hasattr(composable_lora, 'Linear_forward_before_clora'):\n    if hasattr(torch.nn, 'Linear_forward_before_lyco'):\n        composable_lora.Linear_forward_before_clora = torch.nn.Linear_forward_before_lyco\n    else:\n        composable_lora.Linear_forward_before_clora = torch.nn.Linear.forward\n\nif not hasattr(composable_lora, 'Conv2d_forward_before_clora'):\n    if hasattr(torch.nn, 'Conv2d_forward_before_lyco'):\n        composable_lora.Conv2d_forward_before_clora = torch.nn.Conv2d_forward_before_lyco\n    else:\n        composable_lora.Conv2d_forward_before_clora = torch.nn.Conv2d.forward\n\nif not hasattr(composable_lora, 'MultiheadAttention_forward_before_clora'):\n    if hasattr(torch.nn, 'MultiheadAttention_forward_before_lyco'):\n        composable_lora.MultiheadAttention_forward_before_clora = torch.nn.MultiheadAttention_forward_before_lyco\n    else:\n        composable_lora.MultiheadAttention_forward_before_clora = torch.nn.MultiheadAttention.forward\n\nif not hasattr(torch.nn, 'Linear_forward_before_lora'):\n    if hasattr(torch.nn, 'Linear_forward_before_lyco'):\n        torch.nn.Linear_forward_before_lora = torch.nn.Linear_forward_before_lyco\n    else:\n        torch.nn.Linear_forward_before_lora = torch.nn.Linear.forward\n\nif not hasattr(torch.nn, 'Conv2d_forward_before_lora'):\n    if hasattr(torch.nn, 'Conv2d_forward_before_lyco'):\n        torch.nn.Conv2d_forward_before_lora = torch.nn.Conv2d_forward_before_lyco\n    else:\n        torch.nn.Conv2d_forward_before_lora = torch.nn.Conv2d.forward\n\nif not hasattr(torch.nn, 'MultiheadAttention_forward_before_lora'):\n    if hasattr(torch.nn, 'MultiheadAttention_forward_before_lyco'):\n        torch.nn.MultiheadAttention_forward_before_lora = torch.nn.MultiheadAttention_forward_before_lyco\n    else:\n        torch.nn.MultiheadAttention_forward_before_lora = torch.nn.MultiheadAttention.forward\n\nif hasattr(torch.nn, 'Linear_forward_before_lyco'):\n    composable_lora.lyco_notfound = False\nelse:\n    composable_lora.lyco_notfound = True\n\n#torch.nn.Linear.forward = composable_lora.lora_Linear_forward\n#torch.nn.Conv2d.forward = composable_lora.lora_Conv2d_forward\n\ndef check_install_state():\n    if not hasattr(composable_lora, \"noop\"):\n        import warnings\n        warnings.warn( #NOTICE: You Must Restart the WebUI after Install composable_lora!\n            \"module 'composable_lora' not found! Please reinstall composable_lora and restart the WebUI.\")\n\nscript_callbacks.on_script_unloaded(unload)\nif hasattr(script_callbacks, \"on_before_reload\"):\n    script_callbacks.on_before_reload(check_install_state)\nscript_callbacks.on_before_ui(check_install_state)\n\nclass ComposableLoraScript(scripts.Script):\n    def title(self):\n        return \"Composable Lora\"\n\n    def show(self, is_img2img):\n        return scripts.AlwaysVisible\n\n    def ui(self, is_img2img):\n        with gr.Group():\n            with gr.Accordion(\"Composable Lora\", open=False):\n                if not hasattr(composable_lora, \"noop\"):\n                    gr.Markdown('<span style=\"color:red\">Error! Composable Lora install failed! Please reinstall composable_lora and restart the WebUI.</span>')\n                enabled = gr.Checkbox(value=False, label=\"Enabled\")\n                opt_composable_with_step = gr.Checkbox(value=False, label=\"Composable LoRA with step\")\n                opt_uc_text_model_encoder = gr.Checkbox(value=False, label=\"Use Lora in uc text model encoder\")\n                opt_uc_diffusion_model = gr.Checkbox(value=False, label=\"Use Lora in uc diffusion model\")\n                opt_plot_lora_weight = gr.Checkbox(value=False, label=\"Plot the LoRA weight in all steps\")\n                opt_single_no_uc = gr.Checkbox(value=False, label=\"Don't use LoRA in uc if there're no subprompts\")\n                opt_hires_step_as_global = gr.Checkbox(value=False, label=\"Treat hires step as global step\")\n        return [enabled, opt_composable_with_step, opt_uc_text_model_encoder, opt_uc_diffusion_model, opt_plot_lora_weight, opt_single_no_uc, opt_hires_step_as_global]\n\n    def process(self, p: StableDiffusionProcessing, \n            enabled: bool, \n            opt_composable_with_step: bool, \n            opt_uc_text_model_encoder: bool, opt_uc_diffusion_model: \n            bool, opt_plot_lora_weight: bool, opt_single_no_uc: \n            bool, opt_hires_step_as_global: bool):\n        lora_ext.load_lora_ext()\n        if lora_ext.is_sd_1_5:\n            import composable_lycoris\n            if composable_lycoris.has_webui_lycoris:\n                print(\"Error! in sd webui 1.5, composable-lora not support with sd-webui-lycoris extension.\")\n        composable_lora.enabled = enabled\n        composable_lora.opt_uc_text_model_encoder = opt_uc_text_model_encoder\n        composable_lora.opt_uc_diffusion_model = opt_uc_diffusion_model\n        composable_lora.opt_composable_with_step = opt_composable_with_step\n        composable_lora.opt_plot_lora_weight = opt_plot_lora_weight\n        composable_lora.opt_single_no_uc = opt_single_no_uc\n        composable_lora.opt_hires_step_as_global = opt_hires_step_as_global\n\n        composable_lora.num_batches = p.batch_size\n        if hasattr(p, \"hr_second_pass_steps\"):\n            hr_second_pass_steps = p.hr_second_pass_steps\n        else:\n            hr_second_pass_steps = 0\n        if opt_hires_step_as_global:\n            composable_lora.num_steps = p.steps + hr_second_pass_steps\n        else:\n            composable_lora.num_steps = p.steps\n        composable_lora.num_hires_steps = hr_second_pass_steps\n\n        if not hasattr(composable_lora, \"noop\"):\n            raise ModuleNotFoundError( #NOTICE: You Must Restart the WebUI after Install composable_lora!\n                \"No module named 'composable_lora'! Please reinstall composable_lora and restart the WebUI.\")\n        composable_lora_function_handler.on_enable()\n        composable_lora.reset_step_counters()\n\n        prompt = p.all_prompts[0]\n        composable_lora.negative_prompt = p.all_negative_prompts[0]\n        composable_lora.load_prompt_loras(prompt)\n        composable_lora.sd_processing = p\n\n    def process_batch(self, p: StableDiffusionProcessing, *args, **kwargs):\n        composable_lora.sd_processing = p\n        composable_lora.reset_counters()\n\n    def postprocess(self, p, processed, *args):\n        if not hasattr(composable_lora, \"noop\"):\n            raise ModuleNotFoundError( #NOTICE: You Must Restart the WebUI after Install composable_lora!\n                \"No module named 'composable_lora'! Please reinstall composable_lora and restart the WebUI.\")\n        composable_lora_function_handler.on_disable()\n        if composable_lora.enabled:\n            if composable_lora.opt_plot_lora_weight:\n                processed.images.extend([composable_lora.plot_lora()])\n"
  }
]