[
  {
    "path": ".gitignore",
    "content": "__pycache__/\n.idea/\n/deepbnb/settings.py\n/env\n/results/*\n*.csv\n*.xlsx\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://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 <http://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    {project}  Copyright (C) {year}  {fullname}\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<http://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<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Airbnb Scraper: Advanced Airbnb Search using Scrapy\n\n## Disclaimer: No longer maintained\n\n### This project is not currently maintained, due to difficulty in using scrapy to make requests to the Airbnb API. Project is on hold until further notice. Currently exploring a simpler approach here: https://github.com/JoeBashe/stl-scraper\n\nUse Airbnb's unofficial API to efficiently search for rental properties.\nRegex matching, ranged search, open matched properties in a browser, save to CSV, xlsx, or ElasticSearch (alpha).\n\n## Notes\n\n- Airbnb's API is subject to change at any moment, which would break this scraper. They've already changed it several\n  times in the past. Also, using this probably violates their TOS. Please only use for educational or research purposes.\n- The scraper was recently updated to work with Airbnb's new v3 GraphQL API. Some features are still being updated.\n- If you get 403 Forbidden errors when running this scraper, try browsing the Airbnb site in your web browser from the\n  same computer first, then try running the script again.\n\n## Requirements\n\n* **Python 3.10+**\n* [Scrapy](http://scrapy.org/)\n* [openpyxl](https://openpyxl.readthedocs.io/en/default/#installation)\n* ElasticSearch 7+ if using elasticsearch pipeline\n* see [requirements.txt](requirements.txt) for details\n\n## Installation (nix)\n\n```bash\n# Create venv\npython3.10 -m venv env\n\n# Enable venv\n. env/bin/activate\n\n# Install required packages\npip install -Ur requirements.txt\n\n# Create settings.py\ncp deepbnb/settings.py.dist deepbnb/settings.py\n\n# @NOTE: Don't forget to set AIRBNB_API_KEY in settings.py. To find your API key, \n# search Airbnb using Chrome, open dev tools, and look for to the url parameter  \n# named \"key\" in async requests to /api/v2/explore_tabs under the Network tab.\n```\n\n## Configuration\n\nEdit `deepbnb/settings.py` for settings. I've created some custom settings which are\ndocumented [below](https://github.com/digital-engineering/airbnb-scraper#settings). The rest are documented\nin https://docs.scrapy.org/en/latest/topics/settings.html.\n\n## Example Usage\n\n#### Minimal scraper usage:\n\n    scrapy crawl airbnb -a query=\"Colorado Springs, CO\" -o colorado_springs.csv\n\n#### Advanced examples:\n\n##### Madrid, fixed dates\n\n```\nscrapy crawl airbnb \\\n    -a query=\"Madrid, Spain\" \\\n    -a checkin=2023-10-01 \\\n    -a checkout=2023-11-30 \\\n    -a max_price=1900 \\\n    -a min_price=1800 \\\n    -a neighborhoods=\"Acacias,Almagro,Arganzuela,Argüelles,Centro,Cortes,Embajadores,Imperial,Jerónimos,La Latina,Malasaña,Moncloa,Palacio,Recoletos,Retiro,Salamanca,Sol\" \\\n    -s MUST_HAVE=\"(atico|attic|balcon|terra|patio|outdoor|roof|view)\" \\\n    -s CANNOT_HAVE=\"studio\" \\\n    -s MINIMUM_WEEKLY_DISCOUNT=20 \\\n    -s WEB_BROWSER=\"/usr/bin/chromium\" \\\n    -o madrid.xlsx\n```\n\n##### New York ranged date search\n\n```\nscrapy crawl airbnb \\\n    -a query=\"New York, NY\" \\\n    -a checkin=\"2023-01-22+7-0\" \\\n    -a checkout=\"2023-02-22+14-3\" \\\n    -a max_price=1800 \\\n    -s CANNOT_HAVE=\"guest suite\" \\\n    -s MUST_HAVE=\"(walking distance|short walk|no car needed|walk everywhere|metro close|public transport)\" \\\n    -o newyork.csv\n```\n\n## Ranged date queries\n\nIf you have flexible checkin / checkout dates, use the ranged search feature to search a range of checkin / checkout\ndates.\n\n### Search checkin date range +5 days -2 days\n\n    scrapy crawl airbnb \\\n        -a query=\"Minneapolis, MN\" \\\n        -a checkin=\"2023-10-15+5-2\" \\\n        -a checkout=\"2023-11-15\" \\\n        -o minneapolis.csv\n\nThis search would look for rentals in Minneapolis using Oct 15 2023 as base check-in date, and also searching for\nrentals available for check-in 2 days before, up to 5 days after. In other words, check-ins from Oct 13 to Oct 20. This\nis specified by the string `+5-2` appended to the checkin date `2023-10-15+5-2`. The string must always follow the\npattern`+[days_after]-[days_before]` unless `[days_after]` and `[days_before]` are equal, in which case you can\nuse `+-[days]`. The numbers may be any integer 0 or greater (large numbers untested).\n\n### Search checkin date +5 days -2 days, checkout date + or - 3 days\n\n    scrapy crawl airbnb \\\n        -a query=\"Florence, Italy\" \\\n        -a checkin=\"2023-10-15+5-2\" \\\n        -a checkout=\"2023-11-15+-3\" \\\n        -o firenze.csv\n\n## Scraping Description\n\nAfter running the crawl command, the scraper will start. It will first run the\nsearch query, then determine the quantity of result pages, and finally iterate\nthrough each of those, scraping each of the property listings on each page.\n\nScraped items (listings) will be passed to the default item pipeline, where,\noptionally, the `description`, `name`, and `reviews.description` fields will\nbe filtered using either or both of the `CANNOT_HAVE` and `MUST_HAVE` regexes.\nFiltered items will be dropped. Accepted items can be optionally opened in a\ngiven web browser, so that you can easily view your search results.\n\nFinally, the output can be saved to an xlsx format file for additional\nfiltering, sorting, and inspection.\n\n## Parameters\n\nYou can find the values for these by first doing a search manually on the\nAirbnb site.\n\n* `query`: City and State to search. **(required)**\n* `checkin`, `checkout`: Check-in and Check-out dates.\n* `min_price`, `max_price`: Minimum and maximum price for the period.\n  *The Airbnb search algorithm calculates this based upon search length.\n  It will be either the daily or monthly price, depending on the length\n  of the stay.*\n* `neighborhoods`: Comma-separated list of neighborhoods within the city\n  to filter for.\n* `output`: Name of output file. Only `xlsx` output is tested.\n\n## Settings\n\nThese settings can be edited in the `settings.py` file, or appended to the\ncommand line using the `-s` flag as in the example above.\n\n* `CANNOT_HAVE=\"<cannot-have-regex>\"`  \n  Don't accept listings that match the given regex pattern.\n  **(optional)**\n\n\n* `FIELDS_TO_EXPORT=\"['field1', 'field2', ...]\"`  \n  Can be found in settings.py. Contains a list of all possible fields to\n  export, i.e. all fields of `AirbnbScraperItem`. Comment items to\n  remove undesired fields from output. Applies only to `xlsx` output.\n\n\n* `MINIMUM_MONTHLY_DISCOUNT=30`  \n  Minimum monthly discount.\n  **(optional)**\n\n\n* `MINIMUM_WEEKLY_DISCOUNT=25`  \n  Minimum weekly discount.\n  **(optional)**\n\n\n* `MUST_HAVE=\"(<must-have-regex>)\"`  \n  Only accept listings that match the given regex pattern.\n  **(optional)**\n\n\n* `ROOM_TYPES=\"['Camper/RV', 'Campsite', 'Entire guest suite']\"`  \n  Room Types to filter.\n  **(optional)**\n\n\n* `SKIP_LIST=\"['12345678', '12345679', '12345680']\"`  \n  Property IDs to filter.\n  **(optional)**\n\n\n* `WEB_BROWSER=\"/path/to/browser %s\"`  \n  Web browser executable command. **(optional)**\n\n  *Examples*:\n    - MacOS  \n      `WEB_BROWSER=\"open -a /Applications/Google\\ Chrome.app\"`\n\n    - Windows  \n      `WEB_BROWSER=\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\"`\n\n    - Linux  \n      `WEB_BROWSER=\"/usr/bin/google-chrome\"`\n\n## Elasticsearch\n\nEnable `deepbnb.pipelines.ElasticBnbPipeline` in `settings.py`\n\n## Credits\n\n- This project was originally inspired by [this excellent blog post](http://www.verginer.eu/blog/web-scraping-airbnb/)\n  by Luca Verginer.\n- In converting this to use the unofficial API, https://stevesie.com/apps/airbnb-api was very helpful.\n- [This analysis of Bali Airbnbs](https://github.com/daben/m2851-prac1) provided inspiration for more eloquent code.\n"
  },
  {
    "path": "deepbnb/__init__.py",
    "content": ""
  },
  {
    "path": "deepbnb/api/ApiBase.py",
    "content": "import json\n\nfrom abc import abstractmethod, ABC\nfrom logging import LoggerAdapter\nfrom scrapy.http import Response\nfrom urllib.parse import urlencode, urlunparse\n\n\nclass ApiBase(ABC):\n\n    def __init__(self, api_key: str, logger: LoggerAdapter, currency: str):\n        self._api_key = api_key\n        self._currency = currency\n        self._logger = logger\n\n    @abstractmethod\n    def api_request(self, **kwargs):\n        raise NotImplementedError(f'{self.__class__.__name__}.api_request method is not defined')\n\n    @staticmethod\n    def build_airbnb_url(path, query=None):\n        if query is not None:\n            query = urlencode(query)\n\n        return urlunparse(['https', 'www.airbnb.com', path, None, query, None])\n\n    @property\n    def api_key(self):\n        return self._api_key\n\n    @staticmethod\n    def _put_json_param_strings(query: dict):\n        \"\"\"Property format JSON strings for 'variables' & 'extensions' params.\"\"\"\n        query['variables'] = json.dumps(query['variables'], separators=(',', ':'))\n        query['extensions'] = json.dumps(query['extensions'], separators=(',', ':'))\n\n    def read_data(self, response: Response):\n        \"\"\"Read response data as json\"\"\"\n        self._logger.debug(f\"Parsing {response.url}\")\n        data = json.loads(response.body)\n\n        return data\n\n    def _get_search_headers(self, response=None) -> dict:\n        \"\"\"Get headers for search requests.\"\"\"\n        headers = {\n            'Accept':           '*/*',\n            'Accept-Encoding':  'gzip,deflate',\n            'Connection':       'keep-alive',\n            'User-Agent':       'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',\n            'X-Airbnb-Api-Key': self._api_key\n        }\n        if response:\n            headers['Cookie'] = str(response.headers.get('Set-Cookie'))\n\n        return headers\n"
  },
  {
    "path": "deepbnb/api/ExploreSearch.py",
    "content": "import json\nimport scrapy\nimport re\n\nfrom datetime import date, timedelta\nfrom logging import LoggerAdapter\nfrom scrapy import Spider\nfrom urllib.parse import parse_qs, urlparse\n\nfrom deepbnb.api.ApiBase import ApiBase\n\n\nclass ExploreSearch(ApiBase):\n    \"\"\"Airbnb API v3 Search Endpoint\"\"\"\n\n    def __init__(\n            self,\n            api_key: str,\n            logger: LoggerAdapter,\n            currency: str,\n            spider: Spider,\n            room_types: list,\n            geography: dict,\n            query: str\n    ):\n        super().__init__(api_key, logger, currency)\n        self.__geography = geography\n        self.__room_types = room_types\n        self.__query = query\n        self.__spider = spider\n\n    @staticmethod\n    def add_search_params(params, response):\n        parsed_qs = parse_qs(urlparse(response.request.url).query)\n        variables = json.loads(parsed_qs['variables'][0])['request']\n        if 'checkin' in variables:\n            params['checkin'] = variables['checkin']\n            params['checkout'] = variables['checkout']\n\n        if 'priceMax' in variables:\n            params['priceMax'] = variables['priceMax']\n\n        if 'priceMin' in variables:\n            params['priceMin'] = variables['priceMin']\n\n        if 'ne_lat' in parsed_qs:\n            params['ne_lat'] = parsed_qs['ne_lat'][0]\n\n        if 'ne_lng' in parsed_qs:\n            params['ne_lng'] = parsed_qs['ne_lng'][0]\n\n        if 'sw_lat' in parsed_qs:\n            params['sw_lat'] = parsed_qs['sw_lat'][0]\n\n        if 'sw_lng' in parsed_qs:\n            params['sw_lng'] = parsed_qs['sw_lng'][0]\n\n    def api_request(self, query, params=None, callback=None, response=None, headers=None):\n        \"\"\"Perform API request.\"\"\"\n        request = response.follow if response else scrapy.Request\n        callback = callback or self.__spider.parse\n        url = self._get_url(query, params)\n        search_headers = self._get_search_headers(response)\n        headers = headers | search_headers if headers else search_headers\n        return request(url, callback, headers=headers, meta={'playwright': True}, cb_kwargs={'headers': headers})\n\n    def get_paginated_search_params(self, response, data):\n        \"\"\"Consolidate search parameters and return result.\"\"\"\n        metadata = data['data']['dora']['exploreV3']['metadata']\n        pagination = metadata['paginationMetadata']\n        filter_state = data['data']['dora']['exploreV3']['filters']['state']\n\n        place_id = self.__geography.get('place_id', metadata['geography']['placeId'])\n        query = [fs['value']['stringValue'] for fs in filter_state if fs['key'] == 'query'][0]\n\n        params = {'placeId': place_id, 'query': query}\n        if pagination['hasNextPage']:\n            params['lastSearchSessionId'] = pagination['searchSessionId']\n\n        self.add_search_params(params, response)\n\n        return params\n\n    def parse_landing_page(self, response):\n        \"\"\"Parse search response and generate URLs for all searches, then perform them.\"\"\"\n        self._logger.debug(f\"Parsing {response.url}\")\n        json_response = response.xpath('body/pre/text()').get()  # remove html wrapper\n        data = json.loads(json_response)\n        search_params = self.get_paginated_search_params(response, data)\n\n        self.__geography.update(data['data']['dora']['exploreV3']['metadata']['geography'])\n        self._logger.info(f\"Geography:\\n{self.__geography}\")\n\n        yield self.api_request(self.__query, search_params, self.__spider.parse, response)\n\n    def perform_checkin_start_requests(\n            self,\n            checkin: str,\n            checkout: str,\n            checkin_range_spec: str,\n            checkout_range_spec: str,\n            params: dict\n    ):\n        \"\"\"Perform requests for start URLs.\n\n        :param checkin:\n        :param checkout:\n        :param checkin_range_spec:\n        :param checkout_range_spec:\n        :param params:\n        :return:\n        \"\"\"\n        # single request for static start and end dates\n        if not (checkin_range_spec or checkout_range_spec):  # simple start and end date\n            params['checkin'] = checkin\n            params['checkout'] = checkout\n            yield self.api_request(self.__query, params, self.parse_landing_page)\n\n        # multi request for dynamic start and static end date\n        if checkin_range_spec and not checkout_range_spec:  # ranged start date, single end date, iterate over checkin range\n            checkin_start_date, checkin_range = self._build_date_range(checkin, checkin_range_spec)\n            for i in range(checkin_range.days + 1):  # + 1 to include end date\n                params['checkin'] = str(checkin_start_date + timedelta(days=i))\n                params['checkout'] = checkout\n                yield self.api_request(self.__query, params, self.parse_landing_page)\n\n        # multi request for static start and dynamic end date\n        if checkout_range_spec and not checkin_range_spec:  # ranged end date, single start date, iterate over checkout range\n            checkout_start_date, checkout_range = self._build_date_range(checkout, checkout_range_spec)\n            for i in range(checkout_range.days + 1):  # + 1 to include end date\n                params['checkout'] = str(checkout_start_date + timedelta(days=i))\n                params['checkin'] = checkin\n                yield self.api_request(self.__query, params, self.parse_landing_page)\n\n        # double nested multi request, iterate over both start and end date ranges\n        if checkout_range_spec and checkin_range_spec:\n            checkin_start_date, checkin_range = self._build_date_range(checkin, checkin_range_spec)\n            checkout_start_date, checkout_range = self._build_date_range(checkout, checkout_range_spec)\n            for i in range(checkin_range.days + 1):  # + 1 to include end date\n                params['checkin'] = str(checkin_start_date + timedelta(days=i))\n                for j in range(checkout_range.days + 1):  # + 1 to include end date\n                    params['checkout'] = str(checkout_start_date + timedelta(days=j))\n                    yield self.api_request(self.__query, params, self.parse_landing_page)\n\n    @staticmethod\n    def _build_date_range(iso_date: str, range_spec: str):\n        \"\"\"Calculate start and end dates for a range. Return start date and timedelta for number of days.\"\"\"\n        base_date = date.fromisoformat(iso_date)\n        if range_spec.startswith('+-'):  # +-7\n            days = float(re.match(r'\\+-(\\d+)', range_spec).group(1))\n            start_date = base_date - timedelta(days=days)\n            end_date = base_date + timedelta(days=days)\n        else:  # +0-3\n            result = re.match(r'\\+(\\d+)-(\\d+)', range_spec)\n            post_days = float(result.group(1))\n            pre_days = float(result.group(2))\n            start_date = base_date - timedelta(days=pre_days)\n            end_date = base_date + timedelta(days=post_days)\n\n        return start_date, end_date - start_date\n\n    def _get_url(self, search_string: str, params: dict = None):\n        _api_path = '/api/v3/ExploreSearch'\n        query = {\n            'operationName': 'ExploreSearch',\n            'locale':        'en',\n            'currency':      self._currency,\n            '_cb':           'ld7rar1fhh6if',\n        }\n        data = {\n            'variables':  {\n                'request': {\n                    'metadataOnly':          False,\n                    'version':               '1.7.9',\n                    'itemsPerGrid':          20,\n                    'tabId':                 'home_tab',\n                    'refinementPaths':       ['/homes'],\n                    'source':                'structured_search_input_header',\n                    'searchType':            'filter_change',\n                    'query':                 search_string,\n                    # 'roomTypes':             self.__room_types,\n                    'cdnCacheSafe':          False,\n                    'simpleSearchTreatment': 'simple_search_only',\n                    'treatmentFlags':        [\n                        'simple_search_1_1',\n                        'simple_search_desktop_v3_full_bleed',\n                        'flexible_dates_options_extend_one_three_seven_days'\n                    ],\n                    'screenSize':            'large'\n                }\n            },\n            'extensions': {\n                'persistedQuery': {\n                    'version':    1,\n                    'sha256Hash': '13aa9971e70fbf5ab888f2a851c765ea098d8ae68c81e1f4ce06e2046d91b6ea'\n                }\n            }\n        }\n        if params:\n            data['variables']['request'] |= params\n\n        self._put_json_param_strings(data)\n\n        url = self.build_airbnb_url(_api_path, query)\n        url += '&variables=%s' % data['variables']\n        url += '&extensions=%s' % data['extensions']\n\n        return url\n"
  },
  {
    "path": "deepbnb/api/PdpPlatformSections.py",
    "content": "import lxml.html\nimport re\nimport scrapy\n\nfrom typing import Union\nfrom logging import LoggerAdapter\n\nfrom deepbnb.api.ApiBase import ApiBase\nfrom deepbnb.api.PdpReviews import PdpReviews\nfrom deepbnb.items import DeepbnbItem\n\n\nclass PdpPlatformSections(ApiBase):\n    \"\"\"Airbnb API v3 Property Display Endpoint\"\"\"\n\n    # Unused. This is just a list of sections where we presently pull data from. (@see `parse_listing_contents()`)\n    SECTION_IDS = [\n        'AMENITIES_DEFAULT',\n        'DESCRIPTION_DEFAULT',\n        'HOST_PROFILE_DEFAULT',\n        'LOCATION_DEFAULT',\n        'POLICIES_DEFAULT',\n    ]\n\n    def __init__(\n            self,\n            api_key: str,\n            logger: LoggerAdapter,\n            currency: str,\n            data_cache: dict,\n            geography: dict,\n            pdp_reviews: PdpReviews\n    ):\n        super().__init__(api_key, logger, currency)\n        self.__data_cache = data_cache\n        self.__geography = geography\n        self.__regex_amenity_id = re.compile(r'^([a-z0-9]+_)+([0-9]+)_')\n        self.__pdp_reviews = pdp_reviews\n\n    def api_request(self, listing_id: str):\n        \"\"\"Generate scrapy.Request for listing page.\"\"\"\n        _api_path = '/api/v3/PdpPlatformSections'\n        query = {\n            'operationName': 'PdpPlatformSections',\n            'locale':        'en',\n            'currency':      self._currency,\n            'variables':     {\n                'request': {\n                    'id':                            listing_id,\n                    'layouts':                       ['SIDEBAR', 'SINGLE_COLUMN'],\n                    'pdpTypeOverride':               None,\n                    'translateUgc':                  None,\n                    'preview':                       False,\n                    'bypassTargetings':              False,\n                    'displayExtensions':             None,\n                    'adults':                        '1',\n                    'children':                      None,\n                    'infants':                       None,\n                    'causeId':                       None,\n                    'disasterId':                    None,\n                    'priceDropSource':               None,\n                    'promotionUuid':                 None,\n                    'selectedCancellationPolicyId':  None,\n                    'forceBoostPriorityMessageType': None,\n                    'privateBooking':                False,\n                    'invitationClaimed':             False,\n                    'discountedGuestFeeVersion':     None,\n                    'staysBookingMigrationEnabled':  False,\n                    'useNewSectionWrapperApi':       False,\n                    'previousStateCheckIn':          None,\n                    'previousStateCheckOut':         None,\n                    'federatedSearchId':             None,\n                    'interactionType':               None,\n                    'searchId':                      None,\n                    'sectionIds':                    None,\n                    'checkIn':                       None,\n                    'checkOut':                      None,\n                    'p3ImpressionId':                'p3_1608841700_z2VzPeybmBEdZG20'\n                }\n            },\n            'extensions':    {\n                'persistedQuery': {\n                    'version':    1,\n                    'sha256Hash': '625a4ba56ba72f8e8585d60078eb95ea0030428cac8772fde09de073da1bcdd0'\n                }\n            }\n        }\n\n        self._put_json_param_strings(query)\n        url = self.build_airbnb_url(_api_path, query)\n\n        return scrapy.Request(url, callback=self.parse_listing_contents, headers=self._get_search_headers())\n\n    def parse_listing_contents(self, response):\n        \"\"\"Obtain data from an individual listing page, combine with cached data, and return DeepbnbItem.\"\"\"\n        # Collect base data\n        data = self.read_data(response)\n        pdp_sections = data['data']['merlin']['pdpSections']\n        listing_id = pdp_sections['id']\n        sections = pdp_sections['sections']\n        metadata = pdp_sections['metadata']\n        logging_data = metadata['loggingContext']['eventDataLogging']\n\n        # Get sections\n        amenities_section = [s for s in sections if s['sectionId'] == 'AMENITIES_DEFAULT'][0]['section']\n        description_section = [s for s in sections if s['sectionId'] == 'DESCRIPTION_DEFAULT'][0]['section']\n        host_profile = [s for s in sections if s['sectionId'] == 'HOST_PROFILE_DEFAULT'][0]['section']\n        location = [s for s in sections if s['sectionId'] == 'LOCATION_DEFAULT'][0]['section']\n        policies = [s for s in sections if s['sectionId'] == 'POLICIES_DEFAULT'][0]['section']\n\n        # Collect amenity data\n        amenities_groups = amenities_section['seeAllAmenitiesGroups']\n        amenities_access = [g['amenities'] for g in amenities_groups if g['title'] == 'Guest access']\n        amenities_avail = [amenity for g in amenities_groups for amenity in g['amenities'] if amenity['available']]\n\n        # Structure data\n        listing_data_cached = self.__data_cache[listing_id]\n        item = DeepbnbItem(\n            id=listing_id,\n            access=self._render_titles(amenities_access[0]) if amenities_access else None,\n            additional_house_rules=policies['additionalHouseRules'],\n            allows_events='No parties or events' in [r['title'] for r in policies['houseRules']],\n            amenities=self._render_titles(amenities_avail, sep=' - ', join=False),\n            amenity_ids=list(self._get_amenity_ids(amenities_avail)),\n            avg_rating=listing_data_cached['avg_rating'],\n            bathrooms=listing_data_cached['bathrooms'],\n            bedrooms=listing_data_cached['bedrooms'],\n            beds=listing_data_cached['beds'],\n            business_travel_ready=listing_data_cached['business_travel_ready'],\n            city=listing_data_cached.get('city', self.__geography['city']),\n            country=self.__geography['country'],\n            description=self._html_to_text(\n                description_section['htmlDescription']['htmlText']\n            ) if description_section.get('htmlDescription') else None,\n            host_id=listing_data_cached['host_id'],\n            house_rules=[r['title'] for r in policies['houseRules']],\n            is_hotel=metadata['bookingPrefetchData']['isHotelRatePlanEnabled'],\n            latitude=listing_data_cached['latitude'],\n            listing_expectations=self._render_titles(policies['listingExpectations']) if policies else None,\n            longitude=listing_data_cached['longitude'],\n            # max_nights=listing.get('max_nights'),\n            # min_nights=listing['min_nights'],\n            monthly_price_factor=listing_data_cached['monthly_price_factor'],\n            name=listing_data_cached.get('name', listing_id),\n            neighborhood_overview=listing_data_cached.get('neighborhood_overview'),\n            # notes=listing['sectioned_description']['notes'],\n            person_capacity=listing_data_cached['person_capacity'],\n            photo_count=listing_data_cached['photo_count'],\n            photos=listing_data_cached['photos'],\n            place_id=self.__geography['placeId'],\n            price_rate=listing_data_cached['price_rate'],\n            price_rate_type=listing_data_cached['price_rate_type'],\n            province=self.__geography.get('province'),\n            rating_accuracy=logging_data['accuracyRating'],\n            rating_checkin=logging_data['checkinRating'],\n            rating_cleanliness=logging_data['cleanlinessRating'],\n            rating_communication=logging_data['communicationRating'],\n            rating_location=logging_data['locationRating'],\n            rating_value=logging_data['valueRating'],\n            review_count=listing_data_cached['review_count'],\n            reviews=self.__pdp_reviews.api_request(listing_id, 50),\n            room_and_property_type=listing_data_cached['room_and_property_type'],\n            room_type=listing_data_cached['room_type'],\n            room_type_category=listing_data_cached['room_type_category'],\n            satisfaction_guest=logging_data['guestSatisfactionOverall'],\n            star_rating=listing_data_cached['star_rating'],\n            state=self.__geography['state'],\n            # summary=listing['sectioned_description']['summary'],\n            total_price=listing_data_cached['total_price'],\n            url=\"https://www.airbnb.com/rooms/{}\".format(listing_id),\n            weekly_price_factor=listing_data_cached['weekly_price_factor']\n        )\n\n        self._get_detail_property(item, 'transit', 'Getting around', location['seeAllLocationDetails'], 'content')\n        self._get_detail_property(item, 'interaction', 'During your stay', host_profile['hostInfos'], 'html')\n\n        return item\n\n    @staticmethod\n    def _html_to_text(html: str) -> str:\n        \"\"\"Get plaintext from HTML.\"\"\"\n        return lxml.html.document_fromstring(html).text_content()\n\n    @staticmethod\n    def _render_titles(title_list: list, sep: str = ': ', join=True) -> Union[str, list]:\n        \"\"\"Render list of objects with titles and subtitles into string.\"\"\"\n        lines = []\n        for t in title_list:\n            line = '{}{}{}'.format(t['title'], sep, t['subtitle']) if t.get('subtitle') else t.get('title')\n            lines.append(line)\n\n        return '\\n'.join(lines) if join else lines\n\n    def _get_amenity_ids(self, amenities: list):\n        \"\"\"Extract amenity id from `id` string field.\"\"\"\n        for amenity in amenities:\n            match = self.__regex_amenity_id.match(amenity['id'])\n            yield int(match.group(match.lastindex))\n\n    def _get_detail_property(self, item, prop, title, prop_list, key):\n        \"\"\"Search for matching title in property list for prop. If exists, add htmlText for key to item.\"\"\"\n        if title in [i['title'] for i in prop_list]:\n            item[prop] = self._html_to_text([i[key]['htmlText'] for i in prop_list if i['title'] == title][0])\n"
  },
  {
    "path": "deepbnb/api/PdpReviews.py",
    "content": "import json\nimport requests\nimport scrapy\n\nfrom urllib.parse import urlparse, parse_qs\n\nfrom deepbnb.api.ApiBase import ApiBase\n\n\nclass PdpReviews(ApiBase):\n    \"\"\"Airbnb API v3 Reviews Endpoint\"\"\"\n\n    def api_request(self, listing_id: str, limit: int = 7, start_offset: int = 0):\n        \"\"\"Perform API request.\"\"\"\n        # get first batch of reviews\n        reviews, n_reviews_total = self._get_reviews_batch(listing_id, limit, start_offset)\n\n        # get any additional batches\n        start_idx = start_offset + limit\n        for offset in range(start_idx, n_reviews_total, limit):\n            r, _ = self._get_reviews_batch(listing_id, limit, offset)\n            reviews.extend(r)\n\n        return reviews\n\n    def _get_reviews_batch(self, listing_id: str, limit: int, offset: int):\n        \"\"\"Get reviews for a given listing ID in batches.\"\"\"\n        url = self._get_url(listing_id, limit, offset)\n        headers = self._get_search_headers()\n        response = requests.get(url, headers=headers)\n        data = json.loads(response.text)\n        pdp_reviews = data['data']['merlin']['pdpReviews']\n        n_reviews_total = int(pdp_reviews['metadata']['reviewsCount'])\n        reviews = [{\n            'comments':   r['comments'],\n            'created_at': r['createdAt'],\n            'language':   r['language'],\n            'rating':     r['rating'],\n            'response':   r['response'],\n        } for r in pdp_reviews['reviews']]\n\n        return reviews, n_reviews_total\n\n    def _get_url(self, listing_id: str, limit: int = 7, offset: int = None) -> str:\n        _api_path = '/api/v3/PdpReviews'\n        query = {\n            'operationName': 'PdpReviews',\n            'locale':        'en',\n            'currency':      self._currency,\n            'variables':     {\n                'request': {\n                    'fieldSelector':    'for_p3',\n                    'limit':            limit,\n                    'listingId':        listing_id,\n                    'numberOfAdults':   '1',\n                    'numberOfChildren': '0',\n                    'numberOfInfants':  '0'\n                }\n            },\n            'extensions':    {\n                'persistedQuery': {\n                    'version':    1,\n                    'sha256Hash': '4730a25512c4955aa741389d8df80ff1e57e516c469d2b91952636baf6eee3bd'\n                }\n            }\n        }\n\n        if offset:\n            query['variables']['request']['offset'] = offset\n\n        self._put_json_param_strings(query)\n\n        return self.build_airbnb_url(_api_path, query)\n\n    def _parse_reviews(self, response):\n        # parse qs\n        parsed = urlparse(response.request.url)\n        parsed_qs = parse_qs(parsed.query)\n        variables = json.loads(parsed_qs['variables'][0])\n\n        # extract data\n        listing_id = variables['request']['listingId']\n        limit = variables['request']['limit']\n        offset = variables['request'].get('offset', 0)\n        data = self.read_data(response)\n        pdp_reviews = data['data']['merlin']['pdpReviews']\n        n_reviews_total = int(pdp_reviews['metadata']['reviewsCount'])\n\n        if offset == 0:  # get all other reviews\n            for offset in range(limit, n_reviews_total, limit):\n                url = self._get_url(listing_id, limit, offset)\n                yield scrapy.Request(url, callback=self._parse_reviews, headers=self._get_search_headers())\n\n        # return distilled review\n        yield from ({\n            'comments':   r['comments'],\n            'created_at': r['createdAt'],\n            'language':   r['language'],\n            'rating':     r['rating'],\n            'response':   r['response'],\n        } for r in pdp_reviews['reviews'])\n"
  },
  {
    "path": "deepbnb/api/__init__.py",
    "content": ""
  },
  {
    "path": "deepbnb/exporter.py",
    "content": "import openpyxl\n\nfrom scrapy.exporters import BaseItemExporter\n\n\nclass XlsxItemExporter(BaseItemExporter):\n    \"\"\"Export items to Excel spreadsheet.\"\"\"\n\n    def __init__(self, file, include_headers_line=True, join_multivalued=',', **kwargs):\n        \"\"\"Class constructor.\"\"\"\n        # fields_to_export = settings.get('FIELDS_TO_EXPORT', [])\n        # if fields_to_export:\n        #     kwargs['fields_to_export'] = fields_to_export\n\n        super().__init__(**kwargs)\n\n        self.include_headers_line = include_headers_line\n        self._workbook = openpyxl.workbook.Workbook()\n        self._worksheet = self._workbook.active\n        self._headers_not_written = True\n        self._join_multivalued = join_multivalued\n        self._filename = file.name\n        file.close()\n\n    def export_item(self, item):\n        if self._headers_not_written:\n            self._headers_not_written = False\n            self._write_headers_and_set_fields_to_export(item)\n\n        # Make name into a hyperlink\n        item['name'] = '=HYPERLINK(\"https://www.airbnb.com/rooms/{}\", \"{}\")'.format(\n            item['id'], item.get('name', item['id'])),\n\n        fields = self._get_serialized_fields(item, default_value='', include_empty=True)\n        values = tuple(self._build_row(x for _, x in fields))\n        self._worksheet.append(values)\n\n    def finish_exporting(self):\n        self._workbook.save(self._filename)\n\n    def serialize_field(self, field, name, value):\n        serializer = field.get('serializer', self._join_if_needed)\n        return serializer(value)\n\n    @staticmethod\n    def _build_row(values):\n        for s in values:\n            yield s\n\n    def _join_if_needed(self, value):\n        if isinstance(value, (list, tuple)):\n            try:\n                return self._join_multivalued.join(value)\n            except TypeError:  # list in value may not contain strings\n                pass\n        return value\n\n    def _write_headers_and_set_fields_to_export(self, item):\n        if self.include_headers_line:\n            if not self.fields_to_export:\n\n                if isinstance(item, dict):\n                    # for dicts try using fields of the first item\n                    self.fields_to_export = list(item.keys())\n                else:\n                    # use fields declared in Item\n                    self.fields_to_export = list(item.fields.keys())\n\n            row = tuple(self._build_row(self.fields_to_export))\n            self._worksheet.append(row)\n"
  },
  {
    "path": "deepbnb/items.py",
    "content": "# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\n\n\nclass DeepbnbItem(scrapy.Item):\n    # define the fields for your item here like:\n    # name = scrapy.Field()\n    access = scrapy.Field()\n    additional_house_rules = scrapy.Field()\n    allows_events = scrapy.Field()\n    amenities = scrapy.Field()\n    amenity_ids = scrapy.Field()\n    avg_rating = scrapy.Field()\n    bathrooms = scrapy.Field()\n    bedrooms = scrapy.Field()\n    beds = scrapy.Field()\n    business_travel_ready = scrapy.Field()\n    city = scrapy.Field()\n    country = scrapy.Field()\n    description = scrapy.Field()\n    host_id = scrapy.Field()\n    house_rules = scrapy.Field()\n    id = scrapy.Field()\n    interaction = scrapy.Field()\n    is_hotel = scrapy.Field()\n    latitude = scrapy.Field()\n    listing_expectations = scrapy.Field()\n    longitude = scrapy.Field()\n    monthly_price_factor = scrapy.Field()\n    name = scrapy.Field()\n    neighborhood_overview = scrapy.Field()\n    person_capacity = scrapy.Field()\n    photo_count = scrapy.Field()\n    photos = scrapy.Field()\n    place_id = scrapy.Field()\n    price_rate = scrapy.Field()\n    price_rate_type = scrapy.Field()\n    province = scrapy.Field()\n    rating_accuracy = scrapy.Field()\n    rating_checkin = scrapy.Field()\n    rating_cleanliness = scrapy.Field()\n    rating_communication = scrapy.Field()\n    rating_location = scrapy.Field()\n    rating_value = scrapy.Field()\n    review_count = scrapy.Field()\n    reviews = scrapy.Field()\n    room_and_property_type = scrapy.Field()\n    room_type = scrapy.Field()\n    room_type_category = scrapy.Field()\n    satisfaction_guest = scrapy.Field()\n    star_rating = scrapy.Field()\n    state = scrapy.Field()\n    total_price = scrapy.Field()\n    transit = scrapy.Field()\n    url = scrapy.Field()\n    weekly_price_factor = scrapy.Field()\n"
  },
  {
    "path": "deepbnb/middlewares.py",
    "content": "# -*- coding: utf-8 -*-\n\n# Define here the models for your spider middleware\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/spider-middleware.html\n\nfrom scrapy import signals\n\n\nclass DeepbnbSpiderMiddleware(object):\n    # Not all methods need to be defined. If a method is not defined,\n    # scrapy acts as if the spider middleware does not modify the\n    # passed objects.\n\n    @classmethod\n    def from_crawler(cls, crawler):\n        # This method is used by Scrapy to create your spiders.\n        s = cls()\n        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)\n        return s\n\n    def process_spider_input(self, response, spider):\n        # Called for each response that goes through the spider\n        # middleware and into the spider.\n\n        # Should return None or raise an exception.\n        return None\n\n    def process_spider_output(self, response, result, spider):\n        # Called with the results returned from the Spider, after\n        # it has processed the response.\n\n        # Must return an iterable of Request, dict or Item objects.\n        for i in result:\n            yield i\n\n    def process_spider_exception(self, response, exception, spider):\n        # Called when a spider or process_spider_input() method\n        # (from other spider middleware) raises an exception.\n\n        # Should return either None or an iterable of Response, dict\n        # or Item objects.\n        pass\n\n    def process_start_requests(self, start_requests, spider):\n        # Called with the start requests of the spider, and works\n        # similarly to the process_spider_output() method, except\n        # that it doesn’t have a response associated.\n\n        # Must return only requests (not items).\n        for r in start_requests:\n            yield r\n\n    def spider_opened(self, spider):\n        spider.logger.info('Spider opened: %s' % spider.name)\n"
  },
  {
    "path": "deepbnb/model.py",
    "content": "# class Listing(Document):\n#     \"\"\"Base class containing the common fields.\"\"\"\n#     access = Text()\n#     additional_house_rules = Text()\n#     allows_events = Boolean()\n#     amenities = Keyword(multi=True)\n#     amenity_ids = Keyword(multi=True)\n#     avg_rating = Float()\n#     bathrooms = Float()\n#     bedrooms = Integer()\n#     beds = Integer()\n#     business_travel_ready = Boolean()\n#     city = Text(fields={'keyword': Keyword()}, required=True)\n#     country = Text(fields={'keyword': Keyword()}, required=True)\n#     coordinates = GeoPoint()\n#     description = Text()\n#     host_id = Integer(fields={'keyword': Keyword()})\n#     house_rules = Text()\n#     interaction = Text()\n#     is_hotel = Boolean()\n#     monthly_price_factor = Float()\n#     name = Text(fields={'keyword': Keyword()}, required=True)\n#     neighborhood_overview = Text()\n#     person_capacity = Integer()\n#     photo_count = Integer()\n#     photos = Keyword(multi=True)\n#     place_id = Text(fields={'keyword': Keyword()})\n#     price_rate = Float()\n#     price_rate_type = Text(fields={'keyword': Keyword()}, required=True)\n#     province = Text(fields={'keyword': Keyword()})\n#     rating_accuracy = Float()\n#     rating_checkin = Float()\n#     rating_cleanliness = Float()\n#     rating_communication = Float()\n#     rating_location = Float()\n#     rating_value = Float()\n#     review_count = Integer()\n#     reviews = Nested()\n#     room_and_property_type = Text(fields={'keyword': Keyword()}, required=True)\n#     room_type = Text(fields={'keyword': Keyword()}, required=True)\n#     room_type_category = Text(fields={'keyword': Keyword()}, required=True)\n#     satisfaction_guest = Float()\n#     star_rating = Float()\n#     state = Text(fields={'keyword': Keyword()}, required=True)\n#     transit = Text()\n#     url = Text(fields={'keyword': Keyword()}, required=True)\n#     weekly_price_factor = Float()\n"
  },
  {
    "path": "deepbnb/pipelines.py",
    "content": "# -*- coding: utf-8 -*-\nimport elasticsearch.exceptions\nimport re\nimport webbrowser\n\nfrom datetime import datetime\n\n# from deepbnb.model import Listing\nfrom scrapy.exceptions import DropItem\n\n\nclass BnbPipeline:\n    @classmethod\n    def from_crawler(cls, crawler):\n        return cls(\n            minimum_monthly_discount=crawler.settings.get('MINIMUM_MONTHLY_DISCOUNT'),\n            minimum_weekly_discount=crawler.settings.get('MINIMUM_WEEKLY_DISCOUNT'),\n            minimum_photos=crawler.settings.get('MINIMUM_PHOTOS'),\n            skip_list=crawler.settings.get('SKIP_LIST'),\n            cannot_have=crawler.settings.get('CANNOT_HAVE'),\n            must_have=crawler.settings.get('MUST_HAVE'),\n            property_type_blacklist=crawler.settings.get('PROPERTY_TYPE_BLACKLIST'),\n            feed_format=crawler.settings.get('FEED_FORMAT'),  # output file type, autogenerated from -o file ext.\n            web_browser=crawler.settings.get('WEB_BROWSER')\n        )\n\n    def __init__(\n            self,\n            minimum_monthly_discount,\n            minimum_weekly_discount,\n            minimum_photos,\n            skip_list,\n            cannot_have,\n            must_have,\n            property_type_blacklist,\n            feed_format,\n            web_browser\n    ):\n        \"\"\"Class constructor.\"\"\"\n        self._feed_format = feed_format\n        # self._fields_to_check = ['description', 'name', 'summary', 'notes']\n        self._fields_to_check = ['description', 'name']\n        self._minimum_monthly_discount = minimum_monthly_discount\n        self._minimum_weekly_discount = minimum_weekly_discount\n        self._minimum_photos = minimum_photos\n\n        self._skip_list = skip_list\n        self._property_type_blacklist = property_type_blacklist\n\n        self._cannot_have_regex = cannot_have\n        if self._cannot_have_regex:\n            self._cannot_have_regex = re.compile(str(self._cannot_have_regex), re.IGNORECASE)\n\n        self._must_have_regex = must_have\n        if self._must_have_regex:\n            self._must_have_regex = re.compile(str(self._must_have_regex), re.IGNORECASE)\n\n        self._web_browser = web_browser\n        if self._web_browser:\n            self._web_browser = webbrowser.get(web_browser + ' %s')  # append URL placeholder (%s)\n\n    def process_item(self, item, spider):\n        \"\"\"Drop items not fitting parameters. Open in browser if specified. Return accepted items.\"\"\"\n\n        if self._skip_list and str(item.get('id')) in self._skip_list:\n            raise DropItem('Item in skip list: {}'.format(item['id']))\n\n        if self._property_type_blacklist and item['room_and_property_type'] in self._property_type_blacklist:\n            raise DropItem('Skipping property type: {}'.format(item['room_and_property_type']))\n\n        if self._minimum_monthly_discount and 'monthly_discount' in item:\n            if item['monthly_discount'] < self._minimum_monthly_discount:\n                raise DropItem('Monthly discount too low: {}'.format(item['monthly_discount']))\n\n        if self._minimum_weekly_discount and 'weekly_discount' in item:\n            if item['weekly_discount'] < self._minimum_monthly_discount:\n                raise DropItem('Weekly discount too low: {}'.format(item['weekly_discount']))\n\n        if self._minimum_photos and item['photo_count'] < self._minimum_photos:\n            raise DropItem('Photos too low: {} photos'.format(item['photo_count']))\n\n        # check regexes\n        if self._cannot_have_regex:\n            for f in self._fields_to_check:\n                field_val = item[f]\n                if field_val is None:\n                    continue\n                v = str(field_val.encode('ASCII', 'replace'))\n                if self._cannot_have_regex.search(v):\n                    raise DropItem('Found: {}'.format(self._cannot_have_regex.pattern))\n\n        if self._must_have_regex:\n            has_must_haves = False\n            for f in self._fields_to_check:\n                field_val = item[f]\n                if field_val is None:\n                    continue\n                v = str(field_val.encode('ASCII', 'replace'))\n                if self._must_have_regex.search(v):\n                    has_must_haves = True\n                    break\n\n            if not has_must_haves:\n                raise DropItem('Not Found: {}'.format(self._must_have_regex.pattern))\n\n        if self._web_browser:  # open in browser\n            self._web_browser.open_new_tab(item['url'])\n\n        return item\n\n\nclass ElasticBnbPipeline:\n    _datetime_scrape = datetime.now()\n\n    @classmethod\n    def from_crawler(cls, crawler):\n        return cls(elasticsearch_index=crawler.settings.get('ELASTICSEARCH_INDEX'))\n\n    def __init__(self, elasticsearch_index):\n        \"\"\"Class constructor.\"\"\"\n        self._elasticsearch_index = elasticsearch_index\n\n    def process_item(self, item, spider):\n        \"\"\"Insert / update items in ElasticSearch.\"\"\"\n        properties = {\n            'access':                 item['access'],\n            'additional_house_rules': item['additional_house_rules'],\n            'allows_events':          item['allows_events'],\n            'amenities':              item['amenities'],\n            'amenity_ids':            item['amenity_ids'],\n            'avg_rating':             item['avg_rating'],\n            'bathrooms':              item['bathrooms'],\n            'bedrooms':               item['bedrooms'],\n            'beds':                   item['beds'],\n            'business_travel_ready':  item['business_travel_ready'],\n            'city':                   item['city'],\n            'country':                item['country'],\n            'coordinates':            {'lon': item['longitude'], 'lat': item['latitude']},\n            'description':            item['description'],\n            'host_id':                item['host_id'],\n            'house_rules':            item['house_rules'],\n            'interaction':            item.get('interaction'),\n            'is_hotel':               item['is_hotel'],\n            'monthly_price_factor':   item['monthly_price_factor'],\n            'name':                   item['name'],\n            'neighborhood_overview':  item['neighborhood_overview'],\n            'person_capacity':        item['person_capacity'],\n            'photo_count':            item['photo_count'],\n            'photos':                 item['photos'],\n            'place_id':               item['place_id'],\n            'price_rate':             item['price_rate'],\n            'price_rate_type':        item['price_rate_type'],\n            'province':               item['province'],\n            'rating_accuracy':        item['rating_accuracy'],\n            'rating_checkin':         item['rating_checkin'],\n            'rating_cleanliness':     item['rating_cleanliness'],\n            'rating_communication':   item['rating_communication'],\n            'rating_location':        item['rating_location'],\n            'rating_value':           item['rating_value'],\n            'review_count':           item['review_count'],\n            'review_score':           item.get('review_score'),\n            'reviews':                item.get('reviews'),\n            'room_and_property_type': item['room_and_property_type'],\n            'room_type':              item['room_type'],\n            'room_type_category':     item['room_type_category'],\n            'satisfaction_guest':     item['satisfaction_guest'],\n            'datetime_scrape':        self._datetime_scrape,\n            'star_rating':            item['star_rating'],\n            'state':                  item['state'],\n            'transit':                item.get('transit'),\n            'url':                    item['url'],\n            'weekly_price_factor':    item['weekly_price_factor']\n        }\n\n        # update if exists, else insert new\n        try:\n            listing = Listing.get(id=item['id'], index=self._elasticsearch_index)\n            listing.update(**properties)\n        except elasticsearch.exceptions.NotFoundError:\n            properties['meta'] = {'id': item['id']}\n            listing = Listing(**properties)\n            listing.save(index=self._elasticsearch_index)\n\n        return item\n\n\nclass DuplicatesPipeline:\n    \"\"\"Looks for duplicate items, and drops those items that were already processed\n\n    @ref: https://docs.scrapy.org/en/latest/topics/item-pipeline.html#duplicates-filter\n    \"\"\"\n\n    def __init__(self):\n        self.ids_seen = set()\n\n    def process_item(self, item, spider):\n        if item['id'] in self.ids_seen:\n            raise DropItem(\"Duplicate item found: %s\" % item)\n        else:\n            self.ids_seen.add(item['id'])\n            return item\n"
  },
  {
    "path": "deepbnb/settings.py.dist",
    "content": "# -*- coding: utf-8 -*-\n\n# Scrapy settings for deepbnb project\n#\n# For simplicity, this file contains only settings considered important or\n# commonly used. You can find more settings consulting the documentation:\n#\n#     http://doc.scrapy.org/en/latest/topics/settings.html\n#     http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html\n#     http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html\n\nBOT_NAME = 'deepbnb'\n\nSPIDER_MODULES = ['deepbnb.spiders']\nNEWSPIDER_MODULE = 'deepbnb.spiders'\n\n#\n# Scraper config\n#\n\n# Elasticsearch (optional)\n# ELASTICSEARCH_SERVERS = ['localhost']\n# ELASTICSEARCH_INDEX = 'airbnb-listing'\n# ELASTICSEARCH_INDEX_DATE_FORMAT = '%Y-%m'\n# ELASTICSEARCH_TYPE = 'deepbnb'\n# ELASTICSEARCH_UNIQ_KEY = 'url'  # Custom unique key\n\n# Need to create a postgresql database to use this, see http://newcoder.io/scrape/part-3/\n# DATABASE = {\n#     'drivername': 'postgres',\n#     'host':       'localhost',\n#     'port':       '5432',\n#     'username':   'postgres',\n#     'password':   '',\n#     'database':   'scrape'\n# }\n\n# Public development key (get this from the 'key' url parameter in async requests to /api/v2/explore_tabs)\nAIRBNB_API_KEY = ''\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\nUSER_AGENT = 'deepbnb (https://airbnb-scraper)'\n\n# Obey robots.txt rules\nROBOTSTXT_OBEY = True\n\n# https://docs.python.org/3/library/webbrowser.html\n# Open results in web browser\n# WEB_BROWSER = 'chromium'\n\n# Configure maximum concurrent requests performed by Scrapy (default: 16)\n# CONCURRENT_REQUESTS = 32\n\n# Configure a delay for requests for the same website (default: 0)\n# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay\n# See also autothrottle settings and docs\nDOWNLOAD_DELAY = 10\n# The download delay setting will honor only one of:\nCONCURRENT_REQUESTS_PER_DOMAIN = 10\n# CONCURRENT_REQUESTS_PER_IP = 16\n\n# Disable cookies (enabled by default)\n# COOKIES_ENABLED = False\n\n# Disable Telnet Console (enabled by default)\nTELNETCONSOLE_ENABLED = False\n\n# Override the default request headers:\n# DEFAULT_REQUEST_HEADERS = {\n#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n#   'Accept-Language': 'en',\n# }\n\n# Enable or disable spider middlewares\n# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html\n# SPIDER_MIDDLEWARES = {\n#    'deepbnb.middlewares.MyCustomSpiderMiddleware': 543,\n# }\n\n# Enable or disable extensions\n# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html\n# EXTENSIONS = {\n#    'scrapy.extensions.telnet.TelnetConsole': None,\n# }\n\n# Configure item pipelines\n# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html\nITEM_PIPELINES = {\n    'deepbnb.pipelines.DuplicatesPipeline': 299,\n    'deepbnb.pipelines.BnbPipeline':        300,\n    # 'deepbnb.pipelines.ElasticBnbPipeline': 301  # enable if you want to pipeline results to local elasticsearch\n}\n\n# https://docs.scrapy.org/en/latest/topics/feed-exports.html\nFEED_EXPORTERS = {\n    'xlsx': 'deepbnb.exporter.XlsxItemExporter',\n}\n\nFEED_EXPORT_FIELDS = [\n    'name',\n    'url',\n    'price_rate',\n    'price_rate_type',\n    'total_price',\n    'room_and_property_type',\n    'latitude',\n    'longitude',\n    'monthly_price_factor',\n    'weekly_price_factor',\n    'room_type',\n    'person_capacity',\n    'amenities',\n    'review_count',\n    'review_score',\n    'rating_accuracy',\n    'rating_checkin',\n    'rating_cleanliness',\n    'rating_communication',\n    'rating_location',\n    'rating_value',\n    'star_rating',\n    'satisfaction_guest',\n    'description',\n    'neighborhood_overview',\n    'notes',\n    'additional_house_rules',\n    'interaction',\n    'access',\n    'transit',\n    'response_rate',\n    'response_time',\n    'photos',\n]\n\n# Minimum monthly discount percent\n# MINIMUM_MONTHLY_DISCOUNT = 0\n\n# Minimum weekly discount percent\n# MINIMUM_WEEKLY_DISCOUNT = 0\n\n# Minimum photos per listing\nMINIMUM_PHOTOS = 2\n\n# Default currency\n# DEFAULT_CURRENCY = 'BRL'\n\n# Desired hosting amenities and corresponding IDs. Determined by observing search GET parameters.\nPROPERTY_AMENITIES = {\n    # 'a/c':     5,\n    'kitchen': 8,\n    'tv':      58,\n    'washer':  33,\n    'dryer':   34,\n    'wifi':    4,\n}\n\nROOM_TYPES = []\n# Blacklisted property types\nPROPERTY_TYPE_BLACKLIST = ['Camper/RV', 'Campsite', 'Entire guest suite']\n\n# Enable and configure the AutoThrottle extension (disabled by default)\n# See http://doc.scrapy.org/en/latest/topics/autothrottle.html\nAUTOTHROTTLE_ENABLED = True\n\n# The initial download delay\nAUTOTHROTTLE_START_DELAY = 5\n\n# The maximum download delay to be set in case of high latencies\nAUTOTHROTTLE_MAX_DELAY = 60\n\n# The average number of requests Scrapy should be sending in parallel to\n# each remote server\n# AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0\n# Enable showing throttling stats for every response received:\nAUTOTHROTTLE_DEBUG = False\n\n# Enable and configure HTTP caching (disabled by default)\n# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings\n# HTTPCACHE_ENABLED = True\n# HTTPCACHE_EXPIRATION_SECS = 0\n# HTTPCACHE_DIR = 'httpcache'\n# HTTPCACHE_IGNORE_HTTP_CODES = []\n# HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'\n\n# scrapy-playwright settings\nDOWNLOAD_HANDLERS = {\n    \"http\":  \"scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler\",\n    \"https\": \"scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler\",\n}\nTWISTED_REACTOR = \"twisted.internet.asyncioreactor.AsyncioSelectorReactor\"\nPLAYWRIGHT_DEFAULT_NAVIGATION_TIMEOUT = 60000\n"
  },
  {
    "path": "deepbnb/spiders/__init__.py",
    "content": "# This package will contain the spiders of your Scrapy project\n#\n# Please refer to the documentation for information on how to create and manage\n# your spiders.\n"
  },
  {
    "path": "deepbnb/spiders/airbnb.py",
    "content": "import json\nimport re\nimport scrapy\n\nfrom datetime import date, timedelta\nfrom scrapy.http import HtmlResponse\nfrom scrapy_playwright.page import PageMethod\n\nfrom deepbnb.api.ExploreSearch import ExploreSearch\nfrom deepbnb.api.PdpPlatformSections import PdpPlatformSections\nfrom deepbnb.api.PdpReviews import PdpReviews\n\n\nclass AirbnbSpider(scrapy.Spider):\n    \"\"\"Airbnb Spider\n\n    Perform a search, collect data from search results, cache that data, then scrape each listing individually to\n    obtain additional information, and finally compile the data together into a DeepbnbItem.\n    \"\"\"\n\n    name = 'airbnb'\n    allowed_domains = ['airbnb.com']\n    default_currency = 'USD'\n    default_max_price = 3000\n    default_price_increment = 100\n    price_range = (0, default_max_price, default_price_increment)\n    page_limit = 20\n\n    def __init__(\n            self,\n            query,\n            checkin=None,\n            checkout=None,\n            currency=default_currency,\n            max_price=None,\n            min_price=None,\n            ne_lat=None,\n            ne_lng=None,\n            sw_lat=None,\n            sw_lng=None,\n            **kwargs\n    ):\n        \"\"\"Class constructor.\"\"\"\n        super().__init__(**kwargs)\n        self.__checkin = checkin\n        self.__checkout = checkout\n        self.__currency = currency\n        self.__data_cache = {}\n        self.__explore_search = None\n        self.__geography = {}\n        self.__ids_seen = set()\n        self.__ne_lat = ne_lat\n        self.__ne_lng = ne_lng\n        self.__pdp_platform_sections = None\n        self.__pdp_reviews = None\n        self.__query = query\n        self.__search_params = {}\n        self.__set_price_params(max_price, min_price)\n        self.__sw_lat = sw_lat\n        self.__sw_lng = sw_lng\n\n    def start_requests(self):\n        \"\"\"Spider entry point. Generate the first search request(s).\"\"\"\n        self.logger.info(f'starting survey for: {self.__query}')\n        if 'deepbnb.pipelines.ElasticBnbPipeline' in self.settings.get('ITEM_PIPELINES'):\n            self.__create_index_if_not_exists()\n\n        api_key = self.settings.get('AIRBNB_API_KEY')\n        self.__explore_search = ExploreSearch(\n            api_key,\n            self.logger,\n            self.__currency,\n            self,\n            self.settings.get('ROOM_TYPES'),\n            self.__geography,\n            self.__query\n        )\n        self.__pdp_platform_sections = PdpPlatformSections(\n            api_key,\n            self.logger,\n            self.__currency,\n            self.__data_cache,\n            self.__geography,\n            PdpReviews(api_key, self.logger, self.__currency)\n        )\n\n        # get params from injected constructor values\n        params = {}\n        if self.__price_max:\n            params['priceMax'] = self.__price_max\n\n        if self.__price_min:\n            params['priceMin'] = self.__price_min\n\n        if self.__ne_lat:\n            params['ne_lat'] = self.__ne_lat\n\n        if self.__ne_lng:\n            params['ne_lng'] = self.__ne_lng\n\n        if self.__sw_lat:\n            params['sw_lat'] = self.__sw_lat\n\n        if self.__sw_lng:\n            params['sw_lng'] = self.__sw_lng\n\n        if self.__checkin:  # assume self._checkout also\n            checkin, checkout, checkin_range_spec, checkout_range_spec = self._process_checkin_vars()\n            yield from self.__explore_search.perform_checkin_start_requests(\n                checkin, checkout, checkin_range_spec, checkout_range_spec, params)\n        else:\n            yield from self.__city_search()\n\n    def __city_search(self):\n        \"\"\"Search entire city given in self.__query\"\"\"\n        search_path = self.__query.replace(', ', '--').replace(' ', '-') + '/homes'\n        url = self.__explore_search.build_airbnb_url('s/' + search_path)\n        headers = self.__get_search_headers()\n        yield scrapy.Request(url, callback=self.parse_landing_page, headers=headers, meta={\n            'playwright':              True,\n            'playwright_include_page': True,\n            'playwright_page_methods': [PageMethod('wait_for_selector', '#data-deferred-state', state='hidden')]\n        }, errback=self.errback, cb_kwargs={'headers': headers})\n\n    async def errback(self, failure):\n        page = failure.request.meta['playwright_page']\n        await page.close()\n\n    async def parse_landing_page(self, response: HtmlResponse, headers: dict):\n        \"\"\"Parse search response and generate URLs for all searches, then perform them.\"\"\"\n        # debugging: get data from all script data-* attributes\n        # script_data = {s.attrib['id']: json.loads(s.css('::text').get()) for s in response.css('script[id^=data-]')}\n        data_deferred = json.loads(response.xpath('//script[@id=\"data-deferred-state\"]/text()').get())\n        data_deferred['niobeMinimalClientData'][0][0] = json.loads(\n            re.sub(r'^StaysSearch:', '', data_deferred['niobeMinimalClientData'][0][0]))\n\n        explore_data = data_deferred['niobeMinimalClientData'][0][1]['data']['presentation']['explore']\n        if 'sectionIndependentData' in explore_data['sections']:\n            stays_search = explore_data['sections']['sectionIndependentData']['staysSearch']\n            remarketing_data = stays_search['loggingMetadata']['remarketingLoggingData']\n            listing_data = stays_search['searchResults']\n        else:\n            remarketing_data = self.__find_section(explore_data['sections']['sections'], 'EXPLORE_REMARKETING')\n            listing_data_wrapper = self.__find_section(explore_data['sections']['sections'], 'EXPLORE_SECTION_WRAPPER')\n            listing_data = listing_data_wrapper['child']['section']\n\n        yield self.__explore_search.api_request(self.__query, {}, self.parse, response, headers)\n\n    def parse(self, response, **kwargs):\n        \"\"\"Default parse method.\"\"\"\n        self.logger.debug(f\"Parsing {response.url}\")\n        json_response = response.xpath('body/pre/text()').get()  # remove html wrapper\n        data = json.loads(json_response)\n\n        # Handle pagination\n        next_section = {}\n        pagination = data['data']['dora']['exploreV3']['metadata']['paginationMetadata']\n        if pagination['hasNextPage']:\n            items_offset = pagination['itemsOffset']\n            self.__explore_search.add_search_params(next_section, response)\n            next_section.update({'itemsOffset': items_offset})\n\n            yield self.__explore_search.api_request(self.__query, next_section, response=response)\n\n        # handle listings\n        params = {'key': self.__explore_search.api_key}\n        self.__explore_search.add_search_params(params, response)\n        listing_ids = self.__get_listings_from_sections(data['data']['dora']['exploreV3']['sections'])\n        for listing_id in listing_ids:  # request each property page\n            if listing_id in self.__ids_seen:\n                continue  # filter duplicates\n\n            self.__ids_seen.add(listing_id)\n\n            yield self.__pdp_platform_sections.api_request(listing_id)\n\n    @staticmethod\n    def _get_neighborhoods(data):\n        \"\"\"Get all neighborhoods in an area if they exist.\"\"\"\n        neighborhoods = {}\n        meta = data['explore_tabs'][0]['home_tab_metadata']\n        if meta['listings_count'] < 300:\n            return neighborhoods\n\n        for section in meta['filters']['sections']:\n            if section['filter_section_id'] != 'neighborhoods':\n                continue\n            for item in section['items']:\n                key = item['title']\n                neighborhoods[key] = item\n                for param in item['params']:\n                    if param['key'] == 'neighborhood_ids':\n                        neighborhoods[key]['id'] = param['value']\n                        break\n\n        return neighborhoods\n\n    def _collect_listing_data(self, listing_item: dict):\n        \"\"\"Collect listing data from search results, save in _data_cache. All listing data is aggregated together in the\n        parse_listing_contents method.\"\"\"\n        listing = listing_item['listing']\n        pricing = listing_item['pricingQuote'] or {}\n\n        self.__data_cache[listing['id']] = {\n            # get general data\n            'avg_rating':             listing['avgRating'],\n            'bathrooms':              listing['bathrooms'],\n            'bedrooms':               listing['bedrooms'],\n            'beds':                   listing['beds'],\n            'business_travel_ready':  listing['isBusinessTravelReady'],\n            'city':                   listing['city'],\n            'host_id':                listing['user']['id'],\n            'latitude':               listing['lat'],\n            'longitude':              listing['lng'],\n            'name':                   listing['name'],\n            'neighborhood_overview':  listing['neighborhoodOverview'],\n            'person_capacity':        listing['personCapacity'],\n            'photo_count':            listing['pictureCount'],\n            'photos':                 [p['picture'] for p in listing['contextualPictures']],\n            'review_count':           listing['reviewsCount'],\n            'room_and_property_type': listing['roomAndPropertyType'],\n            'room_type':              listing['roomType'],\n            'room_type_category':     listing['roomTypeCategory'],\n            'star_rating':            listing['starRating'],\n\n            # get pricing data\n            'monthly_price_factor':   pricing.get('monthlyPriceFactor'),\n            'weekly_price_factor':    pricing.get('weeklyPriceFactor'),\n            'price_rate':             self.__get_price_rate(pricing),\n            'price_rate_type':        self.__get_rate_type(pricing),\n            # use total price if dates given, price rate otherwise. can't show total price if there are no dates.\n            'total_price':            self.__get_total_price(pricing)\n        }\n\n    def __create_index_if_not_exists(self):\n        index_name = self.settings.get('ELASTICSEARCH_INDEX')\n        # index = Index(index_name)\n        # if not index.exists():\n        #     Listing.init(index_name)\n\n    def __get_listings_from_sections(self, sections: list) -> list:\n        \"\"\"Get listings from \"sections\" (i.e. search results page sections).\n\n         Also collect some data and save it for later. Double check prices are correct, because Airbnb switches to daily\n         pricing if less than 28 days are selected (e.g. during a range search).\n        \"\"\"\n        listing_ids = []\n        for section in [s for s in sections if s['sectionComponentType'] == 'listings_ListingsGrid_Explore']:\n            for listing_item in section.get('items'):\n                pricing = listing_item['pricingQuote']\n                if pricing:\n                    rate_with_service_fee = pricing['rateWithServiceFee']\n                    if rate_with_service_fee is None:  # some properties need dates to show rates\n                        rate_with_service_fee_amt = 0\n                        pricing['rateWithServiceFee'] = {'amount': None}\n                    else:\n                        rate_with_service_fee_amt = rate_with_service_fee['amount']\n\n                    # To account for results where price_max was specified as monthly but quoted rate is nightly, calculate\n                    # monthly rate and drop listing if it is greater. Use 28 days = 1 month. Assume price_max of 1000+ is a\n                    # monthly price requirement.\n                    if (self.__price_max and self.__price_max > 1000\n                            and pricing['structuredStayDisplayPrice']['primaryLine']['qualifier'] != 'month'\n                            and (rate_with_service_fee_amt * 28) > self.__price_max):\n                        continue\n\n                self._collect_listing_data(listing_item)\n                listing_ids.append(listing_item['listing']['id'])\n\n        return listing_ids\n\n    @staticmethod\n    def __get_search_headers() -> dict:\n        return {\n            'Accept':                    'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n            'Accept-Encoding':           'gzip, deflate, br',\n            'Accept-Language':           'en-US,en;q=0.9',\n            'Cache-Control':             'no-cache',\n            'Pragma':                    'no-cache',\n            'Sec-Ch-Ua':                 '\"Not;A=Brand\";v=\"99\", \"Chromium\";v=\"106\"',\n            'Sec-Ch-Ua-Mobile':          '?0',\n            'Sec-Ch-Ua-Platform':        '\"Linux\"',\n            'Sec-Fetch-Dest':            'document',\n            'Sec-Fetch-Mode':            'navigate',\n            'Sec-Fetch-Site':            'none',\n            'Sec-Fetch-User':            '?1',\n            'Upgrade-Insecure-Requests': '1',\n            'User-Agent':                'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'\n        }\n\n    @staticmethod\n    def __get_price_key(pricing) -> str:\n        return 'price' if 'price' in pricing['structuredStayDisplayPrice']['primaryLine'] else 'discountedPrice'\n\n    @staticmethod\n    def __get_price_rate(pricing) -> int | None:\n        if pricing:\n            price_key = AirbnbSpider.__get_price_key(pricing)\n            return int(pricing['structuredStayDisplayPrice']['primaryLine'][price_key].lstrip('$').replace(',', ''))\n\n        return None\n\n    @staticmethod\n    def __get_rate_type(pricing) -> str | None:\n        if pricing:\n            return pricing['structuredStayDisplayPrice']['primaryLine']['qualifier']\n\n        return None\n\n    def __get_total_price(self, pricing) -> int | None:\n        if not self.__checkin:\n            return None  # can't have a price without dates\n\n        if pricing['structuredStayDisplayPrice']['secondaryLine']:\n            price = pricing['structuredStayDisplayPrice']['secondaryLine']['price']\n            amount_match = re.match(r'\\$([\\w,]+) total', price)\n        else:\n            price_key = AirbnbSpider.__get_price_key(pricing)\n            price = pricing['structuredStayDisplayPrice']['primaryLine'][price_key]\n            amount_match = re.match(r'\\$([\\w,]+)', price)\n\n        if not amount_match:\n            raise ValueError('No amount match found for price: %s' % price)\n\n        return int(amount_match[1].replace(',', ''))\n\n    @staticmethod\n    def __find_section(sections: list, section_type: str):\n        result = [i for i in sections if i.get('sectionComponentType') == section_type]\n        return result.pop().get('section') if result else {}\n\n    def _process_checkin_vars(self) -> tuple:\n        \"\"\"Determine if a range is specified, if so, extract ranges, validate, and return as variables.\n\n        @NOTE: Should only be run once on crawler initialization.\n\n        :return: checkin/checkout range specs\n        \"\"\"\n        if not self.__checkin:\n            return None, None, None, None\n\n        checkin_range_spec, checkout_range_spec = None, None\n\n        # Handle ranged queries\n        checkin_plus_range_position = self.__checkin.find('+')\n        if checkin_plus_range_position != -1:  # range_spec e.g. +5-3 means plus five days, minus three days\n            checkin_range_spec = self.__checkin[checkin_plus_range_position:]\n            self.__checkin = self.__checkin[:checkin_plus_range_position]\n\n        checkout_plus_range_position = self.__checkout.find('+')\n        if checkout_plus_range_position != -1:  # range_spec e.g. +-3 means plus or minus 3 days\n            checkout_range_spec = self.__checkout[checkout_plus_range_position:]\n            self.__checkout = self.__checkout[:checkout_plus_range_position]\n\n        # Validate checkin / checkout values\n        today = date.today()\n        if date.fromisoformat(self.__checkin) < today:\n            raise ValueError('Checkin cannot be in past: {}'.format(self.__checkin))\n        tomorrow = today + timedelta(days=1)\n        if date.fromisoformat(self.__checkout) < tomorrow:\n            raise ValueError('Checkout must be tomorrow or later: {}'.format(self.__checkout))\n\n        return self.__checkin, self.__checkout, checkin_range_spec, checkout_range_spec\n\n    def __set_price_params(self, price_max, price_min):\n        \"\"\"Set price parameters based on price_max and price_min input values.\"\"\"\n        self.__price_max = price_max\n        self.__price_min = price_min\n        if self.__price_min and self.__price_max:\n            self.__price_max = int(self.__price_max)\n            self.__price_min = int(self.__price_min)\n            self.price_range = (self.__price_min, self.__price_max, self.default_price_increment)\n\n        if self.__price_min and not self.__price_max:\n            self.__price_min = int(self.__price_min)\n            self.price_range = (self.__price_min, self.default_max_price, self.default_price_increment)\n\n        if not self.__price_min and self.__price_max:\n            self.__price_max = int(self.__price_max)\n            self.price_range = (0, self.__price_max, self.default_price_increment)\n"
  },
  {
    "path": "requirements.txt",
    "content": "elasticsearch==8.4.3\nlxml==4.9.1\nopenpyxl==3.0.10\nrequests==2.28.1\nScrapy==2.6.3\nscrapy-playwright==0.0.22\n"
  },
  {
    "path": "scrapy.cfg",
    "content": "# Automatically created by: scrapy startproject\n#\n# For more information about the [deploy] section see:\n# https://scrapyd.readthedocs.org/en/latest/deploy.html\n\n[settings]\ndefault = deepbnb.settings\n\n[deploy]\n#url = http://localhost:6800/\nproject = deepbnb\n"
  }
]