[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# data & models\n\ndata/\nmodels/\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\nlogs/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\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/\ncover/\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\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\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# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n#poetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\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\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n#.idea/\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU 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"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <h1 align=\"center\">ChatFinance</h3>\n  <p align=\"center\">金融财报问答大模型</p>\n  <p align=\"center\">\n  </p>\n  <p align=\"center\">\n    <a href=\"https://github.com/KylinC/ChatFinance\"><img src=\"https://img.shields.io/badge/release-v0.0.1-blue\" alt=\"GitHub version\"></a>\n    <a href=\"https://github.com/KylinC/ChatFinance\"><img src=\"https://img.shields.io/badge/ROCm-v5.5-orange\" alt=\"GitHub version\"></a>\n    <a href=\"https://github.com/KylinC/ChatFinance\"><img src=\"https://img.shields.io/badge/elasticsearch-v8.9.0-yellowgreen\" alt=\"GitHub version\"></a>\n    <a href=\"https://github.com/KylinC/eMarkDown\"><img src=\"https://img.shields.io/badge/weaviate-v1.19.5-lightgrey\" alt=\"GitHub version\"></a>\n  </p>\n</p>\n\n\n### 框架 Framework \n\n\n\n<div align=\"center\"><img src=\"http://kylinhub.oss-cn-shanghai.aliyuncs.com/uPic/CF.png\" style=\"width=40%;\"/></div>\n\n### 模型 Model\n使用[ChatGLM2-6B](https://huggingface.co/THUDM/chatglm2-6b)模型进行微调，也可以使用base_model进行测试。\n\n```\nbash downloads/download_model.sh\n```\n\n### 数据 Dataset\n\n原始数据为[ChatGLM评估挑战赛-金融赛道数据集](https://modelscope.cn/datasets/modelscope/chatglm_llm_fintech_raw_dataset/summary)，经过OCR处理之后转化为TXT数据\n保留接口：可使用公开金融数据对ElasticSearch和Weaviate数据库进行补充\n\n```\nbash downloads/download_data.sh\n```\n\n### 训练 Training\n> 可以支持AMD ROCm 上的SFT\n\n```\npython sft/chatglm2_6b_sft_lora.py\n```\n\n### 推理 Inference\n\n\n```\nvim configs/server.json # 修改base_path和base_python\nsudo bash inference_6b.sh \n```\n\n### 使用效果 Demo\n\n```\n# 文字概括\n{\"question\": \"根据2020年水发燃气的年报，请简要介绍报告期内公司行业格局和趋势的情况。\", \"answer\": \"根据2020年水发燃气的年报，公司在行业内的行业格局和趋势情况如下：\\n\\n1. 行业格局：在能源行业中，水发煤气在规模和市场份额方面占据领先地位。2020年，水发燃气的总资产达到1867亿元人民币，是行业内唯一一家总资产超过1000亿元人民币的公司。同时，水发煤气在煤炭、石油和天然气等领域的市场份额也位居行业前列。\\n\\n2. 趋势情况：随着能源转型和环保要求的提高，清洁能源已成为能源行业的发展趋势。水发煤气在年报中提到，公司正加大在清洁能源领域的投入，以适应这一趋势。此外，水发煤气还表示，将继续深化在煤炭、石油和天然气等传统领域的业务，以保持公司在能源行业的主导地位。\\n\\n综上所述，水发煤气在2020年的行业格局中占据了领先地位，同时也在积极应对能源转型和环保要求，加大在清洁能源领域的投入，以适应清洁能源的发展趋势。\"}\n\n# 检索\n{\"question\": \"江化微2019年研发费用和财务费用分别是多少元?\", \"answer\": \"江化微2019年研发费用为5.49亿元，财务费用为1.99亿元。\"}\n\n# 开放问题\n{\"question\": \"什么是净利润？\", \"answer\": \"净利润是指企业在扣除所有成本、税金和其他费用后，所剩余的利润。净利润通常用于衡量企业的盈利能力。\"}\n```\n\n\n\n\n\n"
  },
  {
    "path": "configs/inference.json",
    "content": "{\n    \"train_batch_size\": \"auto\",\n    \"gradient_accumulation_steps\": 1,\n    \"steps_per_print\": 10,\n    \"zero_optimization\": {\n    \"stage\": 2,\n    \"allgather_partitions\": true,\n    \"reduce_scatter\": true,\n    \"allgather_bucket_size\": 50000000,\n    \"reduce_bucket_size\": 50000000,\n    \"load_from_fp32_weights\": true,\n    \"overlap_comm\": true\n    },\n    \"gradient_clipping\": 1.0,\n    \"fp16\": {\n    \"enabled\": true,\n    \"loss_scale\": 0,\n    \"loss_scale_window\": 1000,\n    \"hysteresis\": 2,\n    \"min_loss_scale\": 1\n    },\n    \"wall_clock_breakdown\": true,\n    \"zero_allow_untested_optimizer\": true\n}"
  },
  {
    "path": "configs/server.json",
    "content": "{\n    \"base_path\": \"/home/kylin/workspace/ChatFinance\",\n    \"base_python\": \"/home/kylin/anaconda3/bin/python\",\n    \"models_path\": {\n        \"chatglm2\":\"models/chatglm2-6b\",\n        \"text2vec\":\"models/text2vec-base-chinese-paraphrase\"\n    },\n    \"sever_path\": {\n        \"elastic_search\":\"database_server/elastic_search\",\n        \"weaviate\":\"database_server/weaviate\",\n        \"chatglm2\":\"models_server/chatglm2\",\n        \"text2vec\":\"models_server/text2vec\"\n    },\n    \"port\": {\n        \"chatglm2\":50002,\n        \"text2vec\":50001,\n        \"elastic_search\":50004,\n        \"weaviate\":50003\n    }\n}"
  },
  {
    "path": "configs/train.json",
    "content": ""
  },
  {
    "path": "database_server/elastic_search/README",
    "content": "# 如何做不同主机之间的数据迁移\n\n- 在主机A上备份\n\ndocker-compose down\ndocker run --rm -v esdata:/data -v $(pwd):/backup ubuntu tar czvf /backup/esdata.tar.gz /data\n\n- 拷贝\n\nscp esdata.tar.gz\n\n- 恢复数据\n\ndocker run --rm -v esdata:/data -v $(pwd):/backup ubuntu tar xzvf /backup/esdata.tar.gz -C /\n\n"
  },
  {
    "path": "database_server/elastic_search/clear.py",
    "content": "from elasticsearch import Elasticsearch\n\n# Connect to the Elasticsearch instance\nes = Elasticsearch([\"http://localhost:50004\"])\n\n# Fetch all index names\nall_indices = es.indices.get_alias(name=\"*\").keys()\n\nprint(all_indices)\n\n# Delete each index\nfor index in all_indices:\n    es.indices.delete(index=index)\n"
  },
  {
    "path": "database_server/elastic_search/db.py",
    "content": "import sys  # noqa: E501\nsys.path.append(\"/home/kylin/workspace/ChatFinance\")  # noqa: E501\nfrom elasticsearch import Elasticsearch\n\nimport json\n\n\ndef attain_uuid(entities, uuid_dict):\n    for k, v in uuid_dict.items():\n        fg = True\n        for entity in entities:\n            if entity not in k:\n                fg = False\n                break\n        if fg:\n            print(entities, k)\n            return v\n    return None\n\n\nif __name__ == \"__main__\":\n    es = Elasticsearch('http://localhost:50004')\n\n    with open(\"/home/kylin/workspace/ChatFinance/data/chatglm_llm_fintech_raw_dataset/uuid.json\", \"r\") as f:\n        uuid_dict = json.load(f)\n\n    with open(\"/home/kylin/workspace/ChatFinance/data/chatglm_llm_fintech_raw_dataset/allcrawl.json\", \"r\") as f:\n        crawl_dict = json.load(f)\n\n    for i, company in enumerate(crawl_dict):\n        for year in crawl_dict[company]:\n            if year not in [\"2019年报\", \"2020年报\", \"2021年报\"]:\n                continue\n            try:\n                uuid = attain_uuid(\n                    [crawl_dict[company][year]['SECURITY_CODE'], year[:-1]], uuid_dict)\n                for idx, key in enumerate(crawl_dict[company][year]):\n                    doc = {\n                        \"text\": key,\n                    }\n                    resp = es.index(index=str(uuid), id=idx, document=doc)\n            except:\n                print(f\"error {company} {year}\")\n        if i % 99 == 0 and i > 0:\n            print(f\"insert {3*(i+1)} file\")\n    print(f\"insert {3*len(crawl_dict)} file\")\n"
  },
  {
    "path": "database_server/elastic_search/docker-compose.yml",
    "content": "version: '3.4'\nservices:\n  elasticsearch:\n    image: docker.elastic.co/elasticsearch/elasticsearch:8.9.0\n    container_name: elasticsearch\n    environment:\n      - discovery.type=single-node\n      - xpack.security.enabled=false\n      - http.max_content_length=1gb\n      - cluster.max_shards_per_node=50000\n    ports:\n      - \"50004:9200\"\n    networks:\n      - elastic\n    volumes:\n      - esdata:/usr/share/elasticsearch/data\n\n  kibana:\n    image: docker.elastic.co/kibana/kibana:8.9.0\n    container_name: kibana\n    ports:\n      - \"5601:5601\"\n    environment:\n      ELASTICSEARCH_URL: http://elasticsearch:9200\n      ELASTICSEARCH_HOSTS: http://elasticsearch:9200\n    networks:\n      - elastic\n    depends_on:\n      - elasticsearch\n\nnetworks:\n  elastic:\n    driver: bridge\n\nvolumes:\n  esdata:\n"
  },
  {
    "path": "database_server/weaviate/README",
    "content": "# 如何做不同主机之间的数据迁移\n\n- 在主机A上备份\n\ndocker-compose down\ndocker run --rm -v weaviatedata:/data -v $(pwd):/backup ubuntu tar czvf /backup/weaviatedata.tar.gz /data\n\n- 拷贝\n\nscp weaviatedata.tar.gz\n\n- 恢复数据\n\ndocker run --rm -v weaviatedata:/data -v $(pwd):/backup ubuntu tar xzvf /backup/weaviatedata.tar.gz -C /\n\n\n"
  },
  {
    "path": "database_server/weaviate/db.py",
    "content": "import sys  # noqa: E501\nsys.path.append('/home/kylin/workspace/ChatFinance')  # noqa: E501\n\nfrom langchain.vectorstores import Weaviate\nfrom utils import JinaEmbeddings\nfrom jina import Document\nimport weaviate\nimport glob\nimport json\nimport os\n\n\nclient = weaviate.Client(\n    url=\"http://localhost:50003\",  # Replace with your endpoint\n    auth_client_secret=weaviate.AuthApiKey(api_key=\"shadowmotion-secret-key\"))\n\nembedding = JinaEmbeddings(\"127.0.0.1\")\n\n\n# print(embedding.embed_documents(read_qa_file(\"raw/QA.txt\")))\n\n\ndef insert_txt(path, uuid_dict):\n\n    basename = os.path.basename(path).split('.')[0]\n\n    db = Weaviate(client=client, embedding=embedding,\n                  index_name=f\"LangChain_{uuid_dict[basename]}\", text_key=\"text\", by_text=False)\n    print(f\"To insert -> {basename}\")\n    print(f\"index_name: {db._index_name}\")\n\n    texts = []\n\n    with open(path, \"r\", encoding=\"utf-8\") as f:\n        for i, line in enumerate(f):\n            if i > 0 and i % 1000 == 0:\n                db.add_texts(texts=texts)\n                print(f\"文字数据已注入{i}\")\n                texts = []\n            if len(line) <= 1:\n                continue\n            texts.append(line[:-1])\n        db.add_texts(texts=texts)\n        print(f\"文字数据已注入{i}\")\n        texts = []\n\ndef insert_txt_uuid(path, uuid, client, embedding):\n\n    basename = os.path.basename(path).split('.')[0]\n\n    db = Weaviate(client=client, embedding=embedding,\n                  index_name=f\"LangChain_{uuid}\", text_key=\"text\", by_text=False)\n    print(f\"To insert -> {basename}\")\n    print(f\"index_name: {db._index_name}\")\n\n    texts = []\n\n    with open(path, \"r\", encoding=\"utf-8\") as f:\n        for i, line in enumerate(f):\n            if i > 0 and i % 1000 == 0:\n                db.add_texts(texts=texts)\n                # print(f\"文字数据已注入{i}\")\n                texts = []\n            if len(line) <= 1:\n                continue\n            texts.append(line[:-1])\n        db.add_texts(texts=texts)\n        print(f\"文字数据已注入{i}\")\n        texts = []\n\ndef insert_table(path, uuid_dict):\n    basename = os.path.basename(path).split('.')[0]\n\n    db = Weaviate(client=client, embedding=embedding,\n                  index_name=f\"LangChain_{uuid_dict[basename]}\", text_key=\"text\", by_text=False)\n    print(f\"To insert -> {basename}\")\n    print(f\"index_name: {db._index_name}\")\n\n    texts = []\n\n    with open(path, \"r\", encoding=\"utf-8\") as f:\n        for i, line in enumerate(f):\n            if i > 0 and i % 1000 == 0:\n                db.add_texts(texts=texts)\n                print(f\"表格数据已注入{i}\")\n                texts = []\n            if len(line) <= 1:\n                continue\n            texts.append(line[:-1])\n        db.add_texts(texts=texts)\n        print(f\"表格数据已注入{i}\")\n        texts = []\n\ndef insert_table_uuid(path, uuid, client, embedding):\n    basename = os.path.basename(path).split('.')[0]\n\n    db = Weaviate(client=client, embedding=embedding,\n                  index_name=f\"LangChain_{uuid}\", text_key=\"text\", by_text=False)\n    print(f\"To insert -> {basename}\")\n    print(f\"index_name: {db._index_name}\")\n\n    texts = []\n\n    with open(path, \"r\", encoding=\"utf-8\") as f:\n        for i, line in enumerate(f):\n            if i > 0 and i % 1000 == 0:\n                db.add_texts(texts=texts)\n                # print(f\"表格数据已注入{i}\")\n                texts = []\n            if len(line) <= 1:\n                continue\n            texts.append(line[:-1])\n        db.add_texts(texts=texts)\n        print(f\"表格数据已注入{i}\")\n        texts = []\n\n\nif __name__ == \"__main__\":\n    base_tokenizer_model = '/home/kylin/workspace/ChatFinance/models/text2vec-base-chinese-paraphrase'\n\n    with open(\"/home/kylin/workspace/ChatFinance/data/chatglm_llm_fintech_raw_dataset/uuid.json\", \"r\", encoding='utf-8') as f:\n        uuid_dict = json.load(f)\n\n    n = 30000\n    skip = 0\n\n    # TXT_DIRECTORY = \"/home/kylin/workspace/ChatFinance/data/chatglm_llm_fintech_raw_dataset/alldata\"\n    # file_names = glob.glob(TXT_DIRECTORY + '/*')\n    # for i, file_name in enumerate(file_names):\n    #     print(f\"No.{i} insert_txt\")\n    #     try:\n    #         insert_txt(file_name, uuid_dict)\n    #     except:\n    #         print(f\"error: {file_name}\")\n    #     if i >= n - 1:\n    #         break\n\n    TAB_DIRECTORY = \"/home/kylin/workspace/ChatFinance/data/chatglm_llm_fintech_raw_dataset/alltable\"\n    file_names = glob.glob(TAB_DIRECTORY + '/*.cal')\n    print(file_names)\n    for i, file_name in enumerate(file_names):\n        if i < skip:\n            continue\n        print(f\"No.{i} insert_tab\")\n        try:\n            insert_table(file_name, uuid_dict)\n        except:\n            print(f\"error: {file_name}\")\n        if i >= n - 1:\n            break\n"
  },
  {
    "path": "database_server/weaviate/docker-compose.yml",
    "content": "version: '3.4'\nservices:\n  weaviate:\n    image: semitechnologies/weaviate:1.19.5\n    ports:\n      - 50003:8080\n    restart: on-failure:0\n    environment:\n      QUERY_DEFAULTS_LIMIT: 25\n      AUTHENTICATION_APIKEY_ENABLED: 'true'\n      AUTHENTICATION_APIKEY_ALLOWED_KEYS: 'shadowmotion-secret-key,HRSSC-secret-key'\n      AUTHENTICATION_APIKEY_USERS: 'shadowmotion,HRSSC'\n      PERSISTENCE_DATA_PATH: '/var/lib/weaviate'\n      DEFAULT_VECTORIZER_MODULE: 'none'\n      CLUSTER_HOSTNAME: 'node1'\n    volumes:\n      - weaviatedata:/var/lib/weaviate\n    deploy:\n      resources:\n        limits:\n          memory: 50g\n\nvolumes:\n  weaviatedata:\n"
  },
  {
    "path": "database_server/weaviate/scripts/QA.txt",
    "content": "问：能否介绍一下蓝胖子机器智能的主力产品？\n答：蓝胖子机器智能的主力产品是“蓝胖智汇Doraopt”系列AI软件产品及解决方案。这是由我们的AIoT产品事业部打造的，用于提供智能供应链的整体解决方案。\n\n问：蓝胖智汇Doraopt系列具备哪些核心技术和产品方案？\n答：蓝胖智汇Doraopt系列产品拥有AI时间空间多目标优化引擎、仿真推演、智能决策及调度等模块核心技术及对应产品方案。这些技术和产品方案使我们的客户能够高效且智能地管理他们的供应链。\n\n问：蓝胖子机器智能的团队核心技术成员有什么背景？\n答：我们的团队核心技术成员都是具有丰富专业知识的人才，他们来自全球顶级院校，如卡内基梅隆大学、北京大学、澳大利亚国立大学等，专业领域涵盖AI算法、物理、数学及计算机系统等。\n\n问：蓝胖子机器智能是什么样的公司？他们从事哪些业务？\n答：蓝胖子机器智能（Dorabot）是一家成立于2015年的智能无人仓整体解决方案供应商。他们有着深厚的技术背景，运用机器人视觉、运动规划、规划和推理、自主导航、多机协作、机器学习等技术，为多个场景提供一站式解决方案。\n\n问：蓝胖子机器智能的解决方案主要适用于哪些场景？\n答：我们的一站式解决方案主要适用于物流、快递、电商仓储、海港、空港、先进制造等场景。我们为这些场景提供包含分拣、运输、码垛、入库、装载等环节的软硬件相结合的解决方案。\n\n问：蓝胖子机器智能的解决方案包括哪些环节？\n答：蓝胖子机器智能的解决方案涵盖了物流等多个环节，包括分拣、运输、码垛、入库、装载等。我们的目标是为客户提供软硬件相结合的一站式解决方案。\n\n问：蓝胖子机器智能公司的主要产品有哪些？\n答：蓝胖子机器智能公司的主要产品包括软硬件相结合的上件机器人、分拣机器人、自主移动机器人（AMR）、码垛机器人、装载机器人等。这些产品充分利用了我们在AI和机器人技术方面的技术优势。\n\n问：在技术上，蓝胖子机器智能有哪些核心算法？\n答：在技术上，蓝胖子机器智能积累了多种规划及优化算法，包括智能装箱算法、智能调度算法以及多机规划算法。这些算法使我们的产品能够在各种场景下都能有效、高效地执行任务。\n\n问：蓝胖子机器智能的供应链解决方案是如何运作的？\n答：蓝胖子机器智能的供应链解决方案针对企业供应链流通环节的完整业务流程。我们基于AI时间空间多目标优化引擎与多维度大数据洞察，对上下游多个作业环节进行全局统筹与规划。我们的目标是打通生产、装卸、运输、仓储、配送等多个场景，为客户建立业务导向型的智能运营管理平台。\n\n问：蓝胖子机器智能的供应链解决方案能为客户带来什么样的好处？\n答：蓝胖子机器智能的供应链解决方案能够全面提升客户的运营效率。我们的AI优化引擎和大数据洞察能够对上下游多个作业环节进行全局统筹与规划，从而打通生产、装卸、运输、仓储、配送等多个场景，使得客户的供应链运营更加流畅和高效。同时，我们还为客户建立了业务导向型的智能运营管理平台，帮助他们实现更高的运营效率和利润。\n\n问：蓝胖子机器智能公司的混码算法是如何工作的？\n答：蓝胖子机器智能公司的混码算法是基于AI时间空间多目标优化引擎开发的。它能根据订单中的不同货品（SKU）信息，实时生成满足不同场景业务要求的稳定垛型。同时，它还需要满足机械臂运动轨迹等约束条件。这种方法可以有效地提高装箱的效率和满载率。\n\n问：混码算法可以带来什么样的优点？\n答：利用混码算法，可以根据订单中不同的货品信息，实时生成满足各种业务需求的稳定垛型，从而提高仓库的存储和运输效率。同时，算法考虑到了机械臂的运动轨迹等约束条件，这能确保整个操作的流畅性和安全性。此外，混码算法还可以提高装箱的满载率，使得装箱更加充分。\n\n问：我如何联系到蓝胖子机器智能公司？\n答：您可以通过以下方式联系蓝胖子机器智能公司:公司网站:www.dorabot.com 或 www.doraopt.com 地址:中国深圳市南山区左炮台路2号H6 邮箱:info@dorabot.com sales@dorabot.com info.doraopt@dorabot.com 电话:+86 (755) 2165 0069\n\n问：我能在哪里找到更多关于蓝胖子机器智能公司和他们的产品信息？\n答：您可以通过访问蓝胖子机器智能公司的官方网站 www.dorabot.com 和 www.doraopt.com 来了解更多关于他们及其产品的信息。\n\n问：蓝胖子机器智能公司有哪些主要的软件产品？\n答：蓝胖子机器智能公司的主要软件产品包括名为“装满满”的智能装箱SaaS平台。它基于公司自研的AI时间空间多目标优化引擎，可以为用户提供最优的订柜策略和货物装载规划方案，从而解决物流环节中的订柜与装箱问题。\n\n问：“装满满”是什么样的产品，它有哪些功能？\n答：“装满满”是蓝胖子机器智能公司推出的一款智能装箱SaaS平台，它可以为用户提供最优的订柜策略和货物装载规划方案。其主要功能是，通过使用自研的AI时间空间多目标优化引擎，一站式解决物流环节中的订柜与装箱难题。\n\n问：装满满的效果如何，是否已在实际业务中得到应用？\n答：是的，装满满已在十多家行业龙头企业中得到应用。平均空间装载率可以达到85%到90%，每年为客户节省数千万人民币的运营成本。与传统的人工作业相比，其效率有了数倍的提升。\n\n问：装满满的应用场景有哪些？\n答：装满满已与多家合同物流方和智能制造企业合作，应用于海运、陆运以及其他多联式运输场景中。\n\n问：装满满对于节省运营成本有哪些具体表现？\n答：装满满可以大幅度提升空间装载率，平均能达到85%到90%，这可以显著降低运输成本。据统计，每年装满满可以为客户节省数千万人民币的运营成本。\n\n问：客户在装箱过程中通常遇到哪些问题和痛点？\n答：客户在装箱过程中可能会遇到多个问题和痛点。例如，由于货量大且货品SKU种类繁多，拼载规则复杂且周期性发生调整，这对人工拼柜规划提出了挑战。同时，集装箱装载率的要求高，增加了人员培育和管理的成本。此外，手工通过数据表筛选装箱效率低，易出错，增加合规管理成本。在信息协同方面也有缺陷，需要智能化工具帮助降低成本和提高效率。\n\n问：客户在出货过程中通常遇到哪些问题和痛点？\n答：客户在出货过程中，可能会因为出货量庞大，装柜要求多且各异，增加估柜及排柜难度。这可能导致难以快速准确定位货物，以便海关查验。此外，上游环节的变动可能影响估柜及排柜方案的可行性，增加订柜及订舱的成本。另一方面，打托环节依赖人工经验，缺乏作业标准，导致车柜装载率难以提升。\n\n问：蓝胖子机器智能公司的智能装箱解决方案有哪些特点？\n答：蓝胖子机器智能公司的智能装箱解决方案有多个突出的特点。首先，它可以在数分钟内完成千方货物的装柜计划，这大大提高了作业效率，达到了2-3倍的综合作业效率提升。其次，它能够每年为用户节省超过1000万人民币的海运集装箱费用。此外，其装箱方案的可靠性高，所有方案都可以成功应用于仓库实际作业。该解决方案还能缩短装箱规划时间，达到原来的7-8倍。\n\n问：如果我有更多安装方式和定制需求，应该怎么做？\n答：如果您有更多的安装方式和定制需求，可以直接与我们联系，我们的团队将竭诚为您服务。\n\n问：蓝胖子机器智能公司的智能装箱解决方案有哪些部署方式？\n答：蓝胖子机器智能公司的智能装箱解决方案有多种部署方式。这包括作为SaaS在线平台使用，或者通过API接口进行模块化集成。这些部署方式既可以满足复杂业务的灵活配置需求，也可以支持简单业务的一键求解。\n\n问：「装满满」如何处理复杂业务？\n答：针对复杂业务，「装满满」提供了自定义入口，可以自定义货物属性、装箱规则、拼装步骤等，高效求解多条件、海量货物的装箱方案。它支持批量数据多任务同时运算，快速提供计算结果，优于“线性作业”方式，经济效益更高。\n\n问：「装满满」如何处理简单业务？\n答：对于简单业务，「装满满」已配置了简便的货物数据模板。只需上传相关数据，选择装载规则，就能一键求解装箱问题。\n\n问：「装满满」的装载方案是否安全？\n答：是的，「装满满」的装载方案非常安全。它考虑了承重、结构、顺序等影响因素，旨在降低货物损失的风险。此外，它还提供了3D可视化装箱规划，并支持一键分享，有助于多方协同，提升供应链透明度。\n\n问：DoraCLP「装满满」适用于哪些行业？\n答：DoraCLP「装满满」可以广泛应用于多个行业，例如家居业和鞋服业等。\n\n问：「装满满」有何技术优势？\n答：「装满满」利用先进的持续优化学习技术和AI时间空间多目标优化引擎，可以高效处理各种装箱问题，帮助客户实现价值。\n\n问：蓝胖子机器智能公司与哪些公司进行过合作，提供了怎样的解决方案？\n答：蓝胖子机器智能公司与一些知名企业进行过合作。例如，我们与某世界知名零售巨头合作，提供「装满满」智能装箱SaaS平台，高效解决了集装箱拼载规划的各项难题。同时，我们也与某国内家电品牌合作，利用「装满满」智能装箱SaaS平台应对上游订单变动，成功缩短了预估柜、排柜时间，助力了企业降低成本，提高效率，以及实现自动化和数字化转型。\n\n问：「装满满」智能装箱SaaS平台在装载率和计算时间方面有何优势？\n答：「装满满」智能装箱SaaS平台能实现88%-90%的平均装载率，对于家电行业等领域，我们的平台能快速应对上游变化，计算时间可以节约6倍，由原先的小时级降低至分钟级。\n\n问：「装满满」智能装箱SaaS平台如何帮助用户节省成本？\n答：使用我们的「装满满」智能装箱SaaS平台，每装载10000立方米的货物，可以节省大约100万元人民币的货柜海运费。在年度规模上，这可能意味着可以节省数千万元的海运柜成本。\n\n问：「装满满」智能装箱SaaS平台如何提高装箱作业的准确性和效率？\n答：我们的「装满满」智能装箱SaaS平台内置装箱业务规则引擎，可以准确提供打托方案，实际指导估柜订柜作业。另外，我们提供3D可视化装箱方案，可以准确显示货物位置，协助快速通关。\n"
  },
  {
    "path": "database_server/weaviate/scripts/connection.py",
    "content": "# import sys  # noqa: E501\n# sys.path.append('/home/shadowmotion/Documents/code/demo/HRSSC')  # noqa: E501\n\nfrom langchain.vectorstores import Weaviate\nfrom utils import JinaEmbeddings\nfrom jina import Document\nimport weaviate\n\ndef read_qa_file(file_path):\n    with open(file_path, \"r\", encoding='utf-8') as f:\n        lines = f.readlines()\n\n    qa_list = []\n    question, answer = None, None\n    for line in lines:\n        line = line.strip()  # remove leading/trailing whitespaces\n        if line.startswith(\"问：\"):\n            # save the previous qa pair if it exists\n            if question and answer:\n                qa_list.append(f\"{question} {answer}\")\n            # start a new qa pair\n            question = line\n            answer = None\n        elif line.startswith(\"答：\"):\n            answer = line\n    # don't forget the last qa pair\n    if question and answer:\n        qa_list.append(f\"{question} {answer}\")\n\n    return qa_list\n\nclient = weaviate.Client(\n    url=\"http://localhost:8080\",  # Replace with your endpoint\n    auth_client_secret=weaviate.AuthApiKey(api_key=\"shadowmotion-secret-key\"))\n\nembedding = JinaEmbeddings(\"127.0.0.1\")\ndb = Weaviate(client=client, embedding=embedding,\n              index_name=\"LangChain\", text_key=\"text\", by_text=False)\n\n\n# print(embedding.embed_documents(read_qa_file(\"raw/QA.txt\")))\n\ndb.add_texts(texts=read_qa_file(\"./QA.txt\"))\n\n# db.add_documents(\n#     [Document(page_content=\"1\", metadata={\"Q\": \"1+1=\", \"A\": \"2\"})]\n# )\n"
  },
  {
    "path": "database_server/weaviate/scripts/query.py",
    "content": "import sys  # noqa: E501\n# sys.path.append('/home/vdb/Documents/code/demo/HRSSC')  # noqa: E501\n\n\nfrom langchain.vectorstores import Weaviate\nfrom langchain.schema import Document\nfrom utils import JinaEmbeddings\nimport weaviate\nimport json\nimport os\n\nclient = weaviate.Client(\n    url=\"http://localhost:8080\",  # Replace with your endpoint\n    auth_client_secret=weaviate.AuthApiKey(api_key=\"kylin-secret-key\"))\n\nembedding = JinaEmbeddings(\"127.0.0.1\")\n\nwith open(\"../../data/chatglm_llm_fintech_raw_dataset/uuid.json\", \"r\", encoding='utf-8') as f:\n    uuid_dict = json.load(f)\n\nquery_list = [\n    \"公司的法定代表人是谁\",\n    \"电子邮箱是什么\",\n    \"公司的外文名称是什么\",\n]\n\n\nindex_name = \"LangChain_135087231333628284559671447376917039719\"\n\ndb = Weaviate(client=client, embedding=embedding,\n              index_name=index_name, text_key=\"text\", by_text=False)\n\nfor query in query_list[:1]:\n\n    docs = db.similarity_search(query, k=3)\n\n    print(f\" >>>>>>>>>>> {query} <<<<<<<<<<<<\")\n\n    for i, e in enumerate(docs):\n        print(f\" = = = = = = = = = = = k[{i}] = = = = = = = = = = =\")\n        print(e.page_content)\n"
  },
  {
    "path": "database_server/weaviate/utils.py",
    "content": "import warnings  # noqa: E501\nwarnings.filterwarnings('ignore')  # noqa: E501\n\nfrom langchain.embeddings.base import Embeddings\nfrom jina import Document, DocumentArray\nfrom jina import Client\n\nfrom typing import Any, List\n\n\nclass JinaEmbeddings(Embeddings):\n    def __init__(self, host: str = \"0.0.0.0\", port: int = 50001, **kwargs: Any) -> None:\n        self.client = Client(host=host, port=port, **kwargs)\n\n    def _post(self, docs: List[Any], **kwargs: Any) -> Any:\n        payload = dict(inputs=docs, **kwargs)\n        return self.client.post(on=\"/\", **payload)\n\n    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        docs = DocumentArray([Document(text=t) for t in texts])\n        embeddings = self._post(docs).embeddings\n        return [list(map(float, e)) for e in embeddings]\n\n    def embed_query(self, text: str) -> List[float]:\n        docs = DocumentArray([Document(text=text)])\n        print(docs)\n        embedding = self._post(docs).embeddings[0]\n        return list(map(float, embedding))\n\n\nif __name__ == \"__main__\":\n    embedding = JinaEmbeddings(\"127.0.0.1\")\n\n    eg = \"嵌入模型（Embedding model）通常用于将词语或者短语转化为向量表示。嵌入模型通常不会有严格的输入长度限制，因为它主要关注的是如何将单个词或短语转化为向量表示。然而，在某些应用中，嵌入模型可能会在更大的上下文环境中考虑单词，这时可能会有输入长度的限制。如果你使用的是一些预训练的模型，如BERT、GPT等，它们在实际训练过程中会有一个最大序列长度限制，这是由于这些模型的结构决定的。例如，BERT模型的最大输入长度通常设定为512个词语。如果提供的输入序列长度超过这个限制，那么可能需要进行截断，或者采用其他处理策略。如果你的输入长度超过了这个限制，直接输入给模型，可能会导致出错，或者导致模型无法处理那些超出长度限制的部分，因此，通常我们在数据预处理阶段就要处理好这个问题，确保所有输入都不超过模型的长度限制。\"\n\n    print(len(eg))\n\n    r = embedding.embed_query(eg)\n\n    print(len(r))\n"
  },
  {
    "path": "downloads/download_all.sh",
    "content": "#!/bin/bash\n\nbash download_models.sh\n\nbash download_data.sh"
  },
  {
    "path": "downloads/download_data.sh",
    "content": "#!/bin/bash\n\ncd ../data || mkdir ../data\n\ngit clone http://www.modelscope.cn/datasets/modelscope/chatglm_llm_fintech_raw_dataset.git\n\necho \"PDF data downloaded!\""
  },
  {
    "path": "downloads/download_model.sh",
    "content": "#!/bin/bash\n\ncd ../models || mkdir ../models\n\ngit clone https://huggingface.co/shibing624/text2vec-base-chinese-paraphrase\n\necho \"Embedding Model(for vector DB) downloaded!\"\n\ngit clone https://huggingface.co/THUDM/chatglm2-6b\n\necho \"ChatGML-6B Model(for vector DB) downloaded!\""
  },
  {
    "path": "inference_6b.py",
    "content": "from models_server.chatglm2.jina_client import encode\nfrom prompts.intent_recognition import intent_recognition_prompt\nfrom prompts.entity_recognition import entity_recognition_prompt\nfrom prompts.answer_generation import answer_generation_prompt\nfrom prompts.open_question import open_question_prompt\nfrom models_server.text2vec.jina_embedding import JinaEmbeddings\n\nfrom database_server.weaviate.db import insert_table_uuid,insert_txt_uuid\n\nfrom langchain.vectorstores import Weaviate\nfrom elasticsearch import Elasticsearch\n\nimport weaviate\nimport json\nimport os\nimport glob\n\n\ndef parse_entity_recognition(response: str):\n    parse_list = []\n    lines = response.split('\\n')\n    for line in lines:\n        sep = ':' if ':' in lines[-1] else '：'\n        if \"公司名\" in line:\n            parse_list.append(line.split(sep)[1])\n        if \"年份\" in line:\n            parse_list.append(line.split(sep)[1])\n    return parse_list\n\n\ndef parse_intent_recognition(response: str):\n    lines = response.split('\\n')\n    return lines[-1]\n\n\ndef attain_uuid(entities, uuid_dict):\n    for k, v in uuid_dict.items():\n        fg = True\n        for entity in entities:\n            if entity not in k:\n                fg = False\n                break\n        if fg:\n            print(entities, k)\n            return v, k\n    return None, None\n\n\ndef generate(question, uuid_dict, crawl_dict, crawl_name_dict, es, log_file):\n    log_file.write(\"= = 流程开始 = = \\n\")\n    log_file.write(f\"Q:\\n{question}\\n\\n\")\n\n    # -> Intent Recognition\n    log_file.write(\"= = 意图识别 = = \\n\")\n    prompt = intent_recognition_prompt(question)\n    response = encode(prompt, history=[])\n    log_file.write(f\"R:\\n{response[0].text}\\n\\n\")\n\n    if \"检索问题\" not in parse_intent_recognition(response[0].text):\n        log_file.write(\"开放问题直接作答\\n\")\n        prompt = open_question_prompt(question)\n        response = encode(prompt, history=[])\n        answer = response[0].text\n        log_file.write(f\"R:\\n{answer}\\n\\n\")\n        return answer\n    \n    # print(\"意图识别时间：\",time.time()-initial_time)\n\n    ############################ -> Entity Recognition\n    try_year_list = [\"2021年\",\"2022年\"]\n\n    log_file.write(\"= = 实体提取 = = \\n\")\n    prompt = entity_recognition_prompt(question)\n    response = encode(prompt, history=[])\n    log_file.write(f\"R:\\n{response[0].text}\\n\\n\")\n    entities = parse_entity_recognition(response[0].text)\n    uuid, file_name = attain_uuid(entities, uuid_dict)\n    log_file.write(f\"R:\\n{uuid}\\n\\n\")\n    if not uuid and entities[0][0] == '年':\n        entities[0] = entities[0][1:]\n        uuid, file_name = attain_uuid(entities, uuid_dict)\n        log_file.write(f\"R:\\n 1)首字修复，修复公司名称： {entities[0]}\\n\\n\")\n    # if not uuid:\n    #     for try_year in try_year_list:\n    #         old_year = entities[1]\n    #         entities[1] = try_year\n\n    #         uuid, file_name = attain_uuid(entities, uuid_dict)\n    #         if uuid:\n    #             log_file.write(f\"R:\\n 2)年份修复，{old_year} 改为 {entities[1]},uuid:{uuid}\\n\\n\")\n    #             break\n    \n    if not uuid:\n        log_file.write(\"未知公司不予作答\\n\")\n        return \"\"\n    \n    # print(\"实体提取时间：\",time.time()-initial_time)\n\n    extra_information_list = []\n\n    ################################ -> ElasticSearch\n    log_file.write(\"= = ElasticSearch = = \\n\")\n    # index_name = f\"{uuid}\"\n    # # index_name = \"all_property\"\n    # try:\n    #     for word in entities:\n    #         replaced_question = question.replace(word, '')\n\n    #     search_query = {\n    #         \"query\": {\n    #             \"match\": {\n    #                 \"text\": replaced_question\n    #             }\n    #         }\n    #     }\n\n    #     search_resp = es.search(index=index_name, body=search_query)\n\n    #     docs = search_resp[\"hits\"][\"hits\"][:3]\n\n    #     for i, e in enumerate(docs):\n    #         property_name = e['_source']['text']\n    #         company = crawl_name_dict[file_name]\n    #         year = file_name.split(\"__\")[4]+\"报\"\n    #         property_value = crawl_dict[company][year][property_name]\n    #         # if not property_value or property_value in [\"None\", \"null\"]:\n    #         #     continue\n    #         log_file.write(\n    #             f\"ES: = = = = = = = = = = = k[{i}] = = = = = = = = = = =\\n\")\n    #         log_file.write(e['_source']['text'])\n    #         log_file.write(\"\\n\")\n    #         extra_information_list.append(f\"{property_name}是{property_value}\")\n    # except:\n    #     log_file.write(\"数据库暂未录入\\n\")\n        \n        \n    ##################################### -> Embedding 尝试注入\n    if not extra_information_list:\n    # if True:\n        log_file.write(\"= = EmbeddingInsert(Table) = = \\n\")\n        Embedding_Match = False\n        if entities[1][-1]==\"年\":\n            target_year = entities[1][:-1]\n        target_name = entities[0]\n        \n        log_file.write(f\"尝试搜索{target_year}*{target_name}*.cal\\n\")\n        \n        try: \n            target_dir = \"/home/kylin/workspace/ChatFinance/data/chatglm_llm_fintech_raw_dataset/alltable\"\n            # pattern = rf'^{target_year}.*{target_name}.*\\.cal$'\n            \n            pattern = os.path.join(target_dir, f\"{target_year}*{target_name}*.cal\")\n            matched_files = [os.path.abspath(path) for path in glob.glob(pattern)]\n            insert_table_uuid(matched_files[0],uuid,client,embedding)\n            \n            log_file.write(f\"搜索Table注入成功,匹配文件名字：{matched_files[0]}\\n\")\n            Embedding_Match = True\n        except:\n            log_file.write(\"搜索不到相关.cal文件\\n\")\n\n\n\n        # log_file.write(\"= = EmbeddingInsert(Txt) = = \\n\")\n        \n        # log_file.write(f\"尝试搜索{target_year}*{target_name}*.txt\\n\")\n        \n        # try: \n        #     target_dir = \"/home/kylin/workspace/ChatFinance/data/chatglm_llm_fintech_raw_dataset/alldata\"\n        #     # pattern = rf'^{target_year}.*{target_name}.*\\.txt$'\n            \n        #     pattern = os.path.join(target_dir, f\"{target_year}*{target_name}*.txt\")\n        #     matched_files = [os.path.abspath(path) for path in glob.glob(pattern)]\n        #     insert_txt_uuid(matched_files[0],uuid,client,embedding)\n            \n        #     log_file.write(f\"搜索Txt注入成功,匹配文件名字：{matched_files[0]}\\n\")\n        # except:\n        #     log_file.write(\"搜索不到相关.Txt文件\\n\")\n\n    ##################################### -> Embedding Database\n    if not extra_information_list and Embedding_Match:\n    # if Embedding_Match:\n        log_file.write(\"= = EmbeddingDatabase = = \\n\")\n        index_name = f\"LangChain_{uuid}\"\n        try:\n            db = Weaviate(client=client, embedding=embedding,\n                          index_name=index_name, text_key=\"text\", by_text=False)\n\n            for word in entities:\n                replaced_question = question.replace(word, '')\n\n            docs = db.similarity_search(replaced_question, k=5)\n\n            for i, e in enumerate(docs):\n                log_file.write(\n                    f\"ED: = = = = = = = = = k[{i}] = = = = = = = = =\\n\")\n                log_file.write(e.page_content)\n                log_file.write(\"\\n\")\n                extra_information_list.append(e.page_content)\n        except:\n            log_file.write(\"数据库暂未录入\\n\")\n\n        \n    # print(\"向量库搜索时间：\",time.time()-initial_time)\n\n    log_file.write(\"= = AnswerGeneration = = \\n\")\n    extra_information = \"\\n\".join(extra_information_list)\n    log_file.write(extra_information+'\\n')\n    prompt = answer_generation_prompt(extra_information, question)\n    response = encode(prompt, history=[])\n    log_file.write(f\"R:\\n{response[0].text}\\n\\n\")\n    answer=response[0].text\n    return answer\n\n\n# import time\n# initial_time = time.time()\n\n# -> Init Embedding Database\nembedding = JinaEmbeddings(\"127.0.0.1\")\nclient = weaviate.Client(\n    url=\"http://localhost:50003\",  # Replace with your endpoint\n    auth_client_secret=weaviate.AuthApiKey(api_key=\"vdb-secret-key\"))\n\n# print(\"向量库时间：\",time.time()-initial_time)\n\n# -> Init Embedding Database\nes = Elasticsearch('http://localhost:50004')\n\n# print(\"es时间：\",time.time()-initial_time)\n\n# -> Init UUID Dict\nwith open(\"./data/chatglm_llm_fintech_raw_dataset/uuid.json\", \"r\") as f:\n    uuid_dict = json.load(f)\n\n# -> Init crawl Dict\nwith open(\"./data/chatglm_llm_fintech_raw_dataset/allcrawl.json\", \"r\") as f:\n    crawl_dict = json.load(f)\nwith open(\"./data/chatglm_llm_fintech_raw_dataset/name_map_crawl.json\", \"r\") as f:\n    crawl_name_dict = json.load(f)\n    \n# print(\"dict时间：\",time.time()-initial_time)\n\n# question = \"本钢板材在2020年对联营企业和合营企业的投资收益是多少元？\"\n\nimport time\nfrom datetime import datetime\nformatted_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n\nbad_ids = [0, 1, 4, 5, 10, 11, 13, 17, 21, 25, 29, 32, 37, 41, 51, 59, 61, 64, 67, 69, 71, 102, 106, 108, 115, 127, 133, 135, 141, 146, 148, 150, 152, 160, 161, 168, 170, 174, 177, 180, 183, 184, 186, 188, 194, 195, 196, 198, 210, 214, 215, 219, 222, 228, 237, 239, 240, 245, 252, 257, 259, 260, 267, 270, 271, 273, 276, 277, 278, 280, 281, 289, 295, 303, 305, 315, 332, 343, 346, 347, 361, 362, 367, 368, 370, 379, 382, 383, 393, 396, 405, 409, 416, 417, 419, 428, 429, 434, 435, 436, 438, 439, 444, 447, 448, 451, 454, 465, 470, 474, 483, 490, 495, 515, 520, 526, 530, 531, 538, 540, 541, 551, 554, 555, 556, 567, 573, 576, 581, 583, 586, 587, 590, 594, 596, 618, 619, 621, 626, 632, 634, 641, 642, 648, 653, 654, 656, 663, 667, 668, 675, 676, 683, 692, 705, 708, 714, 719, 723, 724, 726, 727, 729, 732, 733, 753, 754, 773, 776, 780, 781, 785, 793, 797, 798, 799, 801, 802, 804, 806, 811, 812, 814, 819, 822, 847, 849, 854, 856, 860, 865, 868, 870, 880, 887, 905, 906, 914, 915, 919, 924, 935, 946, 948, 951, 953, 957, 961, 970, 984, 987, 988, 989, 990, 995, 998, 1009, 1011, 1014, 1016, 1022, 1023, 1027, 1032, 1039, 1041, 1043, 1045, 1047, 1048, 1049, 1051, 1054, 1055, 1058, 1060, 1062, 1066, 1067, 1068, 1069, 1072, 1073, 1074, 1078, 1083, 1084, 1088, 1090, 1091, 1093, 1095, 1099, 1102, 1103, 1104, 1121, 1128, 1130, 1131, 1135, 1144, 1146, 1158, 1161, 1162, 1167, 1169, 1171, 1175, 1176, 1178, 1181, 1182, 1186, 1187, 1190, 1193, 1194, 1198, 1199, 1200, 1201, 1203, 1205, 1207, 1208, 1211, 1221, 1227, 1228, 1230, 1232, 1234, 1238, 1242, 1243, 1245, 1247, 1248, 1253, 1258, 1259, 1260, 1261, 1267, 1268, 1269, 1270, 1271, 1277, 1279, 1285, 1290, 1291, 1295, 1296, 1299, 1301, 1302, 1308, 1310, 1312, 1315, 1316, 1320, 1321, 1322, 1323, 1324, 1326, 1328, 1329, 1330, 1332, 1333, 1334, 1338, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1350, 1356, 1357, 1362, 1364, 1365, 1372, 1374, 1377, 1383, 1384, 1385, 1393, 1395, 1400, 1407, 1410, 1412, 1413, 1421, 1423, 1426, 1428, 1438, 1439, 1440, 1442, 1444, 1446, 1453, 1457, 1458, 1459, 1460, 1466, 1474, 1479, 1480, 1481, 1492, 1493, 1495, 1496, 1504, 1505, 1507, 1508, 1510, 1514, 1519, 1522, 1531, 1536, 1540, 1543, 1545, 1549, 1550, 1556, 1558, 1559, 1563, 1564, 1565, 1570, 1574, 1576, 1577, 1582, 1587, 1588, 1594, 1595, 1598, 1599, 1603, 1604, 1606, 1608, 1613, 1614, 1615, 1616, 1624, 1629, 1630, 1633, 1637, 1647, 1651, 1660, 1662, 1665, 1670, 1671, 1673, 1678, 1680, 1681, 1683, 1686, 1693, 1696, 1698, 1701, 1702, 1705, 1708, 1710, 1711, 1716, 1720, 1722, 1728, 1732, 1741, 1742, 1744, 1751, 1754, 1757, 1758, 1760, 1762, 1764, 1767, 1771, 1774, 1777, 1781, 1783, 1790, 1791, 1794, 1797, 1800, 1804, 1805, 1808, 1809, 1810, 1811, 1817, 1820, 1825, 1826, 1827, 1830, 1831, 1833, 1837, 1846, 1850, 1852, 1856, 1858, 1864, 1868, 1872, 1874, 1875, 1876, 1881, 1883, 1885, 1889, 1892, 1893, 1896, 1897, 1901, 1910, 1911, 1914, 1919, 1920, 1926, 1929, 1932, 1938, 1940, 1942, 1943, 1945, 1946, 1952, 1958, 1961, 1962, 1963, 1964, 1965, 1967, 1968, 1971, 1983, 1989, 1996, 1997, 1999, 2002, 2003, 2006, 2014, 2015, 2016, 2025, 2027, 2029, 2031, 2035, 2048, 2062, 2065, 2069, 2071, 2074, 2082, 2086, 2089, 2090, 2092, 2093, 2094, 2096, 2098, 2099, 2105, 2108, 2109, 2111, 2117, 2118, 2119, 2126, 2131, 2132, 2135, 2137, 2142, 2152, 2167, 2182, 2184, 2190, 2199, 2204, 2213, 2214, 2217, 2219, 2221, 2231, 2233, 2234, 2242, 2243, 2244, 2247, 2259, 2268, 2271, 2272, 2282, 2290, 2292, 2294, 2295, 2296, 2297, 2309, 2311, 2312, 2319, 2322, 2324, 2326, 2329, 2333, 2336, 2339, 2340, 2341, 2345, 2346, 2350, 2355, 2367, 2372, 2375, 2379, 2382, 2383, 2386, 2387, 2389, 2402, 2405, 2410, 2413, 2418, 2423, 2425, 2432, 2438, 2440, 2444, 2451, 2452, 2457, 2459, 2463, 2464, 2465, 2467, 2469, 2478, 2480, 2487, 2490, 2502, 2507, 2508, 2509, 2510, 2511, 2517, 2518, 2523, 2530, 2534, 2538, 2539, 2541, 2546, 2548, 2549, 2556, 2559, 2564, 2567, 2570, 2572, 2573, 2575, 2578, 2584, 2586, 2587, 2591, 2598, 2600, 2603, 2611, 2619, 2624, 2629, 2630, 2636, 2640, 2641, 2643, 2644, 2646, 2648, 2655, 2663, 2668, 2671, 2672,\n               2674, 2677, 2678, 2679, 2680, 2685, 2686, 2687, 2696, 2701, 2708, 2709, 2712, 2713, 2717, 2720, 2725, 2728, 2729, 2732, 2741, 2742, 2743, 2749, 2757, 2761, 2764, 2771, 2774, 2777, 2781, 2782, 2788, 2790, 2791, 2792, 2795, 2796, 2797, 2801, 2803, 2806, 2807, 2810, 2811, 2812, 2816, 2818, 2821, 2835, 2837, 2838, 2844, 2850, 2852, 2855, 2861, 2867, 2877, 2885, 2886, 2890, 2895, 2902, 2904, 2905, 2906, 2908, 2912, 2917, 2919, 2922, 2923, 2924, 2926, 2927, 2928, 2932, 2933, 2946, 2947, 2950, 2951, 2955, 2957, 2959, 2961, 2967, 2968, 2969, 2975, 2978, 2982, 2986, 2991, 2992, 2994, 2996, 2997, 2998, 3006, 3010, 3012, 3013, 3017, 3018, 3019, 3023, 3026, 3029, 3030, 3031, 3036, 3038, 3040, 3043, 3044, 3050, 3051, 3054, 3056, 3062, 3065, 3068, 3071, 3078, 3079, 3080, 3083, 3085, 3086, 3090, 3111, 3112, 3117, 3118, 3119, 3125, 3127, 3128, 3133, 3135, 3137, 3139, 3150, 3153, 3154, 3156, 3158, 3161, 3164, 3166, 3169, 3174, 3177, 3182, 3188, 3190, 3192, 3195, 3199, 3203, 3205, 3208, 3209, 3211, 3212, 3213, 3215, 3216, 3218, 3225, 3226, 3230, 3231, 3237, 3240, 3243, 3244, 3247, 3248, 3252, 3262, 3268, 3273, 3276, 3277, 3281, 3282, 3285, 3286, 3291, 3292, 3293, 3295, 3296, 3298, 3306, 3310, 3314, 3315, 3316, 3318, 3320, 3321, 3323, 3325, 3334, 3340, 3341, 3342, 3343, 3345, 3352, 3353, 3360, 3361, 3362, 3364, 3366, 3370, 3371, 3373, 3376, 3377, 3383, 3384, 3387, 3388, 3392, 3401, 3404, 3411, 3415, 3418, 3419, 3421, 3424, 3427, 3429, 3436, 3437, 3439, 3440, 3445, 3451, 3460, 3461, 3463, 3467, 3480, 3481, 3482, 3493, 3496, 3498, 3500, 3501, 3502, 3504, 3506, 3512, 3513, 3514, 3517, 3518, 3520, 3521, 3522, 3524, 3527, 3537, 3538, 3541, 3547, 3568, 3569, 3572, 3575, 3576, 3579, 3583, 3585, 3588, 3590, 3591, 3594, 3596, 3605, 3622, 3626, 3632, 3633, 3636, 3643, 3644, 3645, 3648, 3649, 3650, 3653, 3656, 3660, 3661, 3663, 3676, 3687, 3695, 3697, 3703, 3705, 3722, 3724, 3730, 3733, 3734, 3736, 3743, 3745, 3748, 3750, 3758, 3759, 3766, 3773, 3791, 3793, 3798, 3799, 3809, 3812, 3813, 3815, 3817, 3819, 3821, 3824, 3829, 3832, 3833, 3837, 3838, 3842, 3847, 3848, 3851, 3852, 3862, 3865, 3870, 3872, 3873, 3875, 3877, 3880, 3881, 3894, 3896, 3899, 3906, 3910, 3913, 3917, 3920, 3923, 3925, 3941, 3944, 3949, 3951, 3969, 3970, 3975, 3976, 3978, 3982, 3986, 3991, 3992, 3997, 3998, 4002, 4012, 4015, 4019, 4020, 4021, 4023, 4024, 4025, 4034, 4035, 4037, 4038, 4039, 4041, 4045, 4049, 4057, 4062, 4063, 4070, 4071, 4074, 4077, 4079, 4080, 4083, 4085, 4086, 4090, 4095, 4100, 4101, 4103, 4106, 4110, 4115, 4121, 4126, 4140, 4143, 4149, 4153, 4158, 4159, 4161, 4167, 4168, 4170, 4173, 4180, 4184, 4191, 4198, 4199, 4204, 4206, 4211, 4213, 4214, 4217, 4221, 4223, 4224, 4226, 4230, 4231, 4232, 4241, 4242, 4244, 4245, 4247, 4248, 4250, 4254, 4259, 4261, 4262, 4263, 4266, 4267, 4271, 4272, 4279, 4286, 4287, 4292, 4299, 4300, 4304, 4305, 4307, 4308, 4310, 4312, 4313, 4314, 4320, 4328, 4332, 4335, 4340, 4344, 4348, 4349, 4351, 4353, 4362, 4364, 4366, 4370, 4372, 4375, 4376, 4379, 4381, 4382, 4384, 4386, 4399, 4400, 4401, 4404, 4408, 4411, 4412, 4413, 4415, 4418, 4419, 4421, 4422, 4434, 4435, 4437, 4439, 4443, 4446, 4447, 4448, 4455, 4456, 4457, 4462, 4463, 4467, 4468, 4471, 4473, 4474, 4477, 4480, 4482, 4485, 4487, 4495, 4497, 4498, 4499, 4503, 4514, 4525, 4526, 4528, 4529, 4532, 4540, 4545, 4548, 4560, 4563, 4565, 4567, 4569, 4571, 4575, 4583, 4584, 4592, 4593, 4596, 4599, 4600, 4601, 4604, 4609, 4616, 4617, 4619, 4625, 4627, 4630, 4636, 4642, 4647, 4651, 4653, 4654, 4657, 4659, 4667, 4672, 4683, 4685, 4686, 4697, 4699, 4700, 4702, 4711, 4714, 4718, 4727, 4729, 4735, 4738, 4739, 4741, 4748, 4751, 4752, 4753, 4763, 4767, 4769, 4776, 4781, 4784, 4788, 4793, 4796, 4797, 4798, 4800, 4808, 4809, 4812, 4816, 4818, 4822, 4826, 4827, 4831, 4832, 4833, 4836, 4837, 4845, 4846, 4847, 4849, 4852, 4855, 4859, 4860, 4861, 4867, 4868, 4869, 4871, 4875, 4876, 4877, 4884, 4891, 4895, 4896, 4907, 4909, 4913, 4918, 4919, 4922, 4926, 4927, 4934, 4935, 4936, 4944, 4945, 4946, 4957, 4959, 4962, 4964, 4965, 4966, 4971, 4973, 4974, 4975, 4985, 4986, 4995, 4999]\n\n\nwith open(f\"./logs/log_{formatted_time}.txt\", \"w\") as log_file, open(f\"./logs/submission_{formatted_time}.json\", \"w\") as sm_file, open(\"./data/chatglm_llm_fintech_raw_dataset/test_questions.jsonl\", \"r\") as qs_file:\n    question_count = 0\n    for question_line in qs_file:\n        question_count += 1\n        ##### id 截断\n        # if question_count<1734:\n        #     continue\n        print(\"question_count:\",question_count)\n        question_dict = json.loads(question_line)\n        ##### bad id 截断\n        if question_dict[\"id\"] not in bad_ids:\n            continue\n        answer = generate(question_dict[\"question\"], uuid_dict, crawl_dict, crawl_name_dict, es, log_file)\n        answer_dict = {\"id\":question_dict[\"id\"],\"question\":question_dict[\"question\"],\"answer\":answer}\n        sm_file.write(f\"{answer_dict}\\n\")\n        time.sleep(3)\n\n\n"
  },
  {
    "path": "inference_6b.sh",
    "content": "#!/bin/bash\n\nJSON_FILE=\"configs/server.json\"\nLOGS=\"logs\"\nBASE_PATH=$(jq -r '.base_path' $JSON_FILE)\nPYTHON_PATH=$(jq -r '.base_python' $JSON_FILE)\nELASTIC_SEARCH_PATH=$(jq -r '.sever_path.elastic_search' $JSON_FILE)\nWEAVIATE_PATH=$(jq -r '.sever_path.weaviate' $JSON_FILE)\nLLM_SERVER=$(jq -r '.sever_path.chatglm2' $JSON_FILE)\nTEXT_SERVER=$(jq -r '.sever_path.text2vec' $JSON_FILE)\n\n\n# 启动 text2vec model (for WEAVIATE)\ncd \"$BASE_PATH/$TEXT_SERVER\" && nohup $PYTHON_PATH jina_server.py > \"$BASE_PATH/$LOGS/text2vec.log\" 2>&1 &\necho \"text2vec model start!\"\n\n# 启动 elastic search\ncd \"$BASE_PATH/$ELASTIC_SEARCH_PATH\" && docker-compose up -d\necho \"elastic DB start!\"\n\n# 启动 chatgml-6b\ncd \"$BASE_PATH/$LLM_SERVER\" && nohup $PYTHON_PATH jina_server.py > \"$BASE_PATH/$LOGS/llm.log\" 2>&1 &\necho \"gml-6b model start!\"\n\n# 启动 weaviate\ncd \"$BASE_PATH/$WEAVIATE_PATH\" && docker-compose up -d\necho \"weaviate DB start!\"\necho \"=====================================\"\n\n# 启动 生成程序\ncd \"$BASE_PATH\"\n$PYTHON_PATH inference_6b.py"
  },
  {
    "path": "models_server/chatglm2/README",
    "content": ""
  },
  {
    "path": "models_server/chatglm2/jina_client.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom jina import Document, DocumentArray\nfrom jina import Client\nimport sys\nimport time\n\nsys.path.append('..')\n\nport = 50002\nc = Client(port=port)\n\n\ndef encode(sentence, history):\n    \"\"\"Get one sentence embeddings from jina server.\"\"\"\n    r = c.post(\n        '/', inputs=DocumentArray([Document(text=sentence, tags={\"history\": history})]))\n    return r\n\n\nif __name__ == '__main__':\n    # 我们创建一个会话的历史，你可以根据需要更改\n    history = []\n\n    # 发起一个聊天会话\n    sentences = ['你好', '中国人认为宇宙万法的那个源头，它是什么', '你跟我说说这宇宙万物的本源是什么？']\n    for sent in sentences:\n        # 创建请求，发送给executor\n        response = encode(sent, history)\n\n        # 打印返回的响应\n        print(f\"Response: {response[0].text}\")\n        print(f\"Updated history: {response[0].tags['history']}\")\n\n        # 更新会话历史\n        history = response[0].tags['history']\n"
  },
  {
    "path": "models_server/chatglm2/jina_server.py",
    "content": "import warnings  \nwarnings.filterwarnings('ignore')  \n\nfrom jina import DocumentArray, Executor, requests, Flow\nfrom transformers import AutoModel, AutoTokenizer\nfrom typing import Dict, Tuple, Union, Optional\nfrom torch.nn import Module\n\nimport logging\nimport torch\nimport pickle\nimport json\nimport os\n\n\ndef auto_configure_device_map(num_gpus: int) -> Dict[str, int]:\n    # transformer.word_embeddings 占用1层\n    # transformer.final_layernorm 和 lm_head 占用1层\n    # transformer.layers 占用 28 层\n    # 总共30层分配到num_gpus张卡上\n    num_trans_layers = 28\n    per_gpu_layers = 30 / num_gpus\n\n    # bugfix: 在linux中调用torch.embedding传入的weight,input不在同一device上,导致RuntimeError\n    # windows下 model.device 会被设置成 transformer.word_embeddings.device\n    # linux下 model.device 会被设置成 lm_head.device\n    # 在调用chat或者stream_chat时,input_ids会被放到model.device上\n    # 如果transformer.word_embeddings.device和model.device不同,则会导致RuntimeError\n    # 因此这里将transformer.word_embeddings,transformer.final_layernorm,lm_head都放到第一张卡上\n    # 本文件来源于https://github.com/THUDM/ChatGLM-6B/blob/main/utils.py\n    # 仅此处做少许修改以支持ChatGLM2\n    device_map = {\n        'transformer.embedding.word_embeddings': 0,\n        'transformer.encoder.final_layernorm': 0,\n        'transformer.output_layer': 0,\n        'transformer.rotary_pos_emb': 0,\n        'lm_head': 0\n    }\n\n    used = 2\n    gpu_target = 0\n    for i in range(num_trans_layers):\n        if used >= per_gpu_layers:\n            gpu_target += 1\n            used = 0\n        assert gpu_target < num_gpus\n        device_map[f'transformer.encoder.layers.{i}'] = gpu_target\n        used += 1\n\n    return device_map\n\n\ndef load_model_on_gpus(checkpoint_path: Union[str, os.PathLike], num_gpus: int = 2, lora_path: Optional[str] = None,\n                       device_map: Optional[Dict[str, int]] = None, **kwargs) -> Module:\n    if num_gpus < 2 and device_map is None:\n        model = AutoModel.from_pretrained(\n            checkpoint_path, trust_remote_code=True, **kwargs).half().cuda()\n    else:\n        lora_path = kwargs.get('lora_path', '')\n        if not lora_path:\n            from accelerate import dispatch_model\n            model = AutoModel.from_pretrained(\n                checkpoint_path, trust_remote_code=True, **kwargs).half()\n            if device_map is None:\n                device_map = auto_configure_device_map(num_gpus)\n            model = dispatch_model(model, device_map=device_map)\n\n        else:\n            from peft import PeftModel\n            if device_map is None:\n                device_map = auto_configure_device_map(num_gpus)\n            model = AutoModel.from_pretrained(\n                checkpoint_path, trust_remote_code=True, device_map=device_map).half()\n            model = PeftModel.from_pretrained(model, lora_path)\n\n    logging.warn(f\"Using Lora From : {lora_path}\")\n\n    return model\n\n\nclass ChatGLM2(Executor):\n    def __init__(\n            self,\n            model_name: str = '',\n            lora_path: str = '',\n            device: str = None,\n            num_gpus: int = 0,\n            *args,\n            **kwargs,\n    ):\n        super().__init__(*args, **kwargs)\n\n        self.pre_history = {}\n        # with open('pre_history.pickle', 'rb') as f:\n        #     self.pre_history[\"pickle\"] = pickle.load(f)\n\n        if device is None:\n            device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n        self.device = torch.device(device)\n\n        if device == \"cuda\":\n            self.model = load_model_on_gpus(\n                model_name, num_gpus=num_gpus, lora_path=lora_path)\n        else:\n            self.model = AutoModel(model_name)\n            self.model.to(device).eval()\n        self.tokenizer = AutoTokenizer.from_pretrained(\n            model_name, trust_remote_code=True)\n\n    @requests\n    def chat(self, docs: DocumentArray, pre_history: bool = False, **kwargs):\n        for doc in docs:\n            prompt = doc.text\n            history = doc.tags.get('history', [])\n            max_length = doc.tags.get('max_length', 8192)\n            top_p = doc.tags.get('top_p', 0.95)\n            temperature = doc.tags.get('temperature', 0.01)\n            if history:\n                history = json.loads(doc.tags['history'])\n            else:\n                if pre_history:\n                    pass\n                else:\n                    # history.append(self.pre_history[\"pickle\"])\n                    pass\n\n            # print('---------prompt----------')\n\n            # print(prompt)\n\n            response, history = self.model.chat(\n                self.tokenizer, prompt, history=history, max_length=max_length, top_p=top_p, temperature=temperature)\n\n            doc.text = response\n            doc.tags['history'] = json.dumps(history, ensure_ascii=False)\n\n            # print('--------response---------')\n\n            # print(response)\n\n            # print('----------end------------')\n\nwith open('../../configs/server.json', 'r') as file:\n    server_config = json.load(file)\nbase_path = server_config[\"base_path\"]\nmodel_path = os.path.join(base_path,server_config[\"models_path\"][\"chatglm2\"])\n# port = server_config[\"port\"][\"chatglm2\"]\nlora_path = \"\"\nf = Flow(port=50002).add(\n    uses=ChatGLM2,\n    uses_with={\n        'model_name': model_path,\n        'lora_path': lora_path,\n        'device': 'cuda',\n        'num_gpus': 1,\n    },\n    gpus='device=0'\n)\n\nwith f:\n    # start server, backend server forever\n    f.block()"
  },
  {
    "path": "models_server/text2vec/jina_embedding.py",
    "content": "import warnings  # noqa: E501\nwarnings.filterwarnings('ignore')  # noqa: E501\n\nfrom langchain.embeddings.base import Embeddings\nfrom docarray import Document, DocumentArray\nfrom jina import Client\n\nfrom typing import Any, List\n\n\nclass JinaEmbeddings(Embeddings):\n    def __init__(self, host: str = \"0.0.0.0\", port: int = 50001, **kwargs: Any) -> None:\n        self.client = Client(host=host, port=port, **kwargs)\n\n    def _post(self, docs: List[Any], **kwargs: Any) -> Any:\n        payload = dict(inputs=docs, **kwargs)\n        return self.client.post(on=\"/\", **payload)\n\n    def embed_documents(self, texts: List[str]) -> List[List[float]]:\n        docs = DocumentArray([Document(text=t) for t in texts])\n        embeddings = self._post(docs).embeddings\n        return [list(map(float, e)) for e in embeddings]\n\n    def embed_query(self, text: str) -> List[float]:\n        docs = DocumentArray([Document(text=text)])\n        embedding = self._post(docs).embeddings[0]\n        return list(map(float, embedding))"
  },
  {
    "path": "models_server/text2vec/jina_server.py",
    "content": "from jina import DocumentArray, Executor, requests\nfrom transformers import AutoModel, AutoTokenizer\nfrom typing import Dict, Optional, Tuple\nfrom jina import Flow\nimport numpy as np\nimport torch\nimport os\nimport json\n\n\nclass Text2vecEncoder(Executor):\n    \"\"\"The Text2vecEncoder encodes sentences into embeddings using transformers models.\"\"\"\n\n    def __init__(\n            self,\n            model_name,\n            base_tokenizer_model: Optional[str] = None,\n            pooling_strategy: str = 'mean',\n            layer_index: int = -1,\n            max_length: Optional[int] = 256,\n            embedding_fn_name: str = '__call__',\n            device: str = None,\n            traversal_paths: str = '@r',\n            batch_size: int = 32,\n            *args,\n            **kwargs,\n    ):\n        \"\"\"\n        The transformer torch encoder encodes sentences into embeddings.\n\n        :param model_name: Name of the pretrained model or path to the\n            model\n        :param base_tokenizer_model: Base tokenizer model\n        :param pooling_strategy: The pooling strategy to be used. The allowed values are\n            ``'mean'``, ``'min'``, ``'max'`` and ``'cls'``.\n        :param layer_index: Index of the layer which contains the embeddings\n        :param max_length: Max length argument for the tokenizer, used for truncation. By\n            default the max length supported by the model will be used.\n        :param embedding_fn_name: Function to call on the model in order to get output\n        :param device: Torch device to put the model on (e.g. 'cpu', 'cuda', 'cuda:1')\n        :param traversal_paths: Used in the encode method an define traversal on the\n             received `DocumentArray`\n        :param batch_size: Defines the batch size for inference on the loaded\n            PyTorch model.\n        \"\"\"\n        super().__init__(*args, **kwargs)\n\n        self.traversal_paths = traversal_paths\n        self.batch_size = batch_size\n\n        base_tokenizer_model = base_tokenizer_model or model_name\n\n        self.pooling_strategy = pooling_strategy\n        self.layer_index = layer_index\n        self.max_length = max_length\n        if device is None:\n            device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n        self.device = torch.device(device)\n        self.embedding_fn_name = embedding_fn_name\n\n        self.tokenizer = AutoTokenizer.from_pretrained(base_tokenizer_model)\n        self.model = AutoModel.from_pretrained(\n            model_name, output_hidden_states=True\n        )\n        self.model.to(device).eval()\n\n    @requests\n    def encode(self, docs: DocumentArray, parameters: Dict = {}, **kwargs):\n        \"\"\"\n        Encode text data into a ndarray of `D` as dimension, and fill the embedding of\n        each Document.\n\n        :param docs: DocumentArray containing text\n        :param parameters: dictionary to define the `traversal_paths` and the\n            `batch_size`. For example,\n            `parameters={'traversal_paths': 'r', 'batch_size': 10}`.\n        :param kwargs: Additional key value arguments.\n        \"\"\"\n\n        docs_batch_generator = DocumentArray(\n            filter(\n                lambda x: bool(x.text),\n                docs[parameters.get('traversal_paths', self.traversal_paths)],\n            )\n        ).batch(batch_size=parameters.get('batch_size', self.batch_size))\n\n        for batch in docs_batch_generator:\n            texts = batch.texts\n\n            with torch.inference_mode():\n                input_tokens = self._generate_input_tokens(texts)\n                outputs = getattr(self.model, self.embedding_fn_name)(\n                    **input_tokens)\n                if isinstance(outputs, torch.Tensor):\n                    outputs = outputs.cpu().numpy()\n                hidden_states = outputs.hidden_states\n                embeds = self._compute_embedding(hidden_states, input_tokens)\n                batch.embeddings = embeds\n\n    def _compute_embedding(\n            self, hidden_states: Tuple['torch.Tensor'], input_tokens: Dict\n    ):\n        fill_vals = {'cls': 0.0, 'mean': 0.0, 'max': -np.inf, 'min': np.inf}\n        fill_val = torch.tensor(\n            fill_vals[self.pooling_strategy], device=self.device)\n        layer = hidden_states[self.layer_index]\n\n        attn_mask = input_tokens['attention_mask']\n\n        # Fix LongFormerModel like model which has mismatch seq_len between\n        # attention_mask and hidden_states\n        padding_len = layer.size(1) - attn_mask.size(1)\n        if padding_len > 0:\n            attn_mask = torch.nn.functional.pad(\n                attn_mask, (0, padding_len), value=0)\n\n        expand_attn_mask = attn_mask.unsqueeze(-1).expand_as(layer)\n\n        layer = torch.where(expand_attn_mask.bool(), layer, fill_val)\n        embeddings = layer.sum(dim=1) / expand_attn_mask.sum(dim=1)\n        return embeddings.cpu().numpy()\n\n    def _generate_input_tokens(self, texts):\n        if not self.tokenizer.pad_token:\n            self.tokenizer.add_special_tokens({'pad_token': '[PAD]'})\n            self.model.resize_token_embeddings(len(self.tokenizer.vocab))\n\n        input_tokens = self.tokenizer(\n            texts,\n            max_length=self.max_length,\n            padding='longest',\n            truncation=True,\n            return_tensors='pt',\n        )\n\n        input_tokens = {k: v.to(self.device) for k, v in input_tokens.items()}\n        return input_tokens\n\n\nwith open('../../configs/server.json', 'r') as file:\n    server_config = json.load(file)\nbase_path = server_config[\"base_path\"]\nmodel_path = os.path.join(base_path,server_config[\"models_path\"][\"text2vec\"])\nprint(model_path)\n# port = server_config[\"port\"][\"text2vec\"]\nlora_path = \"\"\n\nf = Flow(port=50001).add(\n    uses=Text2vecEncoder,\n    uses_with={\n        'model_name': model_path,\n        'device': 'cuda',\n    },\n    gpus='device=0',\n)\n\nwith f:\n    # start server, backend server forever\n    f.block()\n"
  },
  {
    "path": "prompts/answer_generation.py",
    "content": "from langchain import PromptTemplate\n\nPROMPT = \"\"\"\n你需要扮演一位金融专家助手。请根据所提供的额外信息，回答下列问题。请注意，额外信息虽然都是有效的，但你只需使用与问题直接相关的部分。\n\n要求：\n1. 答案应简练、清晰、准确。\n2. 仅使用与问题直接相关的额外信息进行回答。\n3. 避免引入与问题无关的信息。\n\n示例：\n人类：本钢板材在2020年对联营企业和合营企业的投资收益是多少元？\n额外信息：该公司的数据如下所示\n其中:对联营企业和合营企业的投资收益/（损失）是374119.86\n其中:对联营企业和合营企业的投资收益/（损失） 同比是-17.3366874753\n营业总收入(元)是48684792685.58\n营业成本是46392180562.59\nAI:\n本钢板材在2020年对联营企业和合营企业的投资收益是374119.86元。\n\n现在开始：\n\n人类：{query}\n额外信息：该公司的数据如下所示\n{extra_information}\nAI:\n\"\"\"\n\n\ndef answer_generation_raw_prompt():\n    return PromptTemplate(template=PROMPT, input_variables=[\"extra_information\", \"query\"])\n\n\ndef answer_generation_prompt(extra_information: str, query: str):\n    P = PromptTemplate(template=PROMPT, input_variables=[\n                       \"extra_information\", \"query\"])\n    return P.format(extra_information=extra_information, query=query)\n\n\nif __name__ == \"__main__\":\n    print(answer_generation_prompt(\"你们公司的装箱算法可以用在服装业吗\"))"
  },
  {
    "path": "prompts/entity_recognition.py",
    "content": "from langchain import PromptTemplate\n\nPROMPT = \"\"\"\n你需要扮演一个优秀的实体提取助手。你的任务是从人类提供的问句中抽取并精确返回公司名称和年份。\n\n示例一：\n人类：抽取<请根据2020年金宇生物技术股份有限公司的年报，简述公司的社会责任工作情况。>中的公司名，年份。\n公司名：金宇生物技术股份有限公司\n年份：2020年\n\n示例二：\n人类：抽取<2019年安记食品股份有限公司的营业利润率是多少？结果请保留至小数点后两位。>中的公司名，年份。\n公司名：安记食品股份有限公司 \n年份：2019年\n\n示例三：\n人类：抽取<研发费用如何影响公司的技术创新和竞争优势？>中的公司名，年份。\n公司名：无 \n年份：无 \n\n示例四：\n人类：抽取<平潭发展在2021年的投资收益增长率保留到小数点后两位是多少？>中的公司名，年份。\n公司名：平潭发展\n年份：2021年\n\n示例五：\n人类：抽取<请根据江化微2019年的年报，简要介绍报告期内公司主要销售客户的客户集中度情况，并结合同行业情况进行分析。>中的公司名，年份。\n公司名：江化微\n年份：2019年\n\n注意：\n    1.你不需要做任何解释说明，并且严格按照上述示例的格式进行输出。\n    2.如果信息未包含对应实体，请输出\"无\"。\n    3.你不要把信息中<...>的内容当作问题回答，它是作为被实体提取的对象。\n    4.你的回答仅包括\"公司名\"和\"年份\"两个部分，年份请输出20xx年，请避免输出无关的信息。\n\n\n现在开始：\n人类：抽取<{query}>中的公司名，年份。\n\"\"\"\n\n\ndef entity_recognition_raw_prompt():\n    return PromptTemplate(template=PROMPT, input_variables=[\"query\"])\n\n\ndef entity_recognition_prompt(query: str):\n    P = PromptTemplate(template=PROMPT, input_variables=[\"query\"])\n    return P.format(query=query)\n\n\nif __name__ == \"__main__\":\n    print(entity_recognition_prompt(\"你们的装箱算法能不能用在家居业呀？主要用于是沙发的装箱。\"))\n"
  },
  {
    "path": "prompts/information_extraction.py",
    "content": "from langchain import PromptTemplate\n\nPROMPT = \"\"\"\n你需要扮演一个优秀的关键信息提取助手，从人类的对话中提取关键性内容（最多5个关键词），以协助其他助手更精准地回答问题。\n\n注意：你不需要做任何解释说明，只需严格按照示例的格式输出关键词。\n\n示例：\n人类：我有一个服装厂，是否可以应用你们的装箱算法改善装载率呢？\nAI: 服装厂, 装箱算法, 装载率\n\n现在开始：\n人类：{query}\nAI:\n\"\"\"\n\n\ndef information_extraction_raw_prompt():\n    return PromptTemplate(template=PROMPT, input_variables=[\"query\"])\n\n\ndef information_extraction_prompt(query: str):\n    P = PromptTemplate(template=PROMPT, input_variables=[\"query\"])\n    return P.format(query=query)\n\n\nif __name__ == \"__main__\":\n    print(information_extraction_prompt(\"你们的装箱算法能不能用在家居业呀？\"))\n"
  },
  {
    "path": "prompts/intent_recognition.py",
    "content": "\nfrom langchain import PromptTemplate\n\n# 你不需要做任何解释说明，并且严格按照示例的格式进行输出，仅输出[\"金融常识问题\",\"文本检索问题\",\"数值检索问题\"]。\n\n\nPROMPT = \"\"\"\n你需要扮演一个优秀的意图识别助手，你需要写出思考过程，并判断人类的问题是属于（开放问题/检索问题）类别的一项。\n\n示例一：\n人类：判断<能否根据2020年金宇生物技术股份有限公司的年报，给我简要介绍一下报告期内公司的社会责任工作情况？>的类别。\n思考：\n1. 题目中出现了具体公司名称的关键词 \"金宇生物技术股份有限公司\"。\n2. 由于题目包含具体公司名称的关键词，判断该题目属于检索问题。\n答案: 检索问题\n\n示例二：\n人类：判断<2019年四方科技电子信箱是什么>的类别。\n思考：\n1. 题目中出现了具体公司名称的关键词 \"四方科技\"。\n2. 由于题目包含具体公司名称的关键词，判断该题目属于检索问题。\n答案: 检索问题\n\n示例三：\n人类：判断<研发费用对公司的技术创新和竞争优势有何影响？>的类别。\n思考：\n1. 题目中未出现任何具体公司名称的关键词。\n2. 由于题目未包含具体公司名称的关键词，判断该题目属于开放问题。\n答案: 开放问题\n\n示例四：\n人类：判断<请根据江化微2019年的年报，简要介绍报告期内公司主要销售客户的客户集中度情况，并结合同行业情况进行分析。>的类别。\n思考：\n1. 题目中出现了具体公司名称的关键词 \"江化微\"。\n2. 由于题目包含具体公司名称的关键词，判断该题目属于检索问题。\n答案: 检索问题\n\n示例五：\n人类：判断<康希诺生物股份公司在2020年的资产负债比率具体是多少，需要保留至小数点后两位？>的类别。\n思考：\n1. 题目中出现了具体公司名称的关键词 \"康希诺生物股份公司\"。\n2. 由于题目包含具体公司名称的关键词，判断该题目属于检索问题。\n答案: 检索问题\n\n示例六：\n人类：判断<平潭发展在2021年的投资收益增长率保留到小数点后两位是多少？>的类别。\n思考：\n1. 题目中出现了具体公司名称的关键词 \"平潭发展\"。\n2. 由于题目包含具体公司名称的关键词，判断该题目属于检索问题。\n答案: 检索问题\n\n注意：\n    1.你不需要做任何解释说明，并且严格按照上述示例的格式进行输出, 需要包括\"思考\"和\"答案\"两部分。\n    2.\"思考\"仅有\"1.\"和\"2.\"两个步骤，不应该有更多的思考步骤。\n\n现在开始：\n人类：判断<{query}>的类别。\n\"\"\"\n\n\ndef intent_recognition_raw_prompt():\n    return PromptTemplate(template=PROMPT, input_variables=[\"query\"])\n\n\ndef intent_recognition_prompt(query: str):\n    P = PromptTemplate(template=PROMPT, input_variables=[\"query\"])\n    return P.format(query=query)\n\n\nif __name__ == \"__main__\":\n    print(intent_recognition_prompt(\"博云新材在2020年对联营企业和合营企业的投资收益是多少元？\"))\n"
  },
  {
    "path": "prompts/open_question.py",
    "content": "from langchain import PromptTemplate\n\nPROMPT = \"\"\"\n你需要扮演一位金融专家助手。请根据你的专业知识，回答下列问题。\n\n要求：\n1. 答案应简练、清晰、准确。\n2. 仅使用与问题直接相关的额外信息进行回答。\n3. 避免引入与问题无关的信息。\n\n示例一：\n人类：什么是价值投资？\nAI: 价值投资是投资策略的一种，由班杰明·葛拉汉和大卫·多德（英语：DavidDodd）所提出。和价值投资法所对应的是成长投资法。其重点是透过基本面分析中的概念，例如高股息收益率、低市盈率（P/E，股价/每股净利润）和低市净率（P/B，股价/每股净资产），去寻找并投资于一些股价被低估的股票。\n\n示例二：\n人类：什么是营业利润？\nAI: 营业利润（英语：OperatingIncome、OperatingProfit）或译营业利益是营业收入减除营业成本及营业费用后之余额。其为正数，表示本期营业盈余之数；其为负数，表示本期营业亏损之数。当一间公司没有营业外收入与营业外支出，有时营业利润与息税前利润被当作同义词。\n\n示例：\n人类：什么是营业税金及附加？\nAI: 营业税金及附加是指对企业或个人因经营活动所产生的收入或销售额征收的税费，以及可能与之相关的其他费用或附加费。\n\n现在开始：\n\n人类：{query}\nAI:\n\"\"\"\n\ndef open_question_prompt(query: str):\n    P = PromptTemplate(template=PROMPT, input_variables=[\"query\"])\n    return P.format(query=query)\n\n\nif __name__ == \"__main__\":\n    print(open_question_prompt(\"什么是营业额？\"))"
  },
  {
    "path": "prompts/relevance_scoring.py",
    "content": "from langchain import PromptTemplate\n\nPROMPT = \"\"\"\n你需要扮演一个优秀的文本相关性评估助手。你需要评估额外信息是否有助于提供更优质和简练的回答。\n\n你不需要做任何解释说明，并且严格按照示例的格式进行输出，仅回答[\"是\", \"否\"]\n\n以下是一个示例：\n人类：我有一个服装厂，是否可以应用你们的装箱算法改善装载率呢？\n额外信息：问：能否介绍一下蓝胖子机器智能的主力产品？ 答：蓝胖子机器智能的主力产品是“蓝胖智汇Doraopt”系列AI软件产品及解决方案。这是由我们的AIoT产品事业部打造的，用于提供智能供应链的整体解决方案。\nAI:否\n\n现在开始：\n人类：{query}\n额外信息：{extra_information}\nAI:\n\"\"\"\n\n\ndef relevance_scoring_raw_prompt():\n    return PromptTemplate(template=PROMPT, input_variables=[\"query\", \"extra_information\"])\n\n\ndef relevance_scoring_prompt(query: str, extra_information: str):\n    P = PromptTemplate(template=PROMPT, input_variables=[\n                       \"query\", \"extra_information\"])\n    return P.format(query=query, extra_information=extra_information)\n\n\nif __name__ == \"__main__\":\n    print(relevance_scoring_prompt(\n        query=\"你们的装箱算法能不能用在家居业呀？主要用于是沙发的装箱。\",\n        extra_information=\"问：DoraCLP「装满满」适用于哪些行业？ 答：DoraCLP「装满满」可以广泛应用于多个行业，例如家居业和鞋服业等。\"),\n    )\n"
  },
  {
    "path": "requirements.txt",
    "content": "accelerate==0.21.0\nauto_gptq==0.3.2\ncamelot==13.04.13-gpl-pyqt\ndocarray==0.21.0\nitemadapter==0.8.0\njina==3.20.0\nlangchain==0.0.261\nnumpy==1.24.1\npandas==2.0.3\npeft==0.4.0\nscrapy==2.10.0\ntorch==2.1.0.dev20230807+cu118\ntransformers==4.31.0\nweaviate_client==3.22.1\n"
  },
  {
    "path": "sft/chatglm2_6b_sft_adalora.py",
    "content": ""
  },
  {
    "path": "sft/chatglm2_6b_sft_lora.py",
    "content": "import pandas as pd\nimport numpy as np\nimport datasets\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\nimport transformers\nfrom transformers import AutoTokenizer, AutoModel, TrainingArguments, AutoConfig\nfrom peft import get_peft_model, LoraConfig, TaskType, PeftModel\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndftrain = pd.read_parquet('/home/kylin/workspace/ChatFinance/data/sft/intent_sft_10k.parquet')\ndftest = pd.read_parquet('/home/kylin/workspace/ChatFinance/data/sft/intent_sft_10k_val.parquet')\n\n# model.chat\ndef build_inputs(query, history):\n    prompt = \"\"\n    for i, (old_query, response) in enumerate(history):\n        prompt += \"[Round {}]\\n\\n问：{}\\n\\n答：{}\\n\\n\".format(i + 1, old_query, response) # history中的第几轮次，问了什么，得到了什么答案\n    prompt += \"[Round {}]\\n\\n问：{} -> \\n\\n答：\".format(len(history) + 1, query) # 当前轮次，当前问话\n    return prompt\n\nhis = [(\"文本分类任务：对一段问题进行意图识别，分成开放问题或者检索问题。\\n\\n下面是一些范例:\\n\\n什么是投资比率？ -> 开放问题\\n快手科技2021年的营业额是多少？  -> 检索问题\\n利润率是指什么？ -> 开放问题\\n百度集团2021年的硕士生人数比例是多少 -> 检索问题\\n\\n请对以下问题进行分类。返回'开放问题'或者'检索问题'，无需其它说明和解释。\\n\\n什么是股东权益？ ->\\n\\n\", 'n什么是股东权益？ -> 开放问题')]\ndftrain['context'] = [build_inputs(x,history=his) for x in dftrain['text']] # 定义训练集中的上文\ndftrain['target'] = [x for x in dftrain['tag']] # 定义训练集中的标签\ndftrain = dftrain[['context','target']]\n\ndftest['context'] = [build_inputs(x,history=his) for x in dftest['text']]\ndftest['target'] = [x for x in dftest['tag']]\ndftest = dftest[['context','target']]\n\nds_train = datasets.Dataset.from_pandas(dftrain)\nds_val = datasets.Dataset.from_pandas(dftest)\n\nmodel_name = '/home/kylin/workspace/ChatFinance/models/chatglm2-6b'\nmax_seq_length = 512\nskip_over_length = True\ntokenizer = transformers.AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)\nconfig = transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True, device_map='auto')\n\ndef preprocess(example):\n    context = example[\"context\"]\n    target = example[\"target\"]\n    context_ids = tokenizer.encode(\n            context,\n            max_length=max_seq_length,\n            truncation=True)\n    target_ids = tokenizer.encode(\n        target,\n        max_length=max_seq_length,\n        truncation=True,\n        add_special_tokens=False)\n    input_ids = context_ids + target_ids + [config.eos_token_id]\n\n    return {\"input_ids\": input_ids, \"context_len\": len(context_ids),'target_len':len(target_ids)}\n\nds_train_token = ds_train.map(preprocess).select_columns(['input_ids', 'context_len','target_len'])\nif skip_over_length: \n    ds_train_token = ds_train_token.filter(\n        lambda example: example[\"context_len\"]<max_seq_length and example[\"target_len\"]<max_seq_length)\n    \nds_val_token = ds_val.map(preprocess).select_columns(['input_ids', 'context_len','target_len'])\nif skip_over_length:\n    ds_val_token = ds_val_token.filter(\n        lambda example: example[\"context_len\"]<max_seq_length and example[\"target_len\"]<max_seq_length)\n\ndef data_collator(features: list):\n    len_ids = [len(feature[\"input_ids\"]) for feature in features]\n    longest = max(len_ids)\n    input_ids = []\n    labels_list = []\n    for length, feature in sorted(zip(len_ids, features), key=lambda x: -x[0]):\n        ids = feature[\"input_ids\"]\n        context_len = feature[\"context_len\"]\n        labels = (\n            [-100] * context_len + ids[context_len :] + [-100] * (longest - length)\n        ) \n        ids = ids + [tokenizer.pad_token_id] * (longest - length)\n        input_ids.append(torch.LongTensor(ids))\n        labels_list.append(torch.LongTensor(labels))\n    input_ids = torch.stack(input_ids)\n    labels = torch.stack(labels_list)\n    return {\n        \"input_ids\": input_ids,\n        \"labels\": labels,\n    }\n    \n# ds_train_token 是送入训练的数据集\n# num_workers 是数据载入时将使用多线程并行处理，这可以在一定程度上加速数据载入\n# batch_size 是每一个批次的样本数量\n# pin_memory=True: 如果设为 True，那么数据载入器将会在返回Tensor之前，先将其复制到CUDA固定内存中。这样可以使得转移数据到GPU上更快\n# shuffle=True: 如果设为 True，那么在每个训练周期开始时，数据载入器将会打乱数据集的顺序\n# collate_fn=data_collator: 这个函数定义了如何将多个样本合并成一个小批量。在这里，我们使用之前定义的 data_collator 函数，这个函数会按照我们的需要对每个小批量的数据进行预处理\ndl_train = torch.utils.data.DataLoader(ds_train_token,num_workers=2,batch_size=4,\n                                       pin_memory=True,shuffle=True,\n                                       collate_fn = data_collator)\ndl_val = torch.utils.data.DataLoader(ds_val_token,num_workers=2,batch_size=4,\n                                    pin_memory=True,shuffle=True,\n                                     collate_fn = data_collator)\n\ndl_train.size = 300 #用约300个step做一次验证\n\nimport locale\nlocale.getpreferredencoding = lambda: \"UTF-8\"\n\nmodel = AutoModel.from_pretrained(model_name,\n                                  load_in_8bit=False,\n                                  trust_remote_code=True)\n\n#节约cuda，但可能会使得训练时间变长\nmodel.supports_gradient_checkpointing = True  \nmodel.gradient_checkpointing_enable() \nmodel.enable_input_require_grads() \n\n# 关闭了模型的缓存机制，该设置可以避免一些警告，但在模型推理时需要重新开启\nmodel.config.use_cache = False  \n\npeft_config = LoraConfig(\n    task_type=TaskType.CAUSAL_LM, inference_mode=False,\n    r=8,\n    lora_alpha=32, lora_dropout=0.1,\n)\n\nmodel = get_peft_model(model, peft_config)\n\n# 开启模型的并行处理能力，这可以在有多个GPU的情况下提高训练效率\nmodel.is_parallelizable = True\nmodel.model_parallel = True\n\n\n# model.print_trainable_parameters()\n# 可训练参数：1949696\n# 总参数量：6245533696\n# 需要调整的模型参数量的占比 3.1%\n\nfrom torchkeras import KerasModel\nfrom accelerate import Accelerator\n\nclass StepRunner:\n    def __init__(self, net, loss_fn, accelerator=None, stage = \"train\", metrics_dict = None,\n                 optimizer = None, lr_scheduler = None\n                 ):\n        self.net,self.loss_fn,self.metrics_dict,self.stage = net,loss_fn,metrics_dict,stage\n        self.optimizer,self.lr_scheduler = optimizer,lr_scheduler\n        self.accelerator = accelerator if accelerator is not None else Accelerator()\n        if self.stage=='train':\n            self.net.train()\n        else:\n            self.net.eval()\n\n    def __call__(self, batch):\n\n        with self.accelerator.autocast():\n            loss = self.net(input_ids=batch[\"input_ids\"],labels=batch[\"labels\"]).loss\n\n        if self.optimizer is not None and self.stage==\"train\":\n            self.accelerator.backward(loss)\n            if self.accelerator.sync_gradients:\n                self.accelerator.clip_grad_norm_(self.net.parameters(), 1.0)\n            self.optimizer.step()\n            if self.lr_scheduler is not None:\n                self.lr_scheduler.step()\n            self.optimizer.zero_grad()\n\n        all_loss = self.accelerator.gather(loss).sum()\n\n        step_losses = {self.stage+\"_loss\":all_loss.item()}\n\n        step_metrics = {}\n\n        if self.stage==\"train\":\n            if self.optimizer is not None:\n                step_metrics['lr'] = self.optimizer.state_dict()['param_groups'][0]['lr']\n            else:\n                step_metrics['lr'] = 0.0\n        return step_losses,step_metrics\n\nKerasModel.StepRunner = StepRunner\n\n\ndef save_ckpt(self, ckpt_path='checkpoint', accelerator = None):\n    unwrap_net = accelerator.unwrap_model(self.net)\n    unwrap_net.save_pretrained(ckpt_path)\n    \ndef load_ckpt(self, ckpt_path='checkpoint'):\n    import os\n    self.net.load_state_dict(\n        torch.load(os.path.join(ckpt_path,'adapter_model.bin')),strict =False)\n    self.from_scratch = False\n\nKerasModel.save_ckpt = save_ckpt\nKerasModel.load_ckpt = load_ckpt\n\n\nkeras_model = KerasModel(model,loss_fn = None,\n        optimizer=torch.optim.AdamW(model.parameters(),lr=2e-6))\nckpt_path = '~/.ckpt/chatglm2_intent10k'\n\n\nkeras_model.fit(train_data = dl_train,\n                val_data = dl_val,\n                epochs=100,patience=5,\n                monitor='val_loss',mode='min',\n                ckpt_path = ckpt_path,\n                mixed_precision='fp16'\n               )\n\nmodel = AutoModel.from_pretrained(model_name,\n                                  load_in_8bit=False,\n                                  trust_remote_code=True,\n                                  device_map='auto')\nmodel = PeftModel.from_pretrained(model,ckpt_path)\nmodel = model.merge_and_unload() #合并lora权重\n\nmodel.save_pretrained(\"../models/sft/chatglm2-6b-intent10k\", max_shard_size='1GB')\ntokenizer.save_pretrained(\"../models/sft/chatglm2-6b-intent10k\")"
  },
  {
    "path": "sft/chatglm2_6b_sft_qlora.py",
    "content": ""
  },
  {
    "path": "sft/utils.py",
    "content": "import pandas as pd\nimport numpy as np\nimport datasets\n\n\ndef csv2parquet(csv_file_path,parquet_train_file_path,parquet_test_file_path):\n    df = pd.read_csv(csv_file_path)\n\n    ################################\n    #     label       review\n    #       1           绝了\n    #       0           不行\n    #       ....\n    #\n    #################################\n\n    df['tag'] = df['label'].map({0:'差评',1:'好评'}) \n    df = df.rename({'review':'text'},axis = 1)\n    ds_dic = datasets.Dataset.from_pandas(df).train_test_split(\n        test_size = 0.2,shuffle=True, seed = 43)\n    dftrain = ds_dic['train'].to_pandas() \n    dftest = ds_dic['test'].to_pandas()\n    dftrain.to_parquet(parquet_train_file_path)\n    dftest.to_parquet(parquet_test_file_path)\n\n\nif __name__ == '__main__':\n    csv_file_path = \"/home/kylin/workspace/ChatFinance/data/chatglm_llm_fintech_raw_dataset/intent_10k.csv\"\n    parquet_train_file_path = \"/home/kylin/workspace/ChatFinance/data/sft/intent_sft_10k.parquet\"\n    parquet_test_file_path = \"/home/kylin/workspace/ChatFinance/data/sft/intent_sft_10k_val.parquet\"\n    csv2parquet(csv_file_path,parquet_train_file_path,parquet_test_file_path)\n    \n    "
  },
  {
    "path": "sft_6b.sh",
    "content": ""
  },
  {
    "path": "stop_all.sh",
    "content": "#!/bin/bash\n\n# 关闭所有jina_server.py相关进程\nps aux | grep jina_server.py | grep -v grep | awk '{print $2}' | xargs kill -9\n\n\n"
  },
  {
    "path": "utils.py",
    "content": "from models_server.chatglm2.jina_client import encode\nfrom prompts.intent_recognition import intent_recognition_prompt\nfrom prompts.entity_recognition import entity_recognition_prompt\nfrom prompts.answer_generation import answer_generation_prompt\nfrom models_server.text2vec.jina_embedding import JinaEmbeddings\n\nfrom langchain.vectorstores import Weaviate\nfrom elasticsearch import Elasticsearch\n\nimport weaviate\nimport json\n\ndef parse_entity_recognition(response: str):\n    parse_list = []\n    lines = response.split('\\n')\n    for line in lines:\n        sep = ':' if ':' in lines[-1] else '：'\n        if \"公司名\" in line:\n            parse_list.append(line.split(sep)[1])\n        if \"年份\" in line:\n            parse_list.append(line.split(sep)[1])\n    return parse_list\n\ndef parse_intent_recognition(response: str):\n    lines = response.split('\\n')\n    return lines[-1]\n\n\ndef attain_uuid(entities, uuid_dict):\n    for k, v in uuid_dict.items():\n        fg = True\n        for entity in entities:\n            if entity not in k:\n                fg = False\n                break\n        if fg:\n            print(entities, k)\n            return v, k\n    return None, None"
  }
]