[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\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# UV\n#   Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#uv.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/latest/usage/project/#working-with-version-control\n.pdm.toml\n.pdm-python\n.pdm-build/\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\n# PyPI configuration file\n.pypirc\n*.pkl\n*.xlsx\n*.sql\n*.exe\n__pycache__/"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# 抖音，小红书内容互动数据获取\n由于平台的限制，自己发布的视频/笔记的互动数据，无法通过API接口获取，为了实现对内容效果的有效追踪，我通过一些简单的爬虫来对数据进行下载，清洗，导入，最终可以看到发布的内容的互动数据每天的增长情况。\n\n# 作用\n自动抓取抖音，小红书创作者中心里的每条视频的播放，完播，点击，2s跳出，播放时长，点赞，分享，评论，收藏，主页访问，粉丝增量等数据\n\n# 基础设置\n在project_config文件夹的project.py中，设置好对应的路径，通常用默认的就可以。\n\n# 获取缓存文件（pkl文件）\n- 如果已经有了，请直接复制到pkl文件夹中，命名方式\n    - 抖音：douyin + _ + 其他任意字符（最好是账号名），如douyin_123456.pkl\n    - 小红书：xhs + _ + 其他任意字符（最好是账号名）, 如xhs_123456.pkl\n- 如果没有pkl文件，直接运行main.py, 第一次需要扫码登录，登陆后回到代码界面输入回车，即可继续。然后把pkl文件剪切到pkl文件夹\n\n# 用法\n## 安装requirements.txt\n- pip install requirements.txt\n## 直接运行main.py即可\n- 如果只是仅仅对抓取抖音和小红书后台内容有兴趣，直接运行spiders文件夹下的douyin.py或xhs.py即可。\n\n## 数据处理部分，在data_processing文件夹中\n- 可以先从后台下载对应的excel文件，清空标题以外的内容，命名为yesterday.xlsx\n- 系统会自动下载data.xlsx,并在处理完后，自动将data.xlsx命名为yesterday.xlsx\n\n# 有不明白的可以加群聊，大家多互动\n"
  },
  {
    "path": "data_processing/dy_video_analysis.py",
    "content": "'''\n处理下载的抖音视频质量数据，将其转换为当天的数据，并在处理后将其重命名，为下一天继续处理做准备\n'''\n\nimport pandas as pd\nfrom datetime import datetime, timedelta\nimport os\nimport sys\n\nclass DailyDataProcessor:\n    def __init__(self):\n        # 获取当前脚本所在目录 (data_processing目录)\n        current_dir = os.path.dirname(os.path.abspath(__file__))\n\n        # 获取项目根目录（即当前目录的上一级）\n        project_root = os.path.abspath(os.path.join(current_dir, \"..\"))\n\n        # 将项目根目录添加到sys.path中\n        if project_root not in sys.path:\n            sys.path.append(project_root)\n\n        from project_config.project import dy_data_path, dy_yesterday_path, dy_file_path\n\n        self.dy_data_path = dy_data_path\n        self.dy_yesterday_path = dy_yesterday_path\n        self.dy_file_path = dy_file_path\n        self.compare_columns = ['播放量', '点赞量', '分享量', '评论量', '收藏量']\n\n    def get_daily_data(self):\n        # 读取当天数据和昨天的数据\n        data_df = pd.read_excel(self.dy_data_path)\n        yesterday_df = pd.read_excel(self.dy_yesterday_path)\n\n        # 确认发布时间字段格式为日期格式\n        data_df['发布时间'] = pd.to_datetime(data_df['发布时间'])\n        yesterday_df['发布时间'] = pd.to_datetime(yesterday_df['发布时间'])\n\n        # 日期过滤条件\n        min_date = datetime(2025, 3, 4)\n\n        # 筛选出符合条件的数据（开始日期≥2025-03-04）\n        filtered_data_df = data_df[data_df['发布时间'] >= min_date].copy()\n\n        # 使用明确的字段（比如：作品名称）合并今天和昨天的数据\n        daily_data = pd.merge(\n            filtered_data_df,\n            yesterday_df[['作品名称'] + self.compare_columns],\n            on='作品名称',\n            how='left',\n            suffixes=('', '_昨日')\n        )\n\n        # 处理昨日无数据的情况\n        for col in self.compare_columns:\n            yesterday_col = f\"{col}_昨日\"\n            daily_data[yesterday_col] = daily_data[yesterday_col].fillna(0)\n\n            # 计算绝对值差值\n            daily_data[col] = (daily_data[col] - daily_data[yesterday_col]).abs()\n\n            # 删除昨日数据列，保留最终计算结果\n            daily_data.drop(columns=[yesterday_col], inplace=True)\n\n        # 筛选发布时间满足条件的数据\n        daily_data = daily_data[daily_data['发布时间'] >= min_date].reset_index(drop=True)     \n        \n        # 获取昨天日期，格式为YYYY-MM-DD\n        yesterday_str = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')\n        \n        # 在daily_data第一列插入日期字段\n        daily_data.insert(0, '日期', yesterday_str)\n\n        # 在daily_data第一列插入平台字段\n        daily_data.insert(0, '平台', '抖音')\n        \n        # 返回处理后的daily_data\n        return daily_data\n    \n    def update_yesterday_data(self):\n        \"\"\"\n        删除dy_yesterday_path文件，并将dy_data_path重命名为yesterday_data.xlsx\n        :param dy_file_path: 存放yesterday_data.xlsx的目标目录\n        \"\"\"\n        # 确保 dy_yesterday_path 文件存在再删除\n        if os.path.exists(self.dy_yesterday_path):\n            os.remove(self.dy_yesterday_path)\n            print(f\"✅ 已删除旧的昨日数据文件: {self.dy_yesterday_path}\")\n        else:\n            print(\"⚠️ 旧的昨日数据文件不存在，无需删除。\")\n        \n        # 目标文件路径\n        new_yesterday_path = os.path.join(self.dy_file_path, \"yesterday_data.xlsx\")\n        \n        # 重命名 dy_data_path 文件\n        if os.path.exists(self.dy_data_path):\n            os.rename(self.dy_data_path, new_yesterday_path)\n            print(f\"✅ 已将 {self.dy_data_path} 重命名为 {new_yesterday_path}\")\n        else:\n            print(\"❌ 无法重命名，dy_data_path 文件不存在。\")\n\n# 示例调用\nif __name__ == \"__main__\":\n    processor = DailyDataProcessor()\n    daily_data = processor.get_daily_data()\n    daily_data.to_excel('daily_data.xlsx', index=False)\n    print(daily_data)\n"
  },
  {
    "path": "data_processing/dytest.py",
    "content": "import read_sql as rs\nimport os\nimport re\nimport sys\nimport jdy\nimport pandas as pd\nimport asyncio\nfrom datetime import datetime, timedelta\n\n# 配置模块级路径\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\nproject_root = os.path.abspath(os.path.join(current_dir, \"..\"))\nif project_root not in sys.path:\n    sys.path.append(project_root)\n\nfrom project_config.project import xhs_custom_count_sql\nfrom data_processing.xhs_video_analysis import DailyDataProcessor\n\nclass Dividend:\n    \"\"\"\n    视频内容分红管理类：用于读取视频数据、客资数据和简道云信息，\n    进行内容表现分析、分红计算并可上传结果至简道云。\n    \"\"\"\n\n    def __init__(self):\n        self.sql = rs.MSSQLDatabase()\n        self.custom_count_path = xhs_custom_count_sql\n        self.jdy = jdy.JDY()\n        self.daily_process = DailyDataProcessor()\n        self.metrics = ['观看量', '点赞', '收藏', '评论', '分享']\n        self._cached_jdy_data = None\n\n    def get_jdy_data_cached(self):\n        \"\"\"\n        从简道云获取并缓存数据，避免重复调用。\n        \"\"\"\n        if self._cached_jdy_data is None:\n            appId = \"67c280b7c6387c4f4afd50ae\"\n            entryId = \"67c2816ffa795e84a8fe45b9\"\n            self._cached_jdy_data = self.jdy.get_jdy_data(app_id=appId, entry_id=entryId)\n        return self._cached_jdy_data\n\n    def get_custom_count(self):\n        \"\"\"\n        从SQL文件读取客资数量。\n        \"\"\"\n        try:\n            return self.sql.get_from_sqlfile(self.custom_count_path)\n        except Exception as e:\n            print(f\"读取客资数失败: {e}\")\n            return pd.DataFrame()\n\n    def get_daily_video_data(self):\n        \"\"\"\n        获取每日视频数据，字段自动标准化。\n        \"\"\"\n        try:\n            df = self.daily_process.get_daily_data()\n            rename_map = {\n                '播放量': '观看量',\n                '播放次数': '观看量'\n            }\n            df.rename(columns=rename_map, inplace=True)\n            return df\n        except Exception as e:\n            print(\"❌ get_daily_data 报错：\", e)\n            return pd.DataFrame()\n\n    def video_dividend(self):\n        \"\"\"\n        计算每条视频根据表现应得的分成金额。\n        返回包含 [作品名称, 总分成, 日期] 的 DataFrame。\n        \"\"\"\n        video_df = self.get_daily_video_data()\n        print(\"🎬 video_df 字段名：\", video_df.columns.tolist())\n\n        jdy_data = self.get_jdy_data_cached()\n        content_df = pd.DataFrame(jdy_data)\n        print(\"📄 content_df 字段名：\", content_df.columns.tolist())\n\n        content_df['正片标题'] = content_df['_widget_1740646149825'].astype(str).apply(lambda x: re.sub(r'\\s*#.*', '', x))\n        video_df['笔记标题'] = video_df['笔记标题'].astype(str).apply(lambda x: re.sub(r'\\s*#.*', '', x))\n\n        merged_df = content_df.merge(video_df, left_on='正片标题', right_on='笔记标题', how='left')\n        print(\"🧩 merged_df 字段名：\", merged_df.columns.tolist())\n\n        for metric in self.metrics:\n            if metric not in merged_df.columns:\n                print(f\"⚠️ 缺失字段 {metric}，自动填充 0\")\n                merged_df[metric] = 0\n\n        metric_weights = {\n            '观看量': 0.05,\n            '点赞': 0.05,\n            '收藏': 0.3,\n            '评论': 0.3,\n            '分享': 0.3\n        }\n\n        for metric, weight in metric_weights.items():\n            max_val = merged_df[metric].max()\n            merged_df[f'{metric}_标准化'] = merged_df[metric].apply(lambda x: (x / max_val) * weight if max_val > 0 else 0)\n\n        merged_df['总表现分'] = merged_df[[f'{m}_标准化' for m in metric_weights]].sum(axis=1)\n        video_scores = merged_df.groupby('正片标题', as_index=False)['总表现分'].sum()\n        video_scores = video_scores[video_scores['总表现分'] > 0]\n\n        total_money = self.total_money_dy()\n        total_customers = total_money // 50\n        total_scores = video_scores['总表现分'].sum()\n        video_scores['客户数'] = ((video_scores['总表现分'] / total_scores) * total_customers).round().astype(int)\n\n        diff = total_customers - video_scores['客户数'].sum()\n        if diff != 0:\n            idx = video_scores['总表现分'].idxmax()\n            video_scores.at[idx, '客户数'] += diff\n\n        video_scores['总分成'] = video_scores['客户数'] * 50\n        video_scores['日期'] = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')\n        video_scores.rename(columns={'正片标题': '作品名称'}, inplace=True)\n        return video_scores[['作品名称', '总分成', '日期']]\n\n    def total_money_dy(self):\n        \"\"\"\n        总分红池金额（= 客资总数 × 50）。\n        \"\"\"\n        df = self.get_custom_count()\n        return df['客资数'].sum() * 50 if '客资数' in df.columns else 0\n\n    def get_video_people(self):\n        \"\"\"\n        获取视频人员参与信息，返回每条视频对应人员及角色。\n        \"\"\"\n        jdy_data = self.get_jdy_data_cached()\n        rows = []\n        for doc in jdy_data:\n            title_raw = doc.get(\"_widget_1740646149825\", \"\")\n            title_cleaned = re.sub(r'\\s*#.*', '', title_raw)\n            base_fields = {\n                \"账号名称\": doc.get(\"_widget_1741257105163\", \"\"),\n                \"账号ID\": doc.get(\"_widget_1741257105165\", \"\"),\n                \"是否完整内容\": doc.get(\"_widget_1740798082550\", \"\"),\n                \"正片标题\": title_cleaned,\n                \"提交日期\": doc.get(\"_widget_1740646149826\", \"\"),\n                \"来源门店/部门\": doc.get(\"_widget_1741934971937\", {}).get(\"name\", \"\")\n            }\n            user_groups = {\n                \"完整内容提供\": [u.get(\"username\") for u in doc.get(\"_widget_1740798082567\", [])],\n                \"半成品内容提供\": [u.get(\"username\") for u in doc.get(\"_widget_1740798082568\", [])],\n                \"剪辑\": [u.get(\"username\") for u in doc.get(\"_widget_1740798082569\", [])],\n                \"发布运营\": [u.get(\"username\") for u in doc.get(\"_widget_1740798082570\", [])]\n            }\n            max_len = max(len(g) for g in user_groups.values()) or 1\n            aligned_groups = {}\n            for field, users in user_groups.items():\n                aligned_groups[field] = users + [None] * (max_len - len(users))\n            row = {**base_fields, **aligned_groups}\n            rows.append(row)\n\n        df = pd.DataFrame(rows)\n        exploded_dfs = []\n        for group in [\"完整内容提供\", \"半成品内容提供\", \"剪辑\", \"发布运营\"]:\n            temp_df = df[[\"正片标题\", group]].explode(group)\n            temp_df = temp_df.rename(columns={group: \"人员\"})\n            temp_df[\"人员类别\"] = group\n            exploded_dfs.append(temp_df)\n\n        final_df = pd.concat(exploded_dfs, ignore_index=True)\n        base_df = df[[\"正片标题\", \"账号名称\", \"账号ID\", \"是否完整内容\", \"提交日期\", \"来源门店/部门\"]]\n        final_df = final_df.merge(base_df, on=\"正片标题\", how=\"left\")\n        final_df = final_df.dropna(subset=[\"人员\"])\n\n        return final_df[[\"正片标题\", \"账号名称\", \"账号ID\", \"是否完整内容\", \"人员类别\", \"人员\", \"提交日期\", \"来源门店/部门\"]].reset_index(drop=True)\n\n    def everyone_money(self):\n        \"\"\"\n        根据参与人及角色计算每人应得的分红金额。\n        \"\"\"\n        video_people = self.get_video_people()\n        video_money = self.video_dividend()\n        video_people = video_people.rename(columns={\"正片标题\": \"作品名称\"})\n        merged = video_people.merge(video_money, on=\"作品名称\", how=\"left\")\n        merged[\"总分成\"] = merged[\"总分成\"].fillna(0)\n        total_dividend_before = video_money[\"总分成\"].sum()\n        print(f\"🔍 合并前 总分成金额: {total_dividend_before}\")\n\n        RULES = {\n            (\"是\", \"完整内容提供\"): 0.6,\n            (\"是\", \"发布运营\"): 0.4,\n            (\"否\", \"半成品内容提供\"): 0.4,\n            (\"否\", \"剪辑\"): 0.2,\n            (\"否\", \"发布运营\"): 0.4\n        }\n        merged[\"分成比例\"] = merged.apply(lambda row: RULES.get((row[\"是否完整内容\"], row[\"人员类别\"]), 0.2), axis=1)\n        merged = merged.dropna(subset=[\"分成比例\"])\n        merged[\"人数\"] = merged.groupby([\"作品名称\", \"人员类别\"])[\"人员\"].transform(\"count\")\n        merged[\"分成金额\"] = (merged[\"总分成\"] * merged[\"分成比例\"] / merged[\"人数\"]).round(2)\n\n        result = merged.loc[(merged[\"人员\"].notnull()), [\"作品名称\", \"人员\", \"分成金额\"]]\n        total_dividend_after = result[\"分成金额\"].sum()\n        diff = round(total_dividend_before - total_dividend_after, 2)\n        if diff != 0:\n            idx = result[\"分成金额\"].idxmax()\n            result.loc[idx, \"分成金额\"] = round(result.loc[idx, \"分成金额\"] + diff, 2)\n\n        total_dividend_after = result[\"分成金额\"].sum()\n        print(f\"✅ 分配后 总分成金额: {total_dividend_after}\")\n        if round(total_dividend_before, 2) != round(total_dividend_after, 2):\n            print(f\"⚠️ 警告: 总金额有损失！缺少 {round(total_dividend_before - total_dividend_after, 2)}\")\n\n        summary = result.groupby(\"人员\", as_index=False)[\"分成金额\"].sum()\n        summary[\"日期\"] = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')\n        return summary[summary[\"分成金额\"] > 0].reset_index(drop=True)\n\n    def upload_to_jdy(self):\n        \"\"\"\n        将分红结果上传至简道云。\n        \"\"\"\n        appId = \"67c280b7c6387c4f4afd50ae\"\n        entryId = \"67d7097d08e5f607c4cfd028\"\n        final_data = self.everyone_money()\n        asyncio.run(self.jdy.batch_create(app_id=appId, entry_id=entryId, source_data=final_data))\n\nif __name__ == '__main__':\n    dividend = Dividend()\n    print(dividend.total_money_dy())\n    print(dividend.get_custom_count()['客资数'].sum())\n    video_people = dividend.get_video_people()\n    video_people.to_excel('小红书视频管理.xlsx', index=False)\n    people_money = dividend.everyone_money()\n    people_money.to_excel('小红书每人分红金额.xlsx', index=False)\n    data = dividend.video_dividend()\n    data.to_excel('小红书视频分红.xlsx', index=False)\n    # dividend.upload_to_jdy()"
  },
  {
    "path": "data_processing/xhs_video_analysis.py",
    "content": "import pandas as pd\nfrom datetime import datetime, timedelta\nimport os\nimport sys\n\nclass DailyDataProcessor:\n    def __init__(self):\n        # 获取当前脚本所在目录 (data_processing目录)\n        current_dir = os.path.dirname(os.path.abspath(__file__))\n\n        # 获取项目根目录（即当前目录的上一级）\n        project_root = os.path.abspath(os.path.join(current_dir, \"..\"))\n\n        # 将项目根目录添加到sys.path中\n        if project_root not in sys.path:\n            sys.path.append(project_root)\n\n        from project_config.project import xhs_data_path, xhs_yesterday_path, xhs_file_path\n\n        self.xhs_data_path = xhs_data_path\n        self.xhs_yesterday_path = xhs_yesterday_path\n        self.xhs_file_path = xhs_file_path\n\n        # 改为小红书使用的字段\n        self.compare_columns = ['观看量', '点赞', '收藏', '评论', '分享']\n\n        # 视频质量表模板字段顺序（固定）\n        self.template_columns = [\n            '所属平台', '数据日期', '作品名称', '发布时间', '体裁', '审核状态', '播放量', '完播率',\n            '5s完播率', '封面点击率', '2s跳出率', '平均播放时长', '点赞量', '分享量',\n            '评论量', '收藏量', '主页访问量', '粉丝增量'\n        ]\n\n        # 定义字段映射关系\n        self.column_mapping = {\n            '所属平台': '平台',\n            '数据日期': '日期',\n            '作品名称': '笔记标题',\n            '发布时间': '首次发布时间',\n            '体裁': '体裁',\n            '审核状态': None,\n            '播放量': '观看量',\n            '完播率': None,\n            '5s完播率': None,\n            '封面点击率': None,\n            '2s跳出率': None,\n            '平均播放时长': '人均观看时长',\n            '点赞量': '点赞',\n            '分享量': '分享',\n            '评论量': '评论',\n            '收藏量': '收藏',\n            '主页访问量': None,\n            '粉丝增量': '涨粉'\n        }\n\n    def get_daily_data(self):\n        # 读取当天数据和昨天的数据\n        data_df = pd.read_excel(self.xhs_data_path)\n        yesterday_df = pd.read_excel(self.xhs_yesterday_path)\n\n        # 确认首次发布时间字段格式为日期格式\n        data_df['首次发布时间'] = pd.to_datetime(data_df['首次发布时间'])\n        yesterday_df['首次发布时间'] = pd.to_datetime(yesterday_df['首次发布时间'])\n\n        # 日期过滤条件\n        min_date = datetime(2025, 3, 4)\n\n        # 筛选出符合条件的数据（开始日期≥2025-03-04）\n        filtered_data_df = data_df[data_df['首次发布时间'] >= min_date].copy()\n\n        # 使用“笔记标题”作为主键进行合并\n        daily_data = pd.merge(\n            filtered_data_df,\n            yesterday_df[['笔记标题'] + self.compare_columns],\n            on='笔记标题',\n            how='left',\n            suffixes=('', '_昨日')\n        )\n\n        # 处理昨日无数据的情况\n        for col in self.compare_columns:\n            yesterday_col = f\"{col}_昨日\"\n            daily_data[yesterday_col] = daily_data[yesterday_col].fillna(0)\n            daily_data[col] = (daily_data[col] - daily_data[yesterday_col]).abs()\n            daily_data.drop(columns=[yesterday_col], inplace=True)\n\n        daily_data = daily_data[daily_data['首次发布时间'] >= min_date].reset_index(drop=True)\n\n        # 插入日期和平台字段\n        yesterday_str = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')\n        daily_data.insert(0, '日期', yesterday_str)\n        daily_data.insert(0, '平台', '小红书')\n\n        return daily_data\n\n    def update_yesterday_data(self):\n        if os.path.exists(self.xhs_yesterday_path):\n            os.remove(self.xhs_yesterday_path)\n            print(f\"✅ 已删除旧的昨日数据文件: {self.xhs_yesterday_path}\")\n        else:\n            print(\"⚠️ 旧的昨日数据文件不存在，无需删除。\")\n\n        new_yesterday_path = os.path.join(self.xhs_file_path, \"yesterday.xlsx\")\n\n        if os.path.exists(self.xhs_data_path):\n            os.rename(self.xhs_data_path, new_yesterday_path)\n            print(f\"✅ 已将 {self.xhs_data_path} 重命名为 {new_yesterday_path}\")\n        else:\n            print(\"❌ 无法重命名，xhs_data_path 文件不存在。\")\n\n    def convert_to_video_quality_format(self):\n        \"\"\"\n        获取 daily_data，并将其转换为 视频质量数据 模板格式。\n        返回：格式统一的新 DataFrame\n        \"\"\"\n        df = self.get_daily_data()\n        converted_df = pd.DataFrame(columns=self.template_columns)\n        for target_col in self.template_columns:\n            source_col = self.column_mapping.get(target_col)\n            if source_col in df.columns:\n                converted_df[target_col] = df[source_col]\n            else:\n                converted_df[target_col] = None\n        converted_df['所属平台'] = '小红书'\n        return converted_df\n\n# 示例调用\nif __name__ == \"__main__\":\n    processor = DailyDataProcessor()\n    # processor.update_yesterday_data()\n    formatted_df = processor.convert_to_video_quality_format()\n    formatted_df.to_excel('小红书视频质量数据daily.xlsx', index=False)\n    print(\"✅ 已保存转换后的视频质量数据为 '转换后的视频质量数据.xlsx'\")\n"
  },
  {
    "path": "data_processing/xhstest.py",
    "content": "import read_sql as rs\nimport os\nimport re\nimport sys\nimport jdy\nimport pandas as pd\nimport asyncio\nfrom datetime import datetime, timedelta\n\n# 模块级路径配置\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\nproject_root = os.path.abspath(os.path.join(current_dir, \"..\"))\nif project_root not in sys.path:\n    sys.path.append(project_root)\n\nfrom project_config.project import xhs_custom_count_sql\nfrom data_processing.dy_video_analysis import DailyDataProcessor\n\nclass Dividend:\n    def __init__(self):\n        \"\"\"初始化数据库、简道云接口、数据处理路径等配置\"\"\"\n        self.sql = rs.MSSQLDatabase()\n        self.custom_count_path = xhs_custom_count_sql\n        self.jdy = jdy.JDY()\n        self.daily_process = DailyDataProcessor()\n        self.metrics = ['观看量', '点赞', '收藏', '评论', '分享']\n        self._cached_jdy_data = None\n\n    def get_jdy_data_cached(self):\n        \"\"\"缓存简道云数据，避免重复请求\"\"\"\n        if self._cached_jdy_data is None:\n            appId = \"67c280b7c6387c4f4afd50ae\"\n            entryId = \"67c2816ffa795e84a8fe45b9\"\n            self._cached_jdy_data = self.jdy.get_jdy_data(app_id=appId, entry_id=entryId)\n        return self._cached_jdy_data\n\n    def get_custom_count(self):\n        \"\"\"从SQL文件中获取客资数据\"\"\"\n        try:\n            print(f\"Loading SQL from: {self.custom_count_path}\")\n            return self.sql.get_from_sqlfile(self.custom_count_path)\n        except FileNotFoundError as e:\n            print(f\"SQL文件未找到: {e}\")\n            return None\n        except Exception as e:\n            print(f\"数据库操作失败: {e}\")\n            return None\n\n    def get_daily_video_data(self):\n        \"\"\"获取每日视频数据\"\"\"\n        return self.daily_process.get_daily_data()\n\n    def total_money_dy(self):\n        \"\"\"计算奖励总金额 = 客资总和 * 50\"\"\"\n        total_custom = self.get_custom_count()\n        return total_custom['客资数'].sum() * 50\n\n    def video_dividend(self):\n        \"\"\"\n        处理简道云视频数据与每日视频表现数据，计算每条作品应得的分成金额\n        返回包含 [作品名称, 总分成, 日期] 的 DataFrame\n        \"\"\"\n        video_df = self.get_daily_video_data().copy()\n        jdy_data = self.get_jdy_data_cached()\n        content_df = pd.DataFrame(jdy_data)\n\n        content_df['作品名称'] = content_df['_widget_1740646149825'].astype(str).apply(lambda x: re.sub(r'\\s*#.*', '', x))\n        video_df['作品名称'] = video_df['作品名称'].astype(str).apply(lambda x: re.sub(r'\\s*#.*', '', x))\n\n        merged_df = content_df.merge(video_df, on='作品名称', how='left')\n\n        for metric in self.metrics:\n            if metric in merged_df.columns:\n                merged_df[metric] = merged_df[metric].fillna(0)\n\n        total_money = self.total_money_dy()\n        metric_weights = {'观看量': 0.05, '点赞': 0.05, '收藏': 0.3, '评论': 0.3, '分享': 0.3}\n\n        for metric, weight in metric_weights.items():\n            max_val = merged_df[metric].max()\n            merged_df[f'{metric}_标准化'] = merged_df[metric].apply(lambda x: (x / max_val) * weight if max_val > 0 else 0)\n\n        standardized_cols = [f'{m}_标准化' for m in metric_weights]\n        merged_df['总表现分'] = merged_df[standardized_cols].sum(axis=1)\n\n        video_scores = merged_df.groupby('作品名称', as_index=False)['总表现分'].sum()\n        video_scores = video_scores[video_scores['总表现分'] > 0]\n\n        total_customers = total_money // 50\n        total_scores = video_scores['总表现分'].sum()\n        video_scores['客户数'] = ((video_scores['总表现分'] / total_scores) * total_customers).round().astype(int)\n\n        discrepancy = total_customers - video_scores['客户数'].sum()\n        if discrepancy != 0:\n            idx_max = video_scores['总表现分'].idxmax()\n            video_scores.at[idx_max, '客户数'] += discrepancy\n\n        video_scores['总分成'] = video_scores['客户数'] * 50\n        video_scores['日期'] = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')\n        video_scores = video_scores[video_scores['总分成'] > 0]\n        return video_scores[['作品名称', '总分成', '日期']]\n\n    def get_video_people(self):\n        \"\"\"提取简道云中每条作品对应的人员信息\"\"\"\n        jdy_data = self.get_jdy_data_cached()\n        rows = []\n        for doc in jdy_data:\n            title_raw = doc.get(\"_widget_1740646149825\", \"\")\n            title_cleaned = re.sub(r'\\s*#.*', '', title_raw)\n            base_fields = {\n                \"账号名称\": doc.get(\"_widget_1741257105163\", \"\"),\n                \"账号ID\": doc.get(\"_widget_1741257105165\", \"\"),\n                \"是否完整内容\": doc.get(\"_widget_1740798082550\", \"\"),\n                \"作品名称\": title_cleaned,\n                \"提交日期\": doc.get(\"_widget_1740646149826\", \"\"),\n                \"来源门店/部门\": doc.get(\"_widget_1741934971937\", {}).get(\"name\", \"\")\n            }\n            user_groups = {\n                \"完整内容提供\": [u.get(\"username\") for u in doc.get(\"_widget_1740798082567\", [])],\n                \"半成品内容提供\": [u.get(\"username\") for u in doc.get(\"_widget_1740798082568\", [])],\n                \"剪辑\": [u.get(\"username\") for u in doc.get(\"_widget_1740798082569\", [])],\n                \"发布运营\": [u.get(\"username\") for u in doc.get(\"_widget_1740798082570\", [])]\n            }\n            max_len = max(len(g) for g in user_groups.values()) or 1\n            for group, users in user_groups.items():\n                for user in users + [None] * (max_len - len(users)):\n                    row = {**base_fields, \"人员类别\": group, \"人员\": user}\n                    rows.append(row)\n        df = pd.DataFrame(rows)\n        return df.dropna(subset=[\"人员\"])\n\n    def everyone_money(self):\n        \"\"\"根据规则分配分成金额给人员\"\"\"\n        video_people = self.get_video_people()\n        video_money = self.video_dividend()\n\n        merged = video_people.merge(video_money, on=\"作品名称\", how=\"left\")\n        merged[\"总分成\"] = merged[\"总分成\"].fillna(0)\n\n        RULES = {\n            (\"是\", \"完整内容提供\"): 0.6,\n            (\"是\", \"发布运营\"): 0.4,\n            (\"否\", \"半成品内容提供\"): 0.4,\n            (\"否\", \"剪辑\"): 0.2,\n            (\"否\", \"发布运营\"): 0.4\n        }\n\n        merged[\"分成比例\"] = merged.apply(lambda row: RULES.get((row[\"是否完整内容\"], row[\"人员类别\"]), 0.2), axis=1)\n        merged = merged.dropna(subset=[\"分成比例\"])\n        merged[\"人数\"] = merged.groupby([\"作品名称\", \"人员类别\"])[\"人员\"].transform(\"count\")\n        merged[\"分成金额\"] = (merged[\"总分成\"] * merged[\"分成比例\"] / merged[\"人数\"]).round(2)\n\n        result = merged[[\"人员\", \"分成金额\"]].groupby(\"人员\", as_index=False).sum()\n\n        before = video_money[\"总分成\"].sum()\n        after = result[\"分成金额\"].sum()\n        diff = round(before - after, 2)\n        if diff != 0:\n            idx = result[\"分成金额\"].idxmax()\n            result.loc[idx, \"分成金额\"] = round(result.loc[idx, \"分成金额\"] + diff, 2)\n\n        result[\"日期\"] = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')\n        return result[result[\"分成金额\"] > 0].reset_index(drop=True)\n\n    def upload_to_jdy(self):\n        \"\"\"上传结果数据到简道云\"\"\"\n        appId = \"67c280b7c6387c4f4afd50ae\"\n        entryId = \"67d7097d08e5f607c4cfd028\"\n        final_data = self.everyone_money()\n        asyncio.run(self.jdy.batch_create(app_id=appId, entry_id=entryId, source_data=final_data))\n\nif __name__ == '__main__':\n    dividend = Dividend()\n    print(dividend.total_money_dy())\n    print(dividend.get_custom_count()['客资数'].sum())\n\n    video_people = dividend.get_video_people()\n    video_people.to_excel('小红书_视频管理.xlsx', index=False)\n\n    people_money = dividend.everyone_money()\n    people_money.to_excel('小红书_每人分红金额.xlsx', index=False)\n\n    data = dividend.video_dividend()\n    data.to_excel('小红书_视频分红.xlsx', index=False)\n\n    # dividend.upload_to_jdy()\n"
  },
  {
    "path": "main.py",
    "content": "from utils.init_path import setup_project_root\nsetup_project_root()\n\nfrom spiders.xhs import Xhs\nfrom spiders.douyin import Douyin\n\nif __name__ == \"__main__\":\n    print(\"📦 程序启动\")\n\n    try:\n        print(\"▶ 开始处理 Douyin 数据\")\n        Douyin.run_all()\n        print(\"✅ Douyin 处理完成\")\n    except Exception as e:\n        print(f\"❌ Douyin 出错: {e}\")\n\n    try:\n        print(\"▶ 开始处理 XHS 数据\")\n        Xhs.run_all()\n        print(\"✅ XHS 处理完成\")\n    except Exception as e:\n        print(f\"❌ XHS 出错: {e}\")\n\n    print(\"🏁 程序结束\")\n"
  },
  {
    "path": "project_config/__init__.py",
    "content": ""
  },
  {
    "path": "project_config/project.py",
    "content": "from pathlib import Path\nimport os\n\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n# 小红书路径\nxhs_file_path = BASE_DIR / \"xlsx_file\" / \"xhs\"\nxhs_data_path = xhs_file_path / \"汇总笔记列表明细表.xlsx\"\nxhs_yesterday_path = xhs_file_path / \"yesterday.xlsx\"\n\n# 抖音路径\ndy_file_path = BASE_DIR / \"xlsx_file\" / \"douyin\"\ndy_data_path = dy_file_path / \"douyin_汇总数据.xlsx\"\ndy_yesterday_path = dy_file_path / \"yesterday.xlsx\"\n\n# 驱动路径\ndriver_path = BASE_DIR / \"project_config\" / \"msedgedriver.exe\"\n\n# Cookie 路径\npkl_path = BASE_DIR / \"pkl\"\n\n\n# 字段映射关系（name到label）\nfields = [\n        {\"label\": \"所属平台\", \"type\": \"combo\"},\n        {\"label\": \"数据日期\", \"type\": \"datetime\"},\n        {\"label\": \"作品名称\", \"type\": \"text\"},\n        {\"label\": \"发布时间\", \"type\": \"datetime\"},\n        {\"label\": \"体裁\", \"type\": \"text\"},\n        {\"label\": \"审核状态\", \"type\": \"text\"},\n        {\"label\": \"播放量\", \"type\": \"number\"},\n        {\"label\": \"完播率\", \"type\": \"number\"},\n        {\"label\": \"5s完播率\", \"type\": \"number\"},\n        {\"label\": \"封面点击率\", \"type\": \"number\"},\n        {\"label\": \"2s跳出率\", \"type\": \"number\"},\n        {\"label\": \"平均播放时长\", \"type\": \"number\"},\n        {\"label\": \"点赞量\", \"type\": \"number\"},\n        {\"label\": \"分享量\", \"type\": \"number\"},\n        {\"label\": \"评论量\", \"type\": \"number\"},\n        {\"label\": \"收藏量\", \"type\": \"number\"},\n        {\"label\": \"主页访问量\", \"type\": \"number\"},\n        {\"label\": \"粉丝增量\", \"type\": \"number\"},\n    ]\n\n\nif __name__ == '__main__':\n    print(dy_file_path)\n\n"
  },
  {
    "path": "spiders/__init__.py",
    "content": ""
  },
  {
    "path": "spiders/douyin.py",
    "content": "import pickle\nimport time\nimport glob\nimport pandas as pd\nfrom datetime import datetime, timedelta\nfrom selenium import webdriver\nfrom selenium.webdriver.edge.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.edge.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# 自动添加项目根目录到 sys.path\nfrom utils.init_path import setup_project_root\nsetup_project_root()\nfrom project_config.project import (\n    driver_path, pkl_path, dy_file_path\n)\n\n# 动态获取 Douyin Cookie 路径列表\ndef get_douyin_cookie_paths():\n    return [str(p.resolve()) for p in pkl_path.glob(\"douyin_*.pkl\") if p.suffix == \".pkl\"]\n\nclass Douyin:\n    def __init__(self, url, cookies_file):\n        self.url = url\n        self.cookies_file = cookies_file\n        self.data_center_url = \"https://creator.douyin.com/creator-micro/data-center/content\"\n\n        edge_options = Options()\n        edge_options.add_experimental_option(\"prefs\", {\n            \"download.default_directory\": str(dy_file_path),\n            \"download.prompt_for_download\": False,\n            \"download.directory_upgrade\": True,\n            \"safebrowsing.enabled\": True\n        })\n\n        self.driver = webdriver.Edge(\n            service=Service(str(driver_path)),\n            options=edge_options\n        )\n        self.driver.maximize_window()\n\n    def load_cookies(self):\n        try:\n            with open(self.cookies_file, \"rb\") as cookie_file:\n                cookies = pickle.load(cookie_file)\n                self.driver.get(self.url)\n                self.driver.delete_all_cookies()\n                for cookie in cookies:\n                    if 'expiry' in cookie:\n                        cookie['expiry'] = int(cookie['expiry'])\n                    self.driver.add_cookie(cookie)\n                self.driver.refresh()\n                print(f\"✅ Loaded cookies from {self.cookies_file}\")\n                self._post_login_flow()\n        except FileNotFoundError:\n            print(f\"❌ Cookie file not found: {self.cookies_file}\")\n\n    def _post_login_flow(self):\n        self.driver.get(self.data_center_url)\n        self.wait_for_page_ready()\n        self.click_tgzp_tab()\n        self.click_post_list_tab()\n        self.click_export_data_button()\n\n    def wait_for_page_ready(self, timeout=30):\n        WebDriverWait(self.driver, timeout).until(\n            lambda d: d.execute_script(\"return document.readyState\") == 'complete'\n        )\n\n    def click_tgzp_tab(self):\n        locator = (By.XPATH, \"//div[@id='semiTab1' and text()='投稿作品']\")\n        try:\n            element = WebDriverWait(self.driver, 10).until(\n                EC.element_to_be_clickable(locator)\n            )\n            self.driver.execute_script(\"arguments[0].click();\", element)\n            print(\"✅ 点击“投稿作品”成功\")\n        except Exception as e:\n            print(f\"❌ 点击“投稿作品”失败: {e}\")\n\n    def click_post_list_tab(self):\n        locator = (By.XPATH, \"//div[@id='semiTabPanel1']//span[contains(@class, 'douyin-creator-pc-radio-addon') and normalize-space(text())='投稿列表']\")\n        try:\n            element = WebDriverWait(self.driver, 10).until(\n                EC.element_to_be_clickable(locator)\n            )\n            self.driver.execute_script(\"arguments[0].click();\", element)\n            print(\"✅ 点击“投稿列表”成功\")\n        except Exception as e:\n            print(f\"❌ 点击“投稿列表”失败: {e}\")\n\n    def click_export_data_button(self):\n        locator = (By.XPATH, \"//div[contains(@class,'container-ttkmFy')]//button[.//span[text()='导出数据']]\")\n        try:\n            time.sleep(2)\n            button = WebDriverWait(self.driver, 15).until(\n                EC.presence_of_element_located(locator)\n            )\n            self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center'});\", button)\n            self.driver.execute_script(\"arguments[0].click();\", button)\n            print(\"✅ 点击导出数据成功\")\n        except Exception as e:\n            print(f\"❌ 点击导出数据失败: {e}\")\n\n    def run(self):\n        try:\n            self.load_cookies()\n            time.sleep(10)\n        except Exception as e:\n            print(f\"运行出错：{e}\")\n        finally:\n            self.driver.quit()\n\n    @classmethod\n    def cleanup_temp_files(cls, output_path, keyword=\"data\"):\n        deleted = 0\n        for file in glob.glob(os.path.join(output_path, f\"*{keyword}*.xlsx\")):\n            try:\n                os.remove(file)\n                print(f\"🗑️ 已删除临时文件: {file}\")\n                deleted += 1\n            except Exception as e:\n                print(f\"❌ 删除失败: {file}，错误: {e}\")\n        if deleted == 0:\n            print(\"⚠️ 没有发现需要删除的临时文件\")\n\n    @classmethod\n    def merge_xlsx_files(cls, output_path):\n        print(\"🔄 开始合并 Excel 文件...\")\n        all_files = glob.glob(os.path.join(output_path, \"*data*.xlsx\"))\n        df_list = []\n        for file in all_files:\n            try:\n                df = pd.read_excel(file)\n                df[\"来源文件\"] = os.path.basename(file)\n                df_list.append(df)\n            except Exception as e:\n                print(f\"⚠️ 无法读取 {file}: {e}\")\n\n        if df_list:\n            merged_df = pd.concat(df_list, ignore_index=True)\n            final_file = os.path.join(output_path, \"douyin_汇总数据.xlsx\")\n            merged_df.to_excel(final_file, index=False)\n            print(f\"📊 已成功导出汇总文件：{final_file}\")\n        else:\n            print(\"❌ 没有可合并的xlsx文件\")\n            return\n\n        cls.cleanup_temp_files(output_path, keyword=\"data\")\n\n    @classmethod\n    def run_all(cls):\n        print(\"📊 开始运行 run_all()：处理所有 Douyin 账号\")\n        cookie_paths = get_douyin_cookie_paths()\n        print(\"🧾 Cookie 路径列表：\")\n        for p in cookie_paths:\n            print(\" -\", p)\n\n        if not cookie_paths:\n            print(\"❌ 未找到任何 cookie 文件，任务终止\")\n            return\n\n        for cookie_file in cookie_paths:\n            print(f\"\\n================ 当前账号: {cookie_file} ================\\n\")\n            douyin = cls(\"https://creator.douyin.com/creator-micro/home\", cookie_file)\n            douyin.run()\n            print(\"⏳ 等待下载完成...\")\n            time.sleep(15)\n\n        print(\"\\n📁 准备合并 Excel 文件...\")\n        cls.merge_xlsx_files(str(dy_file_path))\n\nif __name__ == \"__main__\":\n    Douyin.run_all()\n"
  },
  {
    "path": "spiders/douyin_test.py",
    "content": "import os\nimport time\nimport glob\nimport pickle\n# 忽略 openpyxl 样式警告\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module=\"openpyxl\")\nimport pandas as pd\nfrom datetime import datetime, timedelta\nfrom selenium import webdriver\nfrom selenium.webdriver.edge.service import Service\nfrom selenium.webdriver.edge.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom webdriver_manager.microsoft import EdgeChromiumDriverManager\n\n# 下载文件保存目录\ndy_file_path = r'E:\\douyin_xhs_data\\douyin'\n\n# 多个 cookie 文件名，放在和 .py 脚本同一目录\ncookie_list = [\n    \"douyin_44698605892.pkl\",\n    \"douyin_bojuegz.pkl\",\n    \"douyin_bojuexiamen.pkl\",\n    \"douyin_NCHQYX520.pkl\",\n    \"douyin_53693141223.pkl\",\n    \"douyin_BJ_520.pkl\"\n]\n\nclass Douyin:\n    def __init__(self, url, cookies_file):\n        self.url = url\n        self.cookies_file = cookies_file\n        self.data_center_url = \"https://creator.douyin.com/creator-micro/data-center/content\"\n\n        # 配置Edge下载目录\n        edge_options = Options()\n        edge_options.add_experimental_option(\"prefs\", {\n            \"download.default_directory\": dy_file_path,  # 设置下载目录\n            \"download.prompt_for_download\": False,       # 不提示保存对话框\n            \"download.directory_upgrade\": True,\n            \"safebrowsing.enabled\": True\n        })\n\n        self.driver = webdriver.Edge(\n            service=Service(EdgeChromiumDriverManager().install()),\n            options=edge_options\n        )\n        self.driver.maximize_window()\n\n    def load_cookies(self):\n        try:\n            with open(self.cookies_file, \"rb\") as cookie_file:\n                cookies = pickle.load(cookie_file)\n                self.driver.get(self.url)\n                self.driver.delete_all_cookies()\n                for cookie in cookies:\n                    if 'expiry' in cookie:\n                        cookie['expiry'] = int(cookie['expiry'])\n                    self.driver.add_cookie(cookie)\n                self.driver.refresh()\n                print(f\"✅ Loaded cookies from {self.cookies_file}\")\n                self._post_login_flow()\n        except FileNotFoundError:\n            print(f\"❌ Cookie file not found: {self.cookies_file}\")\n\n    def _post_login_flow(self):\n        self.driver.get(self.data_center_url)\n        self.wait_for_page_ready()\n        self.click_tgzp_tab()\n        self.click_post_list_tab()\n        self.input_start_date()\n        self.input_end_date()\n        self.click_export_data_button()\n\n    def wait_for_page_ready(self, timeout=30):\n        WebDriverWait(self.driver, timeout).until(\n            lambda d: d.execute_script(\"return document.readyState\") == 'complete'\n        )\n\n    def click_tgzp_tab(self):\n        locator = (By.XPATH, \"//div[@id='semiTab1' and text()='投稿作品']\")\n        try:\n            element = WebDriverWait(self.driver, 10).until(\n                EC.element_to_be_clickable(locator)\n            )\n            self.driver.execute_script(\"arguments[0].click();\", element)\n            print(\"✅ 点击“投稿作品”成功\")\n        except Exception as e:\n            print(f\"❌ 点击“投稿作品”失败: {e}\")\n\n    def click_post_list_tab(self):\n        locator = (By.XPATH, \"//div[@id='semiTabPanel1']//span[contains(@class, 'douyin-creator-pc-radio-addon') and normalize-space(text())='投稿列表']\")\n        try:\n            element = WebDriverWait(self.driver, 10).until(\n                EC.element_to_be_clickable(locator)\n            )\n            self.driver.execute_script(\"arguments[0].click();\", element)\n            print(\"✅ 点击“投稿列表”成功\")\n        except Exception as e:\n            print(f\"❌ 点击“投稿列表”失败: {e}\")\n\n    def input_start_date(self):\n        locator = (By.XPATH, \"//div[@id='semiTabPanel1']//input[@placeholder='开始日期']\")\n        ninety_days_ago = datetime.now() - timedelta(days=90)\n        min_date = datetime(2025, 3, 4)\n        target_date = max(ninety_days_ago, min_date).strftime(\"%Y-%m-%d\")\n        self._fill_date(locator, target_date, \"开始日期\")\n\n    def input_end_date(self):\n        locator = (By.XPATH, \"//div[@id='semiTabPanel1']//input[@placeholder='结束日期']\")\n        target_date = (datetime.now() - timedelta(days=1)).strftime(\"%Y-%m-%d\")\n        self._fill_date(locator, target_date, \"结束日期\")\n\n    def _fill_date(self, locator, date_str, label):\n        try:\n            input_element = WebDriverWait(self.driver, 10).until(\n                EC.presence_of_element_located(locator)\n            )\n            self.driver.execute_script(\"arguments[0].removeAttribute('readonly')\", input_element)\n            self.driver.execute_script(\"arguments[0].value = arguments[1];\", input_element, date_str)\n            self.driver.execute_script(\"\"\"\n                arguments[0].dispatchEvent(new Event('input', { bubbles: true }));\n                arguments[0].dispatchEvent(new Event('change', { bubbles: true }));\n            \"\"\", input_element)\n            print(f\"✅ 输入{label}：{date_str}\")\n        except Exception as e:\n            print(f\"❌ 设置{label}失败: {e}\")\n\n    def click_export_data_button(self):\n        locator = (By.XPATH, \"//div[contains(@class,'container-ttkmFy')]//button[.//span[text()='导出数据']]\")\n        try:\n            time.sleep(2)\n            button = WebDriverWait(self.driver, 15).until(\n                EC.presence_of_element_located(locator)\n            )\n            self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center'});\", button)\n            self.driver.execute_script(\"arguments[0].click();\", button)\n            print(\"✅ 点击导出数据成功\")\n        except Exception as e:\n            print(f\"❌ 点击导出数据失败: {e}\")\n\n    def run(self):\n        try:\n            self.load_cookies()\n            time.sleep(10)\n        except Exception as e:\n            print(f\"运行出错：{e}\")\n        finally:\n            self.driver.quit()\n\ndef merge_xlsx_files(output_path):\n    all_files = glob.glob(os.path.join(output_path, \"*data*.xlsx\"))\n    df_list = []\n    for file in all_files:\n        try:\n            df = pd.read_excel(file)\n            df[\"来源文件\"] = os.path.basename(file)\n            df_list.append(df)\n        except Exception as e:\n            print(f\"⚠️ 无法读取 {file}: {e}\")\n\n    if df_list:\n        merged_df = pd.concat(df_list, ignore_index=True)\n        final_file = os.path.join(output_path, \"douyin_汇总数据.xlsx\")\n        merged_df.to_excel(final_file, index=False)\n        print(f\"📊 已成功导出汇总文件：{final_file}\")\n    else:\n        print(\"❌ 没有可合并的xlsx文件\")\n\nif __name__ == \"__main__\":\n    script_dir = os.path.dirname(os.path.abspath(__file__))\n\n    for cookie_file in cookie_list:\n        full_cookie_path = os.path.join(script_dir, cookie_file)\n        print(f\"\\n🌐 当前账号: {cookie_file}\")\n        douyin = Douyin(\"https://creator.douyin.com/creator-micro/home\", full_cookie_path)\n        douyin.run()\n        print(\"⏳ 等待下载完成...\")\n        time.sleep(15)  # 视网络情况可增大等待时间\n\n    print(\"\\n📁 开始合并所有Excel文件...\")\n    merge_xlsx_files(dy_file_path)\n"
  },
  {
    "path": "spiders/xhs.py",
    "content": "import pickle\nimport time\nimport glob\nimport pandas as pd\nfrom datetime import datetime\nfrom selenium import webdriver\nfrom selenium.webdriver.edge.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.edge.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# 自动添加项目根目录到 sys.path\nfrom utils.init_path import setup_project_root\nsetup_project_root()\nfrom project_config.project import (\n    xhs_file_path, driver_path, pkl_path\n)\n\n# 动态获取 XHS Cookie 路径列表\ndef get_xhs_cookie_paths():\n    return [str(p.resolve()) for p in pkl_path.glob(\"xhs_*.pkl\") if p.suffix == \".pkl\"]\n\nclass Xhs:\n    def __init__(self, url, cookies_file, download_path=xhs_file_path):\n        self.url = url\n        self.cookies_file = cookies_file\n        self.data_center_url = \"https://creator.xiaohongshu.com/statistics/data-analysis\"\n        self.download_path = download_path\n\n        edge_options = Options()\n        prefs = {\n            \"download.default_directory\": str(self.download_path),\n            \"download.prompt_for_download\": False,\n            \"download.directory_upgrade\": True,\n            \"safebrowsing.enabled\": True\n        }\n        edge_options.add_experimental_option(\"prefs\", prefs)\n\n        if self.cookies_file:\n            print(f\"使用本地 EdgeDriver 路径: {driver_path}\")\n            self.driver = webdriver.Edge(\n                service=Service(driver_path),\n                options=edge_options\n            )\n            self.driver.maximize_window()\n        else:\n            self.driver = None\n\n    def run(self):\n        try:\n            self.load_cookies()\n            time.sleep(10)\n        except Exception as e:\n            print(f\"❗ Unknown error occurred: {str(e)}\")\n        finally:\n            if self.driver:\n                self.driver.quit()\n                print(\"🛑 Browser closed\")\n        time.sleep(5)\n\n    def load_cookies(self):\n        try:\n            with open(self.cookies_file, \"rb\") as cookie_file:\n                cookies = pickle.load(cookie_file)\n                self.driver.get(self.url)\n                self.driver.delete_all_cookies()\n                for cookie in cookies:\n                    if 'expiry' in cookie:\n                        cookie['expiry'] = int(cookie['expiry'])\n                    self.driver.add_cookie(cookie)\n                self.driver.refresh()\n                print(\"✅ Cookies loaded, auto-login successful!\")\n                self._post_login_flow()\n        except FileNotFoundError:\n            print(f\"❌ Cookie 文件未找到: {self.cookies_file}\")\n        except Exception as e:\n            print(f\"❌ 加载 Cookie 失败: {e}\")\n\n    def _manual_login(self):\n        print(\"❌ Cookies not found, manual login required\")\n        self.driver.get(self.url)\n        input(\"Please complete login and press Enter to continue...\")\n        self._save_cookies()\n        self._post_login_flow()\n\n    def _save_cookies(self):\n        with open(self.cookies_file, \"wb\") as cookie_file:\n            cookies = [c for c in self.driver.get_cookies() if c['name'] not in ['passport_csrf_token']]\n            pickle.dump(cookies, cookie_file)\n        print(\"✅ Cookies saved successfully\")\n\n    def _post_login_flow(self):\n        self.go_to_data_center()\n        self.click_export_data_button()\n\n    def go_to_data_center(self):\n        print(\"🚀 Navigating to data center...\")\n        self.driver.get(self.data_center_url)\n        self.wait_for_page_ready()\n\n    def wait_for_page_ready(self, timeout=30):\n        WebDriverWait(self.driver, timeout).until(\n            lambda d: d.execute_script(\"return document.readyState\") == 'complete'\n        )\n        print(\"📄 Page loaded successfully\")\n\n    def click_export_data_button(self):\n        locator = (By.XPATH, \"//button[.//span[contains(.,'导出数据')]]\")\n        try:\n            self.wait_for_page_ready()\n            time.sleep(2)\n            button = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located(locator))\n            self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center'});\", button)\n            self.driver.execute_script(\"arguments[0].click();\", button)\n            print(\"✅ 点击“导出数据”成功\")\n        except Exception as e:\n            print(f\"❌ 未能成功点击“导出数据”按钮：{e}\")\n\n    def merge_and_cleanup_xlsx_files(self):\n        keyword = \"笔记列表明细表\"\n        all_files = glob.glob(os.path.join(self.download_path, f\"*{keyword}*.xlsx\"))\n\n        if not all_files:\n            print(\"⚠️ 没有找到任何包含关键字的 Excel 文件\")\n            return None\n\n        all_dfs = []\n        for file in all_files:\n            try:\n                df = pd.read_excel(file, skiprows=1)\n                df['来源文件'] = os.path.basename(file)\n                all_dfs.append(df)\n            except Exception as e:\n                print(f\"❌ 读取失败：{file}，错误：{e}\")\n\n        if all_dfs:\n            result = pd.concat(all_dfs, ignore_index=True)\n            if '首次发布时间' in result.columns:\n                try:\n                    result['首次发布时间'] = pd.to_datetime(\n                        result['首次发布时间'].astype(str),\n                        format='%Y年%m月%d日%H时%M分%S秒',\n                        errors='coerce'\n                    ).dt.strftime('%Y-%m-%d')\n                    print(\"✅ 成功格式化“首次发布时间”为 YYYY-MM-DD\")\n                except Exception as e:\n                    print(f\"⚠️ 格式化“首次发布时间”失败：{e}\")\n\n            output_path = os.path.join(self.download_path, \"汇总笔记列表明细表.xlsx\")\n            result.to_excel(output_path, index=False)\n            print(f\"✅ 汇总成功，已保存：{output_path}\")\n\n            for file in all_files:\n                if os.path.basename(file) == os.path.basename(output_path):\n                    continue\n                try:\n                    os.remove(file)\n                    print(f\"🗑️ 已删除文件：{file}\")\n                except Exception as e:\n                    print(f\"❌ 删除失败：{file}，错误：{e}\")\n            return result\n        else:\n            print(\"⚠️ 没有可用的数据进行汇总\")\n            return None\n\n    @classmethod\n    def run_all(cls):\n        print(\"📊 开始运行 run_all()：处理所有 XHS 账号\")\n        full_paths = get_xhs_cookie_paths()\n        print(\"🧾 Cookie 路径列表：\")\n        for p in full_paths:\n            print(\" -\", p)\n\n        if not full_paths:\n            print(\"❌ 未找到任何 cookie 文件，任务终止\")\n            return\n\n        for full_path in full_paths:\n            try:\n                print(f\"\\n================ 处理：{full_path} ================\\n\")\n                account = cls(url=\"https://creator.xiaohongshu.com/statistics/data-analysis\", cookies_file=full_path)\n                account.run()\n            except Exception as e:\n                print(f\"❌ 账号处理失败：{full_path}，错误：{e}\")\n\n        print(\"📁 准备合并 Excel 文件...\")\n        print(\"🔄 开始合并 Excel 文件...\")\n        merged_instance = cls(url=\"https://creator.xiaohongshu.com/statistics/data-analysis\", cookies_file=\"\")\n        final_df = merged_instance.merge_and_cleanup_xlsx_files()\n        if final_df is not None:\n            print(\"✅ XHS 数据采集成功，展示部分数据：\")\n            print(final_df.head())\n        else:\n            print(\"⚠️ XHS 数据采集未成功或无数据\")\n\nif __name__ == \"__main__\":\n    Xhs.run_all()\n"
  },
  {
    "path": "spiders/xhsspidertest.py",
    "content": "import os, sys\nimport pickle\nimport time\nimport glob\nimport pandas as pd\nfrom datetime import datetime, timedelta\nfrom selenium import webdriver\nfrom selenium.webdriver.edge.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.edge.options import Options\nfrom webdriver_manager.microsoft import EdgeChromiumDriverManager\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver import ActionChains\n# 获取当前脚本所在目录 (data_processing目录)\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\n# 获取项目根目录（即当前目录的上一级）\nproject_root = os.path.abspath(os.path.join(current_dir, \"..\"))\n# 将项目根目录添加到sys.path中\nif project_root not in sys.path:\n    sys.path.append(project_root)\nfrom project_config.project import xhs_cookie_list, xhs_file_path, driver_path\n\n\nclass Xhs:\n    def __init__(self, url, cookies_file, download_path=xhs_file_path):\n        self.url = url\n        self.cookies_file = cookies_file\n        self.data_center_url = \"https://creator.xiaohongshu.com/statistics/data-analysis\"\n        self.download_path = download_path\n\n        # 配置 Edge 下载路径\n        edge_options = Options()\n        prefs = {\n            \"download.default_directory\": self.download_path,\n            \"download.prompt_for_download\": False,\n            \"download.directory_upgrade\": True,\n            \"safebrowsing.enabled\": True\n        }\n        edge_options.add_experimental_option(\"prefs\", prefs)\n\n        # 当 cookies_file 为空时可以选择不初始化 driver（仅用于数据合并）\n        if self.cookies_file:\n            print(f\"使用本地 EdgeDriver 路径: {driver_path}\")\n            self.driver = webdriver.Edge(\n                service=Service(driver_path),\n                options=edge_options\n            )\n            self.driver.maximize_window()\n        else:\n            self.driver = None\n\n    def run(self):\n        try:\n            self.load_cookies()\n            time.sleep(10)\n        except Exception as e:\n            print(f\"❗ Unknown error occurred: {str(e)}\")\n        finally:\n            if self.driver:\n                self.driver.quit()\n                print(\"🛑 Browser closed\")\n        time.sleep(5)\n\n    def load_cookies(self):\n        try:\n            with open(self.cookies_file, \"rb\") as cookie_file:\n                cookies = pickle.load(cookie_file)\n                self.driver.get(self.url)\n                self.driver.delete_all_cookies()\n                for cookie in cookies:\n                    if 'expiry' in cookie:\n                        cookie['expiry'] = int(cookie['expiry'])\n                    self.driver.add_cookie(cookie)\n                self.driver.refresh()\n                print(\"✅ Cookies loaded, auto-login successful!\")\n                self._post_login_flow()\n        except FileNotFoundError:\n            self._manual_login()\n\n    def _manual_login(self):\n        print(\"❌ Cookies not found, manual login required\")\n        self.driver.get(self.url)\n        input(\"Please complete login and press Enter to continue...\")\n        self._save_cookies()\n        self._post_login_flow()\n\n    def _save_cookies(self):\n        with open(self.cookies_file, \"wb\") as cookie_file:\n            cookies = [c for c in self.driver.get_cookies() if c['name'] not in ['passport_csrf_token']]\n            pickle.dump(cookies, cookie_file)\n        print(\"✅ Cookies saved successfully\")\n\n    def _post_login_flow(self):\n        self.go_to_data_center()\n        # 可根据需要解开下面这些注释\n        # self.close_all_popups()\n        # self.click_tgzp_tab()\n        # self.click_post_list_tab()\n        # self.input_start_date()\n        # self.input_end_date()\n        self.click_export_data_button()\n\n    def go_to_data_center(self):\n        print(\"🚀 Navigating to data center...\")\n        self.driver.get(self.data_center_url)\n        self.wait_for_page_ready()\n\n    def wait_for_page_ready(self, timeout=30):\n        WebDriverWait(self.driver, timeout).until(\n            lambda d: d.execute_script(\"return document.readyState\") == 'complete'\n        )\n        print(\"📄 Page loaded successfully\")\n\n    def close_all_popups(self):\n        print(\"🛡️ Starting popup defense mechanism\")\n        self._close_generic_popup([\"下一页\", \"立即体验\", \"我知道了\", \"完成\"])\n        self._try_close_popup((By.XPATH, \"//div[contains(@class,'banner-close')]\"), \"Floating ads\")\n        self._try_close_popup((By.XPATH, \"//div[contains(@class,'mask-close')]\"), \"Final modal\")\n\n    def _close_generic_popup(self, texts):\n        for text in texts:\n            locator = (By.XPATH, f\"//button[contains(.,'{text}')]\")\n            self._try_close_popup(locator, f\"Popup: {text}\")\n\n    def _try_close_popup(self, locator, name, timeout=8):\n        try:\n            btn = WebDriverWait(self.driver, timeout).until(EC.element_to_be_clickable(locator))\n            self.driver.execute_script(\"arguments[0].click();\", btn)\n            print(f\"✅ Closed {name}\")\n            return True\n        except:\n            print(f\"⏳ {name} not found or not clickable\")\n            return False\n\n    def click_tgzp_tab(self):\n        locator = (By.XPATH, \"//div[@id='semiTab1' and text()='投稿作品']\")\n        el = self.wait_for_element_clickable(locator)\n        if el:\n            el.click()\n            print(\"✅ 点击“投稿作品”成功\")\n\n    def click_post_list_tab(self):\n        locator = (By.XPATH, \"//span[contains(text(),'投稿列表')]\")\n        el = self.wait_for_element_clickable(locator)\n        if el:\n            el.click()\n            print(\"✅ 点击“投稿列表”成功\")\n\n    def input_start_date(self):\n        start_date_obj = max(datetime.now() - timedelta(days=90), datetime(2025, 3, 4))\n        start_date_str = start_date_obj.strftime(\"%Y-%m-%d\")\n\n        # 更稳妥的定位方法（用contains而非精确匹配）\n        locator = (By.XPATH, \"//div[contains(text(),'笔记发布时间')]/../..//input[@placeholder='开始时间']\")\n        \n        try:\n            el = WebDriverWait(self.driver, 30).until(EC.presence_of_element_located(locator))\n            print(f\"🔍 元素找到: tag={el.tag_name}, placeholder={el.get_attribute('placeholder')}\")\n\n            # 确保元素可见\n            self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center'});\", el)\n            time.sleep(1)\n            self.driver.execute_script(\"arguments[0].removeAttribute('readonly')\", el)\n\n            actions = ActionChains(self.driver)\n            actions.move_to_element(el).click().pause(0.5)\n            actions.key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).pause(0.2)\n            actions.send_keys(Keys.BACKSPACE).pause(0.2)\n            actions.send_keys(start_date_str).pause(0.2)\n            actions.send_keys(Keys.ENTER).perform()\n\n            print(f\"✅ 使用ActionChains设置开始日期成功：{start_date_str}\")\n        except Exception as e:\n            print(f\"❌ 使用ActionChains设置开始日期失败：{start_date_str}，错误：{e}\")\n\n    def input_end_date(self):\n        end_date_obj = datetime.now() - timedelta(days=1)\n        end_date_str = end_date_obj.strftime(\"%Y-%m-%d\")\n\n        locator = (By.XPATH, \"//div[contains(text(),'笔记发布时间')]/../..//input[@placeholder='结束时间']\")\n        \n        try:\n            el = WebDriverWait(self.driver, 30).until(EC.presence_of_element_located(locator))\n            print(f\"🔍 元素找到: tag={el.tag_name}, placeholder={el.get_attribute('placeholder')}\")\n\n            self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center'});\", el)\n            time.sleep(1)\n            self.driver.execute_script(\"arguments[0].removeAttribute('readonly')\", el)\n\n            actions = ActionChains(self.driver)\n            actions.move_to_element(el).click().pause(0.5)\n            actions.key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).pause(0.2)\n            actions.send_keys(Keys.BACKSPACE).pause(0.2)\n            actions.send_keys(end_date_str).pause(0.2)\n            actions.send_keys(Keys.ENTER).perform()\n\n            print(f\"✅ 使用ActionChains设置结束日期成功：{end_date_str}\")\n        except Exception as e:\n            print(f\"❌ 使用ActionChains设置结束日期失败：{end_date_str}，错误：{e}\")\n\n\n\n\n    def click_export_data_button(self):\n        # 新 XPath，更灵活匹配含“导出数据”的按钮\n        locator = (By.XPATH, \"//button[.//span[contains(.,'导出数据')]]\")\n        try:\n            self.wait_for_page_ready()\n            time.sleep(2)\n            button = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located(locator))\n            self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center'});\", button)\n            self.driver.execute_script(\"arguments[0].click();\", button)\n            print(\"✅ 点击“导出数据”成功\")\n        except Exception as e:\n            print(f\"❌ 未能成功点击“导出数据”按钮：{e}\")\n\n    def wait_for_element_clickable(self, locator, timeout=20):\n        try:\n            return WebDriverWait(self.driver, timeout).until(EC.element_to_be_clickable(locator))\n        except:\n            return None\n\n    def merge_and_cleanup_xlsx_files(self):\n        \"\"\"\n        查找下载目录下所有包含关键词的 Excel 文件，合并成一个 DataFrame，\n        同时保存合并后的 Excel 文件并删除单个文件。\n        返回合并后的 DataFrame（若没有数据则返回 None）。\n        \"\"\"\n        keyword = \"笔记列表明细表\"\n        all_files = glob.glob(os.path.join(self.download_path, f\"*{keyword}*.xlsx\"))\n\n        if not all_files:\n            print(\"⚠️ 没有找到任何包含关键字的 Excel 文件\")\n            return None\n\n        all_dfs = []\n        for file in all_files:\n            try:\n                # 跳过第一行（说明性提示），从第二行开始读取\n                df = pd.read_excel(file, skiprows=1)\n                df['来源文件'] = os.path.basename(file)\n                all_dfs.append(df)\n            except Exception as e:\n                print(f\"❌ 读取失败：{file}，错误：{e}\")\n\n        if all_dfs:\n            result = pd.concat(all_dfs, ignore_index=True)\n            if '首次发布时间' in result.columns:\n                try:\n                    result['首次发布时间'] = pd.to_datetime(\n                        result['首次发布时间'].astype(str),\n                        format='%Y年%m月%d日%H时%M分%S秒',\n                        errors='coerce'\n                    ).dt.strftime('%Y-%m-%d')\n                    print(\"✅ 成功格式化“首次发布时间”为 YYYY-MM-DD\")\n                except Exception as e:\n                    print(f\"⚠️ 格式化“首次发布时间”失败：{e}\")\n                    \n            output_path = os.path.join(self.download_path, \"汇总笔记列表明细表.xlsx\")\n            result.to_excel(output_path, index=False)\n            print(f\"✅ 汇总成功，已保存：{output_path}\")\n\n            for file in all_files:\n                # 跳过最终合并输出文件\n                if os.path.basename(file) == os.path.basename(output_path):\n                    continue\n                try:\n                    os.remove(file)\n                    print(f\"🗑️ 已删除文件：{file}\")\n                except Exception as e:\n                    print(f\"❌ 删除失败：{file}，错误：{e}\")\n            return result\n        else:\n            print(\"⚠️ 没有可用的数据进行汇总\")\n            return None\n\n    @classmethod\n    def process_all_accounts(cls, cookie_list):\n        \"\"\"\n        处理多个账号：\n        1. 根据传入的 cookie_list 和当前脚本目录，依次初始化 Xhs 实例并运行 run() 方法；\n        2. 最后调用 merge_and_cleanup_xlsx_files() 合并所有下载的 Excel 文件，\n           返回合并后的 DataFrame。\n        \"\"\"\n        base_dir = os.path.dirname(os.path.abspath(__file__))\n        for cookie_file in cookie_list:\n            print(f\"\\n================ 处理：{cookie_file} ================\\n\")\n            full_path = os.path.join(base_dir, cookie_file)\n            account = cls(url=\"https://creator.xiaohongshu.com/statistics/data-analysis\", cookies_file=full_path)\n            account.run()\n        # 调用一个临时实例来执行合并方法（下载目录为统一配置）\n        merged_instance = cls(url=\"https://creator.xiaohongshu.com/statistics/data-analysis\", cookies_file=\"\")  \n        df = merged_instance.merge_and_cleanup_xlsx_files()\n        return df\n\n# ==========================\n# 主程序入口（调用 process_all_accounts 即可）\n# ==========================\n\nif __name__ == \"__main__\":\n    # 调用 process_all_accounts 方法处理所有账号并返回合并后的 DataFrame\n    final_df = Xhs.process_all_accounts(xhs_cookie_list)\n    if final_df is not None:\n        print(\"✅ 最终合并的 DataFrame：\")\n        print(final_df.head())\n    else:\n        print(\"⚠️ 未能生成合并的 DataFrame\")\n"
  },
  {
    "path": "utils/init_path.py",
    "content": "import sys\nfrom pathlib import Path\n\ndef setup_project_root():\n    \"\"\"\n    自动将项目根目录添加到 sys.path，确保可以导入项目模块（如 project_config）。\n    \"\"\"\n    current_file = Path(__file__).resolve()\n    project_root = current_file.parent.parent  # 即 XHS_DOUYIN_CONTENT 路径\n    sys_path_strs = [str(p) for p in sys.path]\n    if str(project_root) not in sys_path_strs:\n        sys.path.insert(0, str(project_root))\n        print(f\"✅ 添加项目路径: {project_root}\")\n    else:\n        print(f\"✅ 路径已存在: {project_root}\")\n\n"
  }
]