[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# TensorFlow training files\nlogs\ncheckpoints\nexported\ntflite\noptimized"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"models\"]\n\tpath = models\n\turl = https://github.com/yinguobing/models.git\n[submodule \"face_detector\"]\n\tpath = face_detector\n\turl = https://github.com/yinguobing/face_detector.git\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# facial-landmark-detection-hrnet\nA TensorFlow implementation of HRNet for facial landmark detection.\n\n![ms_marvel](./doc/../docs/ms_marvel.gif)\n\nWatch this demo video: [HRNet Facial Landmark Detection (bilibili)](https://www.bilibili.com/video/BV1Vy4y1C79p/).\n\n## Features\n - Support multiple public dataset: WFLW, IBUG, etc.\n - Advanced model architecture: HRNet v2\n - Data augmentation: randomly scale/rotate/flip\n - Model optimization: quantization, pruning\n\n## Getting Started\n\nThese instructions will get you a copy of the project up and running on your local machine for development and testing purposes.\n\n### Prerequisites\n\n![TensorFlow](https://img.shields.io/badge/TensorFlow-v2.3-brightgreen)\n![TensorFlow Model Optimizer Toolkit](https://img.shields.io/badge/TensorFlow_Model_Optimization_Toolkit-v0.5-brightgreen)\n![OpenCV](https://img.shields.io/badge/OpenCV-v4.3-brightgreen)\n![Numpy](https://img.shields.io/badge/Numpy-v1.17-brightgreen)\n\n### Installing\n#### Get the source code for training\n\n```shell\n# From your favorite development directory\ngit clone --recursive https://github.com/yinguobing/facial-landmark-detection-hrnet.git\n```\n\n#### Generate the training data\nThere are multiple public facial mark datasets available which can be used to generate training heatmaps we need. For this training process the images will be augmented. The first step is transforming  the dataset into a more uniform distribution that is easier to process. You can do this yourself or, use this repo:\n\n```shell\n# From your favorite development directory\ngit clone https://github.com/yinguobing/face-mesh-generator.git\n\n# Checkout the desired branch\ngit checkout features/export_for_mark_regression\n```\nUse the module `generate_mesh_dataset.py` to generate training data. Popular public datasets like IBUG, 300-W, WFLW are supported. Checkout the full list here: [facial-landmark-dataset](https://github.com/yinguobing/facial-landmark-dataset).\n\n\n## Training\nDeep neural network training can be complicated as you have to make sure everything is ready like datasets, checkpoints, logs, etc. But do not worry. Following these steps you should be fine.\n\n### Setup the model.\n\nIn the module `train.py`, setup your model's name and the number of marks.\n```python\n# What is the model's name?\nname = \"hrnetv2\"\n\n# How many marks are there for a single face sample?\nnumber_marks = 98\n```\n\n### Set the training and testing datasets\n\nThese files do not change frequently so set them in the source code. Take WFLW as an example.\n\n```python\n# Training data.\ntrain_files_dir = \"/path/to/wflw_train\"\n\n# Testing data.\ntest_files_dir = \"/path/to/wflw_test\"\n```\n\n### Set the validation datasets\n\nThe loss value from this dataset will be used to decide which checkpoint should be preserved. Set `None` if no files available. Then about 512 of the training files will be used as validation samples.\n\n```python\n# Validation data.\nval_files_dir = None\n```\n\n### Provide a sanity check image\n\nThis sample image will be logged into TensorBoard with detected marks drawing on it. In this way you can check the model's behavior visually during training.\n\n```python\nsample_image = \"docs/face.jpg\"\n```\n\n### Start training\nSet the hyper parameters in the command line.\n\n```Shell\npython3 train.py --epochs=80 --batch_size=32\n```\n\nTraining checkpoints can be found in directory `checkpoints`. Before training started, this directory will be checked and the model will be restored if any checkpoint is available. Only the best model (smallest validation loss) will be saved.\n\n### Resume training\nIf training was interrupted, resume it by providing `--initial_epoch` argument.\n\n```bash\npython3 train.py --epochs=80 --initial_epoch=61\n```\n\n### Monitor the training process\nUse TensorBoard. The log and profiling files are in directory `logs`\n\n```shell\ntensorboard --logdir /path/to/facial-landmark-detection-hrnet/logs\n\n```\n\n### Training speedup\nYou can download this checkpoint file to speedup the training process.\n\n- [GoogleDrive](https://drive.google.com/file/d/1cQKrYdX0O7DsBodjTufzVzm70gXwsyaP/view?usp=sharing) \n- [百度云盘](https://pan.baidu.com/s/1XDp6hDx_aXYTV5_OF1cc6g) (提取码 b3vm)\n\n## Evaluation\nA quick evaluation on validation datasets will be performed automatically after training. For a full evaluation, please run the `evaluate.py` file. The NME value will be printed after evaluation.\n\n```\npython3 evaluate.py\n```\n\n## Export\nEven though the model wights are saved in the checkpoint, it is better to save the entire model so you won't need the source code to restore it. This is useful for inference and model optimization later.\n\n### For cloud/PC applications\nExported model will be saved in `saved_model` format in directory `exported`. You can restore the model with `Keras` directly. Loading the model in OpenCV is also [supported](https://github.com/yinguobing/facial-landmark-detection-hrnet/issues/3).\n\n```shell\npython3 train.py --export_only=True\n```\n### For Android phones, embedded and IoT devices\nTensorFlow lite and TensorFlow Model Optimization Toolkit will help you to get a optimized model for these applications. Please follow the instructions of the later section *Optimization*.\n\n### For iPhone\nApple has developed a conversion tool named [coremltools](https://github.com/apple/coremltools) which can convert and quantize the TensorFlow model into the native model format supported and accelrated by iPhone's Neural Engine.\n\n```bash\n# Install the package\npip install --upgrade coremltools\n\n# Do the conversion.\npython3 coreml_conversion.py\n```\n\n## Inference\nCheck out module `predict.py` for details. \n\nA pre-trained model is provided in case you want to try it in no time, or do not have adequate equipments to train it yourself.\n\nURL: https://pan.baidu.com/s/1EQsB0LnSkfvoNjMvkFV5dQ  \nAccess code: qg5e\n\n## Optimization\nOptimize the model so it can run on mobile, embedded, and IoT devices. TensorFlow supports post-training quantization, quantization aware training, pruning, and clustering.\n\n### Post training quantization\nThere are multiple means for post training quantization: dynamic range, integer only, float16. To quantize the model, run:\n\n```bash\npython3 quantization.py\n```\nQuantized tflite file will be find in the `optimized` directory.\n\n### Pruning\nModel pruning could dramatically reduce the model size while minimize the side effects on model accuracy. There is a demo video showing the performance of a pruned model with 80% of weights pruned (set to zero): [TensorFlow model pruning (bilibili)](https://www.bilibili.com/video/BV1Uz4y1o7Fb/)\n\nTo prune the model in this repo, run:\n\n```bash\npython3 pruning.py\n\n```\nPruned model file will be find in the `optimized` directory.\n\n\n### Quantization aware training\nDue to the conflict between pruning and quantization aware training, please checkout the other branch for details.\n\n```bash\ngit checkout features/quantization-aware-training\npython3 train.py --quantization=True\n```\n\n## Authors\nYin Guobing (尹国冰) - yinguobing\n\n![wechat](docs/wechat.png)\n\n## License\n![GitHub](https://img.shields.io/github/license/yinguobing/facial-landmark-detection-hrnet)\n\n## Acknowledgments\nThe HRNet authors and the dataset authors who made their work public.\n"
  },
  {
    "path": "callbacks.py",
    "content": "\"\"\"A module containing custom callbacks.\"\"\"\nimport cv2\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom preprocessing import normalize\nfrom postprocessing import parse_heatmaps\n\n\nclass EpochBasedLearningRateSchedule(keras.callbacks.Callback):\n    \"\"\"Sets the learning rate according to epoch schedule.\"\"\"\n\n    def __init__(self, schedule):\n        \"\"\"\n        Args:\n            schedule: a tuple that takes an epoch index (integer, indexed from 0)\n            and current learning rate.\n        \"\"\"\n        super(EpochBasedLearningRateSchedule, self).__init__()\n        self.schedule = schedule\n\n    def on_epoch_begin(self, epoch, logs=None):\n        if not hasattr(self.model.optimizer, \"lr\"):\n            raise ValueError('Optimizer must have a \"lr\" attribute.')\n\n        # Get the current learning rate from model's optimizer.\n        lr = float(tf.keras.backend.get_value(\n            self.model.optimizer.learning_rate))\n\n        # Get the scheduled learning rate.\n        def _lr_schedule(epoch, lr, schedule):\n            \"\"\"Helper function to retrieve the scheduled learning rate based on\n             epoch.\"\"\"\n            if epoch < schedule[0][0] or epoch > schedule[-1][0]:\n                return lr\n            for i in range(len(schedule)):\n                if epoch == schedule[i][0]:\n                    return schedule[i][1]\n            return lr\n\n        scheduled_lr = _lr_schedule(epoch, lr, self.schedule)\n\n        # Set the value back to the optimizer before this epoch starts\n        tf.keras.backend.set_value(self.model.optimizer.lr, scheduled_lr)\n        print(\"\\nEpoch %05d: Learning rate is %6.6f.\" % (epoch, scheduled_lr))\n\n\nclass LogImages(keras.callbacks.Callback):\n    def __init__(self, logdir, sample_image):\n        super().__init__()\n        self.file_writer = tf.summary.create_file_writer(logdir)\n        self.sample_image = sample_image\n\n    def on_epoch_end(self, epoch, logs={}):\n        # Read in the image file.\n        image = cv2.imread(self.sample_image)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        img = cv2.resize(image, (256, 256))\n        img = normalize(img)\n\n        # Do prediction.\n        heatmaps = self.model.predict(tf.expand_dims(img, 0))[0]\n\n        # Parse the heatmaps to get mark locations.\n        marks, _ = parse_heatmaps(heatmaps, image.shape[:2])\n        for mark in marks:\n            cv2.circle(image, tuple(mark.astype(int)), 2, (0, 255, 0), -1)\n\n        with self.file_writer.as_default():\n            # tf.summary needs a 4D tensor\n            img_tensor = tf.expand_dims(image, 0)\n            tf.summary.image(\"test-sample\", img_tensor, step=epoch)\n"
  },
  {
    "path": "coreml_conversion.py",
    "content": "\"\"\"Convert the TensorFlow model to CoreML model supported by Apple devices.\n\nMacOS is REQUIRED for quantization.\n\"\"\"\n\nimport os\n\nimport coremltools as ct\nimport tensorflow as tf\nfrom coremltools.models.neural_network import quantization_utils\n\nif __name__ == \"__main__\":\n    # Converted model will be exported here.\n    export_dir = \"./mlmodels\"\n    if not os.path.exists(export_dir):\n        os.mkdir(export_dir)\n\n    # Restore the model.\n    model = tf.keras.models.load_model(\"./exported\")\n\n    # Do the conversion.\n    mlmodel = ct.convert(model)\n    mlmodel.save(\"./mlmodels/hrnetv2_fp32.mlmodel\")\n\n    # Quantization: FP16\n    model_fp16 = quantization_utils.quantize_weights(mlmodel, nbits=16)\n    model_fp16.save(\"./mlmodels/hrnetv2_fp16.mlmodel\")\n\n    # Quantization: INT8\n    model_int8 = quantization_utils.quantize_weights(mlmodel, nbits=8)\n    model_int8.save(\"./mlmodels/model_int8.mlmodel\")\n\n"
  },
  {
    "path": "dataset.py",
    "content": "\"\"\"This module provides the training and testing datasets.\"\"\"\nimport cv2\nimport numpy as np\nimport tensorflow as tf\n\nfrom fmd.universal import Universal\nfrom preprocessing import (flip_randomly, generate_heatmaps, normalize,\n                           rotate_randomly, scale_randomly)\n\n\ndef data_generator(data_dir, name, image_size, number_marks, training):\n    \"\"\"A generator function used to make TensorFlow dataset.\n\n    Currently only `universal` dataset (image + json) of FMD is supported.\n\n    Args:\n        data_dir: the direcotry of the raw image and json files. \n        name: the name of the dataset.\n        image_size: the width and height of the input images for the network.\n        number_marks: how many marks/points does one sample contains.\n        training: generated data will be used for training or not.\n\n    Yields:\n        preprocessed image and heatmaps.\n    \"\"\"\n\n    # Initialize the dataset with files.\n    dataset = Universal(name.decode(\"utf-8\"))\n    dataset.populate_dataset(data_dir.decode(\"utf-8\"), key_marks_indices=None)\n    dataset.meta.update({\"num_marks\": number_marks})\n\n    image_size = tuple(image_size)\n    width, _ = image_size\n    for sample in dataset:\n        # Follow the official preprocessing implementation.\n        image = sample.read_image(\"RGB\")\n        marks = sample.marks\n\n        if training:\n            # Rotate the image randomly.\n            image, marks = rotate_randomly(image, marks, (-30, 30))\n\n            # Scale the image randomly.\n            image, marks = scale_randomly(image, marks, output_size=image_size)\n\n            # Flip the image randomly.\n            image, marks = flip_randomly(image, marks)\n        else:\n            # Scale the image to output size.\n            marks = marks / image.shape[0] * width\n            image = cv2.resize(image, image_size)\n\n        # Normalize the image.\n        image_float = normalize(image.astype(float))\n\n        # Generate heatmaps.\n        heatmaps = generate_heatmaps(marks, width, (64, 64))\n        heatmaps = np.transpose(heatmaps, (1, 2, 0))\n\n        yield image_float, heatmaps\n\n\nclass WFLWSequence(tf.keras.utils.Sequence):\n    \"\"\"A Sequence implementation for WFLW dataset generation.\n\n    This class is not used in training. It simply demonstrates how to generate\n    a TensorFlow dataset by using Keras `Sequence`.\n    \"\"\"\n\n    def __init__(self, data_dir, name, training, batch_size):\n        self.training = training\n        self.batch_size = batch_size\n        self.filenames = []\n        self.marks = []\n\n        # Initialize the dataset with files.\n        dataset = Universal(name)\n        dataset.populate_dataset(data_dir, key_marks_indices=[\n            60, 64, 68, 72, 76, 82])\n\n        for sample in dataset:\n            self.filenames.append(sample.image_file)\n            self.marks.append(sample.marks)\n\n    def __len__(self):\n        return int(np.ceil(len(self.filenames) / float(self.batch_size)))\n\n    def __getitem__(self, index):\n        batch_files = self.filenames[index *\n                                     self.batch_size:(index + 1) * self.batch_size]\n        batch_marks = self.marks[index *\n                                 self.batch_size:(index + 1) * self.batch_size]\n\n        batch_x = []\n        batch_y = []\n\n        for filename, marks in zip(batch_files, batch_marks):\n            # Follow the official preprocessing implementation.\n            image = cv2.imread(filename)\n            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n            if self.training:\n                # Rotate the image randomly.\n                image, marks = rotate_randomly(image, marks, (-30, 30))\n\n                # Scale the image randomly.\n                image, marks = scale_randomly(image, marks)\n\n                # Flip the image randomly.\n                image, marks = flip_randomly(image, marks)\n            else:\n                # Scale the image to output size.\n                marks = marks / image.shape[0] * 256\n                image = cv2.resize(image, (256, 256))\n\n            # Normalize the image.\n            image_float = normalize(image.astype(float))\n\n            # Generate heatmaps.\n            _, img_width, _ = image.shape\n            heatmaps = generate_heatmaps(marks, img_width, (64, 64))\n            heatmaps = np.transpose(heatmaps, (1, 2, 0))\n\n            # Generate the batch data.\n            batch_x.append(image_float)\n            batch_y.append(heatmaps)\n\n        return np.array(batch_x), np.array(batch_y)\n\n\ndef build_dataset(data_dir,\n                  name,\n                  number_marks,\n                  image_shape=(256, 256, 3),\n                  training=True,\n                  batch_size=None,\n                  shuffle=True,\n                  prefetch=None):\n    \"\"\"Generate TensorFlow dataset from image and json files.\n\n    Args:\n        data_dir: the directory of the images and json files.\n        name: dataset name.\n        image_shape: the shape of the target output image of the dataset.\n        number_marks: how many marks/points does one sample contains.\n        training: True if dataset is for training.\n        batch_size: batch size.\n        shuffle: True if data should be shuffled.\n        prefetch: Set to True to prefetch data.\n\n    Returns:\n        a tf.data.dataset.\n    \"\"\"\n    dataset = tf.data.Dataset.from_generator(\n        data_generator,\n        output_types=(tf.float32, tf.float32),\n        output_shapes=(image_shape, (64, 64, number_marks)),\n        args=[data_dir, name, image_shape[:2], number_marks, training])\n\n    print(\"Dataset built from generator: {}\".format(name))\n\n    # Shuffle the data.\n    if shuffle:\n        dataset = dataset.shuffle(1024)\n\n    # Batch the data.\n    dataset = dataset.batch(batch_size)\n\n    # Prefetch the data.\n    if prefetch is not None:\n        dataset = dataset.prefetch(prefetch)\n\n    return dataset\n\n\nif __name__ == \"__main__\":\n    def top_k_indices(x, k):\n        \"\"\"Returns the k largest element indices from a numpy array. You can find\n        the original code here: https://stackoverflow.com/q/6910641\n        \"\"\"\n        flat = x.flatten()\n        indices = np.argpartition(flat, -k)[-k:]\n        indices = indices[np.argsort(-flat[indices])]\n        return np.unravel_index(indices, x.shape)\n\n    def get_peak_location(heatmap, image_size=(256, 256)):\n        \"\"\"Return the interpreted location of the top 2 predictions.\"\"\"\n        h_height, h_width = heatmap.shape\n        [y1, y2], [x1, x2] = top_k_indices(heatmap, 2)\n        x = (x1 + (x2 - x1)/4) / h_width * image_size[0]\n        y = (y1 + (y2 - y1)/4) / h_height * image_size[1]\n\n        return int(x), int(y)\n\n    def _parse_heatmaps(img, heatmaps):\n        # Parse the heatmaps to get mark locations.\n        heatmaps = np.transpose(heatmaps, (2, 0, 1))\n        for heatmap in heatmaps:\n            mark = get_peak_location(heatmap)\n            cv2.circle(img, mark, 2, (0, 255, 0), -1)\n\n        # Show individual heatmaps stacked.\n        heatmap_idvs = np.hstack(heatmaps[:8])\n        for row in range(1, 12, 1):\n            heatmap_idvs = np.vstack(\n                [heatmap_idvs, np.hstack(heatmaps[row:row+8])])\n\n        return img, heatmap_idvs\n\n    data_dir = \"/home/robin/data/facial-marks/wflw_cropped/train\"\n    batch_size = 1\n\n    # Build a sequence dataset.\n    dataset_sequence = make_wflw_dataset(data_dir, \"wflw_sequence\",\n                                         training=True,\n                                         batch_size=batch_size,\n                                         mode=\"sequence\")\n\n    # Build dataset from generator.\n    dataset_from_generator = make_wflw_dataset(data_dir, \"wflw_generator\",\n                                               training=True,\n                                               batch_size=batch_size,\n                                               mode=\"generator\")\n    if not isinstance(dataset_from_generator, tf.keras.utils.Sequence):\n        dataset_from_generator = dataset_from_generator.batch(batch_size)\n\n    for sample_s, sample_g in zip(dataset_sequence, dataset_from_generator):\n        img_s, heatmap_s = sample_s\n        img_g, heatmap_g = sample_g\n\n        img_s, heatmaps_s = _parse_heatmaps(img_s[0], heatmap_s[0])\n        img_g, heatmaps_g = _parse_heatmaps(\n            img_g[0].numpy(), heatmap_g[0].numpy())\n\n        # Show the result in windows.\n        cv2.imshow(\"images\", np.hstack((img_s, img_g)))\n        cv2.imshow(\"heatmaps\", np.hstack((heatmaps_s, heatmaps_g)))\n\n        if cv2.waitKey() == 27:\n            break\n"
  },
  {
    "path": "evaluate.py",
    "content": "\"\"\"Evaluation of the HRNet model on public facial mark datasets.\"\"\"\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\n\nimport fmd\nfrom postprocessing import parse_heatmaps\nfrom preprocessing import crop_face, normalize\nfrom quantization import TFLiteModelPredictor\n\n\ndef compute_nme(prediction, ground_truth):\n    \"\"\"This function is based on the official HRNet implementation.\"\"\"\n\n    interocular = np.linalg.norm(ground_truth[60, ] - ground_truth[72, ])\n    rmse = np.sum(np.linalg.norm(\n        prediction - ground_truth, axis=1)) / (interocular)\n\n    return rmse\n\n\ndef evaluate(dataset: fmd.mark_dataset.dataset, model):\n    \"\"\"Evaluate the model on the dataset. The evaluation method should be the \n    same with the official code.\n\n    Args:\n        dataset: a FMD dataset\n        model: any model having `predict` method.\n    \"\"\"\n    # For NME\n    nme_count = 0\n    nme_sum = 0\n    count_failure_008 = 0\n    count_failure_010 = 0\n\n    # Loop though the dataset samples.\n    for sample in tqdm(dataset):\n        # Get image and marks.\n        image = sample.read_image()\n        marks = sample.marks\n\n        # Crop the face out of the image.\n        image_cropped, border, bbox = crop_face(image, marks, scale=1.2)\n        image_size = image_cropped.shape[:2]\n\n        # Get the prediction from the model.\n        image_cropped = cv2.resize(image_cropped, (256, 256))\n        img_rgb = cv2.cvtColor(image_cropped, cv2.COLOR_BGR2RGB)\n        img_input = normalize(np.array(img_rgb, dtype=np.float32))\n\n        # Do prediction.\n        heatmaps = model.predict(tf.expand_dims(img_input, 0))[0]\n\n        # Parse the heatmaps to get mark locations.\n        marks_prediction, _ = parse_heatmaps(heatmaps, image_size)\n\n        # Transform the marks back to the original image dimensions.\n        x0 = bbox[0] - border\n        y0 = bbox[1] - border\n        marks_prediction[:, 0] += x0\n        marks_prediction[:, 1] += y0\n\n        # Compute NME.\n        nme_temp = compute_nme(marks_prediction, marks[:, :2])\n\n        if nme_temp > 0.08:\n            count_failure_008 += 1\n        if nme_temp > 0.10:\n            count_failure_010 += 1\n\n        nme_sum += nme_temp\n        nme_count = nme_count + 1\n\n        # # Visualize the result.\n        # for mark in marks_prediction:\n        #     cv2.circle(image, tuple(mark.astype(int)), 2, (0, 255, 0), -1)\n\n        # cv2.imshow(\"cropped\", image_cropped)\n        # cv2.imshow(\"image\", image)\n        # if cv2.waitKey(1) == 27:\n        #     break\n\n    # NME\n    nme = nme_sum / nme_count\n    failure_008_rate = count_failure_008 / nme_count\n    failure_010_rate = count_failure_010 / nme_count\n\n    msg = \"NME:{:.4f}, [008]:{:.4f}, [010]:{:.4f}\".format(\n        nme, failure_008_rate, failure_010_rate)\n\n    return msg\n\n\ndef make_dataset():\n    wflw_dir = \"/home/robin/data/facial-marks/wflw/WFLW_images\"\n    ds_wflw = fmd.wflw.WFLW(False, \"wflw_test\")\n    ds_wflw.populate_dataset(wflw_dir)\n\n    return ds_wflw\n\n\nif __name__ == \"__main__\":\n\n    # Evaluate with FP32 model.\n    model = tf.keras.models.load_model(\"exported/hrnetv2\")\n    print(\"FP32: \", evaluate(make_dataset(), model))\n\n    # # Evaluate with FP16 model.\n    # model_qdr = TFLiteModelPredictor(\n    #     \"./optimized/hrnet_quant_fp16.tflite\")\n    # print(\"FP16 quantized:\", evaluate(make_dataset(), model_qdr))\n"
  },
  {
    "path": "fmd/__init__.py",
    "content": "\"\"\"Facial landmark dataset toolkit.\n\nUseage: https://github.com/yinguobing/facial-landmark-dataset\n\"\"\"\nfrom .aflw2000_3d import AFLW2000_3D\nfrom .afw import AFW\nfrom .ds300vw import DS300VW\nfrom .ds300w import DS300W\nfrom .helen import HELEN\nfrom .ibug import IBUG\nfrom .lfpw import LFPW\nfrom .wflw import WFLW\n"
  },
  {
    "path": "fmd/aflw2000_3d.py",
    "content": "import cv2\nimport numpy as np\nfrom scipy.io import loadmat\n\nfrom fmd.mark_dataset.dataset import MarkDataset\nfrom fmd.mark_dataset.util import FileListGenerator\n\n\nclass AFLW2000_3D(MarkDataset):\n    # To use this class, there are two functions should be overridden.\n\n    def populate_dataset(self, image_dir):\n        \"\"\"Populate the AFLW2000_3D dataset with essential data.\n\n        Args:\n            image_dir: the direcotry of the dataset images.\n        \"\"\"\n        # As required by the abstract method, we need to override this function.\n        # 1. populate the image file list.\n        lg = FileListGenerator()\n        self.image_files = lg.generate_list(image_dir)\n\n        # 2. Populate the mark file list. Note the order should be same with the\n        # image file list. Since the AFLW2000_3D dataset had the mark file named\n        # after the image file but with different extention name `mat`. We will\n        # make use of this.\n        self.mark_files = [img_path.split(\n            \".\")[-2] + \".mat\" for img_path in self.image_files]\n\n        # 3 Set the key marks indices. Here key marks are: left eye left corner,\n        #  left eye right corner, right eye left corner, right eye right corner,\n        #  mouse left corner, mouse right corner. For AFLW2000_3D the indices \n        # are 36, 39, 42, 45, 48, 54. Most of the time you need to do this \n        # manually. Refer to the mark dataset for details.\n        self.key_marks_indices = [36, 39, 42, 45, 48, 54]\n\n        # Even optional, it is highly recommended to update the meta data.\n        self.meta.update({\"authors\": \"Chinese Academy of Sciences\",\n                          \"year\": 2015,\n                          \"num_marks\": 68,\n                          \"num_samples\": len(self.image_files)\n                          })\n\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a \n        numpy array in form of [[x, y, z], [x, y, z]].\"\"\"\n        marks = []\n        mat_data = loadmat(mark_file)\n        marks = mat_data['pt3d_68'].T\n        assert marks.shape[1] == 3, \"Marks should be 3D, check z axis values.\"\n        return marks\n"
  },
  {
    "path": "fmd/afw.py",
    "content": "\"\"\"Toolkit for dataset AFW\n\nUseage: https://github.com/yinguobing/facial-landmark-dataset/issues/4\n\"\"\"\n\nimport cv2\nimport numpy as np\n\nfrom fmd.mark_dataset.dataset import MarkDataset\nfrom fmd.mark_dataset.util import FileListGenerator\n\n\nclass AFW(MarkDataset):\n    # To use this class, there are two functions need to be overridden.\n\n    def populate_dataset(self, image_dir):\n        \"\"\"Populate the AFW dataset with essential data.\n\n        Args:\n            image_dir: the direcotry of the dataset images.\n        \"\"\"\n        # As required by the abstract method, we need to override this function.\n        # 1. populate the image file list.\n        lg = FileListGenerator()\n        self.image_files = lg.generate_list(image_dir)\n\n        # 2. Populate the mark file list. Note the order should be same with the\n        # image file list. Since the AFW dataset had the mark file named after\n        # the image file but with different extention name `pts`. We will make\n        # use of this.\n        self.mark_files = [img_path.split(\n            \".\")[-2] + \".pts\" for img_path in self.image_files]\n\n        # 3 Set the key marks indices. Here key marks are: left eye left corner,\n        #  left eye right corner, right eye left corner, right eye right corner,\n        #  mouse left corner, mouse right corner. For AFW the indices are 36,\n        # 39, 42, 45, 48, 54. Most of the time you need to do this manually.\n        # Refer to the mark dataset for details.\n        self.key_marks_indices = [36, 39, 42, 45, 48, 54]\n\n        # Even optional, it is highly recommended to update the meta data.\n        self.meta.update({\"authors\": \"Imperial College London\",\n                          \"year\": 2013,\n                          \"num_marks\": 68,\n                          \"num_samples\": len(self.image_files)\n                          })\n\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a \n        numpy array in form of [[x, y, z], [x, y, z]].\"\"\"\n        marks = []\n        with open(mark_file) as fid:\n            for line in fid:\n                if \"version\" in line or \"points\" in line or \"{\" in line or \"}\" in line:\n                    continue\n                else:\n                    loc_x, loc_y = line.strip().split(sep=\" \")\n                    marks.append([float(loc_x), float(loc_y), 0.0])\n        marks = np.array(marks, dtype=np.float)\n        assert marks.shape[1] == 3, \"Marks should be 3D, check z axis values.\"\n        return marks\n"
  },
  {
    "path": "fmd/ds300vw.py",
    "content": "\"\"\"Dataset tools for 300VW. \n\nRead this issue on GitHub before using:\nhttps://github.com/yinguobing/facial-landmark-dataset/issues/5\"\"\"\n\nimport cv2\nimport numpy as np\n\nfrom fmd.mark_dataset.dataset import MarkDataset\nfrom fmd.mark_dataset.util import FileListGenerator\n\n\nclass DS300VW(MarkDataset):\n    # To use this class, there are two functions should be overridden.\n\n    def populate_dataset(self, image_dir):\n        \"\"\"Populate the 300vW dataset with essential data.\n\n        Args:\n            image_dir: the direcotry of the dataset images.\n        \"\"\"\n        # As required by the abstract method, we need to override this function.\n        # 1. populate the image file list.\n        lg = FileListGenerator()\n        self.image_files = lg.generate_list(image_dir)\n\n        # 2. Populate the mark file list. Note the order should be same with the\n        # image file list. Since the 300VW dataset had the mark file named after\n        # the image file but with different extention name `pts`. We will make\n        # use of this.\n        self.mark_files = [img_path.split(\n            \".\")[-2] + \".pts\" for img_path in self.image_files]\n\n        # 3 Set the key marks indices. Here key marks are: left eye left corner,\n        #  left eye right corner, right eye left corner, right eye right corner,\n        #  mouse left corner, mouse right corner. For 300VW the indices are 36,\n        # 39, 42, 45, 48, 54. Most of the time you need to do this manually.\n        # Refer to the mark dataset for details.\n        self.key_marks_indices = [36, 39, 42, 45, 48, 54]\n\n        # Even optional, it is highly recommended to update the meta data.\n        self.meta.update({\"authors\": \"Imperial College London\",\n                          \"year\": 2015,\n                          \"num_marks\": 68,\n                          \"num_samples\": len(self.image_files)\n                          })\n\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a \n        numpy array in form of [[x, y, z], [x, y, z]].\"\"\"\n        marks = []\n        with open(mark_file) as fid:\n            for line in fid:\n                if \"version\" in line or \"points\" in line or \"{\" in line or \"}\" in line:\n                    continue\n                else:\n                    loc_x, loc_y = line.strip().split(sep=\" \")\n                    marks.append([float(loc_x), float(loc_y), 0.0])\n        marks = np.array(marks, dtype=np.float)\n        assert marks.shape[1] == 3, \"Marks should be 3D, check z axis values.\"\n        return marks\n"
  },
  {
    "path": "fmd/ds300w.py",
    "content": "\"\"\"Toolkit for dataset 300W\n\nUseage: https://github.com/yinguobing/facial-landmark-dataset/issues/1\n\"\"\"\n\nimport cv2\nimport numpy as np\n\nfrom fmd.mark_dataset.dataset import MarkDataset\nfrom fmd.mark_dataset.util import FileListGenerator\n\n\nclass DS300W(MarkDataset):\n    # To use this class, there are two functions should be overridden.\n\n    def populate_dataset(self, image_dir):\n        \"\"\"Populate the 300W dataset with essential data.\n\n        Args:\n            image_dir: the direcotry of the dataset images.\n        \"\"\"\n        # As required by the abstract method, we need to override this function.\n        # 1. populate the image file list.\n        lg = FileListGenerator()\n        self.image_files = lg.generate_list(image_dir)\n\n        # 2. Populate the mark file list. Note the order should be same with the\n        # image file list. Since the 300W dataset had the mark file named after\n        # the image file but with different extention name `pts`. We will make\n        # use of this.\n        self.mark_files = [img_path.split(\n            \".\")[-2] + \".pts\" for img_path in self.image_files]\n\n        # 3 Set the key marks indices. Here key marks are: left eye left corner,\n        #  left eye right corner, right eye left corner, right eye right corner,\n        #  mouse left corner, mouse right corner. For 300W the indices are 36,\n        # 39, 42, 45, 48, 54. Most of the time you need to do this manually.\n        # Refer to the mark dataset for details.\n        self.key_marks_indices = [36, 39, 42, 45, 48, 54]\n\n        # Even optional, it is highly recommended to update the meta data.\n        self.meta.update({\"authors\": \"Imperial College London\",\n                          \"year\": 2013,\n                          \"num_marks\": 68,\n                          \"num_samples\": len(self.image_files)\n                          })\n\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a \n        numpy array in form of [[x, y, z], [x, y, z]].\"\"\"\n        marks = []\n        with open(mark_file) as fid:\n            for line in fid:\n                if \"version\" in line or \"points\" in line or \"{\" in line or \"}\" in line:\n                    continue\n                else:\n                    loc_x, loc_y = line.strip().split(sep=\" \")\n                    marks.append([float(loc_x), float(loc_y), 0.0])\n        marks = np.array(marks, dtype=np.float)\n        assert marks.shape[1] == 3, \"Marks should be 3D, check z axis values.\"\n        return marks\n"
  },
  {
    "path": "fmd/ds300w_lp.py",
    "content": "import cv2\nimport numpy as np\nfrom scipy.io import loadmat\n\nfrom mark_dataset.dataset import MarkDataset\nfrom mark_dataset.util import FileListGenerator\n\n\nclass DS300W_LP(MarkDataset):\n    # To use this class, there are two functions should be overridden.\n\n    def populate_dataset(self, image_dir):\n        \"\"\"Populate the 300W_LP dataset with essential data.\n\n        Args:\n            image_dir: the direcotry of the dataset images.\n        \"\"\"\n        # As required by the abstract method, we need to override this function.\n        # 1. populate the image file list.\n        lg = FileListGenerator()\n        self.image_files = lg.generate_list(image_dir)\n\n        # 2. Populate the mark file list. Note the order should be same with the\n        # image file list. Since the 300W_LP dataset had the mark file named\n        # after the image file but with different extention name `mat`. We will\n        # make use of this.\n        self.mark_files = [img_path.split(\n            \".\")[-2] + \".mat\" for img_path in self.image_files]\n\n        # 3 Set the key marks indices. Here key marks are: left eye left corner,\n        #  left eye right corner, right eye left corner, right eye right corner,\n        #  mouse left corner, mouse right corner. For 300W_LP the indices \n        # are 36, 39, 42, 45, 48, 54. Most of the time you need to do this \n        # manually. Refer to the mark dataset for details.\n        self.key_marks_indices = [36, 39, 42, 45, 48, 54]\n\n        # Even optional, it is highly recommended to update the meta data.\n        self.meta.update({\"authors\": \"Chinese Academy of Sciences\",\n                          \"year\": 2015,\n                          \"num_marks\": 68,\n                          \"num_samples\": len(self.image_files)\n                          })\n\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a \n        numpy array in form of [[x, y, z], [x, y, z]].\"\"\"\n        marks = []\n        mat_data = loadmat(mark_file)\n        marks = np.pad(mat_data['pt2d'].T, (0, 1))\n        assert marks.shape[1] == 3, \"Marks should be 3D, check z axis values.\"\n        return marks\n"
  },
  {
    "path": "fmd/helen.py",
    "content": "\"\"\"Dataset tookit for HELEN.\n\nUseage: https://github.com/yinguobing/facial-landmark-dataset/issues/3\n\"\"\"\n\nimport cv2\nimport numpy as np\n\nfrom fmd.mark_dataset.dataset import MarkDataset\nfrom fmd.mark_dataset.util import FileListGenerator\n\n\nclass HELEN(MarkDataset):\n    # To use this class, there are two functions need to be overridden.\n\n    def populate_dataset(self, image_dir):\n        \"\"\"Populate the HELEN dataset with essential data.\n\n        Args:\n            image_dir: the direcotry of the dataset images.\n        \"\"\"\n        # As required by the abstract method, we need to override this function.\n        # 1. populate the image file list.\n        lg = FileListGenerator()\n        self.image_files = lg.generate_list(image_dir)\n\n        # 2. Populate the mark file list. Note the order should be same with the\n        # image file list. Since the HELEN dataset had the mark file named after\n        # the image file but with different extention name `pts`. We will make\n        # use of this.\n        self.mark_files = [img_path.split(\n            \".\")[-2] + \".pts\" for img_path in self.image_files]\n\n        # 3 Set the key marks indices. Here key marks are: left eye left corner,\n        #  left eye right corner, right eye left corner, right eye right corner,\n        #  mouse left corner, mouse right corner. For HELEN the indices are 36,\n        # 39, 42, 45, 48, 54. Most of the time you need to do this manually.\n        # Refer to the mark dataset for details.\n        self.key_marks_indices = [36, 39, 42, 45, 48, 54]\n\n        # Even optional, it is highly recommended to update the meta data.\n        self.meta.update({\"authors\": \"Imperial College London\",\n                          \"year\": 2013,\n                          \"num_marks\": 68,\n                          \"num_samples\": len(self.image_files)\n                          })\n\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a \n        numpy array in form of [[x, y, z], [x, y, z]].\"\"\"\n        marks = []\n        with open(mark_file) as fid:\n            for line in fid:\n                if \"version\" in line or \"points\" in line or \"{\" in line or \"}\" in line:\n                    continue\n                else:\n                    loc_x, loc_y = line.strip().split(sep=\" \")\n                    marks.append([float(loc_x), float(loc_y), 0.0])\n        marks = np.array(marks, dtype=np.float)\n        assert marks.shape[1] == 3, \"Marks should be 3D, check z axis values.\"\n        return marks\n"
  },
  {
    "path": "fmd/ibug.py",
    "content": "\"\"\"Dataset toolkit for IBUG\n\nUseage: https://github.com/yinguobing/facial-landmark-dataset/issues/3\n\"\"\"\n\nimport cv2\nimport numpy as np\n\nfrom fmd.mark_dataset.dataset import MarkDataset\nfrom fmd.mark_dataset.util import FileListGenerator\n\n\nclass IBUG(MarkDataset):\n    # To use this class, there are two functions need to be overridden.\n\n    def populate_dataset(self, image_dir):\n        \"\"\"Populate the IBUG dataset with essential data.\n\n        Args:\n            image_dir: the direcotry of the dataset images.\n        \"\"\"\n        # As required by the abstract method, we need to override this function.\n        # 1. populate the image file list.\n        lg = FileListGenerator()\n        self.image_files = lg.generate_list(image_dir)\n\n        # 2. Populate the mark file list. Note the order should be same with the\n        # image file list. Since the IBUG dataset had the mark file named after\n        # the image file but with different extention name `pts`. We will make\n        # use of this.\n        self.mark_files = [img_path.split(\n            \".\")[-2] + \".pts\" for img_path in self.image_files]\n\n        # 3 Set the key marks indices. Here key marks are: left eye left corner,\n        #  left eye right corner, right eye left corner, right eye right corner,\n        #  mouse left corner, mouse right corner. For IBUG the indices are 36,\n        # 39, 42, 45, 48, 54. Most of the time you need to do this manually.\n        # Refer to the mark dataset for details.\n        self.key_marks_indices = [36, 39, 42, 45, 48, 54]\n\n        # Even optional, it is highly recommended to update the meta data.\n        self.meta.update({\"authors\": \"Imperial College London\",\n                          \"year\": 2013,\n                          \"num_marks\": 68,\n                          \"num_samples\": len(self.image_files)\n                          })\n\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a \n        numpy array in form of [[x, y, z], [x, y, z]].\"\"\"\n        marks = []\n        with open(mark_file) as fid:\n            for line in fid:\n                if \"version\" in line or \"points\" in line or \"{\" in line or \"}\" in line:\n                    continue\n                else:\n                    loc_x, loc_y = line.strip().split(sep=\" \")\n                    marks.append([float(loc_x), float(loc_y), 0.0])\n        marks = np.array(marks, dtype=np.float)\n        assert marks.shape[1] == 3, \"Marks should be 3D, check z axis values.\"\n        return marks\n"
  },
  {
    "path": "fmd/lfpw.py",
    "content": "\"\"\"Dataset tookit for LFPW.\n\nUseage: https://github.com/yinguobing/facial-landmark-dataset/issues/2\n\"\"\"\n\nimport cv2\nimport numpy as np\n\nfrom fmd.mark_dataset.dataset import MarkDataset\nfrom fmd.mark_dataset.util import FileListGenerator\n\n\nclass LFPW(MarkDataset):\n    # To use this class, there are two functions need to be overridden.\n\n    def populate_dataset(self, image_dir):\n        \"\"\"Populate the LFPW dataset with essential data.\n\n        Args:\n            image_dir: the direcotry of the dataset images.\n        \"\"\"\n        # As required by the abstract method, we need to override this function.\n        # 1. populate the image file list.\n        lg = FileListGenerator()\n        self.image_files = lg.generate_list(image_dir)\n\n        # 2. Populate the mark file list. Note the order should be same with the\n        # image file list. Since the LFPW dataset had the mark file named after\n        # the image file but with different extention name `pts`. We will make\n        # use of this.\n        self.mark_files = [img_path.split(\n            \".\")[-2] + \".pts\" for img_path in self.image_files]\n\n        # 3 Set the key marks indices. Here key marks are: left eye left corner,\n        #  left eye right corner, right eye left corner, right eye right corner,\n        #  mouse left corner, mouse right corner. For LFPW the indices are 36,\n        # 39, 42, 45, 48, 54. Most of the time you need to do this manually.\n        # Refer to the mark dataset for details.\n        self.key_marks_indices = [36, 39, 42, 45, 48, 54]\n\n        # Even optional, it is highly recommended to update the meta data.\n        self.meta.update({\"authors\": \"Imperial College London\",\n                          \"year\": 2013,\n                          \"num_marks\": 68,\n                          \"num_samples\": len(self.image_files)\n                          })\n\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a \n        numpy array in form of [[x, y, z], [x, y, z]].\"\"\"\n        marks = []\n        with open(mark_file) as fid:\n            for line in fid:\n                if \"version\" in line or \"points\" in line or \"{\" in line or \"}\" in line:\n                    continue\n                else:\n                    loc_x, loc_y = line.strip().split(sep=\" \")\n                    marks.append([float(loc_x), float(loc_y), 0.0])\n        marks = np.array(marks, dtype=np.float)\n        assert marks.shape[1] == 3, \"Marks should be 3D, check z axis values.\"\n        return marks\n"
  },
  {
    "path": "fmd/mark_dataset/__init__.py",
    "content": ""
  },
  {
    "path": "fmd/mark_dataset/data_pair.py",
    "content": "\"\"\"This module constains the implimentation of class DataPair.\"\"\"\nimport json\n\nimport cv2\nimport numpy as np\n\n\nclass DataPair(object):\n    \"\"\"A pair of data consists of a single image and coresponding marks.\"\"\"\n\n    def __init__(self, image_file, marks, key_marks_indices):\n        \"\"\"Construct a facial mark data pair\n\n        Args:\n            image_file: a path to the image.\n            marks: facial marks stored in a numpy array, as [[x, y, z], [x, y, z]\n            ...].\n            key_marks_indices: the indices of key marks. Key marks are: left eye\n            left corner, left eye right corner, right eye left corner, right eye\n            right corner, mouse left corner, mouse right corner.\n\n        Returns:\n            a DataPair object.\n        \"\"\"\n        self.image_file = image_file\n        self.marks = marks\n        self.key_marks_indices = key_marks_indices\n\n    def read_image(self, format=\"BGR\"):\n        \"\"\"Read in the image as a Numpy array.\n\n        Args:\n            format: Color channel order, \"BGR\" as default. Set it to \"RGB\" if you\n            want to use it in matplotlib.\n\n        Returns:\n            an image as numpy array.\n        \"\"\"\n        image_bgr = cv2.imread(self.image_file, cv2.IMREAD_COLOR)\n        if format is \"RGB\":\n            return cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n        return image_bgr\n\n    def get_marks(self):\n        \"\"\"Return all the marks.\n\n        Args:\n            None\n\n        Returns:\n            The full marks as a numpy array.\n        \"\"\"\n        return self.marks\n\n    def get_key_marks(self):\n        \"\"\"Return the key marks of the current marks, in the order of: left eye\n            left corner, left eye right corner, right eye left corner, right eye\n            right corner, mouse left corner, mouse right corner.\n\n        Args:\n            None\n\n        Returns:\n            key marks in form of [[x, y, z],[x, y, z]] as a numpy array.\n        \"\"\"\n        key_marks = []\n        [key_marks.append(self.marks[i]) for i in self.key_marks_indices]\n        return np.array(key_marks)\n\n    def save_mark_to_json(self, file_name):\n        \"\"\"Save the marks to a json file.\n\n        Args:\n            file_name: the full path of the json file.\n\n        Returns:\n            None\n        \"\"\"\n        with open(file_name, \"w\") as fid:\n            json.dump(self.marks.tolist(), fid)\n"
  },
  {
    "path": "fmd/mark_dataset/dataset.py",
    "content": "from abc import ABC, abstractmethod\nfrom .data_pair import DataPair\nimport numpy as np\n\n\nclass MarkDataset(ABC):\n\n    def __init__(self, dataset_name):\n        self.meta = {\"name\": dataset_name,\n                     \"authors\": None,\n                     \"year\": None,\n                     \"num_marks\": None,\n                     \"num_samples\": None}\n        self.image_files = None\n        self.mark_files = None\n        self.key_marks_indices = None\n        self.index = 0\n        super().__init__()\n\n    def __str__(self):\n        # This function overridden makes the instance printable.\n        description = \"\".join(\"{}: {}\\n\".format(k, v)\n                              for k, v in self.meta.items())\n        return description\n\n    def __len__(self):\n        _len = self.meta['num_samples']\n        return 0 if _len is None else _len\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        if self.index == len(self.image_files):\n            raise StopIteration\n        dp = self._make_datapair(self.index)\n        self.index += 1\n        return dp\n\n    def _make_datapair(self, data_index):\n        # Get the coresponding marks.\n        marks = self.get_marks_from_file(\n            self.mark_files[data_index]).astype(float)\n\n        # Construct a datapair.\n        return DataPair(self.image_files[data_index], marks, self.key_marks_indices)\n\n    @abstractmethod\n    def populate_dataset(self):\n        \"\"\"An abstract method to be overridden. This function should populate\n        the dataset with essential data, including:\n\n        * `image_files` This is a list of dataset image file paths. It should\n        contain all the image samples.\n\n        * `mark_files`. This is a list of dataset mark file paths. It should\n        contain all the mark files. Note alignment of image and mark files is\n        **required**. For instance:\n            image_files: [\"a.jpg\", \"b.jpg\", \"c.jpg\"]\n            mark_files; [\"a.json\", \"b.json\", \"c.json\"]\n\n        * `key_mark_indices` This is a list of indices of specific marks.\n        Currently they are: left eye left corner, left eye right corner, right\n        eye left corner, right eye right corner, mouse left corner, mouse right\n        corner.\n\n        Remember to set the meta data, even this is optional.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a\n        numpy array in form of [[x, y, z], [x, y, z]].\"\"\"\n        pass\n\n    def pick_one(self):\n        \"\"\"Randomly pick a data pair.\"\"\"\n        # Pick a number randomly.\n        straw = np.random.randint(0, len(self.image_files))\n\n        return self._make_datapair(straw)\n\n    def export(self, export_dir):\n        \"\"\"Export the dataset in the FMD format.\n\n        Args:\n            export_dir: the directory to save the dataset.\n        \"\"\"\n        pass\n"
  },
  {
    "path": "fmd/mark_dataset/util.py",
    "content": "\"\"\"\nSome convenient tools for dataset parsing and construction.\n\"\"\"\nimport csv\nimport os\nimport cv2\n\n\nclass FileListGenerator:\n    \"\"\"Generate a list of specific files in directory.\"\"\"\n\n    def __init__(self):\n        \"\"\"Initialization\"\"\"\n        # The list to be populated.\n        self.file_list = []\n\n    def generate_list(self, target_dir, format_list=[\"jpg\", \"png\"]):\n        \"\"\"Generate the file list of format_list in target_dir\n\n        Args:\n            target_dir: the directory in which files will be listed.\n            format_list: a list of file extention names.\n\n        Returns:\n            a list of file urls.\n\n        \"\"\"\n        self.file_list.clear()\n        # Walk through directories and list all files.\n        for file_path, _, current_files in os.walk(target_dir, followlinks=False):\n            for filename in current_files:\n                # First make sure the file is exactly of the format we need.\n                # Then process the file.\n                if filename.split('.')[-1] in format_list:\n                    # Get file url.\n                    file_url = os.path.join(file_path, filename)\n                    self.file_list.append(file_url)\n\n        return self.file_list\n\n    def save_file_path_list(self, list_name='list.csv'):\n        \"\"\"Save the list in csv format.\n\n        Args:\n            list_name: the file name to be written.\n\n        \"\"\"\n        with open(list_name, 'w', newline='') as csv_file:\n            writer = csv.DictWriter(csv_file, fieldnames=['file_url'])\n\n            # Write the header.\n            writer.writeheader()\n\n            # Write all the rows.\n            for each_record in self.file_list:\n                writer.writerow({'file_url': each_record})\n\n    def save_basename_list(self, list_name='basename.csv'):\n        basename_list = []\n        for each_record in self.file_list:\n            basename = os.path.basename(each_record)\n            print(basename)\n            basename_list.append(basename.split(\".\")[-2])\n\n        with open(list_name, 'w', newline='') as csv_file:\n            writer = csv.DictWriter(csv_file, fieldnames=['file_basename'])\n\n            # Write the header.\n            writer.writeheader()\n\n            # Write all the rows.\n            for each_record in basename_list:\n                writer.writerow({'file_basename': each_record})\n\n\ndef draw_marks(image, marks, mark_size=3, color=(0, 255, 0), line_width=-1):\n    \"\"\"Draw the marks in image.\n    Args:\n        image: the image on which to be drawn.\n        marks: points coordinates in a numpy array.\n        mark_size: the size of the marks.\n        color: the color of the marks, in BGR format, ranges 0~255.\n        line_width: the width of the mark's outline. Set to -1 to fill it.\n    \"\"\"\n    # We are drawing in an image, this is a 2D situation.\n    for point in marks:\n        cv2.circle(image, (int(point[0]), int(point[1])),\n                   mark_size, color, line_width, cv2.LINE_AA)\n"
  },
  {
    "path": "fmd/universal.py",
    "content": "\"\"\"Dataset toolkit for Universal data format.\n\nIn this format the marks are stored in a json file which has same basename of \nthe image file.\n\nExample:\n    /path/to/sample.jpg\n    /path/to/sample.json\n\"\"\"\n\nimport json\n\nimport cv2\nimport numpy as np\n\nfrom fmd.mark_dataset.dataset import MarkDataset\nfrom fmd.mark_dataset.util import FileListGenerator\n\n\nclass Universal(MarkDataset):\n    # To use this class, there are two functions need to be overridden.\n\n    def populate_dataset(self, image_dir, key_marks_indices):\n        \"\"\"Populate the IBUG dataset with essential data.\n\n        Args:\n            image_dir: the direcotry of the dataset images.\n        \"\"\"\n        # As required by the abstract method, we need to override this function.\n        # 1. populate the image file list.\n        lg = FileListGenerator()\n        self.image_files = lg.generate_list(image_dir)\n\n        # 2. Populate the mark file list. Note the order should be same with the\n        # image file list. Since the IBUG dataset had the mark file named after\n        # the image file but with different extention name `pts`. We will make\n        # use of this.\n        self.mark_files = [img_path.split(\n            \".\")[-2] + \".json\" for img_path in self.image_files]\n\n        # 3 Set the key marks indices. Here key marks are: left eye left corner,\n        #  left eye right corner, right eye left corner, right eye right corner,\n        #  mouse left corner, mouse right corner. For IBUG the indices are 36,\n        # 39, 42, 45, 48, 54. Most of the time you need to do this manually.\n        # Refer to the mark dataset for details.\n        self.key_marks_indices = key_marks_indices\n\n        # Even optional, it is highly recommended to update the meta data.\n        self.meta.update({\"authors\": \"YinGuobing\",\n                          \"year\": 2020,\n                          \"num_marks\": 98,\n                          \"num_samples\": len(self.image_files)\n                          })\n\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a \n        numpy array in form of [[x, y, z], [x, y, z]].\"\"\"\n        marks = []\n        with open(mark_file) as fid:\n            mark_list = json.load(fid)\n            marks = np.reshape(\n                mark_list, (self.meta['num_marks'], -1)).astype(float)\n        if marks.shape[1] == 2:\n            marks = np.pad(marks, ((0, 0), (0, 1)), constant_values=-1)\n        assert marks.shape[1] == 3, \"Marks should be 3D, check z axis values.\"\n        return marks\n"
  },
  {
    "path": "fmd/wflw.py",
    "content": "\"\"\"Dataset tookit for WFLW.\n\nUseage: https://github.com/yinguobing/facial-landmark-dataset/issues/6\n\"\"\"\n\nimport os\n\nimport cv2\nimport numpy as np\n\nfrom fmd.mark_dataset.dataset import MarkDataset\nfrom fmd.mark_dataset.util import FileListGenerator\n\n\nclass WFLW(MarkDataset):\n    \"\"\"Please make sure the uncompressed files are in the same folder:\n\n    .\n    ├── WFLW_annotations\n    └── WFLW_images\n    \"\"\"\n\n    def __init__(self, is_train, name):\n        \"\"\"Initialize a WFLW dataset.\n\n        Args:\n            is_train: construct the training set if set to True, else test set.\n\n        \"\"\"\n        super(WFLW, self).__init__(dataset_name=name)\n        self.is_train = is_train\n\n    def populate_dataset(self, image_dir):\n        \"\"\"Populate the WFLW dataset with essential data.\n\n        Args:\n            image_dir: the direcotry of the dataset images.\n        \"\"\"\n        # As required by the abstract method, we need to override this function.\n\n        # 1. Populate the mark file list. Note the order should be same with the\n        # image file list. Since WFLW was not using single mark file, a virtual\n        # mark file will be generated.\n\n        # First, parse all the marks and store them in memory.\n        self.dataset_root_folder = os.path.dirname(image_dir)\n        mark_file_test = os.path.join(self.dataset_root_folder,\n                                      \"WFLW_annotations\",\n                                      \"list_98pt_rect_attr_train_test\",\n                                      \"list_98pt_rect_attr_test.txt\")\n        mark_file_train = os.path.join(self.dataset_root_folder,\n                                       \"WFLW_annotations\",\n                                       \"list_98pt_rect_attr_train_test\",\n                                       \"list_98pt_rect_attr_train.txt\")\n\n        self.image_files = []\n        self.mark_group = []\n\n        def _read_mark_file(mark_file):\n            with open(mark_file) as fid:\n                for line in fid:\n                    raw_data = line.strip().split(sep=\" \")\n                    marks = np.array(raw_data[:98*2], np.float).reshape(-1, 2)\n                    marks = np.pad(marks, ((0, 0), (0, 1)),\n                                   mode='constant', constant_values=0)\n                    image_path = os.path.join(image_dir, raw_data[-1])\n                    self.image_files.append(image_path)\n                    self.mark_group.append(marks)\n\n        if self.is_train:\n            _read_mark_file(mark_file_train)\n        else:\n            _read_mark_file(mark_file_test)\n\n        # This is the virtual mark files. It is actually a int number.\n        self.mark_files = range(len(self.image_files))\n\n        # 3. Set the key marks indices. Here key marks are: left eye left corner,\n        #  left eye right corner, right eye left corner, right eye right corner,\n        #  mouse left corner, mouse right corner.\n        self.key_marks_indices = [60, 64, 68, 72, 76, 82]\n\n        # Even optional, it is highly recommended to update the meta data.\n        self.meta.update({\"authors\": \"Tsinghua National Laboratory\",\n                          \"year\": 2018,\n                          \"num_marks\": 98,\n                          \"num_samples\": len(self.image_files)\n                          })\n\n    def get_marks_from_file(self, mark_file):\n        \"\"\"This function should read the mark file and return the marks as a\n        numpy array in form of [[x, y, z], [x, y, z]].\n        Be carefull we are using int numbers as virtual mark files\"\"\"\n        return self.mark_group[mark_file]\n"
  },
  {
    "path": "mark_operator.py",
    "content": "\"\"\"A module provids common operations for point marks.\n\nAll marks, or points are numpy arrays of format like:\n    mark = [x, y, z]\n    marks = [[x, y, z],\n             [x, y, z],\n             ...,\n             [x, y, z]]\n\nVectors are also numpy arrays:\n    vector = [x, y, z]\n    vectors = [[x, y, z],\n               [x, y, z],\n               ...,\n               [x, y, z]]\n\n\"\"\"\nimport numpy as np\n\n\nclass MarkOperator(object):\n    \"\"\"Operator instances are used to transform the marks.\"\"\"\n\n    def __init__(self):\n        pass\n\n    def get_distance(self, mark1, mark2):\n        \"\"\"Calculate the distance between two marks.\"\"\"\n        return np.linalg.norm(mark2 - mark1)\n\n    def get_angle(self, vector1, vector2, in_radian=False):\n        \"\"\"Return the angel between two vectors.\"\"\"\n        d = np.dot(vector1, vector2)\n        cos_angle = d / (np.linalg.norm(vector1) * np.linalg.norm(vector2))\n        if cos_angle > 1.0:\n            radian = 0\n        elif cos_angle < -1.0:\n            radian = np.pi\n        else:\n            radian = np.arccos(cos_angle)\n\n        c = np.cross(vector1, vector2)\n        if (c.ndim == 0 and c < 0) or (c.ndim == 1 and c[2] < 0):\n            radian = 2*np.pi - radian\n\n        return radian if in_radian is True else np.rad2deg(radian)\n\n    def pad_to_3d(self, marks_2d, pad_value=-1):\n        \"\"\"Pad the 2D marks with zeros in z axis.\"\"\"\n        marks_3d = np.pad(marks_2d, ((0, 0), (0, 1)),\n                          mode='constant', constant_values=pad_value)\n\n        return marks_3d\n\n    def get_center(self, marks):\n        \"\"\"Return the center point of the mark group.\"\"\"\n        x, y, z = (np.amax(marks, 0) + np.amin(marks, 0)) / 2\n\n        return np.array([x, y, z])\n\n    def get_height_width_depth(self, marks):\n        \"\"\"Return the height and width of the marks bounding box.\"\"\"\n        height, width, depth = np.amax(marks, 0) - np.amin(marks, 0)\n\n        return height, width, depth\n\n    def rotate(self, marks, radian, center=(0, 0)):\n        \"\"\"Rotate the marks around center by angle\"\"\"\n        _points = marks[:, :2] - np.array(center, np.float)\n        cos_angle = np.cos(-radian)\n        sin_angle = np.sin(-radian)\n        rotaion_matrix = np.array([[cos_angle, sin_angle],\n                                   [-sin_angle, cos_angle]])\n        marks[:, :2] = np.dot(_points, rotaion_matrix) + center\n\n        return marks\n\n    def flip_lr(self, marks, width):\n        \"\"\"Flip the marks in horizontal direction.\"\"\"\n        marks[:, 0] = width - marks[:, 0]\n\n        # Reset the order of the marks. The HRNet authors had provided this\n        # information in the official repository.\n        num_marks = marks.shape[0]\n        if num_marks == 98:     # WFLW\n            mirrored_pairs = np.array([\n                [0,  32], [1,  31], [2,  30], [3,  29], [4,  28], [5,  27],\n                [6,  26], [7,  25], [8,  24], [9,  23], [10, 22], [11, 21],\n                [12, 20], [13, 19], [14, 18], [15, 17], [33, 46], [34, 45],\n                [35, 44], [36, 43], [37, 42], [38, 50], [39, 49], [40, 48],\n                [41, 47], [60, 72], [61, 71], [62, 70], [63, 69], [64, 68],\n                [65, 75], [66, 74], [67, 73], [55, 59], [56, 58], [76, 82],\n                [77, 81], [78, 80], [87, 83], [86, 84], [88, 92], [89, 91],\n                [95, 93], [96, 97]\n            ])\n        elif num_marks == 68:   # IBUG, etc.\n            mirrored_pairs = np.array([\n                [1,  17], [2,  16], [3,  15], [4,  14], [5,  13], [6,  12],\n                [7,  11], [8,  10], [18, 27], [19, 26], [20, 25], [21, 24],\n                [22, 23], [32, 36], [33, 35], [37, 46], [38, 45], [39, 44],\n                [40, 43], [41, 48], [42, 47], [49, 55], [50, 54], [51, 53],\n                [62, 64], [61, 65], [68, 66], [59, 57], [60, 56]]) - 1\n        else:\n            raise ValueError(\n                \"Number of points {} not supported, please check the dataset.\".format(num_marks))\n\n        tmp = marks[mirrored_pairs[:, 0]]\n        marks[mirrored_pairs[:, 0]] = marks[mirrored_pairs[:, 1]]\n        marks[mirrored_pairs[:, 1]] = tmp\n\n        return marks\n\n    def _generate_heatmap(self, heatmap_size, center_point, sigma):\n        \"\"\"Generating a heatmap with Gaussian distribution.\n\n        Args:\n            heatmap_size: a tuple containing the size of the heatmap.\n            center_point: a tuple containing the center point of the distribution.\n            sigma: how large area the distribution covers.\n\n        Returns:\n            a heatmap\n        \"\"\"\n        def _generate_gaussian_map(sigma):\n            \"\"\"Generate gaussian distribution with center value equals to 1.\"\"\"\n            heat_range = 2 * sigma * 3 + 1\n            xs = np.arange(0, heat_range, 1, np.float32)\n            ys = xs[:, np.newaxis]\n            x_core = y_core = heat_range // 2\n            gaussian = np.exp(-((xs - x_core) ** 2 + (ys - y_core)\n                                ** 2) / (2 * sigma ** 2))\n\n            return gaussian\n\n        # Check that any part of the gaussian is in-bounds\n        map_height, map_width = heatmap_size\n        x, y = int(center_point[0]), int(center_point[1])\n\n        radius = sigma * 3\n        x0, y0 = x - radius, y - radius\n        x1, y1 = x + radius + 1, y + radius + 1\n\n        # If the distribution is out of the map, return an empty map.\n        if (x0 >= map_width or y0 >= map_height or x1 < 0 or y1 < 0):\n            return np.zeros(heatmap_size)\n\n        # Generate a Gaussian map.\n        gaussian = _generate_gaussian_map(sigma)\n\n        # Get the intersection area of the Gaussian map.\n        x_gauss = max(0, -x0), min(x1, map_width) - x0\n        y_gauss = max(0, -y0), min(y1, map_height) - y0\n        gaussian = gaussian[y_gauss[0]: y_gauss[1], x_gauss[0]: x_gauss[1]]\n\n        # Pad the Gaussian with zeros to get the heatmap.\n        pad_width = np.max(\n            [[0, 0, 0, 0], [y0, map_height-y1, x0, map_width-x1, ]], axis=0).reshape([2, 2])\n        heatmap = np.pad(gaussian, pad_width, mode='constant')\n\n        return heatmap\n\n    def generate_heatmaps(self, norm_marks, map_size=(64, 64), sigma=3):\n        \"\"\"Generate heatmaps for all the marks.\"\"\"\n        maps = []\n        width, height = map_size\n        for norm_mark in norm_marks:\n            x = width * norm_mark[0]\n            y = height * norm_mark[1]\n            heatmap = self._generate_heatmap(map_size, (x, y), sigma)\n            maps.append(heatmap)\n\n        return np.array(maps, dtype=np.float32)\n"
  },
  {
    "path": "network.py",
    "content": "import tensorflow as tf\nimport tensorflow_model_optimization as tfmot\nfrom tensorflow import keras\nfrom tensorflow.keras import Model, layers\n\nfrom models.hrnet import HRNetBody, hrnet_body\n\n\ndef hrnet_stem(filters=64):\n    stem_layers = [layers.Conv2D(filters, 3, 2, 'same'),\n                   layers.BatchNormalization(),\n                   layers.Conv2D(filters, 3, 2, 'same'),\n                   layers.BatchNormalization(),\n                   layers.Activation('relu')]\n\n    def forward(x):\n        for layer in stem_layers:\n            x = layer(x)\n        return x\n\n    return forward\n\n\ndef hrnet_heads(input_channels=64, output_channels=17):\n    # Construct up sacling layers.\n    scales = [2, 4, 8]\n    up_scale_layers = [layers.UpSampling2D((s, s)) for s in scales]\n    concatenate_layer = layers.Concatenate(axis=3)\n    heads_layers = [layers.Conv2D(filters=input_channels, kernel_size=(1, 1),\n                                  strides=(1, 1), padding='same'),\n                    layers.BatchNormalization(),\n                    layers.Activation('relu'),\n                    layers.Conv2D(filters=output_channels, kernel_size=(1, 1),\n                                  strides=(1, 1), padding='same')]\n\n    def forward(inputs):\n        scaled = [f(x) for f, x in zip(up_scale_layers, inputs[1:])]\n        x = concatenate_layer([inputs[0], scaled[0], scaled[1], scaled[2]])\n        for layer in heads_layers:\n            x = layer(x)\n        return x\n\n    return forward\n\n\nclass HRNetStem(layers.Layer, tfmot.sparsity.keras.PrunableLayer):\n\n    def __init__(self, filters=64, **kwargs):\n        super(HRNetStem, self).__init__(**kwargs)\n\n        self.filters = filters\n\n    def build(self, input_shape):\n        # The stem of the network.\n        self.conv_1 = layers.Conv2D(self.filters, 3, 2, 'same')\n        self.batch_norm_1 = layers.BatchNormalization()\n        self.conv_2 = layers.Conv2D(self.filters, 3, 2, 'same')\n        self.batch_norm_2 = layers.BatchNormalization()\n        self.activation = layers.Activation('relu')\n\n        self.built = True\n\n    def call(self, inputs):\n        x = self.conv_1(inputs)\n        x = self.batch_norm_1(x)\n        x = self.conv_2(x)\n        x = self.batch_norm_2(x)\n        x = self.activation(x)\n\n        return x\n\n    def get_config(self):\n        config = super(HRNetStem, self).get_config()\n        config.update({\"filters\": self.filters})\n\n        return config\n\n    def get_prunable_weights(self):\n        prunable_weights = [getattr(self.conv_1, 'kernel'),\n                            getattr(self.conv_2, 'kernel')]\n\n        return prunable_weights\n\n\nclass HRNetHeads(layers.Layer):\n\n    def __init__(self, input_channels=64, output_channels=17, **kwargs):\n        super(HRNetHeads, self).__init__(**kwargs)\n\n        self.input_channels = input_channels\n        self.output_channels = output_channels\n\n    def build(self, input_shape):\n        # Up sampling layers.\n        scales = [2, 4, 8]\n        self.up_scale_layers = [layers.UpSampling2D((s, s)) for s in scales]\n        self.concatenate = layers.Concatenate(axis=3)\n        self.conv_1 = layers.Conv2D(filters=self.input_channels, kernel_size=(1, 1),\n                                    strides=(1, 1), padding='same')\n        self.batch_norm = layers.BatchNormalization()\n        self.activation = layers.Activation('relu')\n        self.conv_2 = layers.Conv2D(filters=self.output_channels, kernel_size=(1, 1),\n                                    strides=(1, 1), padding='same')\n\n        self.built = True\n\n    def call(self, inputs):\n        scaled = [f(x) for f, x in zip(self.up_scale_layers, inputs[1:])]\n        x = self.concatenate([inputs[0], scaled[0], scaled[1], scaled[2]])\n        x = self.conv_1(x)\n        x = self.batch_norm(x)\n        x = self.activation(x)\n        x = self.conv_2(x)\n\n        return x\n\n    def get_config(self):\n        config = super(HRNetHeads, self).get_config()\n        config.update({\"input_channels\": self.input_channels,\n                       \"output_channels\": self.output_channels})\n\n        return config\n\n    def get_prunable_weights(self):\n        prunable_weights = [getattr(self.conv_1, 'kernel'),\n                            getattr(self.conv_2, 'kernel')]\n\n        return prunable_weights\n\n\ndef hrnet_v2(input_shape, output_channels, width=18, name=\"hrnetv2\"):\n    \"\"\"This function returns a functional model of HRNetV2.\n\n    Args:\n        width: the hyperparameter width.\n        output_channels: number of output channels.\n\n    Returns:\n        a functional model.\n    \"\"\"\n    # Get the output size of the HRNet body.\n    last_stage_width = sum([width * pow(2, n) for n in range(4)])\n\n    # Describe the model.\n    inputs = keras.Input(input_shape, dtype=tf.float32)\n    x = hrnet_stem(64)(inputs)\n    x = hrnet_body(width)(x)\n    outputs = hrnet_heads(input_channels=last_stage_width,\n                          output_channels=output_channels)(x)\n\n    # Construct the model and return it.\n    model = keras.Model(inputs=inputs, outputs=outputs, name=name)\n\n    return model\n\n\nif __name__ == \"__main__\":\n    model_2 = hrnet_v2((256, 256, 3), 18, 98)\n    model_2.summary()\n"
  },
  {
    "path": "postprocessing.py",
    "content": "\"\"\"The post processing module for HRNet facial landmark detection.\"\"\"\nimport cv2\nimport numpy as np\n\n\ndef top_k_indices(x, k):\n    \"\"\"Returns the k largest element indices from a numpy array. You can find\n    the original code here: https://stackoverflow.com/q/6910641\n    \"\"\"\n    flat = x.flatten()\n    indices = np.argpartition(flat, -k)[-k:]\n    indices = indices[np.argsort(-flat[indices])]\n    return np.unravel_index(indices, x.shape)\n\n\ndef get_peak_location(heatmap, image_size=(256, 256)):\n    \"\"\"Return the interpreted location of the top 2 predictions.\"\"\"\n    h_height, h_width = heatmap.shape\n    [y1, y2], [x1, x2] = top_k_indices(heatmap, 2)\n    x = (x1 + (x2 - x1)/4) / h_width * image_size[0]\n    y = (y1 + (y2 - y1)/4) / h_height * image_size[1]\n\n    return int(x), int(y)\n\n\ndef parse_heatmaps(heatmaps, image_size):\n    # Parse the heatmaps to get mark locations.\n    marks = []\n    heatmaps = np.transpose(heatmaps, (2, 0, 1))\n    for heatmap in heatmaps:\n        marks.append(get_peak_location(heatmap, image_size))\n\n    # Show individual heatmaps stacked.\n    heatmap_grid = np.hstack(heatmaps[:8])\n    for row in range(1, 12, 1):\n        heatmap_grid = np.vstack(\n            [heatmap_grid, np.hstack(heatmaps[row:row+8])])\n\n    return np.array(marks), heatmap_grid\n\n\ndef draw_marks(image, marks):\n    for m in marks:\n        for mark in m:\n            cv2.circle(image, tuple(mark.astype(int)), 2, (0, 255, 0), -1)\n"
  },
  {
    "path": "predict.py",
    "content": "\"\"\"Sample module for predicting face marks with HRNetV2.\"\"\"\nfrom argparse import ArgumentParser\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\n\nfrom postprocessing import parse_heatmaps, draw_marks\nfrom preprocessing import normalize\nfrom face_detector.detector import Detector\n\n# Take arguments from user input.\nparser = ArgumentParser()\nparser.add_argument(\"--video\", type=str, default=None,\n                    help=\"Video file to be processed.\")\nparser.add_argument(\"--cam\", type=int, default=None,\n                    help=\"The webcam index.\")\nparser.add_argument(\"--write_video\", type=bool, default=False,\n                    help=\"Write output video.\")\nargs = parser.parse_args()\n\n# Allow GPU memory growth.\ndevices = tf.config.list_physical_devices('GPU')\nfor device in devices:\n    tf.config.experimental.set_memory_growth(device, True)\n\nif __name__ == \"__main__\":\n    \"\"\"Run human head pose estimation from video files.\"\"\"\n\n    # What is the threshold value for face detection.\n    threshold = 0.7\n\n    # Construct a face detector.\n    detector_face = Detector('assets/face_model')\n\n    # Restore the model.\n    model = tf.keras.models.load_model(\"./exported/hrnetv2\")\n\n    # Setup the video source. If no video file provided, the default webcam will\n    # be used.\n    video_src = args.cam if args.cam is not None else args.video\n    if video_src is None:\n        print(\"Warning: video source not assigned, default webcam will be used.\")\n        video_src = 0\n\n    cap = cv2.VideoCapture(video_src)\n\n    # If reading frames from a webcam, try setting the camera resolution.\n    if video_src == 0:\n        cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n\n    # Get the real frame resolution.\n    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n    frame_rate = cap.get(cv2.CAP_PROP_FPS)\n\n    # Video output by video writer.\n    if args.write_video:\n        video_writer = cv2.VideoWriter(\n            'output.avi', cv2.VideoWriter_fourcc(*'avc1'), frame_rate, (frame_width, frame_height))\n\n    # Introduce a metter to measure the FPS.\n    tm = cv2.TickMeter()\n\n    # Loop through the video frames.\n    while True:\n        tm.start()\n\n        # Read frame, crop it, flip it, suits your needs.\n        frame_got, frame = cap.read()\n        if frame_got is False:\n            break\n\n        # Crop it if frame is larger than expected.\n        # frame = frame[0:480, 300:940]\n\n        # If frame comes from webcam, flip it so it looks like a mirror.\n        if video_src == 0:\n            frame = cv2.flip(frame, 2)\n\n        # Preprocess the input image.\n        _image = detector_face.preprocess(frame)\n\n        # Run the model\n        boxes, scores, _ = detector_face.predict(_image, threshold)\n\n        # Transform the boxes into squares.\n        boxes = detector_face.transform_to_square(\n            boxes, scale=1.22, offset=(0, 0.13))\n\n        # Clip the boxes if they cross the image boundaries.\n        boxes, _ = detector_face.clip_boxes(\n            boxes, (0, 0, frame_height, frame_width))\n        boxes = boxes.astype(np.int32)\n\n        if boxes.size > 0:\n            faces = []\n            for facebox in boxes:\n                # Crop the face image\n                top, left, bottom, right = facebox\n                face_image = frame[top:bottom, left:right]\n\n                # Preprocess it.\n                face_image = cv2.resize(face_image, (256, 256))\n                face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB)\n                face_image = normalize(np.array(face_image, dtype=np.float32))\n                faces.append(face_image)\n\n            faces = np.array(faces, dtype=np.float32)\n\n            # Do prediction.\n            heatmap_group = model.predict(faces)\n\n            # Parse the heatmaps to get mark locations.\n            mark_group = []\n            heatmap_grids = []\n            for facebox, heatmaps in zip(boxes, heatmap_group):\n                top, left, bottom, right = facebox\n                width = height = (bottom - top)\n\n                marks, heatmap_grid = parse_heatmaps(heatmaps, (width, height))\n\n                # Convert the marks locations from local CNN to global image.\n                marks[:, 0] += left\n                marks[:, 1] += top\n\n                mark_group.append(marks)\n                heatmap_grids.append(heatmap_grid)\n\n            # Draw the marks and the facebox in the original frame.\n            draw_marks(frame, mark_group)\n            detector_face.draw_boxes(frame, boxes, scores)\n\n            # Show the first heatmap.\n            cv2.imshow(\"heatmap_grid\", heatmap_grid[0])\n\n        # Show the result in windows.\n        cv2.imshow('image', frame)\n\n        # Write video file.\n        if args.write_video:\n            video_writer.write(frame)\n\n        if cv2.waitKey(1) == 27:\n            break\n"
  },
  {
    "path": "preprocessing.py",
    "content": "\"\"\"This module provides commonly used image preprocessing functions.\"\"\"\nimport cv2\nimport numpy as np\n\nfrom mark_operator import MarkOperator\n\nMO = MarkOperator()\n\n\ndef crop_face(image, marks, scale=1.8, shift_ratios=(0, 0)):\n    \"\"\"Crop the face area from the input image.\n\n    Args:\n        image: input image.\n        marks: the facial marks of the face to be cropped.\n        scale: how much to scale the face box.\n        shift_ratios: shift the face box to (right, down) by facebox size * ratios\n\n    Returns:\n        Cropped image, new marks, padding_width and bounding box.\n    \"\"\"\n    # How large the bounding box is?\n    x_min, y_min, _ = np.amin(marks, 0)\n    x_max, y_max, _ = np.amax(marks, 0)\n    side_length = max((x_max - x_min, y_max - y_min)) * scale\n\n    # Where is the center point of the bounding box?\n    x_center = (x_min + x_max) / 2\n    y_center = (y_min + y_max) / 2\n\n    # Face box is scaled, get the new corners, shifted.\n    img_height, img_width, _ = image.shape\n    x_shift, y_shift = np.array(shift_ratios) * side_length\n\n    x_start = int(x_center - side_length / 2 + x_shift)\n    y_start = int(y_center - side_length / 2 + y_shift)\n    x_end = int(x_center + side_length / 2 + x_shift)\n    y_end = int(y_center + side_length / 2 + y_shift)\n\n    # In case the new bbox is out of image bounding.\n    border_width = 0\n    border_x = min(x_start, y_start)\n    border_y = max(x_end - img_width, y_end - img_height)\n    if border_x < 0 or border_y > 0:\n        border_width = max(abs(border_x), abs(border_y))\n        x_start += border_width\n        y_start += border_width\n        x_end += border_width\n        y_end += border_width\n        image_with_border = cv2.copyMakeBorder(image, border_width,\n                                               border_width,\n                                               border_width,\n                                               border_width,\n                                               cv2.BORDER_CONSTANT,\n                                               value=[0, 0, 0])\n        image_cropped = image_with_border[y_start:y_end,\n                                          x_start:x_end]\n    else:\n        image_cropped = image[y_start:y_end, x_start:x_end]\n\n    return image_cropped, border_width, (x_start, y_start, x_end, y_end)\n\n\ndef normalize(inputs):\n    \"\"\"Preprocess the inputs. This function follows the official implementation\n    of HRNet.\n\n    Args:\n        inputs: a TensorFlow tensor of image.\n\n    Returns:\n        a normalized image.\n    \"\"\"\n    img_mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)\n    img_std = np.array([0.229, 0.224, 0.225], dtype=np.float32)\n\n    # Normalization\n    return ((inputs / 255.0) - img_mean)/img_std\n\n\ndef rotate_randomly(image, marks, degrees=(-30, 30)):\n    \"\"\"Rotate the image randomly in degree range (-degrees, degrees).\n\n    Args:\n        image: an image with face to be processed.\n        marks: face marks.\n        degrees: degree ranges to rotate.\n\n    Returns:\n        a same size image rotated, and the rotated marks.\n    \"\"\"\n    degree = np.random.random_sample() * (degrees[1] - degrees[0]) + degrees[0]\n    img_height, img_width, _ = image.shape\n    rotation_mat = cv2.getRotationMatrix2D(((img_width-1)/2.0,\n                                            (img_height-1)/2.0), degree, 1)\n    image_rotated = cv2.warpAffine(\n        image, rotation_mat, (img_width, img_height))\n\n    marks_rotated = MO.rotate(marks, np.deg2rad(degree),\n                              (img_width/2, img_height/2))\n\n    return image_rotated, marks_rotated\n\n\ndef scale_randomly(image, marks, output_size=(256, 256), scale_range=(0, 1)):\n    \"\"\"Scale the image randomly in a valid range defined by factor.\n\n    This function automatically calculates the valid scale range so that the\n    marks will always be visible in the image.\n\n    Args:\n        image: an image fully covered the face area in which the face is also \n            centered.\n        marks: face marks as numpy array in pixels.\n        scale_range: a tuple (a, b) defines the min and max values of the scale\n            range from the valid range.\n        output_size: output image size.\n\n    Returns:\n        processed image with target output size and new marks.\n    \"\"\"\n    img_height, img_width, _ = image.shape\n    face_height, face_width, _ = MO.get_height_width_depth(marks)\n\n    # The input image may not be a square. Choose the min range as valid range.\n    valid_range = min(img_height - face_height, img_width - face_width) / 2\n\n    # Get the new range from user input.\n    low, high = (np.array(scale_range) * valid_range).astype(int)\n    margin = np.random.randint(low, high)\n\n    # Cut the margins to the new image bounding box.\n    x_start = y_start = margin\n    x_stop, y_stop = (img_width - margin, img_height - margin)\n\n    # Crop and resize the image.\n    image_cropped = image[y_start:y_stop, x_start:x_stop]\n    image_resized = cv2.resize(image_cropped, output_size)\n\n    # Get the new mark locations.\n    marks -= [margin, margin, 0]\n    marks = (marks / (img_width - margin * 2) * output_size[0]).astype(int)\n\n    return image_resized, marks\n\n\ndef flip_randomly(image, marks, probability=0.5):\n    \"\"\"Flip the image in horizontal direction.\n\n    Args:\n        image: input image.\n        marks: face marks.\n\n    Returns:\n        flipped image, flipped marks\n    \"\"\"\n    if np.random.random_sample() < probability:\n        image = cv2.flip(image, 1)\n        marks = MO.flip_lr(marks, image.shape[0])\n\n    return image, marks\n\n\ndef generate_heatmaps(marks, img_size, map_size):\n    \"\"\"A convenient function to generate heatmaps from marks.\"\"\"\n    marks_norm = marks / img_size\n    heatmaps = MO.generate_heatmaps(marks_norm, map_size=map_size)\n\n    return heatmaps\n"
  },
  {
    "path": "pruning.py",
    "content": "\"\"\"Optimize the model with pruning.\"\"\"\nimport os\nfrom argparse import ArgumentParser\n\nimport tensorflow as tf\nimport tensorflow_model_optimization as tfmot\nfrom tensorflow import keras\n\nfrom dataset import build_dataset_from_wflw\nfrom network import hrnet_v2\n\n\nparser = ArgumentParser()\nparser.add_argument(\"--epochs\", default=60, type=int,\n                    help=\"Number of training epochs.\")\nparser.add_argument(\"--batch_size\", default=32, type=int,\n                    help=\"Training batch size.\")\nargs = parser.parse_args()\n\n\nif __name__ == \"__main__\":\n    # There are 3 steps for model pruning.\n    #   1. Load the model with pretrained weights.\n    #   2. Prune the model during training.\n    #   3. Export the model.\n\n    # Where are the pretrained weights.\n    checkpoint_dir = \"./checkpoints\"\n\n    # Where the pruned model will be exported\n    pruned_model_path = \"./optimized/pruned\"\n\n    if not os.path.exists(pruned_model_path):\n        os.makedirs(pruned_model_path)\n\n    # First, create the model and restore it with pretrained weights.\n    model = hrnet_v2((256, 256, 3), width=18, output_channels=98)\n\n    # Restore the latest model from checkpoint.\n    latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)\n    model.load_weights(latest_checkpoint)\n    print(\"Checkpoint restored: {}\".format(latest_checkpoint))\n\n    # Second, Setup the pruning.\n    pruning_params = {\n        'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(\n            initial_sparsity=0.5,\n            final_sparsity=0.8,\n            begin_step=0,\n            end_step=500\n        )\n    }\n    model_pruned = tfmot.sparsity.keras.prune_low_magnitude(\n        model, **pruning_params)\n\n    # Hyper parameters for training.\n    epochs = args.epochs\n    batch_size = args.batch_size\n\n    callbacks = [\n        tfmot.sparsity.keras.UpdatePruningStep(),\n        tfmot.sparsity.keras.PruningSummaries(log_dir=\"./logs\"),\n    ]\n\n    # Construct training datasets.\n    train_files_dir = \"/home/robin/data/facial-marks/wflw_cropped/train\"\n    dataset_train = build_dataset_from_wflw(train_files_dir, \"wflw_train\",\n                                            training=True,\n                                            batch_size=batch_size,\n                                            shuffle=True,\n                                            prefetch=tf.data.experimental.AUTOTUNE,\n                                            mode=\"generator\")\n\n    # Construct dataset for validation & testing.\n    test_files_dir = \"/home/robin/data/facial-marks/wflw_cropped/test\"\n    dataset_val = build_dataset_from_wflw(test_files_dir, \"wflw_test\",\n                                          training=False,\n                                          batch_size=batch_size,\n                                          shuffle=False,\n                                          prefetch=tf.data.experimental.AUTOTUNE,\n                                          mode=\"generator\")\n\n    # Compile the model for pruning.\n    model_pruned.compile(optimizer=keras.optimizers.Adam(0.0001),\n                         loss=keras.losses.MeanSquaredError(),\n                         metrics=[keras.metrics.MeanSquaredError()])\n    model_pruned.summary()\n\n    # Start training loop.\n    model_pruned.fit(dataset_train, validation_data=dataset_val,\n                     epochs=epochs, callbacks=callbacks,\n                     initial_epoch=args.initial_epoch)\n\n    # At last, Export the pruned model.\n    model_for_export = tfmot.sparsity.keras.strip_pruning(model_pruned)\n    model_for_export.save(pruned_model_path, include_optimizer=False)\n    print(\"Pruned model saved to: {}\".format(pruned_model_path))\n"
  },
  {
    "path": "quantization.py",
    "content": "import os\nimport cv2\nimport numpy as np\nimport tensorflow as tf\n\nimport fmd\nfrom mark_operator import MarkOperator\nfrom preprocessing import crop_face, normalize\n\nMODE = {\"DynamicRangeQuantization\": None,\n        \"IntegerWithFloatFallback\": None,\n        \"IntergerOnly\": None,\n        \"FP16\": None,\n        \"16x8\": None}\n\n\ndef representative_dataset_gen():\n    wflw_dir = \"/home/robin/data/facial-marks/wflw/WFLW_images\"\n    ds_wflw = fmd.wflw.WFLW(False, \"wflw_test\")\n    ds_wflw.populate_dataset(wflw_dir)\n\n    for _ in range(100):\n        sample = ds_wflw.pick_one()\n\n        # Get image and marks.\n        image = sample.read_image()\n        marks = sample.marks\n\n        # Crop the face out of the image.\n        image_cropped, _, _ = crop_face(image, marks, scale=1.2)\n\n        # Get the prediction from the model.\n        image_cropped = cv2.resize(image_cropped, (256, 256))\n        img_rgb = cv2.cvtColor(image_cropped, cv2.COLOR_BGR2RGB)\n        img_input = normalize(np.array(img_rgb, dtype=np.float32))\n\n        yield [np.expand_dims(img_input, axis=0)]\n\n\ndef quantize(saved_model, mode=None, representative_dataset=None):\n    \"\"\"TensorFlow model quantization by TFLite.\n\n    Args:\n        saved_model: the model's directory.\n        mode: the quantization mode.\n\n    Returns:\n        a tflite model quantized.\n    \"\"\"\n    converter = tf.lite.TFLiteConverter.from_saved_model(\"./exported\")\n\n    # By default, do Dynamic Range Quantization.\n    converter.optimizations = [tf.lite.Optimize.DEFAULT]\n\n    # Integer With Float Fallback\n    if mode[\"IntegerWithFloatFallback\"]:\n        converter.representative_dataset = representative_dataset\n\n    # Integer only.\n    if mode[\"IntergerOnly\"]:\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [\n            tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\n        converter.inference_input_type = tf.int8  # or tf.uint8\n        converter.inference_output_type = tf.int8  # or tf.uint8\n\n    # Float16 only.\n    if mode[\"FP16\"]:\n        converter.target_spec.supported_types = [tf.float16]\n\n    # [experimental] 16-bit activations with 8-bit weights\n    if mode[\"16x8\"]:\n        converter.representative_dataset = representative_dataset\n        converter.target_spec.supported_ops = [\n            tf.lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8]\n\n    # Finally, convert the model.\n    tflite_model = converter.convert()\n\n    return tflite_model\n\n\nclass TFLiteModelPredictor(object):\n    \"\"\"A light weight class for TFLite model prediction.\"\"\"\n\n    def __init__(self, model_path):\n        self.interpreter = tf.lite.Interpreter(model_path)\n        self.interpreter.allocate_tensors()\n        self.input_index = self.interpreter.get_input_details()[0][\"index\"]\n        self.output_index = self.interpreter.get_output_details()[0][\"index\"]\n\n    def predict(self, inputs):\n        self.interpreter.set_tensor(self.input_index, inputs)\n        self.interpreter.invoke()\n        predictions = self.interpreter.get_tensor(self.output_index)\n\n        return predictions\n\n\nif __name__ == \"__main__\":\n    # The directory to save quantized models.\n    export_dir = \"./optimized\"\n\n    if not os.path.exists(export_dir):\n        os.makedirs(export_dir)\n\n    # The model to be quantized.\n    saved_model = \"./exported\"\n\n    # Dynamic range quantization\n    mode = MODE.copy()\n    mode.update({\"DynamicRangeQuantization\": True})\n    tflite_model = quantize(saved_model, mode)\n    open(\"./optimized/hrnet_quant_dynamic_range.tflite\", \"wb\").write(tflite_model)\n\n    # Full integer quantization - Integer with float fallback.\n    mode = MODE.copy()\n    mode.update({\"IntegerWithFloatFallback\": True})\n    tflite_model = quantize(saved_model, mode, representative_dataset_gen)\n    open(\"./optimized/hrnet_quant_int_fp_fallback.tflite\", \"wb\").write(tflite_model)\n\n    # Full integer quantization - Integer only\n    mode = MODE.copy()\n    mode.update({\"IntegerOnly\": True})\n    tflite_model = quantize(saved_model, mode,  representative_dataset_gen)\n    open(\"./optimized/hrnet_quant_int_only.tflite\", \"wb\").write(tflite_model)\n\n    # Float16 quantization\n    mode = MODE.copy()\n    mode.update({\"FP16\": True})\n    tflite_model = quantize(saved_model, mode)\n    open(\"./optimized/hrnet_quant_fp16.tflite\", \"wb\").write(tflite_model)\n\n    # 16x8 quantization\n    mode = MODE.copy()\n    mode.update({\"16x8\": True})\n    tflite_model = quantize(saved_model, mode)\n    open(\"./optimized/hrnet_quant_16x8.tflite\", \"wb\").write(tflite_model)\n"
  },
  {
    "path": "train.py",
    "content": "\"\"\"The training script for HRNet facial landmark detection.\n\"\"\"\nimport os\nfrom argparse import ArgumentParser\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom callbacks import EpochBasedLearningRateSchedule, LogImages\nfrom dataset import build_dataset\nfrom network import hrnet_v2\n\nparser = ArgumentParser()\nparser.add_argument(\"--epochs\", default=60, type=int,\n                    help=\"Number of training epochs.\")\nparser.add_argument(\"--initial_epoch\", default=0, type=int,\n                    help=\"From which epochs to resume training.\")\nparser.add_argument(\"--batch_size\", default=32, type=int,\n                    help=\"Training batch size.\")\nparser.add_argument(\"--export_only\", default=False, type=bool,\n                    help=\"Save the model without training.\")\nparser.add_argument(\"--eval_only\", default=False, type=bool,\n                    help=\"Evaluate the model without training.\")\nargs = parser.parse_args()\n\n\nif __name__ == \"__main__\":\n    # Deep neural network training is complicated. The first thing is making\n    # sure you have everything ready for training, like datasets, checkpoints,\n    # logs, etc. Modify these paths to suit your needs.\n\n    # What is the model's name?\n    name = \"hrnetv2\"\n\n    # How many marks are there for a single face sample?\n    number_marks = 98\n\n    # Where are the training files?\n    train_files_dir = \"/home/robin/data/facial-marks/wflw_cropped/train\"\n\n    # Where are the testing files?\n    test_files_dir = \"/home/robin/data/facial-marks/wflw_cropped/test\"\n\n    # Where are the validation files? Set `None` if no files available. Then 10%\n    # of the training files will be used as validation samples.\n    val_files_dir = None\n\n    # Do you have a sample image which will be logged into tensorboard for\n    # testing purpose?\n    sample_image = \"docs/face.jpg\"\n\n    # That should be sufficient for training. However if you want more\n    # customization, please keep going.\n\n    # Checkpoint is used to resume training.\n    checkpoint_dir = os.path.join(\"checkpoints\", name)\n\n    # Save the model for inference later.\n    export_dir = os.path.join(\"exported\", name)\n\n    # Log directory will keep training logs like loss/accuracy curves.\n    log_dir = os.path.join(\"logs\", name)\n\n    # All sets. Now it's time to build the model. This model is defined in the\n    # `network` module with TensorFlow's functional API.\n    input_shape = (256, 256, 3)\n    model = hrnet_v2(input_shape=input_shape, output_channels=number_marks,\n                     width=18, name=name)\n\n    # Model built. Restore the latest model if checkpoints are available.\n    if not os.path.exists(checkpoint_dir):\n        os.makedirs(checkpoint_dir)\n        print(\"Checkpoint directory created: {}\".format(checkpoint_dir))\n\n    latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)\n    if latest_checkpoint:\n        print(\"Checkpoint found: {}, restoring...\".format(latest_checkpoint))\n        model.load_weights(latest_checkpoint)\n        print(\"Checkpoint restored: {}\".format(latest_checkpoint))\n    else:\n        print(\"Checkpoint not found. Model weights will be initialized randomly.\")\n\n    # If the restored model is ready for inference, save it and quit training.\n    if args.export_only:\n        if latest_checkpoint is None:\n            print(\"Warning: Model not restored from any checkpoint.\")\n        print(\"Saving model to {} ...\".format(export_dir))\n        model.save(export_dir)\n        print(\"Model saved at: {}\".format(export_dir))\n        quit()\n\n    # Construct a dataset for evaluation.\n    dataset_test = build_dataset(test_files_dir, \"test\",\n                                 number_marks=number_marks,\n                                 image_shape=input_shape,\n                                 training=False,\n                                 batch_size=args.batch_size,\n                                 shuffle=False,\n                                 prefetch=tf.data.experimental.AUTOTUNE)\n\n    # If only evaluation is required.\n    if args.eval_only:\n        model.evaluate(dataset_test)\n        quit()\n\n    # Finally, it's time to train the model.\n\n    # Compile the model and print the model summary.\n    model.compile(optimizer=keras.optimizers.Adam(0.001, amsgrad=True, epsilon=0.001),\n                  loss=keras.losses.MeanSquaredError(),\n                  metrics=[keras.metrics.MeanSquaredError()])\n    # model.summary()\n\n    # Schedule the learning rate with (epoch to start, learning rate) tuples\n    schedule = [(1, 0.001),\n                (30, 0.0001),\n                (50, 0.00001)]\n\n    # All done. The following code will setup and start the trainign.\n\n    # Save a checkpoint. This could be used to resume training.\n    callback_checkpoint = keras.callbacks.ModelCheckpoint(\n        filepath=os.path.join(checkpoint_dir, name),\n        save_weights_only=True,\n        verbose=1,\n        save_best_only=True)\n\n    # Visualization in TensorBoard\n    callback_tensorboard = keras.callbacks.TensorBoard(log_dir=log_dir,\n                                                       histogram_freq=1024,\n                                                       write_graph=True,\n                                                       update_freq='epoch')\n    # Learning rate decay.\n    callback_lr = EpochBasedLearningRateSchedule(schedule)\n\n    # Log a sample image to tensorboard.\n    callback_image = LogImages(log_dir, sample_image)\n\n    # List all the callbacks.\n    callbacks = [callback_checkpoint, callback_tensorboard, #callback_lr,\n                 callback_image]\n\n    # Construct training datasets.\n    dataset_train = build_dataset(train_files_dir, \"train\",\n                                  number_marks=number_marks,\n                                  image_shape=input_shape,\n                                  training=True,\n                                  batch_size=args.batch_size,\n                                  shuffle=True,\n                                  prefetch=tf.data.experimental.AUTOTUNE)\n\n    # Construct dataset for validation. The loss value from this dataset will be\n    # used to decide which checkpoint should be preserved.\n    if val_files_dir:\n        dataset_val = build_dataset(val_files_dir, \"validation\",\n                                    number_marks=number_marks,\n                                    image_shape=input_shape,\n                                    training=False,\n                                    batch_size=args.batch_size,\n                                    shuffle=False,\n                                    prefetch=tf.data.experimental.AUTOTUNE)\n    else:\n        dataset_val = dataset_train.take(int(512/args.batch_size))\n        dataset_train = dataset_train.skip(int(512/args.batch_size))\n\n    # Start training loop.\n    model.fit(dataset_train,\n              validation_data=dataset_val,\n              epochs=args.epochs,\n              callbacks=callbacks,\n              initial_epoch=args.initial_epoch)\n\n    # Run a full evaluation after training.\n    model.evaluate(dataset_test)\n"
  }
]