pax_global_header00006660000000000000000000000064136063213730014516gustar00rootroot0000000000000052 comment=3edd9749699394e2961d3b9bd33d260aea5583c8 BerryNet-upstream-3.9.0/000077500000000000000000000000001360632137300151175ustar00rootroot00000000000000BerryNet-upstream-3.9.0/.eslintrc.yaml000066400000000000000000000001351360632137300177030ustar00rootroot00000000000000env: node: true es6: true extends: google rules: comma-dangle: [2, only-multiline] BerryNet-upstream-3.9.0/.github/000077500000000000000000000000001360632137300164575ustar00rootroot00000000000000BerryNet-upstream-3.9.0/.github/FUNDING.yml000066400000000000000000000013571360632137300203020ustar00rootroot00000000000000# These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: berrynet # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: ['https://paypal.me/berrynet'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] BerryNet-upstream-3.9.0/.gitignore000066400000000000000000000002001360632137300170770ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__ *.pyc # Distribution / packaging build dist *.egg-info # Environments env BerryNet-upstream-3.9.0/.gitlab-ci.yml000066400000000000000000000033311360632137300175530ustar00rootroot00000000000000# Official language image. Look for the different tagged releases at: # https://hub.docker.com/r/library/python/tags/ image: gitlab-ci:base # Change pip's cache directory to be inside the project directory since we can # only cache local items. variables: PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache" # Pip's cache doesn't store the python packages # https://pip.pypa.io/en/stable/reference/pip_install/#caching # # If you want to also cache the installed packages, you have to install # them in a virtualenv and cache it as well. cache: paths: - .cache/pip stages: - build - test - deploy before_script: - python3 -V # Print out python version for debugging - eval $(ssh-agent -s) - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null - mkdir -p ~/.ssh && chmod 700 ~/.ssh - echo "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts && chmod 644 ~/.ssh/known_hosts build-wheel: stage: build script: - pip3 wheel --wheel-dir=./dist . artifacts: paths: - dist/ unit-test: stage: test dependencies: - build-wheel script: - pip3 install dist/*.whl tensorflow - apt update && apt install -y libsm6 libxrender-dev - python3 setup.py test allow_failure: true pep8-codestyle: stage: test script: - pycodestyle . allow_failure: true pylint-codestyle: stage: test script: - pylint berrynet allow_failure: true deploy-pypi: stage: deploy dependencies: - build-wheel script: - git clone git@gitlab.com:DT42/infrastructure42/dt42pypi.git - cp dist/berrynet*.whl dt42pypi/ && cd dt42pypi - dir2pi -n . - git add . && git commit -m "Add $CI_PROJECT_NAME $CI_COMMIT_TAG wheel. This is an auto-commit by GitLab-CI Runner." - git pull && git push only: - tags BerryNet-upstream-3.9.0/.gitmodules000066400000000000000000000001531360632137300172730ustar00rootroot00000000000000[submodule "inference/darkflow"] path = inference/darkflow url = https://github.com/thtrieu/darkflow.git BerryNet-upstream-3.9.0/AUTHORS000066400000000000000000000005541360632137300161730ustar00rootroot00000000000000# Authors and contributors ordered by first contribution. Bofu Chen - bofu AT dt42 dot io Joseph Liu - joseph AT dt42 dot io Kai-Heng Feng - khfeng AT dt42 dot io Tammy Yang - tammy AT dt42 dot io Paul Liu - paulliu AT debian dot org Katsuya Hyodo (PINTO0309) - rmsdh122 AT yahoo dot co dot jp Sherry Chung - sherry AT dt42 dot io Mei Mei - meimei AT dt42 dot io BerryNet-upstream-3.9.0/BACKERS.md000066400000000000000000000011161360632137300165120ustar00rootroot00000000000000

Sponsors & Backers

BerryNet is a GPL-licensed FLOSS project. It's an independent project with its ongoing development made possible entirely thanks to the support by these awesome [backers](https://github.com/DT42/BerryNet/blob/master/BACKERS.md). If you'd like to join them, please consider: * [Become a backer or sponsor on Open Collective](https://opencollective.com/berrynet). * [One-time donation via PayPal or crypto-currencies.](https://github.com/DT42/BerryNet/wiki/Donation#one-time-donations)

One-Time Donations

* Penk Chen BerryNet-upstream-3.9.0/CONTRIBUTING.md000066400000000000000000000003041360632137300173450ustar00rootroot00000000000000We use [Developer Certificate of Origin](https://developercertificate.org/). To use DCO, you only need to add your signature into a Git commit: ``` $ git commit -s -m "your commit message." ``` BerryNet-upstream-3.9.0/LICENSE.txt000066400000000000000000001045131360632137300167460ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . BerryNet-upstream-3.9.0/README.md000066400000000000000000000205571360632137300164070ustar00rootroot00000000000000

BerryNet Logo

Deep Learning Gateway on Raspberry Pi And Other Edge Devices

[Supporting BerryNet](https://github.com/DT42/BerryNet/wiki/Donation) * [Become a backer or sponsor on Open Collective](https://opencollective.com/berrynet). * [One-time donation via PayPal or crypto-currencies](https://github.com/DT42/BerryNet/wiki/Donation#one-time-donations). # Introduction This project turns edge devices such as Raspberry Pi into an intelligent gateway with deep learning running on it. No internet connection is required, everything is done locally on the edge device itself. Further, multiple edge devices can create a distributed AIoT network. At DT42, we believe that bringing deep learning to edge devices is the trend towards the future. It not only saves costs of data transmission and storage but also makes devices able to respond according to the events shown in the images or videos without connecting to the cloud. ![Figure 1](https://user-images.githubusercontent.com/292790/45943626-a3d28b80-c019-11e8-829c-5eb6afd3faa4.png)

Figure 1: BerryNet architecture

Figure 1 shows the software architecture of the project, we use Node.js/Python, MQTT and an AI engine to analyze images or video frames with deep learning. So far, there are two default types of AI engines, the classification engine (with Inception v3 [[1]](https://arxiv.org/pdf/1512.00567.pdf) model) and the object detection engine (with TinyYOLO [[2]](https://pjreddie.com/media/files/papers/YOLO9000.pdf) model or MobileNet SSD [[3]](https://arxiv.org/pdf/1704.04861.pdf) model). Figure 2 shows the differences between classification and object detection. ![Figure 2](https://cloud.githubusercontent.com/assets/292790/25520013/d9497738-2c2c-11e7-9693-3840647f2e1e.jpg)

Figure 2: Classification vs detection

One of the application of this intelligent gateway is to use the camera to monitor the place you care about. For example, Figure 3 shows the analyzed results from the camera hosted in the DT42 office. The frames were captured by the IP camera and they were submitted into the AI engine. The output from the AI engine will be shown in the dashboard. We are working on the Email and IM notification so you can get a notification when there is a dog coming into the meeting area with the next release. ![Figure 3](https://cloud.githubusercontent.com/assets/292790/25498294/0ab79976-2bba-11e7-9114-46e328d15a18.gif)

Figure 3: Object detection result example

To bring easy and flexible edge AI experience to user, we keep expending support of the AI engines and the reference HWs. ![Figure 4](https://user-images.githubusercontent.com/292790/64026655-c2b69780-cb71-11e9-90b9-6269319012f1.png)

Figure 4: Reference hardwares

# Installation You can install BerryNet by using pre-built image or from source. Please refer to the [Wiki page](https://github.com/DT42/BerryNet/wiki/Installation) for the details. We are pushing BerryNet into Debian repository, so you will be able to install by only typing one command in the future. Here is the quick steps to install from source: ``` $ git clone https://github.com/DT42/BerryNet.git $ cd BerryNet $ ./configure ``` # Start and Stop BerryNet BerryNet performs an AIoT application by connecting independent components together. Component types include but not limited to AI engine, I/O processor, data processor (algorithm), or data collector. We recommend to manage BerryNet componetns by [supervisor](http://supervisord.org/), but you can also run BerryNet components manually. You can manage BerryNet via `supervisorctl`: ``` # Check status of BerryNet components $ sudo supervisorctl status all # Stop Camera client $ sudo supervisorctl stop camera # Restart all components $ sudo supervisorctl restart all # Show last stderr logs of camera client $ sudo supervisorctl tail camera stderr ``` For more possibilities of supervisorctl, please refer to the [official tutorial](http://supervisord.org/running.html#running-supervisorctl). The default application has three components: * Camera client to provide input images * Object detection engine to find type and position of the detected objects in an image * Dashboard to display the detection results You will learn how to configure or change the components in the [Configuration](#configuration) section. # Dashboard: Freeboard ## Open Freeboard on RPi3 (with touch screen) Freeboard is a web-based dashboard. Here are the steps to show the detection result iamge and text on Freeboard: * 1: Enter `http://127.0.0.1:8080` in browser's URL bar, and press enter * 2: [Download](https://raw.githubusercontent.com/DT42/BerryNet/master/config/dashboard-tflitedetector.json) the Freeboard configuration for default application, `dashboard-tflitedetector.json` * 2: Click `LOAD FREEBOARD`, and select the newly downloaded `dashboard-tflitedetector.json` * 3: Wait for seconds, you should see the inference result image and text on Freeboard ## Open Freeboard on another computer Assuming that you have two devices: * Device A with IP `192.168.1.42`, BerryNet default application runs on it * Device B with IP `192.168.1.43`, you want to open Freeboard and see the detection result on it Here are the steps: * 1: Enter `http://192.168.1.42:8080` in browser's URL bar, and press enter * 2: [Download](https://raw.githubusercontent.com/DT42/BerryNet/master/config/dashboard-tflitedetector.json) the Freeboard configuration for default application, `dashboard-tflitedetector.json` * 3: Replace all the `localhost` to `192.168.1.42` in `dashboard-tflitedetector.json` * 2: Click `LOAD FREEBOARD`, and select the newly downloaded `dashboard-tflitedetector.json` * 3: Wait for seconds, you should see the inference result image and text on Freeboard For more details about dashboard configuration (e.g. how to add widgets), please refer to [Freeboard project](https://github.com/Freeboard/freeboard). # Enable Data Collector You might want to store the snapshot and inference results for data analysis. To run BerryNet data collector manually, you can run the command below: ``` $ bn_data_collector --topic-config --data-dirpath ``` The topic config indicates what MQTT topic the data collector will listen, and what handler will be triggered. Here is a topic config exmaple: ``` { "berrynet/engine/tflitedetector/result": "self.update" } ``` The inference result image and text will be saved into the indicated result directory. # Configuration The default supervisor config is at `/etc/supervisor/conf.d/berrynet-tflite.conf`. To write your own supervisor config, you can refer to [here](https://github.com/DT42/BerryNet/tree/master/config/supervisor/conf.d) for more example supervisor configs of BerryNet ## Camera Client BerryNet camera client can run in two modes: stream or file. In stream mode, local camera (e.g. USB camera and RPi camera) and IP camera can be supported, and input frame rate (FPS) can be changed on demand (default is 1). In file mode, user can indicate filepath as input source. To run camera client in stream mode: ``` $ bn_camera --fps 5 ``` To run camera client in file mode: ``` $ bn_camera --mode file --filepath ``` # Use Your Data To Train The original instruction of retraining YOLOv2 model see [github repository of darknet](https://github.com/AlexeyAB/darknet#how-to-train-to-detect-your-custom-objects) In the current of BerryNet, TinyYolo is used instead of YOLOv2. The major differences are: 1. Create file yolo-obj.cfg with the same content as in `tiny-yolo.cfg` 2. Download pre-trained weights of darknet reference model, `darknet.weights.12`, for the convolutional layers (6.1MB) https://drive.google.com/drive/folders/0B-oZJEwmkAObMzAtc2QzZDhyVGM?usp=sharing The rest parts are the same as retraining YOLO. If you use [LabelMe](http://labelme.csail.mit.edu/Release3.0/) to annotate data, `utils/xmlTotxt.py` can help convert the xml format to the text format that darknet uses. # Discussion Please refer to the [Telegram Group](https://t.me/berrynetdev) or [Google Group](https://groups.google.com/a/dt42.io/d/forum/berrynet) for questions, suggestions, or any idea discussion. BerryNet-upstream-3.9.0/README.md.old000066400000000000000000000140241360632137300171540ustar00rootroot00000000000000# BerryNet: Deep Learning Gateway on Raspberry Pi And Other Edge Devices This project turns edge devices such as Raspberry Pi 3 into an intelligent gateway with deep learning running on it. No internet connection is required, everything is done locally on the edge device itself. Further, multiple edge devices can create a distributed AIoT network. At DT42, we believe that bringing deep learning to edge devices is the trend towards the future. It not only saves costs of data transmission and storage but also makes devices able to respond according to the events shown in the images or videos without connecting to the cloud. ![Figure 1](https://user-images.githubusercontent.com/292790/45943626-a3d28b80-c019-11e8-829c-5eb6afd3faa4.png)

Figure 1: BerryNet architecture

Figure 1 shows the software architecture of the project, we use Node.js/Python, MQTT and an AI engine to analyze images or video frames with deep learning. So far, there are two default types of AI engines, the classification engine (with Inception v3 [[1]](https://arxiv.org/pdf/1512.00567.pdf) model) and the object detection engine (with TinyYOLO [[2]](https://pjreddie.com/media/files/papers/YOLO9000.pdf) model or MobileNet SSD [[3]](https://arxiv.org/pdf/1704.04861.pdf) model). Figure 2 shows the differences between classification and object detection. ![Figure 2](https://cloud.githubusercontent.com/assets/292790/25520013/d9497738-2c2c-11e7-9693-3840647f2e1e.jpg)

Figure 2: Classification vs detection

One of the application of this intelligent gateway is to use the camera to monitor the place you care about. For example, Figure 3 shows the analyzed results from the camera hosted in the DT42 office. The frames were captured by the IP camera and they were submitted into the AI engine. The output from the AI engine will be shown in the dashboard. We are working on the Email and IM notification so you can get a notification when there is a dog coming into the meeting area with the next release. ![Figure 3](https://cloud.githubusercontent.com/assets/292790/25498294/0ab79976-2bba-11e7-9114-46e328d15a18.gif)

Figure 3: Object detection result example

To bring easy and flexible edge AI experience to user, we keep expending support of the AI engines and the reference HWs. ![Figure 4](https://user-images.githubusercontent.com/292790/45943641-b6e55b80-c019-11e8-9c90-28c96074c577.png)

Figure 4: Reference hardwares

# Installation You can install BerryNet by using pre-built image or from source. Please refer to the [Wiki page](https://github.com/DT42/BerryNet/wiki/Installation) for the details. We are pushing BerryNet into Debian repository, so you will be able to install by only typing one command in the future. Here is the quick steps to install from source: ``` $ git clone https://github.com/DT42/BerryNet.git $ cd BerryNet $ ./configure ``` # Start and Stop BerryNet BerryNet is managed by [systemd](https://freedesktop.org/wiki/Software/systemd/). You can manage BerryNet via `berrynet-manager`: ``` $ berrynet-manager [start | stop | status | log] ``` # Configuration All the configurations are in `config.js`. * Choose AI Engine. * Two types of AI engines currently: object classifier and object detector. * Configure IP camera's snapshot access interface. * Please refer to [IP camera setup](doc/ipcam.md) for more details. * MQTT topics. # Dashboard ## Open dashboard on RPi3 (with touch screen) Open browser and enter the URL: `http://localhost:8080/index.html#source=dashboard.json` The default dashboard configuration file will be loaded. ## Open dashboard on browser from any computer Open browser and enter the URL: `http://:8080/index.html#source=dashboard.json` Click the data sources, and change MQTT broker's IP address to the gateway's IP. For more details about dashboard configuration (e.g. how to add widgets), please refer to [freeboard project](https://github.com/Freeboard/freeboard). # Provide Image Input To capture an image via configured IP camera ``` $ mosquitto_pub -h localhost -t berrynet/event/camera -m snapshot_ipcam ``` To capture an image via board-connected camera (RPi camera or USB webcam) ``` $ mosquitto_pub -h localhost -t berrynet/event/camera -m snapshot_boardcam ``` To provide a local image ``` $ mosquitto_pub -h localhost -t berrynet/event/localImage -m ``` To start and stop streaming from board-connected camera ``` $ mosquitto_pub -h localhost -t berrynet/event/camera -m stream_boardcam_start $ mosquitto_pub -h localhost -t berrynet/event/camera -m stream_boardcam_stop ``` To start and stop streaming from Nest IP camera ``` $ mosquitto_pub -h localhost -t berrynet/event/camera -m stream_nest_ipcam_start $ mosquitto_pub -h localhost -t berrynet/event/camera -m stream_nest_ipcam_stop ``` # Enable Data Collector You might want to store the snapshot and inference results for data analysis. To enable data collector, you can set the storage directory path in config.js: ``` config.storageDirPath = ''; ``` and restart BerryNet. # Use Your Data To Train The original instruction of retraining YOLOv2 model see [github repository of darknet](https://github.com/AlexeyAB/darknet#how-to-train-to-detect-your-custom-objects) In the current of BerryNet, TinyYolo is used instead of YOLOv2. The major differences are: 1. Create file yolo-obj.cfg with the same content as in `tiny-yolo.cfg` 2. Download pre-trained weights of darknet reference model, `darknet.weights.12`, for the convolutional layers (6.1MB) https://drive.google.com/drive/folders/0B-oZJEwmkAObMzAtc2QzZDhyVGM?usp=sharing The rest parts are the same as retraining YOLO. If you use [LabelMe](http://labelme.csail.mit.edu/Release3.0/) to annotate data, `utils/xmlTotxt.py` can help convert the xml format to the text format that darknet uses. # Discussion Please refer to the [Telegram Group](https://t.me/berrynetdev) or [Google Group](https://groups.google.com/a/dt42.io/d/forum/berrynet) for questions, suggestions, or any idea discussion. BerryNet-upstream-3.9.0/berrynet-manager000077500000000000000000000034121360632137300203070ustar00rootroot00000000000000#! /bin/sh # # Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . help() { echo "Usage: $0 " echo " start : launch dlsystem" echo " stop : terminate dlsystem" echo " status : check the state of all services" echo " log : dump logfiles of all services" exit 1 } if [ $# -lt 1 ]; then help fi case $1 in start | stop | status) sudo systemctl $1 \ detection_fast_server.service \ agent.service \ broker.service \ dashboard.service \ localimg.service \ camera.service \ journal.service \ data_collector.service ;; log) sudo journalctl -x --no-pager -u detection_fast_server.service sudo journalctl -x --no-pager -u agent.service sudo journalctl -x --no-pager -u broker.service sudo journalctl -x --no-pager -u dashboard.service sudo journalctl -x --no-pager -u localimg.service sudo journalctl -x --no-pager -u camera.service sudo journalctl -x --no-pager -u journal.service sudo journalctl -x --no-pager -u data_collector.service ;; *) help esac BerryNet-upstream-3.9.0/berrynet/000077500000000000000000000000001360632137300167515ustar00rootroot00000000000000BerryNet-upstream-3.9.0/berrynet/__init__.py000066400000000000000000000005141360632137300210620ustar00rootroot00000000000000import os from logzero import setup_logger # Save log file at different place to prevent permission error. if os.geteuid() == 0: # root LOGGING_FLLEPATH='/tmp/berrynet.log' else: LOGGING_FLLEPATH='{}/.cache/berrynet.log'.format(os.getenv('HOME')) logger = setup_logger(name='berrynet-logger', logfile=LOGGING_FLLEPATH) BerryNet-upstream-3.9.0/berrynet/client/000077500000000000000000000000001360632137300202275ustar00rootroot00000000000000BerryNet-upstream-3.9.0/berrynet/client/__init__.py000066400000000000000000000000001360632137300223260ustar00rootroot00000000000000BerryNet-upstream-3.9.0/berrynet/client/camera.py000066400000000000000000000130551360632137300220350ustar00rootroot00000000000000#!/usr/bin/python3 # # Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . import argparse import logging import time from datetime import datetime import cv2 from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload def parse_args(): ap = argparse.ArgumentParser() ap.add_argument( '--mode', default='stream', help='Camera creates frame(s) from stream or file. (default: stream)' ) ap.add_argument( '--stream-src', type=str, default='0', help=('Camera stream source. ' 'It can be device node ID or RTSP URL. ' '(default: 0)') ) ap.add_argument( '--fps', type=float, default=1, help='Frame per second in streaming mode. (default: 1)' ) ap.add_argument( '--filepath', default='', help='Input image path in file mode. (default: empty)' ) ap.add_argument( '--broker-ip', default='localhost', help='MQTT broker IP.' ) ap.add_argument( '--broker-port', default=1883, type=int, help='MQTT broker port.' ) ap.add_argument('--display', action='store_true', help=('Open a window and display the sent out frames. ' 'This argument is only effective in stream mode.') ) ap.add_argument('--debug', action='store_true', help='Debug mode toggle' ) return vars(ap.parse_args()) def main(): args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) comm_config = { 'subscribe': {}, 'broker': { 'address': args['broker_ip'], 'port': args['broker_port'] } } comm = Communicator(comm_config, debug=True) duration = lambda t: (datetime.now() - t).microseconds / 1000 if args['mode'] == 'stream': counter = 0 # Check input stream source if args['stream_src'].isdigit(): # source is a physically connected camera stream_source = '/dev/video{}'.format(int(args['stream_src'])) capture = cv2.VideoCapture(int(args['stream_src'])) else: # source is an IP camera stream_source = args['stream_src'] capture = cv2.VideoCapture(args['stream_src']) cam_fps = capture.get(cv2.CAP_PROP_FPS) if cam_fps > 30 or cam_fps < 1: logger.warn('Camera FPS is {} (>30 or <1). Set it to 30.'.format(cam_fps)) cam_fps = 30 out_fps = args['fps'] interval = int(cam_fps / out_fps) # warmup #t_warmup_start = time.time() #t_warmup_now = time.time() #warmup_counter = 0 #while t_warmup_now - t_warmup_start < 1: # capture.read() # warmup_counter += 1 # t_warmup_now = time.time() logger.debug('===== VideoCapture Information =====') logger.debug('Stream Source: {}'.format(stream_source)) logger.debug('Camera FPS: {}'.format(cam_fps)) logger.debug('Output FPS: {}'.format(out_fps)) logger.debug('Interval: {}'.format(interval)) #logger.debug('Warmup Counter: {}'.format(warmup_counter)) logger.debug('====================================') while True: status, im = capture.read() if (status is False): logger.warn('ERROR: Failure happened when reading frame') counter += 1 if counter == interval: logger.debug('Drop frames: {}'.format(counter-1)) counter = 0 # Open a window and display the ready-to-send frame. # This is useful for development and debugging. if args['display']: cv2.imshow('Frame', im) cv2.waitKey(1) t = datetime.now() retval, jpg_bytes = cv2.imencode('.jpg', im) mqtt_payload = payload.serialize_jpg(jpg_bytes) comm.send('berrynet/data/rgbimage', mqtt_payload) logger.debug('send: {} ms'.format(duration(t))) else: pass elif args['mode'] == 'file': # Prepare MQTT payload im = cv2.imread(args['filepath']) retval, jpg_bytes = cv2.imencode('.jpg', im) t = datetime.now() mqtt_payload = payload.serialize_jpg(jpg_bytes) logger.debug('payload: {} ms'.format(duration(t))) logger.debug('payload size: {}'.format(len(mqtt_payload))) # Client publishes payload t = datetime.now() comm.send('berrynet/data/rgbimage', mqtt_payload) logger.debug('mqtt.publish: {} ms'.format(duration(t))) logger.debug('publish at {}'.format(datetime.now().isoformat())) else: logger.error('User assigned unknown mode {}'.format(args['mode'])) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/client/dashboard.py000066400000000000000000000052451360632137300225360ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Dashboard agent service. """ import argparse import json from os.path import join as pjoin from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload class DashboardService(object): def __init__(self, service_name, comm_config): self.service_name = service_name self.comm_config = comm_config self.comm_config['subscribe']['berrynet/engine/tensorflow/result'] = self.update self.comm_config['subscribe']['berrynet/engine/mvclassification/result'] = self.update self.comm = Communicator(self.comm_config, debug=True) self.basedir = '/usr/local/berrynet/dashboard/www/freeboard' def update(self, pl): payload_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(payload_json['bytes']) inference_result = [ '{0}: {1}
'.format(anno['label'], anno['confidence']) for anno in payload_json['annotations'] ] logger.debug('inference results: {}'.format(inference_result)) with open(pjoin(self.basedir, 'snapshot.jpg'), 'wb') as f: f.write(jpg_bytes) self.comm.send('berrynet/dashboard/snapshot', 'snapshot.jpg') self.comm.send('berrynet/dashboard/inferenceResult', json.dumps(inference_result)) def run(self, args): """Infinite loop serving inference requests""" self.comm.run() def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--service_name', required=True, help='Engine service name used as PID filename') return vars(ap.parse_args()) def main(): args = parse_args() comm_config = { 'subscribe': {}, 'broker': { 'address': 'localhost', 'port': 1883 } } dashboard_service = DashboardService(args['service_name'], comm_config) dashboard_service.run(args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/client/data_collector.py000066400000000000000000000103751360632137300235660ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Data collector service. """ import argparse import json import os from datetime import datetime from os.path import join as pjoin from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload class DataCollectorService(object): def __init__(self, comm_config, data_dirpath): self.comm_config = comm_config for topic, functor in self.comm_config['subscribe'].items(): self.comm_config['subscribe'][topic] = eval(functor) self.comm_config['subscribe']['berrynet/engine/tensorflow/result'] = self.update self.comm_config['subscribe']['berrynet/engine/mvclassification/result'] = self.update self.comm = Communicator(self.comm_config, debug=True) self.data_dirpath = data_dirpath def update(self, pl): if not os.path.exists(self.data_dirpath): try: os.mkdir(self.data_dirpath) except Exception as e: logger.warn('Failed to create {}'.format(self.data_dirpath)) raise(e) payload_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(payload_json['bytes']) payload_json.pop('bytes') logger.debug('inference text result: {}'.format(payload_json)) timestamp = datetime.now().isoformat() with open(pjoin(self.data_dirpath, timestamp + '.jpg'), 'wb') as f: f.write(jpg_bytes) with open(pjoin(self.data_dirpath, timestamp + '.json'), 'w') as f: f.write(json.dumps(payload_json, indent=4)) def save_pipeline_result(self, pl): if not os.path.exists(self.data_dirpath): try: os.mkdir(self.data_dirpath) except Exception as e: logger.warn('Failed to create {}'.format(self.data_dirpath)) raise(e) payload_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(payload_json['image_blob']) payload_json.pop('image_blob') logger.debug('inference text result: {}'.format(payload_json)) timestamp = datetime.now().isoformat() with open(pjoin(self.data_dirpath, timestamp + '.jpg'), 'wb') as f: f.write(jpg_bytes) with open(pjoin(self.data_dirpath, timestamp + '.json'), 'w') as f: f.write(json.dumps(payload_json, indent=4)) def run(self, args): """Infinite loop serving inference requests""" self.comm.run() def parse_args(): ap = argparse.ArgumentParser() ap.add_argument( '--data-dirpath', default='/tmp/berrynet-data', help='Dirpath where to store collected data.' ) ap.add_argument( '--broker-ip', default='localhost', help='MQTT broker IP.' ) ap.add_argument( '--broker-port', default=1883, type=int, help='MQTT broker port.' ) ap.add_argument( '--topic-config', default=None, help='Path of the MQTT topic subscription JSON.' ) return vars(ap.parse_args()) def main(): args = parse_args() if args['topic_config']: with open(args['topic_config']) as f: topic_config = json.load(f) else: topic_config = {} comm_config = { 'subscribe': topic_config, 'broker': { 'address': args['broker_ip'], 'port': args['broker_port'] } } dc_service = DataCollectorService(comm_config, args['data_dirpath']) dc_service.run(args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/client/data_collector_ui.py000066400000000000000000000242731360632137300242650ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Data collector with UI showing inference result for human """ import argparse import json import os import sys import threading import tkinter as tk from datetime import datetime from os.path import join as pjoin import cv2 import numpy as np from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload from PIL import Image from PIL import ImageTk class DataCollectorService(object): def __init__(self, comm_config, data_dirpath): self.comm_config = comm_config for topic, functor in self.comm_config['subscribe'].items(): self.comm_config['subscribe'][topic] = eval(functor) #self.comm_config['subscribe']['berrynet/data/rgbimage'] = self.update self.comm_config['subscribe']['berrynet/engine/pipeline/result'] = self.save_pipeline_result self.comm = Communicator(self.comm_config, debug=True) self.data_dirpath = data_dirpath def update(self, pl): payload_json = payload.deserialize_payload(pl.decode('utf-8')) # update UI with the latest inference result self.ui.update(payload_json, 'bytes') if self.data_dirpath: if not os.path.exists(self.data_dirpath): try: os.mkdir(self.data_dirpath) except Exception as e: logger.warn('Failed to create {}'.format(self.data_dirpath)) raise(e) jpg_bytes = payload.destringify_jpg(payload_json['bytes']) payload_json.pop('bytes') logger.debug('inference text result: {}'.format(payload_json)) timestamp = datetime.now().isoformat() with open(pjoin(self.data_dirpath, timestamp + '.jpg'), 'wb') as f: f.write(jpg_bytes) with open(pjoin(self.data_dirpath, timestamp + '.json'), 'w') as f: f.write(json.dumps(payload_json, indent=4)) def save_pipeline_result(self, pl): payload_json = payload.deserialize_payload(pl.decode('utf-8')) # update UI with the latest inference result self.ui.update(payload_json, 'image_blob') if self.data_dirpath: if not os.path.exists(self.data_dirpath): try: os.mkdir(self.data_dirpath) except Exception as e: logger.warn('Failed to create {}'.format(self.data_dirpath)) raise(e) jpg_bytes = payload.destringify_jpg(payload_json['image_blob']) payload_json.pop('image_blob') logger.debug('inference text result: {}'.format(payload_json)) timestamp = datetime.now().isoformat() with open(pjoin(self.data_dirpath, timestamp + '.jpg'), 'wb') as f: f.write(jpg_bytes) with open(pjoin(self.data_dirpath, timestamp + '.json'), 'w') as f: f.write(json.dumps(payload_json, indent=4)) def send_snapshot_trigger(self): payload = {} payload['timestamp'] = datetime.now().isoformat() mqtt_payload = json.dumps(payload) self.comm.send('berrynet/trigger/controller/snapshot', mqtt_payload) def run(self, args): """Infinite loop serving inference requests""" self.comm.run() class UI(object): def __init__(self, dc_service, dc_kwargs): # Create data collector attributes self.dc_service = dc_service self.dc_kwargs = dc_kwargs self.dc_service.ui = self # Create UI attributes self.window = tk.Tk() self.window.title('BerryNet Inference Dashboard') self.window.protocol('WM_DELETE_WINDOW', self.on_closing) self.canvas_w = dc_kwargs['image_width'] self.canvas_h = dc_kwargs['image_height'] self.crowd_factor = 3 # Add label: inference result text self.result = tk.Label(self.window, text='TBD', font=('Courier New', 10), justify=tk.LEFT) #self.result.pack(expand=True, side=tk.LEFT) self.result.grid(row=0, column=0, padx=10) #self.result.columnconfigure(1, weight=2) # Add canvas: inference result image #self.canvas = tk.Canvas(self.window, width=1920, height=1080) self.canvas = tk.Canvas(self.window) self.photo = ImageTk.PhotoImage( image=Image.fromarray( np.zeros((self.canvas_h, self.canvas_w, 3), dtype=np.uint8))) self.image_id = self.canvas.create_image( 0, 0, image=self.photo, anchor=tk.NW) #self.canvas.pack(side=tk.LEFT) self.canvas.grid(row=0, column=1, rowspan=2, columnspan=4, sticky='nesw') # Add button: snapshot trigger self.snapshot_button = tk.Button(self.window, text='Query', command=self.snapshot) #self.snapshot_button.pack(expand=True) self.snapshot_button.grid(row=1, column=0) # Add button and label: threshold controller self.threshold = tk.Label(self.window, text=self.crowd_factor, font=('Courier New', 10), justify=tk.LEFT) self.threshold.grid(row=1, column=1) self.snapshot_button = tk.Button(self.window, text='+', command=self.increase_threshold) self.snapshot_button.grid(row=1, column=2) self.snapshot_button = tk.Button(self.window, text='-', command=self.decrease_threshold) self.snapshot_button.grid(row=1, column=3) # Create data collector thread t = threading.Thread(name='Data Collector', target=self.dc_service.run, args=(self.dc_kwargs,)) t.start() # Start the main UI program self.window.mainloop() def update(self, data, imgkey='bytes'): ''' Args: data: Inference result loaded from JSON object ''' # Retrieve result image jpg_bytes = payload.destringify_jpg(data[imgkey]) img = payload.jpg2rgb(jpg_bytes) # Retrieve result text, and update text area data.pop(imgkey) result_text = self.process_output(data) if 'safely' in result_text: text_color = 'blue' else: text_color = 'red' self.result.config(text=result_text, fg=text_color) # update image area resized_img = Image.fromarray(img).resize((self.canvas_h, self.canvas_w)) self.photo = ImageTk.PhotoImage(image=resized_img) win_w = self.photo.width() + self.result.winfo_width() win_h = self.photo.height() + self.snapshot_button.winfo_height() self.window.geometry('{}x{}'.format(win_w, win_h)) self.canvas.itemconfig(self.image_id, image=self.photo) def snapshot(self): self.dc_service.send_snapshot_trigger() def increase_threshold(self): self.crowd_factor += 1 self.threshold.config(text=self.crowd_factor) def decrease_threshold(self): self.crowd_factor -= 1 self.threshold.config(text=self.crowd_factor) def process_output(self, output): ''' Args: output: Inference result, JSON object Returns: Stringified JSON data. ''' if 'annotations' in output.keys(): count = 0 for obj in output['annotations']: if obj['label'] == 'person': count += 1 #logger.info('label = {}'.format(k)) msg = '{} persons at the corner\n\n'.format(count) if count > self.crowd_factor: msg += 'Too crowded,\nsuggest to go straight' else: msg += 'You can turn right safely' return msg else: return json.dumps(output, indent=4) def on_closing(self): self.dc_service.comm.disconnect() self.window.destroy() def parse_args(): ap = argparse.ArgumentParser() ap.add_argument( '--data-dirpath', default=None, help='Dirpath where to store collected data.' ) ap.add_argument( '--broker-ip', default='localhost', help='MQTT broker IP.' ) ap.add_argument( '--broker-port', default=1883, type=int, help='MQTT broker port.' ) ap.add_argument( '--topic-config', default=None, help='Path of the MQTT topic subscription JSON.' ) ap.add_argument( '--image-width', type=int, default=300, help='Image display width in pixel.' ) ap.add_argument( '--image-height', type=int, default=300, help='Image display height in pixel.' ) return vars(ap.parse_args()) def main(): args = parse_args() if args['topic_config']: with open(args['topic_config']) as f: topic_config = json.load(f) else: topic_config = {} comm_config = { 'subscribe': topic_config, 'broker': { 'address': args['broker_ip'], 'port': args['broker_port'] } } dc_service = DataCollectorService(comm_config, args['data_dirpath']) UI(dc_service, args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/client/fbdashboard.py000066400000000000000000000244241360632137300230460ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Framebuffer dashboard. """ import argparse import json import logging import os import random import sys import time from datetime import datetime from os.path import join as pjoin import cv2 from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * class FBDashboardService(object): def __init__(self, comm_config, data_dirpath=None, no_decoration=False, debug=False, save_frame=False): self.comm_config = comm_config for topic, functor in self.comm_config['subscribe'].items(): self.comm_config['subscribe'][topic] = eval(functor) self.comm = Communicator(self.comm_config, debug=True) self.data_dirpath = data_dirpath self.no_decoration = no_decoration self.frame = None self.debug = debug self.save_frame = save_frame def update(self, pl): payload_json = payload.deserialize_payload(pl.decode('utf-8')) if 'bytes' in payload_json.keys(): img_k = 'bytes' elif 'image_blob' in payload_json.keys(): img_k = 'image_blob' else: raise Exception('No image data in MQTT payload') jpg_bytes = payload.destringify_jpg(payload_json[img_k]) payload_json.pop(img_k) logger.debug('inference text result: {}'.format(payload_json)) img = payload.jpg2rgb(jpg_bytes) if self.no_decoration: self.frame = img else: try: res = payload_json['annotations'] except KeyError: res = [ { 'label': 'hello', 'confidence': 0.42, 'left': random.randint(50, 60), 'top': random.randint(50, 60), 'right': random.randint(300, 400), 'bottom': random.randint(300, 400) } ] self.frame = overlay_on_image(img, res) # Save frames for analysis or debugging if self.debug and self.save_frame: if not os.path.exists(self.data_dirpath): try: os.mkdir(self.data_dirpath) except Exception as e: logger.warn('Failed to create {}'.format(self.data_dirpath)) raise(e) timestamp = datetime.now().isoformat() with open(pjoin(self.data_dirpath, timestamp + '.jpg'), 'wb') as f: f.write(jpg_bytes) with open(pjoin(self.data_dirpath, timestamp + '.json'), 'w') as f: f.write(json.dumps(payload_json, indent=4)) def update_fb(self): if self.frame is not None: gl_draw_fbimage(self.frame) def run(self, args): """Infinite loop serving inference requests""" self.comm.start_nb() def gl_draw_fbimage(rgbimg): h, w = rgbimg.shape[:2] glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, rgbimg) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glColor3f(1.0, 1.0, 1.0) glEnable(GL_TEXTURE_2D) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glBegin(GL_QUADS) glTexCoord2d(0.0, 1.0) glVertex3d(-1.0, -1.0, 0.0) glTexCoord2d(1.0, 1.0) glVertex3d( 1.0, -1.0, 0.0) glTexCoord2d(1.0, 0.0) glVertex3d( 1.0, 1.0, 0.0) glTexCoord2d(0.0, 0.0) glVertex3d(-1.0, 1.0, 0.0) glEnd() glFlush() glutSwapBuffers() def init(): glClearColor(0.7, 0.7, 0.7, 0.7) def idle(): glutPostRedisplay() def keyboard(key, x, y): key = key.decode('utf-8') if key == 'q': print("\n\nFinished\n\n") sys.exit() def opencv_frame(src, w=None, h=None, fps=30): vidcap = cv2.VideoCapture(src) if not vidcap.isOpened(): print('opened failed') sys.exit(errno.ENOENT) # set frame w/h if indicated if w and h: vidcap.set(cv2.CAP_PROP_FRAME_WIDTH, w) vidcap.set(cv2.CAP_PROP_FRAME_HEIGHT, h) # set FPS rate = int(vidcap.get(cv2.CAP_PROP_FPS)) if rate > fps or rate < 1: print('Illegal data rate {} (1-30)'.format(rate)) rate = fps print('fps: {}'.format(rate)) # frame generator while True: success, image = vidcap.read() if not success: print('Failed to read frame') break yield image #Vcap = opencv_frame(0, w=320, h=240) Vcap = opencv_frame(0) def draw_box(image, annotations): """Draw information of annotations onto image. Args: image: Image nparray. annotations: List of detected object information. Returns: Image nparray containing object information on it. """ print('draw_box, annotations: {}'.format(annotations)) img = image.copy() for anno in annotations: # draw bounding box box_color = (0, 0, 255) box_thickness = 1 cv2.rectangle(img, (int(anno['left']), int(anno['top'])), (int(anno['right']), int(anno['bottom'])), box_color, box_thickness) # draw label label_background_color = box_color label_text_color = (255, 255, 255) if 'track_id' in anno.keys(): label = 'ID:{} {}'.format(anno['track_id'], anno['label']) else: label = anno['label'] label_text = '{} ({} %)'.format(label, int(anno['confidence'] * 100)) label_size = cv2.getTextSize(label_text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)[0] label_left = anno['left'] label_top = anno['top'] - label_size[1] if (label_top < 1): label_top = 1 label_right = label_left + label_size[0] label_bottom = label_top + label_size[1] cv2.rectangle(img, (int(label_left - 1), int(label_top - 1)), (int(label_right + 1), int(label_bottom + 1)), label_background_color, -1) cv2.putText(img, label_text, (int(label_left), int(label_bottom)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, label_text_color, 1) return img def overlay_on_image(display_image, object_info): """Modulized version of overlay_on_image function """ if isinstance(object_info, type(None)): print('WARNING: object info is None') return display_image return draw_box(display_image, object_info) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument( '--data-dirpath', default='/tmp/berrynet-data', help='Dirpath where to store collected data.' ) ap.add_argument( '--broker-ip', default='localhost', help='MQTT broker IP.' ) ap.add_argument( '--broker-port', default=1883, type=int, help='MQTT broker port.' ) ap.add_argument( '--topic', nargs='*', default=['berrynet/engine/tflitedetector/result'], help='The topic to listen, and can be indicated multiple times.' ) ap.add_argument( '--topic-action', default='self.update', help='The action for the indicated topics.' ) ap.add_argument( '--topic-config', default=None, help='Path of the MQTT topic subscription JSON.' ) ap.add_argument( '--no-decoration', action='store_true', help='Display image in payload without applying result information.' ) ap.add_argument( '--no-full-screen', action='store_true', help='Display fbdashboard in a window.' ) ap.add_argument('--debug', action='store_true', help='Debug mode toggle' ) ap.add_argument('--debug-save-frame', action='store_true', help='Save frames for debugging. --debug also needs to be set.' ) return vars(ap.parse_args()) def main(): args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) # Topics and actions can come from two sources: CLI and config file. # Setup topic_config by parsing values from the two sources. if args['topic_config']: with open(args['topic_config']) as f: topic_config = json.load(f) else: topic_config = {} topic_config.update({t:args['topic_action'] for t in args['topic']}) comm_config = { 'subscribe': topic_config, 'broker': { 'address': args['broker_ip'], 'port': args['broker_port'] } } fbd_service = FBDashboardService(comm_config, args['data_dirpath'], args['no_decoration'], args['debug'], args['debug_save_frame']) fbd_service.run(args) glutInitWindowPosition(0, 0) glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE) glutCreateWindow("BerryNet Result Dashboard, q to quit") glutDisplayFunc(fbd_service.update_fb) glutKeyboardFunc(keyboard) init() glutIdleFunc(idle) if args['no_full_screen']: pass else: glutFullScreen() glutMainLoop() if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/client/gmail.py000066400000000000000000000202521360632137300216730ustar00rootroot00000000000000# Copyright 2019 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . # Reference # https://www.geeksforgeeks.org/send-mail-attachment-gmail-account-using-python/ """Gmail client sends an email with inference result. The email will contain two attachments: image and text. """ import argparse import json import logging import os import smtplib from datetime import datetime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders from os.path import join as pjoin from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload def create_mime_attachment(filepath): filename = os.path.basename(filepath) attachment = open(filepath, "rb") # instance of MIMEBase and named as p p = MIMEBase('application', 'octet-stream') # To change the payload into encoded form p.set_payload(attachment.read()) # encode into base64 encoders.encode_base64(p) p.add_header('Content-Disposition', "attachment; filename= %s" % filename) return p def send_email_text(sender_address, sender_password, receiver_address, body='', subject='BerryNet mail client notification', attachments=None): # instance of MIMEMultipart msg = MIMEMultipart() msg['From'] = sender_address msg['To'] = receiver_address msg['Subject'] = subject logger.debug('Sender: {}'.format(msg['From'])) logger.debug('Receiver: {}'.format(msg['To'])) logger.debug('Subject: {}'.format(msg['Subject'])) # attach the body with the msg instance msg.attach(MIMEText(body, 'plain')) for fpath in attachments: logger.debug('Attachment: {}'.format(fpath)) msg.attach(create_mime_attachment(fpath)) # creates SMTP session s = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security s.starttls() # Authentication s.login(sender_address, sender_password) # Converts the Multipart msg into a string text = msg.as_string() # sending the mail s.sendmail(sender_address, receiver_address, text) # terminating the session s.quit() class GmailService(object): def __init__(self, comm_config): self.comm_config = comm_config for topic, functor in self.comm_config['subscribe'].items(): self.comm_config['subscribe'][topic] = eval(functor) self.comm = Communicator(self.comm_config, debug=True) self.email = comm_config['email'] self.pipeline_compatible = comm_config['pipeline_compatible'] self.target_label = comm_config['target_label'] def find_target_label(self, target_label, generalized_result): label_list = [i['label'] for i in generalized_result['annotations']] logger.debug('Result labels: {}'.format(label_list)) return target_label in label_list def update(self, pl): payload_json = payload.deserialize_payload(pl.decode('utf-8')) if self.pipeline_compatible: b64img_key = 'image_blob' else: b64img_key = 'bytes' jpg_bytes = payload.destringify_jpg(payload_json[b64img_key]) payload_json.pop(b64img_key) logger.debug('inference text result: {}'.format(payload_json)) match_target_label = self.find_target_label(self.target_label, payload_json) logger.debug('Find target label {0}: {1}'.format( self.target_label, match_target_label)) if match_target_label: timestamp = datetime.now().isoformat() notification_image = pjoin('/tmp', timestamp + '.jpg') notification_text = pjoin('/tmp', timestamp + '.json') with open(notification_image, 'wb') as f: f.write(jpg_bytes) with open(notification_text, 'w') as f: f.write(json.dumps(payload_json, indent=4)) try: send_email_text( self.email['sender_address'], self.email['sender_password'], self.email['receiver_address'], body=('Target label {} is found. ' 'Please check the attachments.' ''.format(self.target_label)), subject='BerryNet mail client notification', attachments=set([notification_image, notification_text])) except Exception as e: logger.warn(e) os.remove(notification_image) os.remove(notification_text) else: # target label is not in generalized result, do nothing pass def run(self, args): """Infinite loop serving inference requests""" self.comm.run() def parse_args(): ap = argparse.ArgumentParser() ap.add_argument( '--sender-address', required=True, help='Email address of sender. Ex: foo@email.org' ) ap.add_argument( '--sender-password', required=True, help='Password of sender email address.' ) ap.add_argument( '--receiver-address', required=True, help='Email address of receiver. Ex: bar@email.org' ) ap.add_argument( '--target-label', required=True, help='Send notification email if the label is in inference result.' ) ap.add_argument( '--broker-ip', default='localhost', help='MQTT broker IP.' ) ap.add_argument( '--broker-port', default=1883, type=int, help='MQTT broker port.' ) ap.add_argument( '--topic', nargs='*', default=['berrynet/engine/tflitedetector/result'], help='The topic to listen, and can be indicated multiple times.' ) ap.add_argument( '--topic-action', default='self.update', help='The action for the indicated topics.' ) ap.add_argument( '--topic-config', default=None, help='Path of the MQTT topic subscription JSON.' ) ap.add_argument( '--pipeline-compatible', action='store_true', help=( 'Change key of b64 image string in generalized result ' 'from bytes to image_blob. ' 'Note: This is an experimental parameter.' ) ) ap.add_argument('--debug', action='store_true', help='Debug mode toggle' ) return vars(ap.parse_args()) def main(): args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) # Topics and actions can come from two sources: CLI and config file. # Setup topic_config by parsing values from the two sources. if args['topic_config']: with open(args['topic_config']) as f: topic_config = json.load(f) else: topic_config = {} topic_config.update({t:args['topic_action'] for t in args['topic']}) comm_config = { 'subscribe': topic_config, 'broker': { 'address': args['broker_ip'], 'port': args['broker_port'] }, 'email': { 'sender_address': args['sender_address'], 'sender_password': args['sender_password'], 'receiver_address': args['receiver_address'] }, 'pipeline_compatible': args['pipeline_compatible'], 'target_label': args['target_label'] } dc_service = GmailService(comm_config) dc_service.run(args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/client/snapshot.py000066400000000000000000000064741360632137300224530ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """ Snapshot service will listen to a trigger event (MQTT topic), and send a snapshot retrieved from camera. """ import argparse import json from datetime import datetime import cv2 from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload class SnapshotService(object): def __init__(self, comm_config): self.comm_config = comm_config for topic, functor in self.comm_config['subscribe'].items(): self.comm_config['subscribe'][topic] = eval(functor) self.comm_config['subscribe']['berrynet/trigger/controller/snapshot'] = self.snapshot self.comm = Communicator(self.comm_config, debug=True) def snapshot(self, pl): '''Send camera snapshot. The functionality is the same as using camera client in file mode. The difference is that snapshot client retrieves image from camera instead of given filepath. ''' duration = lambda t: (datetime.now() - t).microseconds / 1000 # WORKAROUND: Prevent VideoCapture from buffering frames. # VideoCapture will buffer frames automatically, and we need # to find a way to disable it. self.capture = cv2.VideoCapture(0) status, im = self.capture.read() if (status is False): logger.warn('ERROR: Failure happened when reading frame') t = datetime.now() retval, jpg_bytes = cv2.imencode('.jpg', im) mqtt_payload = payload.serialize_jpg(jpg_bytes) self.comm.send('berrynet/data/rgbimage', mqtt_payload) logger.debug('send: {} ms'.format(duration(t))) self.capture.release() def run(self, args): """Infinite loop serving inference requests""" self.comm.run() def parse_args(): ap = argparse.ArgumentParser() ap.add_argument( '--broker-ip', default='localhost', help='MQTT broker IP.' ) ap.add_argument( '--broker-port', default=1883, type=int, help='MQTT broker port.' ) ap.add_argument( '--topic-config', default=None, help='Path of the MQTT topic subscription JSON.' ) return vars(ap.parse_args()) def main(): args = parse_args() if args['topic_config']: with open(args['topic_config']) as f: topic_config = json.load(f) else: topic_config = {} comm_config = { 'subscribe': topic_config, 'broker': { 'address': args['broker_ip'], 'port': args['broker_port'] } } dc_service = SnapshotService(comm_config) dc_service.run(args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/client/telegram_bot.py000066400000000000000000000161101360632137300232440ustar00rootroot00000000000000#!/usr/bin/env python3 # # Copyright 2019 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . import argparse import json import io import logging import os import telegram.ext from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload class TelegramBotService(object): def __init__(self, comm_config, token, target_label='', debug=False): self.comm_config = comm_config for topic, functor in self.comm_config['subscribe'].items(): self.comm_config['subscribe'][topic] = eval(functor) self.comm = Communicator(self.comm_config, debug=True) if os.path.isfile(token): self.token = self.get_token_from_config(token) else: self.token = token self.target_label = target_label self.debug = debug # Telegram Updater employs Telegram Dispatcher which dispatches # updates to its registered handlers. self.updater = telegram.ext.Updater(self.token, use_context=True) self.cameraHandlers = [] def get_token_from_config(self, config): with open(config) as f: cfg = json.load(f) return cfg['token'] def match_target_label(self, target_label, bn_result): labels = [r['label'] for r in bn_result['annotations']] if target_label in labels: logger.debug('Find {0} in inference result {1}'.format(target_label, labels)) return True else: logger.debug('Not find {0} in inference result {1}'.format(target_label, labels)) return False def update(self, pl): try: payload_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(payload_json["bytes"]) jpg_file_descriptor = io.BytesIO(jpg_bytes) for u in self.cameraHandlers: if self.updater is None: continue if self.target_label == '': logger.info("Send photo to %s" % u) self.updater.bot.send_photo(chat_id = u, photo=jpg_file_descriptor) elif self.match_target_label(self.target_label, payload_json): logger.info("Send notification photo with result to %s" % u) self.updater.bot.send_photo(chat_id = u, photo=jpg_file_descriptor) else: pass except Exception as e: logger.info(e) def run(self, args): """Infinite loop serving inference requests""" self.comm.start_nb() self.connect_telegram() def connect_telegram(self): try: self.updater.dispatcher.add_handler( telegram.ext.CommandHandler('help', self.handler_help)) self.updater.dispatcher.add_handler( telegram.ext.CommandHandler('hello', self.handler_hello)) self.updater.dispatcher.add_handler( telegram.ext.CommandHandler('camera', self.handler_camera)) self.updater.dispatcher.add_handler( telegram.ext.CommandHandler('stop', self.handler_stop)) self.updater.start_polling() except Exception as e: logger.critical(e) def handler_help(self, update, context): logger.info("Received command `help`") update.message.reply_text( 'I support these commands: help, hello, camera') def handler_hello(self, update, context): logger.info("Received command `hello`") update.message.reply_text( 'Hello, {}'.format(update.message.from_user.first_name)) def handler_camera(self, update, context): logger.info("Received command `camera`, chat id: %s" % update.message.chat_id) # Register the chat-id for receiving images if (update.message.chat_id not in self.cameraHandlers): self.cameraHandlers.append (update.message.chat_id) update.message.reply_text('Dear, I am ready to help send notification') def handler_stop(self, update, context): logger.info("Received command `stop`, chat id: %s" % update.message.chat_id) # Register the chat-id for receiving images while (update.message.chat_id in self.cameraHandlers): self.cameraHandlers.remove (update.message.chat_id) update.message.reply_text('Bye') def parse_args(): ap = argparse.ArgumentParser() ap.add_argument( '--token', help=('Telegram token got from BotFather, ' 'or filepath of a JSON config file with token.') ) ap.add_argument( '--target-label', default='', help='Send a notification if the target label is in the result.' ) ap.add_argument( '--broker-ip', default='localhost', help='MQTT broker IP.' ) ap.add_argument( '--broker-port', default=1883, type=int, help='MQTT broker port.' ) ap.add_argument( '--topic', nargs='*', default=['berrynet/engine/tflitedetector/result'], help='The topic to listen, and can be indicated multiple times.' ) ap.add_argument( '--topic-action', default='self.update', help='The action for the indicated topics.' ) ap.add_argument( '--topic-config', default=None, help='Path of the MQTT topic subscription JSON.' ) ap.add_argument('--debug', action='store_true', help='Debug mode toggle' ) return vars(ap.parse_args()) def main(): args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) # Topics and actions can come from two sources: CLI and config file. # Setup topic_config by parsing values from the two sources. if args['topic_config']: with open(args['topic_config']) as f: topic_config = json.load(f) else: topic_config = {} topic_config.update({t:args['topic_action'] for t in args['topic']}) comm_config = { 'subscribe': topic_config, 'broker': { 'address': args['broker_ip'], 'port': args['broker_port'] } } telbot_service = TelegramBotService(comm_config, args['token'], args['target_label'], args['debug']) telbot_service.run(args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/comm/000077500000000000000000000000001360632137300177045ustar00rootroot00000000000000BerryNet-upstream-3.9.0/berrynet/comm/__init__.py000066400000000000000000000033451360632137300220220ustar00rootroot00000000000000#!/usr/bin/python3 import paho.mqtt.client as mqtt import paho.mqtt.publish as publish from berrynet import logger from logzero import setup_logger def on_connect(client, userdata, flags, rc): logger.debug('Connected with result code ' + str(rc)) for topic in client.comm_config['subscribe'].keys(): logger.debug('Subscribe topic {}'.format(topic)) client.subscribe(topic) def on_message(client, userdata, msg): """Dispatch received message to its bound functor. """ logger.debug('Receive message from topic {}'.format(msg.topic)) #logger.debug('Message payload {}'.format(msg.payload)) client.comm_config['subscribe'][msg.topic](msg.payload) class Communicator(object): def __init__(self, comm_config, debug=False): self.client = mqtt.Client() self.client.comm_config = comm_config self.client.on_connect = on_connect self.client.on_message = on_message def run(self): self.client.connect( self.client.comm_config['broker']['address'], self.client.comm_config['broker']['port'], 60) self.client.loop_forever() def start_nb(self): self.client.connect( self.client.comm_config['broker']['address'], self.client.comm_config['broker']['port'], 60) self.client.loop_start() def stop_nb(self): self.client.loop_stop() def send(self, topic, payload): logger.debug('Send message to topic {}'.format(topic)) #logger.debug('Message payload {}'.format(payload)) publish.single(topic, payload, hostname=self.client.comm_config['broker']['address']) def disconnect(self): self.client.disconnect() BerryNet-upstream-3.9.0/berrynet/comm/payload.py000066400000000000000000000057421360632137300217170ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . import base64 import json from datetime import datetime import cv2 import numpy as np def stringify_jpg(jpg_bytes): return base64.b64encode(jpg_bytes).decode('utf-8') def destringify_jpg(stringified_jpg): """ :return: JPEG bytes :rtype: bytes """ return base64.b64decode(stringified_jpg.encode('utf-8')) def jpg2bgr(jpg_bytes): """ :return: BGR bytes :rtype: numpy array """ array = np.frombuffer(jpg_bytes, dtype=np.uint8) return cv2.imdecode(array, flags=1) def jpg2rgb(jpg_bytes): """ :return: RGB bytes :rtype: numpy array """ return cv2.cvtColor(jpg2bgr(jpg_bytes), cv2.COLOR_BGR2RGB) def bgr2rgb(bgr_nparray): """Convert image nparray from BGR to RGB. Args: bgr_nparray: Image nparray in BGR color model. Returns: Image nparray in RGB color model. """ return cv2.cvtColor(bgr_nparray, cv2.COLOR_BGR2RGB) def rgb2bgr(rgb_nparray): """Convert image nparray from RGB to BGR. Args: rgb_nparray: Image nparray in RGB color model. Returns: Image nparray in BGR color model. """ return cv2.cvtColor(rgb_nparray, cv2.COLOR_RGB2BGR) def serialize_payload(json_object): return json.dumps(json_object) def serialize_jpg(jpg_bytes): """Create Serialized JSON object consisting of image bytes and meta :param imarray: JPEG bytes :type imarray: bytes :return: serialized image JSON :rtype: string """ obj = {} obj['timestamp'] = datetime.now().isoformat() obj['bytes'] = stringify_jpg(jpg_bytes) return json.dumps(obj) def deserialize_payload(payload): return json.loads(payload) #def deserialize_jpg(jpg_json): # """Deserialized JSON object created by josnify_image. # # :param string : # :return: # :rtype: # """ # return json.loads(jpg_json) if __name__ == '__main__': im = cv2.imread('/home/debug/codes/darknet/data/dog.jpg') retval, jpg_bytes = cv2.imencode('.jpg', im) # size of stringified dog.jpg is 1.33x larger than original s_jpg = serialize_jpg(jpg_bytes) d_jpg = deserialize_payload(s_jpg) # TODO: Can we write JPEG bytes into file directly to prevent # bytes -> numpy array -> decode RGB -> write encoded JPEG cv2.imwrite('/tmp/dog.jpg', jpg2bgr(destringify_jpg(d_jpg['bytes']))) BerryNet-upstream-3.9.0/berrynet/dlmodelmgr.py000066400000000000000000000037171360632137300214610ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """ DL Model Manager, following the DLModelBox model package speccification. """ from __future__ import print_function import argparse import json import os from berrynet import logger class DLModelManager(object): def __init__(self): self.basedir = '/usr/share/dlmodels' def get_model_names(self): return os.listdir(self.basedir) def get_model_meta(self, modelname): meta_filepath = os.path.join(self.basedir, modelname, 'meta.json') with open(meta_filepath, 'r') as f: meta = json.load(f) meta['model'] = os.path.join(self.basedir, modelname, meta['model']) meta['label'] = os.path.join(self.basedir, modelname, meta['label']) for k, v in meta['config'].items(): meta['config'][k] = os.path.join(self.basedir, modelname, meta['config'][k]) return meta def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--modelname', help='Model package name (without version)') return vars(ap.parse_args()) if __name__ == '__main__': args = parse_args() logger.debug('model package name: ', args['modelname']) dlmm = DLModelManager() for name in dlmm.get_model_names(): print(dlmm.get_model_meta(name)) BerryNet-upstream-3.9.0/berrynet/engine/000077500000000000000000000000001360632137300202165ustar00rootroot00000000000000BerryNet-upstream-3.9.0/berrynet/engine/__init__.py000066400000000000000000000032521360632137300223310ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """ Deep learning engine template provides unified interfaces for different backends (e.g. TensorFlow, Caffe2, etc.) """ class DLEngine(object): def __init__(self): self.model_input_cache = [] self.model_output_cache = [] self.cache = { 'model_input': [], 'model_output': '', 'model_output_filepath': '' } def create(self): # Workaround to posepone TensorFlow initialization. # If TF is initialized in __init__, and pass an engine instance # to engine service, TF session will stuck in run(). pass def process_input(self, tensor): return tensor def inference(self, tensor): output = None return output def process_output(self, output): return output def cache_data(self, key, value): self.cache[key] = value def save_cache(self): with open(self.cache['model_output_filepath'], 'w') as f: f.write(str(self.cache['model_output'])) BerryNet-upstream-3.9.0/berrynet/engine/caffe_engine.py000066400000000000000000000046551360632137300231730ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """TensorFlow inference engine. """ from __future__ import print_function import argparse import json import numpy as np import caffe from berrynet import logger #from berrynet.dlmodelmgr import DLModelManager from berrynet.engine import DLEngine class CaffeEngine(DLEngine): # FIXME: Get model information by model manager def __init__(self, model_def, pretrained_model, mean_file, label, image_dims = [256,256], channel_swap=[2,1,0], raw_scale=255.0, top_k=5): super(CaffeEngine, self).__init__() # Load model caffe.set_mode_cpu() self.classifier = caffe.Classifier(model_def, pretrained_model, image_dims=image_dims, mean=mean_file, raw_scale=raw_scale, channel_swap=channel_swap) # Load labels self.labels = [line.rstrip() for line in open(label)] self.top_k = top_k def create(self): pass def process_input(self, rgb_array): self.inputs = rgb_array return self.inputs def inference(self, tensor): self.predictions = self.classifier.predict(self.inputs, False) return self.predictions def process_output(self, output): predictions_list = self.predictions[0].tolist() data = zip(predictions_list, caffe_labels) processed_output = {'annotations': []} i=0 for d in sorted(data, reverse=True): human_string = d[1] score = d[0] anno = { 'type': 'classification', 'label': human_string, 'confidence': score } processed_output['annotations'].append(anno) i = i + 1 if (i >= self.top_k): break return processed_output def save_cache(self): pass BerryNet-upstream-3.9.0/berrynet/engine/darknet_engine.py000066400000000000000000000134531360632137300235530ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Darknet inference engine. """ from __future__ import print_function import argparse import json import math import time import cv2 import numpy as np from berrynet import logger #from berrynet.dlmodelmgr import DLModelManager from berrynet.engine import DLEngine from ctypes import * class BOX(Structure): _fields_ = [("x", c_float), ("y", c_float), ("w", c_float), ("h", c_float)] class IMAGE(Structure): _fields_ = [("w", c_int), ("h", c_int), ("c", c_int), ("data", POINTER(c_float))] class METADATA(Structure): _fields_ = [("classes", c_int), ("names", POINTER(c_char_p))] lib = CDLL("/usr/lib/libdarknet.so", RTLD_GLOBAL) lib.network_width.argtypes = [c_void_p] lib.network_width.restype = c_int lib.network_height.argtypes = [c_void_p] lib.network_height.restype = c_int predict = lib.network_predict predict.argtypes = [c_void_p, POINTER(c_float)] predict.restype = POINTER(c_float) make_image = lib.make_image make_image.argtypes = [c_int, c_int, c_int] make_image.restype = IMAGE make_boxes = lib.make_boxes make_boxes.argtypes = [c_void_p] make_boxes.restype = POINTER(BOX) free_ptrs = lib.free_ptrs free_ptrs.argtypes = [POINTER(c_void_p), c_int] num_boxes = lib.num_boxes num_boxes.argtypes = [c_void_p] num_boxes.restype = c_int make_probs = lib.make_probs make_probs.argtypes = [c_void_p] make_probs.restype = POINTER(POINTER(c_float)) reset_rnn = lib.reset_rnn reset_rnn.argtypes = [c_void_p] load_net = lib.load_network load_net.argtypes = [c_char_p, c_char_p, c_int] load_net.restype = c_void_p free_image = lib.free_image free_image.argtypes = [IMAGE] letterbox_image = lib.letterbox_image letterbox_image.argtypes = [IMAGE, c_int, c_int] letterbox_image.restype = IMAGE load_meta = lib.get_metadata lib.get_metadata.argtypes = [c_char_p] lib.get_metadata.restype = METADATA load_image = lib.load_image_color load_image.argtypes = [c_char_p, c_int, c_int] load_image.restype = IMAGE rgbgr_image = lib.rgbgr_image rgbgr_image.argtypes = [IMAGE] predict_image = lib.network_predict_image predict_image.argtypes = [c_void_p, IMAGE] predict_image.restype = POINTER(c_float) network_detect = lib.network_detect network_detect.argtypes = [c_void_p, IMAGE, c_float, c_float, c_float, POINTER(BOX), POINTER(POINTER(c_float))] def c_array(ctype, values): arr = (ctype*len(values))() arr[:] = values return arr def nparray_to_image(arr): """Convert nparray to Darknet image struct. Args: arr: nparray containing source image in BGR color model. Returns: Darknet image struct, whose data is a C array containing flatten image in BGR color model. """ arr = arr.transpose(2,0,1) c = arr.shape[0] h = arr.shape[1] w = arr.shape[2] arr = (arr/255.0).flatten() data = c_array(c_float, arr) im = IMAGE(w, h, c, data) rgbgr_image(im) return im def detect_np(net, meta, np_img, thresh=.3, hier_thresh=.5, nms=.45): im = nparray_to_image(np_img) boxes = make_boxes(net) probs = make_probs(net) num = num_boxes(net) t_start = time.time() network_detect(net, im, thresh, hier_thresh, nms, boxes, probs) t_end = time.time() logger.debug('inference time: {} s'.format(t_end - t_start)) res = [] for j in range(num): for i in range(meta.classes): if probs[j][i] > 0: res.append( { 'type': 'detection', 'label': meta.names[i].decode('utf-8'), 'confidence': probs[j][i], 'left': boxes[j].x - (boxes[j].w / 2), 'top': boxes[j].y - (boxes[j].h / 2), 'right': boxes[j].x + (boxes[j].w / 2), 'bottom': boxes[j].y + (boxes[j].h / 2), 'id': -1 } ) free_ptrs(cast(probs, POINTER(c_void_p)), num) return res class DarknetEngine(DLEngine): # FIXME: Get model information by model manager def __init__(self, config, model, meta=''): super(DarknetEngine, self).__init__() self.net = load_net(config, model, 0) self.meta = load_meta(meta) self.classes = self.meta.classes self.labels = [self.meta.names[i].decode('utf-8') for i in range(self.classes)] # Warmup zero_image = np.zeros(shape=(416, 416, 3), dtype=np.uint8) detect_np(self.net, self.meta, zero_image) def process_input(self, rgb_array): return rgb_array def inference(self, tensor): return detect_np(self.net, self.meta, tensor) def process_output(self, output): return {'annotations': output} if __name__ == '__main__': engine = DarknetEngine( config=b'/usr/share/dlmodels/tinyyolovoc-20170816/tiny-yolo-voc.cfg', model=b'/usr/share/dlmodels/tinyyolovoc-20170816/tiny-yolo-voc.weights', meta=b'/usr/share/dlmodels/tinyyolovoc-20170816/voc.data' ) im = cv2.imread('data/dog.jpg') for i in range(3): r = engine.inference(im) print(r) BerryNet-upstream-3.9.0/berrynet/engine/movidius.py000066400000000000000000000136721360632137300224400ustar00rootroot00000000000000#!/usr/bin/python # # Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . import os import cv2 import numpy as np from mvnc import mvncapi as mvnc class MovidiusNeuralGraph(object): def __init__(self, graph_filepath, label_filepath): # mvnc.SetGlobalOption(mvnc.GlobalOption.LOGLEVEL, 2) devices = mvnc.EnumerateDevices() if len(devices) == 0: raise Exception('No devices found') self.device = mvnc.Device(devices[0]) self.device.OpenDevice() # Load graph with open(graph_filepath, mode='rb') as f: graphfile = f.read() self.graph = self.device.AllocateGraph(graphfile) # Load labels self.labels = [] with open(label_filepath, 'r') as f: for line in f: label = line.split('\n')[0] if label != 'classes': self.labels.append(label) f.close() def __exit__(self, exc_type, exc_value, traceback): self.graph.DeallocateGraph() self.device.CloseDevice() def inference(self, data): self.graph.LoadTensor(data.astype(np.float16), 'user object') output, userobj = self.graph.GetResult() return output def get_graph(self): return self.graph def get_labels(self): return self.labels def process_inceptionv3_input(img): image_size = 299 mean = 128 std = 1.0/128 dx, dy, dz = img.shape delta = float(abs(dy - dx)) if dx > dy: # crop the x dimension img = img[int(0.5*delta):dx-int(0.5*delta), 0:dy] else: img = img[0:dx, int(0.5*delta):dy-int(0.5*delta)] img = cv2.resize(img, (image_size, image_size)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for i in range(3): img[:, :, i] = (img[:, :, i] - mean) * std return img def process_inceptionv3_output(output, labels): processed_output = {'annotations': []} decimal_digits = 2 top_k = 5 top_inds = output.argsort()[::-1][:top_k] for i in range(top_k): human_string = labels[top_inds[i]] score = round(float(output[top_inds[i]]), decimal_digits) anno = { 'type': 'classification', 'label': human_string, 'confidence': score } processed_output['annotations'].append(anno) return processed_output #return [(labels[top_inds[i]], output[top_inds[i]]) for i in range(5)] def print_inceptionv3_output(output, labels): top_inds = output.argsort()[::-1][:5] for i in range(5): print(top_inds[i], labels[top_inds[i]], output[top_inds[i]]) def process_mobilenetssd_input(bgr_nparray): """Normalize MobileNet SSD input image. Args: img: Image nparray in BGR color model. Returns: Pre-processed image nparray in BGR color model. """ img = cv2.resize(bgr_nparray, (300, 300)) img = img - 127.5 img = img * 0.007843 return img def process_mobilenetssd_output(output, img_w, img_h, labels, threshold=0.1): """ More details about inference result format: https://github.com/movidius/ncappzoo/blob/master/caffe/SSD_MobileNet/run.py Args: output: Inference result returned by Graph.GetResult(). img_w: Width of input image. img_h: Height of input image. labels: threshold: Returns: Annotations as dictionary, key is "annotations" and value a list of parsed results. Example: 'annotations': [ { "label": "car", "confidence": 0.93, "left": 100, "top": 100, "right": 200, "bottom": 200 }, ... ] """ boxnum_index = 0 result_index = 7 result_size = 7 num_valid_boxes = int(output[boxnum_index]) annotations = [] for i in range(num_valid_boxes): base_index = result_index + result_size * i result_objinfo = output[base_index:(base_index + result_size)] anno = {} anno['label'] = labels[int(result_objinfo[1])] anno['confidence'] = float(result_objinfo[2]) anno['left'] = int(result_objinfo[3] * img_w) anno['top'] = int(result_objinfo[4] * img_h) anno['right'] = int(result_objinfo[5] * img_w) anno['bottom'] = int(result_objinfo[6] * img_h) if anno['confidence'] >= threshold: annotations.append(anno) return {'annotations': annotations} if __name__ == '__main__': graph_filepath = '' # model filepath label_filepath = '' # label filepath path_to_images = '' # image dirpath image_filenames = [os.path.join(path_to_images, image_name) for image_name in []] # image filename list movidius = MovidiusNeuralGraph(graph_filepath, label_filepath) labels = movidius.get_labels() print(''.join(['*' for i in range(79)])) print('inception-v3 on NCS') for image_filename in image_filenames: img = cv2.imread(image_filename).astype(np.float32) img = process_inceptionv3_input(img) print(''.join(['*' for i in range(79)])) print('Start download to NCS...') output = movidius.inference(img) print_inceptionv3_output(output, labels) print(''.join(['*' for i in range(79)])) print('Finished') BerryNet-upstream-3.9.0/berrynet/engine/movidius_engine.py000066400000000000000000000043761360632137300237660ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Movidius classification inference engine. """ from __future__ import print_function from berrynet.engine import DLEngine from berrynet.engine import movidius as mv class MovidiusEngine(DLEngine): def __init__(self, model, label): super(MovidiusEngine, self).__init__() self.mvng = mv.MovidiusNeuralGraph(model, label) def process_input(self, tensor): return mv.process_inceptionv3_input(tensor) def inference(self, tensor): return self.mvng.inference(tensor) def process_output(self, output): return mv.process_inceptionv3_output( output, self.mvng.get_labels()) def save_cache(self): with open(self.cache['model_output_filepath'], 'w') as f: for i in self.cache['model_output']: print("%s (score = %.5f)" % (i[0], i[1]), file=f) class MovidiusMobileNetSSDEngine(DLEngine): def __init__(self, model, label): super(MovidiusMobileNetSSDEngine, self).__init__() self.mvng = mv.MovidiusNeuralGraph(model, label) self.labels = self.mvng.get_labels() self.classes = len(self.labels) def process_input(self, tensor): self.img_w = tensor.shape[1] self.img_h = tensor.shape[0] return mv.process_mobilenetssd_input(tensor) def inference(self, tensor): return self.mvng.inference(tensor) def process_output(self, output): return mv.process_mobilenetssd_output( output, self.img_w, self.img_h, self.mvng.get_labels()) BerryNet-upstream-3.9.0/berrynet/engine/openvino_engine.py000066400000000000000000000415551360632137300237640ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """OpenVINO classification inference engine. """ import logging import os import sys from argparse import ArgumentParser from time import time from berrynet.engine import DLEngine import cv2 import numpy as np from berrynet import logger from openvino.inference_engine import IENetwork, IEPlugin class OpenVINOClassifierEngine(DLEngine): def __init__(self, model, labels=None, top_k=3, device='CPU'): """ Args: model: Path to an .xml file with a trained model. device: Specify the target device to infer on; CPU, GPU, FPGA or MYRIAD is acceptable. Sample will look for a suitable plugin for device specified (CPU by default) labels: Labels mapping file top_k: Number of top results """ super(OpenVINOClassifierEngine, self).__init__() model_bin = model model_xml = os.path.splitext(model_bin)[0] + ".xml" if labels: with open(labels, 'r') as f: # Allow label name with spaces. To use onlyh the 1st word, # uncomment another labels_map implementation below. self.labels_map = [l.strip() for l in f.readlines()] #self.labels_map = [x.split(sep=' ', maxsplit=1)[-1].strip() # for x in f] else: self.labels_map = None self.top_k = top_k # Plugin initialization for specified device and # load extensions library if specified # # Note: MKLDNN CPU-targeted custom layer support is not included # because we do not use it yet. self.plugin = IEPlugin(device=device, plugin_dirs=None) # Read IR logger.debug('Loading network files:' '\n\txml: {0}\n\tbin: {1}'.format(model_xml, model_bin)) net = IENetwork.from_ir(model=model_xml, weights=model_bin) if self.plugin.device == "CPU": supported_layers = self.plugin.get_supported_layers(net) not_supported_layers = [l for l in net.layers.keys() if l not in supported_layers] if len(not_supported_layers) != 0: logger.error("Following layers are not supported by the plugin for specified device {}:\n {}".format(self.plugin.device, ', '.join(not_supported_layers))) sys.exit(1) assert len(net.inputs.keys()) == 1, "Sample supports only single input topologies" assert len(net.outputs) == 1, "Sample supports only single output topologies" # input_blob and and out_blob are the layer names in string format. logger.debug("Preparing input blobs") self.input_blob = next(iter(net.inputs)) self.out_blob = next(iter(net.outputs)) net.batch_size = 1 self.n, self.c, self.h, self.w = net.inputs[self.input_blob].shape # Loading model to the plugin logger.debug("Loading model to the plugin") self.exec_net = self.plugin.load(network=net) del net def __delete__(self, instance): del self.exec_net del self.plugin def process_input(self, tensor): """Resize tensor (if needed) and change layout from HWC to CHW. Args: tensor: Input BGR tensor (OpenCV convention) Returns: Resized and transposed tensor """ if tensor.shape[:-1] != (self.h, self.w): logger.warning("Input tensor is resized from {} to {}".format( tensor.shape[:-1], (self.h, self.w))) tensor = cv2.resize(tensor, (self.w, self.h)) tensor = tensor.transpose((2, 0, 1)) # Change data layout from HWC to CHW return tensor def inference(self, tensor): logger.debug("Starting inference") res = self.exec_net.infer(inputs={self.input_blob: tensor}) return res[self.out_blob] def process_output(self, output): logger.debug("Processing output blob") logger.debug("Top {} results: ".format(self.top_k)) annotations = [] for i, probs in enumerate(output): probs = np.squeeze(probs) top_ind = np.argsort(probs)[-self.top_k:][::-1] for id in top_ind: det_label = self.labels_map[id] if self.labels_map else "#{}".format(id) logger.debug("\t{:.7f} label {}".format(probs[id], det_label)) annotations.append({ 'type': 'classification', 'label': det_label, 'confidence': float(probs[id]) }) return {'annotations': annotations} class OpenVINODetectorEngine(DLEngine): def __init__(self, model, labels=None, threshold=0.3, device='CPU'): super(OpenVINODetectorEngine, self).__init__() # Prepare model and labels model_bin = model model_xml = os.path.splitext(model_bin)[0] + ".xml" if labels: with open(labels, 'r') as f: self.labels_map = [x.strip() for x in f] else: self.labels_map = None self.threshold = threshold # Plugin initialization for specified device and # load extensions library if specified # # Note: MKLDNN CPU-targeted custom layer support is not included # because we do not use it yet. if device == 'CPU': plugin_dirs = '/opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/lib/intel64' self.plugin = IEPlugin(device=device, plugin_dirs=plugin_dirs) self.plugin.add_cpu_extension(plugin_dirs + '/libcpu_extension_avx2.so') self.plugin.add_cpu_extension(plugin_dirs + '/libcpu_extension_avx512.so') self.plugin.add_cpu_extension(plugin_dirs + '/libcpu_extension_sse4.so') logger.debug('plugin dirs: {}'.format(plugin_dirs)) else: plugin_dirs = None self.plugin = IEPlugin(device=device, plugin_dirs=plugin_dirs) # Read IR logger.debug('Loading network files:' '\n\txml: {0}\n\tbin: {1}'.format(model_xml, model_bin)) net = IENetwork(model=model_xml, weights=model_bin) if self.plugin.device == "CPU": supported_layers = self.plugin.get_supported_layers(net) not_supported_layers = [l for l in net.layers.keys() if l not in supported_layers] if len(not_supported_layers) != 0: logger.error("Following layers are not supported by the plugin for specified device {}:\n {}". format(self.plugin.device, ', '.join(not_supported_layers))) logger.error("Please try to specify cpu extensions library path in demo's command line parameters using -l " "or --cpu_extension command line argument") sys.exit(1) assert len(net.inputs.keys()) == 1, "Demo supports only single input topologies" assert len(net.outputs) == 1, "Demo supports only single output topologies" # input_blob and and out_blob are the layer names in string format. logger.debug("Preparing input blobs") self.input_blob = next(iter(net.inputs)) self.out_blob = next(iter(net.outputs)) self.n, self.c, self.h, self.w = net.inputs[self.input_blob].shape # Loading model to the plugin self.exec_net = self.plugin.load(network=net, num_requests=2) del net # Initialize engine mode: sync or async # # FIXME: async mode does not work currently. # process_input needs to provide two input tensors for async. self.is_async_mode = False self.cur_request_id = 0 self.next_request_id = 1 def __delete__(self, instance): del self.exec_net del self.plugin def process_input(self, tensor, next_tensor=None): frame = tensor next_frame = next_tensor # original input shape will be used in process_output self.img_w = tensor.shape[1] self.img_h = tensor.shape[0] # Main sync point: # in the truly Async mode we start the NEXT infer request, while waiting for the CURRENT to complete # in the regular mode we start the CURRENT request and immediately wait for it's completion if self.is_async_mode: in_frame = cv2.resize(next_frame, (self.w, self.h)) in_frame = in_frame.transpose((2, 0, 1)) # Change data layout from HWC to CHW in_frame = in_frame.reshape((self.n, self.c, self.h, self.w)) else: in_frame = cv2.resize(frame, (self.w, self.h)) in_frame = in_frame.transpose((2, 0, 1)) # Change data layout from HWC to CHW in_frame = in_frame.reshape((self.n, self.c, self.h, self.w)) return in_frame def inference(self, tensor): inf_start = time() if self.is_async_mode: self.exec_net.start_async(request_id=self.next_request_id, inputs={self.input_blob: tensor}) else: self.exec_net.start_async(request_id=self.cur_request_id, inputs={self.input_blob: tensor}) if self.exec_net.requests[self.cur_request_id].wait(-1) == 0: inf_end = time() det_time = inf_end - inf_start if self.is_async_mode: logger.debug('Inference time: N\A for async mode') else: logger.debug("Inference time: {:.3f} ms".format(det_time * 1000)) # Parse detection results of the current request res = self.exec_net.requests[self.cur_request_id].outputs[self.out_blob] else: res = None return res # FIXME: async mode does not work currently. # process_input needs to provide two input tensors for async. if self.is_async_mode: self.cur_request_id, self.next_request_id = self.next_request_id, self.cur_request_id frame = next_frame def process_output(self, output): logger.debug("Processing output blob") logger.debug("Threshold: {}".format(self.threshold)) annotations = [] for obj in output[0][0]: # Collect objects when probability more than specified threshold if obj[2] > self.threshold: xmin = int(obj[3] * self.img_w) ymin = int(obj[4] * self.img_h) xmax = int(obj[5] * self.img_w) ymax = int(obj[6] * self.img_h) class_id = int(obj[1]) det_label = self.labels_map[class_id] if self.labels_map else str(class_id) annotations.append({ 'label': det_label, 'confidence': float(obj[2]), 'left': xmin, 'top': ymin, 'right': xmax, 'bottom': ymax }) return {'annotations': annotations} def get_distribution_info(): """Get Debuan or Ubuntu distribution information. """ info = {} with open('/etc/lsb-release') as f: info_l = [i.strip().split('=') for i in f.readlines()] for i in info_l: info[i[0]] = i[1] logger.debug('Distribution info: {}'.format(info)) return info def set_openvino_environment(): """The same effect as executing /bin/setupvars.sh. """ dist_info = get_distribution_info() python_version = 3.5 os.environ['INSTALLDIR'] = '/opt/intel/computer_vision_sdk_2018.4.420' os.environ['INTEL_CVSDK_DIR'] = os.environ['INSTALLDIR'] os.environ['LD_LIBRARY_PATH'] = ( '{installdir}/deployment_tools/model_optimizer/bin:' '{ld_library_path}').format( installdir = os.environ.get('INSTALLDIR'), ld_library_path = os.environ.get('LD_LIBRARY_PATH' or '') ) os.environ['InferenceEngine_DIR'] = os.path.join( os.environ.get('INTEL_CVSDK_DIR'), 'deployment_tools/inference_engine/share' ) os.environ['IE_PLUGINS_PATH'] = os.path.join( os.environ.get('INTEL_CVSDK_DIR'), 'deployment_tools/inference_engine/lib/ubuntu_{}.04/intel64'.format( dist_info['DISTRIB_RELEASE']) ) os.environ['LD_LIBRARY_PATH'] = ( '/opt/intel/opencl:' '{installdir}/deployment_tools/inference_engine/external/gna/lib:' '{installdir}/deployment_tools/inference_engine/external/mkltiny_lnx/lib:' '{installdir}/deployment_tools/inference_engine/external/omp/lib:' '{ie_plugins_path}:' '{ld_library_path}').format( installdir = os.environ.get('INSTALLDIR'), ie_plugins_path = os.environ.get('IE_PLUGINS_PATH'), ld_library_path = os.environ.get('LD_LIBRARY_PATH' or '') ) os.environ['PATH'] = ( '{intel_cvsdk_dir}/deployment_tools/model_optimizer:' '{path}').format( intel_cvsdk_dir = os.environ.get('INTEL_CVSDK_DIR'), path = os.environ.get('PATH'), ) os.environ['PYTHONPATH'] = ( '{intel_cvsdk_dir}/deployment_tools/model_optimizer:' '{pythonpath}').format( intel_cvsdk_dir = os.environ.get('INTEL_CVSDK_DIR'), pythonpath = os.environ.get('PYTHONPATH' or '') ) os.environ['PYTHONPATH'] = ( '{intel_cvsdk_dir}/python/python$python_version:' '{intel_cvsdk_dir}/python/python$python_version/ubuntu16:' '{pythonpath}').format( intel_cvsdk_dir = os.environ.get('INTEL_CVSDK_DIR'), pythonpath = os.environ.get('PYTHONPATH' or '') ) def parse_argsr(): parser = ArgumentParser() parser.add_argument( "-e", "--engine", help=("Classifier or Detector engine. " "classifier, or detector is acceptable. " "(classifier by default)"), default="classifier", type=str) parser.add_argument( "-m", "--model", help="Path to an .xml file with a trained model.", required=True, type=str) parser.add_argument( "-l", "--labels", help="Labels mapping file", default=None, type=str) parser.add_argument( "--top_k", help="Number of top results", default=10, type=int) parser.add_argument( "-d", "--device", help="Specify the target device to infer on; CPU, GPU, FPGA or MYRIAD is acceptable. Sample will look for a suitable plugin for device specified (CPU by default)", default="CPU", type=str) parser.add_argument( "-i", "--input", help="Path to a folder with images or path to an image files", required=True, type=str) parser.add_argument( "--debug", help="Debug mode toggle", default=False, action="store_true") return parser.parse_args() def main(): args = parse_argsr() if args.debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args.engine == 'classifier': engine = OpenVINOClassifierEngine( model = args.model, device = args.device, labels = args.labels, top_k = args.top_k) elif args.engine == 'detector': engine = OpenVINODetectorEngine( model = args.model, device = args.device, labels = args.labels) else: raise Exception('Illegal engine {}, it should be ' 'classifier or detector'.format(args.engine)) #set_openvino_environment() #if args.debug: # logger.debug('OpenVINO environment vars') # target_vars = ['INSTALLDIR', # 'INTEL_CVSDK_DIR', # 'LD_LIBRARY_PATH', # 'InferenceEngine_DIR', # 'IE_PLUGINS_PATH', # 'PATH', # 'PYTHONPATH'] # for i in target_vars: # logger.debug('\t{var}: {val}'.format( # var = i, # val = os.environ.get(i))) bgr_array = cv2.imread(args.input) t = time() image_data = engine.process_input(bgr_array) output = engine.inference(image_data) model_outputs = engine.process_output(output) logger.debug('Result: {}'.format(model_outputs)) logger.debug('Classification takes {} s'.format(time() - t)) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/engine/tensorflow_engine.py000066400000000000000000000071261360632137300243250ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """TensorFlow inference engine. """ from __future__ import print_function import argparse import json import cv2 import numpy as np import tensorflow as tf from berrynet import logger #from berrynet.dlmodelmgr import DLModelManager from berrynet.engine import DLEngine class TensorFlowEngine(DLEngine): # FIXME: Get model information by model manager def __init__(self, model, label, input_layer, output_layer, top_k=3): super(TensorFlowEngine, self).__init__() # Load model with tf.gfile.FastGFile(model, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') # Load labels self.labels = [line.rstrip() for line in tf.gfile.FastGFile(label)] # Load other configs self.input_layer = input_layer self.output_layer = output_layer self.top_k = top_k # NOTE: Do NOT call read_tensor_from_nparray twice to prevent from # recreating unexpected placeholders. self.tensor_op = self.read_tensor_from_nparray( input_height=299, input_width=299, input_mean=0, input_std=255) def create(self): # Create session self.sess = tf.Session() def process_input(self, rgb_array): return self.sess.run(self.tensor_op, feed_dict={'inarray:0': rgb_array}) def inference(self, tensor): return self.sess.run(self.output_layer, {self.input_layer: tensor}) def process_output(self, output): processed_output = {'annotations': []} decimal_digits = 2 predictions = np.squeeze(output) top_k_index = predictions.argsort()[-self.top_k:][::-1] for node_id in top_k_index: human_string = self.labels[node_id] score = round(float(predictions[node_id]), decimal_digits) anno = { 'type': 'classification', 'label': human_string, 'confidence': score } processed_output['annotations'].append(anno) logger.debug('%s (score = %.5f)' % (human_string, score)) return processed_output def save_cache(self): pass # NOTE: Copied from trainer.component def read_tensor_from_nparray(self, input_height=192, input_width=192, input_mean=0, input_std=255): """ Create normalized tensor based on input numpy array """ image_reader = tf.placeholder(tf.uint8, name='inarray') float_caster = tf.cast(image_reader, tf.float32) dims_expander = tf.expand_dims(float_caster, 0) resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width]) normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std]) return normalized BerryNet-upstream-3.9.0/berrynet/engine/tflite_engine.py000066400000000000000000000235351360632137300234140ustar00rootroot00000000000000import logging import time from argparse import ArgumentParser from os import path import cv2 import numpy as np import tensorflow as tf from berrynet.engine import DLEngine from berrynet import logger class TFLiteDetectorEngine(DLEngine): def __init__(self, model, labels, threshold=0.5, num_threads=1): """ Builds Tensorflow graph, load model and labels """ # Load labels self.labels = self._load_label(labels) self.classes = len(self.labels) # Define lite graph and Load Tensorflow Lite model into memory self.interpreter = tf.lite.Interpreter( model_path=model) self.interpreter.allocate_tensors() self.input_details = self.interpreter.get_input_details() self.output_details = self.interpreter.get_output_details() self.input_dtype = self.input_details[0]['dtype'] self.num_threads = num_threads self.threshold = threshold def __delete__(self, instance): #tf.reset_default_graph() #self.sess = tf.InteractiveSession() del self.interpreter def process_input(self, tensor): """Resize and normalize image for network input""" self.img_w = tensor.shape[1] self.img_h = tensor.shape[0] frame = cv2.cvtColor(tensor, cv2.COLOR_BGR2RGB) frame = cv2.resize(frame, (300, 300)) frame = np.expand_dims(frame, axis=0) if self.input_dtype == np.float32: frame = (2.0 / 255.0) * frame - 1.0 frame = frame.astype('float32') else: # default data type returned by cv2.imread is np.unit8 pass return frame def inference(self, tensor): self.interpreter.set_num_threads(int(self.num_threads)); self.interpreter.set_tensor(self.input_details[0]['index'], tensor) self.interpreter.invoke() # get results boxes = self.interpreter.get_tensor( self.output_details[0]['index']) classes = self.interpreter.get_tensor( self.output_details[1]['index']) scores = self.interpreter.get_tensor( self.output_details[2]['index']) num = self.interpreter.get_tensor( self.output_details[3]['index']) return { 'boxes': boxes, 'classes': classes, 'scores': scores, 'num': num } def process_output(self, output): # get results boxes = np.squeeze(output['boxes'][0]) classes = np.squeeze(output['classes'][0] + 1).astype(np.int32) scores = np.squeeze(output['scores'][0]) num = output['num'][0] annotations = [] number_boxes = boxes.shape[0] for i in range(number_boxes): box = tuple(boxes[i].tolist()) ymin, xmin, ymax, xmax = box if scores[i] < self.threshold: continue annotations.append({ 'label': self.labels[classes[i]], 'confidence': float(scores[i]), 'left': int(xmin * self.img_w), 'top': int(ymin * self.img_h), 'right': int(xmax * self.img_w), 'bottom': int(ymax * self.img_h) }) return {'annotations': annotations} def _load_label(self, path): with open(path, 'r') as f: labels = list(map(str.strip, f.readlines())) return labels class TFLiteClassifierEngine(DLEngine): def __init__(self, model, labels, top_k=3, num_threads=1, input_mean=127.5, input_std=127.5): """ Builds Tensorflow graph, load model and labels """ # Load labels self.labels = self._load_label(labels) self.classes = len(self.labels) # Define lite graph and Load Tensorflow Lite model into memory self.interpreter = tf.lite.Interpreter( model_path=model) self.interpreter.allocate_tensors() self.input_details = self.interpreter.get_input_details() self.output_details = self.interpreter.get_output_details() self.floating_model = False if self.input_details[0]['dtype'] == np.float32: self.floating_model = True self.input_mean = input_mean self.input_std = input_std self.top_k = int(top_k) self.num_threads = num_threads def __delete__(self, instance): #tf.reset_default_graph() #self.sess = tf.InteractiveSession() del self.interpreter def process_input(self, tensor): """Resize and normalize image for network input""" self.img_w = tensor.shape[1] self.img_h = tensor.shape[0] frame = cv2.cvtColor(tensor, cv2.COLOR_BGR2RGB) frame = cv2.resize(frame, (self.input_details[0]['shape'][2], self.input_details[0]['shape'][1])) frame = np.expand_dims(frame, axis=0) if self.floating_model: frame = (np.float32(frame) - self.input_mean) / self.input_std return frame def inference(self, tensor): self.interpreter.set_num_threads(int(self.num_threads)); self.interpreter.set_tensor(self.input_details[0]['index'], tensor) self.interpreter.invoke() output_data = self.interpreter.get_tensor(self.output_details[0]['index']) results = np.squeeze(output_data) return { 'scores': results, } def process_output(self, output): # get results scores = output['scores'] top_k_results = scores.argsort()[-self.top_k:][::-1] processed_output = {'annotations': []} for i in top_k_results: human_string = self.labels[i] if self.floating_model: score = float(scores[i]) else: score = float(scores[i])/255.0 anno = { 'type': 'classification', 'label': human_string, 'confidence': score } processed_output['annotations'].append(anno) return processed_output def _load_label(self, path): with open(path, 'r') as f: labels = list(map(str.strip, f.readlines())) return labels def parse_argsr(): parser = ArgumentParser() parser.add_argument( "-e", "--engine", help=("Classifier or Detector engine. " "classifier, or detector is acceptable. " "(classifier by default)"), default="classifier", type=str) parser.add_argument( "-m", "--model", help="Path to an .xml file with a trained model.", required=True, type=str) parser.add_argument( "-l", "--labels", help="Labels mapping file", default=None, type=str) parser.add_argument( "--top_k", help="Number of top results", default=3, type=int) parser.add_argument( "--num_threads", help="Number of threads", default=1, type=int) parser.add_argument( "-i", "--input", help="Path to a folder with images or path to an image files", required=True, type=str) parser.add_argument( "--debug", help="Debug mode toggle", default=False, action="store_true") return parser.parse_args() def main(): # Example command # $ python3 tflite_engine.py -e detector \ # -m detect.tflite --labels labels.txt -i dog.jpg --debug args = parse_argsr() if args.debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args.engine == 'classifier': engine = TFLiteClassifierEngine( model = args.model, labels = args.labels, top_k = args.top_k, num_threads = args.num_threads) elif args.engine == 'detector': engine = TFLiteDetectorEngine( model = args.model, labels = args.labels, num_threads = args.num_threads) else: raise Exception('Illegal engine {}, it should be ' 'classifier or detector'.format(args.engine)) for i in range(5): bgr_array = cv2.imread(args.input) t = time.time() image_data = engine.process_input(bgr_array) output = engine.inference(image_data) model_outputs = engine.process_output(output) # Reference result # input: # darknet/data/dog.jpg # output: # Inference takes 0.7533011436462402 s # Inference takes 0.5741658210754395 s # Inference takes 0.6120760440826416 s # Inference takes 0.6191139221191406 s # Inference takes 0.5809791088104248 s # label: bicycle conf: 0.9563907980918884 (139, 116) (567, 429) # label: car conf: 0.8757821917533875 (459, 80) (690, 172) # label: dog conf: 0.869189441204071 (131, 218) (314, 539) # label: car conf: 0.40003547072410583 (698, 122) (724, 152) logger.debug('Inference takes {} s'.format(time.time() - t)) if args.engine == 'classifier': for r in model_outputs['annotations']: logger.debug('label: {0} conf: {1}'.format( r['label'], r['confidence'] )) elif args.engine == 'detector': for r in model_outputs['annotations']: logger.debug('label: {0} conf: {1} ({2}, {3}) ({4}, {5})'.format( r['label'], r['confidence'], r['left'], r['top'], r['right'], r['bottom'] )) else: raise Exception('Can not get result ' 'from illegal engine {}'.format(args.engine)) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/service/000077500000000000000000000000001360632137300204115ustar00rootroot00000000000000BerryNet-upstream-3.9.0/berrynet/service/__init__.py000066400000000000000000000054741360632137300225340ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Engine service is a bridge between incoming data and inference engine. """ import os import time from datetime import datetime from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload class EngineService(object): def __init__(self, service_name, engine, comm_config): self.service_name = service_name self.engine = engine self.comm_config = comm_config for topic, functor in self.comm_config['subscribe'].items(): self.comm_config['subscribe'][topic] = eval(functor) self.comm_config['subscribe']['berrynet/data/rgbimage'] = self.inference self.comm = Communicator(self.comm_config, debug=True) def inference(self, pl): duration = lambda t: (datetime.now() - t).microseconds / 1000 t = datetime.now() logger.debug('payload size: {}'.format(len(pl))) logger.debug('payload type: {}'.format(type(pl))) jpg_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(jpg_json['bytes']) logger.debug('destringify_jpg: {} ms'.format(duration(t))) t = datetime.now() rgb_array = payload.jpg2rgb(jpg_bytes) logger.debug('jpg2rgb: {} ms'.format(duration(t))) t = datetime.now() image_data = self.engine.process_input(rgb_array) output = self.engine.inference(image_data) model_outputs = self.engine.process_output(output) logger.debug('Result: {}'.format(model_outputs)) logger.debug('Classification takes {} ms'.format(duration(t))) #self.engine.cache_data('model_output', model_outputs) #self.engine.cache_data('model_output_filepath', output_name) #self.engine.save_cache() self.result_hook(self.generalize_result(jpg_json, model_outputs)) def generalize_result(self, eng_input, eng_output): eng_input.update(eng_output) return eng_input def result_hook(self, generalized_result): logger.debug('base result_hook') def run(self, args): """Infinite loop serving inference requests""" self.engine.create() self.comm.run() BerryNet-upstream-3.9.0/berrynet/service/darknet_service.py000066400000000000000000000103471360632137300241400ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Engine service is a bridge between incoming data and inference engine. """ import argparse import logging import math import cv2 from berrynet import logger from berrynet.comm import payload from berrynet.dlmodelmgr import DLModelManager from berrynet.engine.darknet_engine import DarknetEngine from berrynet.service import EngineService from berrynet.utils import generate_class_color from berrynet.utils import draw_bb class DarknetService(EngineService): def __init__(self, service_name, engine, comm_config, draw=False): super(DarknetService, self).__init__(service_name, engine, comm_config) self.draw = draw def inference(self, pl): jpg_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(jpg_json['bytes']) bgr_array = payload.jpg2bgr(jpg_bytes) image_data = self.engine.process_input(bgr_array) output = self.engine.inference(image_data) model_outputs = self.engine.process_output(output) classes = self.engine.classes labels = self.engine.labels if self.draw is False: self.result_hook(self.generalize_result(jpg_json, model_outputs)) else: self.result_hook( draw_bb(bgr_array, self.generalize_result(jpg_json, model_outputs), generate_class_color(class_num=classes), labels)) def result_hook(self, generalized_result): logger.debug('result_hook, annotations: {}'.format(generalized_result['annotations'])) self.comm.send('berrynet/engine/darknet/result', payload.serialize_payload(generalized_result)) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument( '--service_name', default='darknet', help='Human-readable service name for service management.') ap.add_argument( '-m', '--model', help='Model file path') ap.add_argument( '-l', '--label', help='Label file path') ap.add_argument( '-p', '--model_package', default='', help='Model package name. Find model and label file paths automatically.') ap.add_argument( '--draw', action='store_true', help='Draw bounding boxes on image in result') ap.add_argument( '--debug', action='store_true', help='Debug mode toggle') return vars(ap.parse_args()) def main(): args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args['model_package'] != '': dlmm = DLModelManager() meta = dlmm.get_model_meta(args['model_package']) args['model'] = meta['model'] args['label'] = meta['label'] logger.debug('model filepath: ' + args['model']) logger.debug('label filepath: ' + args['label']) engine = DarknetEngine( config=meta['config']['config'].encode('utf-8'), model=args['model'].encode('utf-8'), meta=meta['config']['meta'].encode('utf-8') ) comm_config = { 'subscribe': {}, 'broker': { 'address': 'localhost', 'port': 1883 } } engine_service = DarknetService(args['service_name'], engine, comm_config, args['draw']) engine_service.run(args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/service/mockup_service.py000066400000000000000000000051701360632137300240040ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Mockup service with relay engine (default engine). """ import argparse import json import logging import os from berrynet import logger from berrynet.comm import payload from berrynet.engine import DLEngine from berrynet.service import EngineService class MockupEngine(DLEngine): def inference(self, tensor): return { 'annotations': { 'label': 'dt42', 'confidence': 0.99 } } class MockupService(EngineService): def __init__(self, service_name, engine, comm_config): super().__init__(service_name, engine, comm_config) if not os.path.exists('/tmp/mockup'): os.mkdir('/tmp/mockup') #def generalize_result(self, eng_input, eng_output): # logger.debug() # eng_input.update(eng_output) # return eng_input def result_hook(self, generalized_result): gr = generalized_result jpg_bytes = payload.destringify_jpg(gr.pop('bytes')) logger.debug('generalized result (readable only): {}'.format(gr)) with open('/tmp/mockup/{}.jpg'.format(gr['timestamp']), 'wb') as f: f.write(jpg_bytes) with open('/tmp/mockup/{}.json'.format(gr['timestamp']), 'w') as f: f.write(json.dumps(gr, indent=4)) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--debug', action='store_true', help='Debug mode toggle') return vars(ap.parse_args()) def main(): args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) eng = MockupEngine() comm_config = { 'subscribe': {}, 'broker': { 'address': 'localhost', 'port': 1883 } } engine_service = MockupService('mockup service', eng, comm_config) engine_service.run(args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/service/movidius_service.py000066400000000000000000000135471360632137300243540ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Engine service is a bridge between incoming data and inference engine. """ import argparse import logging from datetime import datetime from berrynet import logger from berrynet.comm import payload from berrynet.dlmodelmgr import DLModelManager from berrynet.engine.movidius_engine import MovidiusEngine from berrynet.engine.movidius_engine import MovidiusMobileNetSSDEngine from berrynet.service import EngineService from berrynet.utils import draw_bb from berrynet.utils import generate_class_color class MovidiusClassificationService(EngineService): def __init__(self, service_name, engine, comm_config): super(MovidiusClassificationService, self).__init__(service_name, engine, comm_config) def result_hook(self, generalized_result): logger.debug('result_hook, annotations: {}'.format(generalized_result['annotations'])) self.comm.send('berrynet/engine/mvclassification/result', payload.serialize_payload(generalized_result)) class MovidiusMobileNetSSDService(EngineService): def __init__(self, service_name, engine, comm_config, draw=False): super(MovidiusMobileNetSSDService, self).__init__(service_name, engine, comm_config) self.draw = draw def inference(self, pl): duration = lambda t: (datetime.now() - t).microseconds / 1000 t = datetime.now() logger.debug('payload size: {}'.format(len(pl))) logger.debug('payload type: {}'.format(type(pl))) jpg_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(jpg_json['bytes']) logger.debug('destringify_jpg: {} ms'.format(duration(t))) t = datetime.now() bgr_array = payload.jpg2bgr(jpg_bytes) logger.debug('jpg2bgr: {} ms'.format(duration(t))) t = datetime.now() image_data = self.engine.process_input(bgr_array) output = self.engine.inference(image_data) model_outputs = self.engine.process_output(output) logger.debug('Result: {}'.format(model_outputs)) logger.debug('Detection takes {} ms'.format(duration(t))) classes = self.engine.classes labels = self.engine.labels logger.debug('draw = {}'.format(self.draw)) if self.draw is False: self.result_hook(self.generalize_result(jpg_json, model_outputs)) else: self.result_hook( draw_bb(bgr_array, self.generalize_result(jpg_json, model_outputs), generate_class_color(class_num=classes), labels)) def result_hook(self, generalized_result): logger.debug('result_hook, annotations: {}'.format(generalized_result['annotations'])) self.comm.send('berrynet/engine/mvmobilenetssd/result', payload.serialize_payload(generalized_result)) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--model', help='Model file path') ap.add_argument('--label', help='Label file path') ap.add_argument('--model_package', default='', help='Model package name') ap.add_argument('--service_name', required=True, help='Valid value: Classification, MobileNetSSD') ap.add_argument('--num_top_predictions', default=5, help='Display this many predictions') ap.add_argument('--draw', action='store_true', help='Draw bounding boxes on image in result') ap.add_argument('--debug', action='store_true', help='Debug mode toggle') return vars(ap.parse_args()) def main(): # Test Movidius engine args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args['model_package'] != '': dlmm = DLModelManager() meta = dlmm.get_model_meta(args['model_package']) args['model'] = meta['model'] args['label'] = meta['label'] logger.debug('model filepath: ' + args['model']) logger.debug('label filepath: ' + args['label']) comm_config = { 'subscribe': {}, 'broker': { 'address': 'localhost', 'port': 1883 } } if args['service_name'] == 'Classification': mvng = MovidiusEngine(args['model'], args['label']) service_functor = MovidiusClassificationService elif args['service_name'] == 'MobileNetSSD': mvng = MovidiusMobileNetSSDEngine(args['model'], args['label']) service_functor = MovidiusMobileNetSSDService else: logger.critical('Legal service names are Classification, MobileNetSSD') engine_service = service_functor(args['service_name'], mvng, comm_config, draw=args['draw']) engine_service.run(args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/service/openvino_service.py000066400000000000000000000202321360632137300243370ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Engine service is a bridge between incoming data and inference engine. """ import argparse import logging from datetime import datetime from berrynet import logger from berrynet.comm import payload from berrynet.dlmodelmgr import DLModelManager from berrynet.engine.openvino_engine import OpenVINOClassifierEngine from berrynet.engine.openvino_engine import OpenVINODetectorEngine from berrynet.service import EngineService from berrynet.utils import draw_bb from berrynet.utils import generate_class_color class OpenVINOClassifierService(EngineService): def __init__(self, service_name, engine, comm_config, draw=False): super(OpenVINOClassifierService, self).__init__(service_name, engine, comm_config) self.draw = draw def inference(self, pl): duration = lambda t: (datetime.now() - t).microseconds / 1000 t = datetime.now() logger.debug('payload size: {}'.format(len(pl))) logger.debug('payload type: {}'.format(type(pl))) jpg_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(jpg_json['bytes']) logger.debug('destringify_jpg: {} ms'.format(duration(t))) t = datetime.now() bgr_array = payload.jpg2bgr(jpg_bytes) logger.debug('jpg2bgr: {} ms'.format(duration(t))) t = datetime.now() image_data = self.engine.process_input(bgr_array) output = self.engine.inference(image_data) model_outputs = self.engine.process_output(output) logger.debug('Result: {}'.format(model_outputs)) logger.debug('Detection takes {} ms'.format(duration(t))) #classes = self.engine.classes #labels = self.engine.labels logger.debug('draw = {}'.format(self.draw)) if self.draw is False: self.result_hook(self.generalize_result(jpg_json, model_outputs)) else: #self.result_hook( # draw_bb(bgr_array, # self.generalize_result(jpg_json, model_outputs), # generate_class_color(class_num=classes), # labels)) self.result_hook(self.generalize_result(jpg_json, model_outputs)) def result_hook(self, generalized_result): logger.debug('result_hook, annotations: {}'.format(generalized_result['annotations'])) self.comm.send('berrynet/engine/ovclassifier/result', payload.serialize_payload(generalized_result)) class OpenVINODetectorService(EngineService): def __init__(self, service_name, engine, comm_config, draw=False): super(OpenVINODetectorService, self).__init__(service_name, engine, comm_config) self.draw = draw def inference(self, pl): duration = lambda t: (datetime.now() - t).microseconds / 1000 t = datetime.now() logger.debug('payload size: {}'.format(len(pl))) logger.debug('payload type: {}'.format(type(pl))) jpg_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(jpg_json['bytes']) logger.debug('destringify_jpg: {} ms'.format(duration(t))) t = datetime.now() bgr_array = payload.jpg2bgr(jpg_bytes) logger.debug('jpg2bgr: {} ms'.format(duration(t))) t = datetime.now() image_data = self.engine.process_input(bgr_array) output = self.engine.inference(image_data) model_outputs = self.engine.process_output(output) logger.debug('Result: {}'.format(model_outputs)) logger.debug('Detection takes {} ms'.format(duration(t))) classes = len(self.engine.labels_map) labels = self.engine.labels_map logger.debug('draw = {}'.format(self.draw)) if self.draw is False: self.result_hook(self.generalize_result(jpg_json, model_outputs)) else: self.result_hook( draw_bb(bgr_array, self.generalize_result(jpg_json, model_outputs), generate_class_color(class_num=classes), labels)) def result_hook(self, generalized_result): logger.debug('result_hook, annotations: {}'.format(generalized_result['annotations'])) self.comm.send('berrynet/engine/ovdetector/result', payload.serialize_payload(generalized_result)) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument( '-s', '--service', help=('Classifier or Detector service. ' 'classifier, or detector is acceptable. ' '(classifier by default)'), default='classifier', type=str) ap.add_argument( '--service_name', default='openvino_classifier', help='Human-readable service name for service management.') ap.add_argument( '-m', '--model', help='Model file path') ap.add_argument( '-l', '--label', help='Label file path') ap.add_argument( '-p', '--model_package', default='', help='Model package name. Find model and label file paths automatically.') ap.add_argument( '--top_k', help='Display top K classification results.', default=3, type=int) ap.add_argument( '-d', '--device', help='Specify the target device to infer on; CPU, GPU, FPGA or MYRIAD is acceptable. Sample will look for a suitable plugin for device specified (CPU by default)', default='CPU', type=str) ap.add_argument( '--draw', action='store_true', help='Draw bounding boxes on image in result') ap.add_argument( '--debug', action='store_true', help='Debug mode toggle') return vars(ap.parse_args()) def main(): # Test OpenVINO classifier engine args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args['model_package'] != '': dlmm = DLModelManager() meta = dlmm.get_model_meta(args['model_package']) args['model'] = meta['model'] args['label'] = meta['label'] logger.debug('model filepath: ' + args['model']) logger.debug('label filepath: ' + args['label']) comm_config = { 'subscribe': {}, 'broker': { 'address': 'localhost', 'port': 1883 } } if args['service'] == 'classifier': engine = OpenVINOClassifierEngine( model = args['model'], labels = args['label'], top_k = args['top_k'], device = args['device']) service_functor = OpenVINOClassifierService elif args['service'] == 'detector': engine = OpenVINODetectorEngine( model = args['model'], labels = args['label'], device = args['device']) service_functor = OpenVINODetectorService else: raise Exception('Illegal service {}, it should be ' 'classifier or detector'.format(args['service'])) engine_service = service_functor(args['service_name'], engine, comm_config, draw=args['draw']) engine_service.run(args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/service/tensorflow_service.py000066400000000000000000000077131360632137300247150ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Engine service is a bridge between incoming data and inference engine. """ import argparse import logging from berrynet import logger from berrynet.comm import payload from berrynet.dlmodelmgr import DLModelManager from berrynet.engine.tensorflow_engine import TensorFlowEngine from berrynet.service import EngineService class TensorFlowService(EngineService): def __init__(self, service_name, engine, comm_config): super(TensorFlowService, self).__init__(service_name, engine, comm_config) def result_hook(self, generalized_result): logger.debug('result_hook, annotations: {}'.format(generalized_result['annotations'])) self.comm.send('berrynet/engine/tensorflow/result', payload.serialize_payload(generalized_result)) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--model', help='Model file path') ap.add_argument('--label', help='Label file path') ap.add_argument('--model_package', default='', help='Model package name. Find model and label file paths automatically.') ap.add_argument('--service_name', default='tensorflow', help='Human-readable service name for service management.') ap.add_argument('--num_top_predictions', help='Display this many predictions', default=3, type=int) ap.add_argument('--debug', action='store_true', help='Debug mode toggle') return vars(ap.parse_args()) def main(): # Test TensorFlow engine args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) logger.debug('model filepath: ' + args['model']) logger.debug('label filepath: ' + args['label']) model = 'berrynet/engine/inception_v3_2016_08_28_frozen.pb' label = 'berrynet/engine/imagenet_slim_labels.txt' jpg_filepath = 'berrynet/engine/grace_hopper.jpg' input_layer = 'input:0' output_layer = 'InceptionV3/Predictions/Reshape_1:0' tfe = TensorFlowEngine(model, label, input_layer, output_layer) comm_config = { 'subscribe': {}, 'broker': { 'address': 'localhost', 'port': 1883 } } engine_service = TensorFlowService(args['service_name'], tfe, comm_config) engine_service.run(args) if __name__ == '__main__': # Test Movidius engine #import movidius as mv #logging.basicConfig(level=logging.DEBUG) #args = parse_args() #if args['model_package'] != '': # dlmm = DLModelManager() # meta = dlmm.get_model_meta(args['model_package']) # args['model'] = meta['model'] # args['label'] = meta['label'] #logging.debug('model filepath: ' + args['model']) #logging.debug('label filepath: ' + args['label']) #logging.debug('image_dir: ' + args['image_dir']) #mvng = mv.MovidiusNeuralGraph(args['model'], args['label']) #engine_service = EngineService(args['service_name'], mvng) #engine_service.run(args) main() BerryNet-upstream-3.9.0/berrynet/service/tflite_service.py000066400000000000000000000175431360632137300240040ustar00rootroot00000000000000# Copyright 2019 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Engine service is a bridge between incoming data and inference engine. """ import argparse import logging import time from berrynet import logger from berrynet.comm import payload from berrynet.dlmodelmgr import DLModelManager from berrynet.engine.tflite_engine import TFLiteClassifierEngine from berrynet.engine.tflite_engine import TFLiteDetectorEngine from berrynet.service import EngineService from berrynet.utils import draw_bb from berrynet.utils import generate_class_color class TFLiteClassifierService(EngineService): def __init__(self, service_name, engine, comm_config, draw=False): super(TFLiteClassifierService, self).__init__(service_name, engine, comm_config) self.draw = draw def inference(self, pl): t0 = time.time() logger.debug('payload size: {}'.format(len(pl))) logger.debug('payload type: {}'.format(type(pl))) jpg_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(jpg_json['bytes']) logger.debug('destringify_jpg: {} ms'.format(time.time() - t0)) t1 = time.time() bgr_array = payload.jpg2bgr(jpg_bytes) logger.debug('jpg2bgr: {} ms'.format(time.time() - t1)) t2 = time.time() image_data = self.engine.process_input(bgr_array) logger.debug('Input processing takes {} ms'.format(time.time() - t2)) t3 = time.time() output = self.engine.inference(image_data) model_outputs = self.engine.process_output(output) logger.debug('Result: {}'.format(model_outputs)) logger.debug('Classification takes {} ms'.format(time.time() - t3)) classes = self.engine.classes labels = self.engine.labels logger.debug('draw = {}'.format(self.draw)) if self.draw is False: self.result_hook(self.generalize_result(jpg_json, model_outputs)) else: self.result_hook( draw_label(bgr_array, self.generalize_result(jpg_json, model_outputs), color, labels)) def result_hook(self, generalized_result): logger.debug('result_hook, annotations: {}'.format(generalized_result['annotations'])) self.comm.send('berrynet/engine/tfliteclassifier/result', payload.serialize_payload(generalized_result)) class TFLiteDetectorService(EngineService): def __init__(self, service_name, engine, comm_config, draw=False): super(TFLiteDetectorService, self).__init__(service_name, engine, comm_config) self.draw = draw def inference(self, pl): t0 = time.time() logger.debug('payload size: {}'.format(len(pl))) logger.debug('payload type: {}'.format(type(pl))) jpg_json = payload.deserialize_payload(pl.decode('utf-8')) jpg_bytes = payload.destringify_jpg(jpg_json['bytes']) logger.debug('destringify_jpg: {} ms'.format(time.time() - t0)) t1 = time.time() bgr_array = payload.jpg2bgr(jpg_bytes) logger.debug('jpg2bgr: {} ms'.format(time.time() - t1)) t2 = time.time() image_data = self.engine.process_input(bgr_array) output = self.engine.inference(image_data) model_outputs = self.engine.process_output(output) logger.debug('Result: {}'.format(model_outputs)) logger.debug('Detection takes {} ms'.format(time.time() - t2)) classes = self.engine.classes labels = self.engine.labels logger.debug('draw = {}'.format(self.draw)) if self.draw is False: self.result_hook(self.generalize_result(jpg_json, model_outputs)) else: self.result_hook( draw_bb(bgr_array, self.generalize_result(jpg_json, model_outputs), generate_class_color(class_num=classes), labels)) def result_hook(self, generalized_result): logger.debug('result_hook, annotations: {}'.format(generalized_result['annotations'])) self.comm.send('berrynet/engine/tflitedetector/result', payload.serialize_payload(generalized_result)) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument( '-s', '--service', help=('Classifier or Detector service. ' 'classifier, or detector is acceptable. ' '(classifier by default)'), default='classifier', type=str) ap.add_argument( '--service_name', default='tflite_classifier', help='Human-readable service name for service management.') ap.add_argument( '-m', '--model', help='Model file path') ap.add_argument( '-l', '--label', help='Label file path') ap.add_argument( '-p', '--model_package', default='', help='Model package name. Find model and label file paths automatically.') ap.add_argument( '--top_k', help='Display top K classification results.', default=3, type=int) ap.add_argument( '--num_threads', default=1, help="Number of threads for running inference.") ap.add_argument( '--draw', action='store_true', help='Draw bounding boxes on image in result') ap.add_argument( '--debug', action='store_true', help='Debug mode toggle') return vars(ap.parse_args()) def main(): # Test TFLite engines args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args['model_package'] != '': dlmm = DLModelManager() meta = dlmm.get_model_meta(args['model_package']) args['model'] = meta['model'] args['label'] = meta['label'] logger.debug('model filepath: ' + args['model']) logger.debug('label filepath: ' + args['label']) comm_config = { 'subscribe': {}, 'broker': { 'address': 'localhost', 'port': 1883 } } if args['service'] == 'classifier': engine = TFLiteClassifierEngine( model = args['model'], labels = args['label'], top_k = args['top_k'], num_threads = args['num_threads']) service_functor = TFLiteClassifierService elif args['service'] == 'detector': engine = TFLiteDetectorEngine( model = args['model'], labels = args['label'], num_threads = args['num_threads']) service_functor = TFLiteDetectorService else: raise Exception('Illegal service {}, it should be ' 'classifier or detector'.format(args['service'])) engine_service = service_functor(args['service_name'], engine, comm_config, draw=args['draw']) engine_service.run(args) if __name__ == '__main__': main() BerryNet-upstream-3.9.0/berrynet/utils.py000066400000000000000000000140521360632137300204650ustar00rootroot00000000000000# Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Utility Functions. """ import math import cv2 from berrynet.comm import payload def generate_class_color(class_num=20): """Generate a RGB color set based on given class number. Args: class_num: Default is VOC dataset class number. Returns: A tuple containing RGB colors. """ colors = [(1, 0, 1), (0, 0, 1), (0, 1, 1), (0, 1, 0), (1, 1, 0), (1, 0, 0)] const = 1234567 # only for offset calculation colorset = [] for cls_i in range(class_num): offset = cls_i * const % class_num ratio = (float(offset) / class_num) * (len(colors) - 1) i = math.floor(ratio) j = math.ceil(ratio) ratio -= i rgb = [] for ch_i in range(3): r = (1 - ratio) * colors[i][ch_i] + ratio * colors[j][ch_i] rgb.append(math.ceil(r * 255)) colorset.append(tuple(rgb[::-1])) return tuple(colorset) def draw_bb(bgr_nparr, infres, class_colors, labels): """Draw bounding boxes on an image. Args: bgr_nparr: image data in numpy array format infres: Darkflow inference results class_colors: Bounding box color candidates, list of RGB tuples. Returens: Generalized result whose image data is drew w/ bounding boxes. """ for res in infres['annotations']: left = int(res['left']) top = int(res['top']) right = int(res['right']) bottom = int(res['bottom']) label = res['label'] color = class_colors[labels.index(label)] confidence = res['confidence'] imgHeight, imgWidth, _ = bgr_nparr.shape thick = int((imgHeight + imgWidth) // 300) cv2.rectangle(bgr_nparr,(left, top), (right, bottom), color, thick) cv2.putText(bgr_nparr, label, (left, top - 12), 0, 1e-3 * imgHeight, color, thick//3) #cv2.imwrite('prediction.jpg', bgr_nparr) infres['bytes'] = payload.stringify_jpg( cv2.imencode('.jpg', bgr_nparr)[1]) return infres def draw_box(image, annotations): """Draw information of annotations onto image. Args: image: Image nparray. annotations: List of detected object information. Returns: Image nparray containing object information on it. """ print('draw_box, annotations: {}'.format(annotations)) img = image.copy() for anno in annotations: # draw bounding box box_color = (0, 0, 255) box_thickness = 1 cv2.rectangle(img, (anno['left'], anno['top']), (anno['right'], anno['bottom']), box_color, box_thickness) # draw label label_background_color = box_color label_text_color = (255, 255, 255) if 'track_id' in anno.keys(): label = 'ID:{} {}'.format(anno['track_id'], anno['label']) else: label = anno['label'] label_text = '{} ({} %)'.format(label, int(anno['confidence'] * 100)) label_size = cv2.getTextSize(label_text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)[0] label_left = anno['left'] label_top = anno['top'] - label_size[1] if (label_top < 1): label_top = 1 label_right = label_left + label_size[0] label_bottom = label_top + label_size[1] cv2.rectangle(img, (label_left - 1, label_top - 1), (label_right + 1, label_bottom + 1), label_background_color, -1) cv2.putText(img, label_text, (label_left, label_bottom), cv2.FONT_HERSHEY_SIMPLEX, 0.5, label_text_color, 1) return img def overlay_on_image(display_image, object_info): """Modulized version of overlay_on_image function """ if isinstance(object_info, type(None)): print('WARNING: object info is None') return display_image return draw_box(display_image, object_info) def draw_label(bgr_nparr, infres, class_color, save_image_path=None): """Draw bounding boxes on an image. Args: bgr_nparr: image data in numpy array format infres: Inference results followed generic format specification. class_color: Label color, a RGB tuple. Returens: Generalized result whose image data is drew w/ labels. """ left = 0 top = 0 for res in infres['annotations']: imgHeight, imgWidth, _ = bgr_nparr.shape thick = int((imgHeight + imgWidth) // 300) # putText can not handle newline char yet, # so we have to put multiple texts manually. cv2.putText(bgr_nparr, '{0}: {1}'.format(res['label'], res['confidence']), (left + 10, top + 20), # bottom-left corner of text 0, # fontFace 1e-3 * imgHeight, # fontScale class_color, thick // 3) top += 20 infres['bytes'] = payload.stringify_jpg( cv2.imencode('.jpg', bgr_nparr)[1]) if save_image_path: cv2.imwrite(save_image_path, bgr_nparr) return infres BerryNet-upstream-3.9.0/broker.js000066400000000000000000000027041360632137300167440ustar00rootroot00000000000000// Copyright 2017 DT42 // // This file is part of BerryNet. // // BerryNet is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // BerryNet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BerryNet. If not, see . 'use strict'; const mosca = require('mosca'); // ascoltatore: https://github.com/mcollina/ascoltatori const ascoltatore = { type: 'mongo', url: 'mongodb://localhost:27017/mqtt', pubsubCollection: 'ascoltatori', mongo: {} }; const settings = { port: 1883, backend: ascoltatore, http: { port: 3000, bundle: true, static: './' } }; const server = new mosca.Server(settings); server.on('clientConnected', (client) => { console.log('client connected', client.id); }); // fired when a message is received server.on('published', (packet, client) => { console.log('Server published. Avoid showing package content here.'); }); // fired when the mqtt server is ready server.on('ready', () => { console.log('Mosca server is up and running'); }); BerryNet-upstream-3.9.0/camera.js000066400000000000000000000126201360632137300167060ustar00rootroot00000000000000// Copyright 2017 DT42 // // This file is part of BerryNet. // // BerryNet is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // BerryNet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BerryNet. If not, see . 'use strict'; const fs = require('fs'); const mqtt = require('mqtt'); const request = require('request'); const spawnsync = require('child_process').spawnSync; const config = require('./config'); const cv = require('opencv'); const broker = config.brokerHost; const client = mqtt.connect(broker); const topicActionLog = config.topicActionLog; const topicActionInference = config.topicActionInference; const topicEventCamera = config.topicEventCamera; const cameraURI = config.ipcameraSnapshot; const snapshotFile = '/tmp/snapshot.jpg'; const snapshotWidth = config.boardcameraImageWidth; const snapshotHeight = config.boardcameraImageHeight; const cameraCmd = '/usr/bin/raspistill'; const cameraArgs = ['-vf', '-hf', '-w', snapshotWidth, '-h', snapshotHeight, '-o', snapshotFile]; const usbCameraCmd = '/usr/bin/fswebcam'; const usbCameraArgs = ['-r', snapshotWidth + 'x' + snapshotHeight, '--no-banner', '-D', '0.5', snapshotFile]; const fps = 30; var cameraIntervalID = null; var cameraInterval = 1000.0 / fps; var cameraCV = null; var frameCounter = 0; function log(m) { client.publish(topicActionLog, m); console.log(m); } client.on('connect', () => { client.subscribe(topicEventCamera); log(`camera client: connected to ${broker} successfully.`); }); client.on('message', (t, m) => { log(`camera client: on topic ${t}, received message ${m}.`); const action = m.toString(); if (action == 'snapshot_picam') { /* NOTE: We use V4L2 to support RPi camera, so RPi camera's usage is * the same as USB camera. Both RPi and USB cameras are called * "board camera". * * This action is obsoleted and will be removed in the future. */ // Take a snapshot from RPi3 camera. The snapshot will be displayed // on dashboard. spawnsync(cameraCmd, cameraArgs); fs.readFile(snapshotFile, function(err, data) { if (err) { log('camera client: cannot get image.'); } else { log('camera client: publishing image.'); client.publish(topicActionInference, data); } }); } else if (action == 'snapshot_ipcam') { // Take a snapshot from IP camera. The snapshot will be sent to // configured email address. request.get( {uri: cameraURI, encoding: null}, (e, res, body) => { if (!e && res.statusCode == 200) { log('camera client: publishing image.'); client.publish(topicActionInference, body); } else { log('camera client: cannot get image.'); } } ); } else if (action == 'snapshot_boardcam') { // Take a snapshot from USB camera. spawnsync(usbCameraCmd, usbCameraArgs); fs.readFile(snapshotFile, function(err, data) { if (err) { log('camera client: cannot get image.'); } else { log('camera client: publishing image.'); client.publish(topicActionInference, data); } }); } else if (action == 'stream_boardcam_start') { if ((!cameraCV) && (!cameraIntervalID)) { cameraCV = new cv.VideoCapture(0); cameraCV.setWidth(snapshotWidth); cameraCV.setHeight(snapshotHeight); cameraIntervalID = setInterval(function() { cameraCV.read(function(err, im) { if (err) { throw err; } if (frameCounter < fps * 2) { frameCounter++; } else { frameCounter = 0; im.save(snapshotFile); fs.readFile(snapshotFile, function(err, data) { if (err) { log('camera client: cannot get image.'); } else { log('camera client: publishing image.'); client.publish(topicActionInference, data); } }); } im.release(); }); }, cameraInterval); } } else if (action == 'stream_boardcam_stop') { if (cameraCV) { cameraCV.release(); cameraCV = null; } if (cameraIntervalID) { clearInterval(cameraIntervalID); cameraIntervalID = null; } } else if (action == 'stream_nest_ipcam_start') { if (!cameraIntervalID) { cameraIntervalID = setInterval(function() { request.get( {uri: cameraURI, encoding: null}, (e, res, body) => { if (!e && res.statusCode == 200) { log('camera client: publishing image.'); client.publish(topicActionInference, body); } else { log('camera client: cannot get image.'); } } ); }, cameraInterval); } } else if (action == 'stream_nest_ipcam_stop') { if (cameraIntervalID) { clearInterval(cameraIntervalID); cameraIntervalID = null; } } else { log('camera client: unkown action.'); } }); BerryNet-upstream-3.9.0/client.js000066400000000000000000000005771360632137300167440ustar00rootroot00000000000000var mqtt = require('mqtt'); //var client = mqtt.connect('mqtt://test.mosquitto.org'); var client = mqtt.connect('mqtt://localhost:1883'); client.on('connect', function () { client.subscribe('presence'); client.publish('presence', 'Hello mqtt'); }); client.on('message', function (topic, message) { // message is Buffer console.log(message.toString()); client.end(); }); BerryNet-upstream-3.9.0/config.js000066400000000000000000000047011360632137300167240ustar00rootroot00000000000000// Copyright 2017 DT42 // // This file is part of BerryNet. // // BerryNet is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // BerryNet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BerryNet. If not, see . 'use strict'; const path = require('path'); let config = {}; // system configs config.projectDir = __dirname; config.inferenceEngine = 'detector'; // {classifier, detector} // gateway configs function padTopicBase(topic) { return path.join(config.topicBase, topic); } config.snapshot = path.join( config.projectDir, 'dashboard/www/freeboard/snapshot.jpg'); config.brokerHost = 'mqtt://localhost'; config.topicBase = 'berrynet'; config.topicActionLog = padTopicBase('action/log'); config.topicActionInference = padTopicBase('action/inference'); config.topicEventCamera = padTopicBase('event/camera'); config.topicEventLocalImage = padTopicBase('event/localImage'); config.topicNotifyEmail = padTopicBase('notify/email'); config.topicNotifySMS = padTopicBase('notify/sms'); config.topicNotifyLINE = padTopicBase('notify/line'); config.topicDashboardLog = padTopicBase('dashboard/log'); config.topicDashboardSnapshot = padTopicBase('dashboard/snapshot'); config.topicDashboardInferenceResult = padTopicBase('dashboard/inferenceResult'); config.topicJSONInferenceResult = padTopicBase('data/jsonInferenceResult'); // IP camera config.ipcameraSnapshot = ''; // Board camera, e.g. USB and RPi cameras config.boardcameraImageWidth = 640; config.boardcameraImageHeight = 480; // data collector configs config.storageDirPath = ''; // email notification config.senderEmail = ''; config.senderPassword = ''; config.receiverEmail = ''; // for compatibility config.sender_email = config.senderEmail; config.sender_password = config.senderPassword; config.receiver_email = config.receiverEmail; // Authentication and channel information for LINE config.LINETargetUserID = ''; config.LINEChannelSecret = ''; config.LINEChannelAccessToken = ''; // make config importable module.exports = config; BerryNet-upstream-3.9.0/config/000077500000000000000000000000001360632137300163645ustar00rootroot00000000000000BerryNet-upstream-3.9.0/config/bcm2835-v4l2.conf000066400000000000000000000001121360632137300210750ustar00rootroot00000000000000# BerryNet supports accessing RPi camera access via OpenCV. bcm2835_v4l2 BerryNet-upstream-3.9.0/config/berrynet-bionic.list000066400000000000000000000002261360632137300223540ustar00rootroot00000000000000# For details, please refer to https://github.com/DT42/BerryNet-repo deb http://repo.berrynet.org/ bionic/ deb-src http://repo.berrynet.org/ bionic/ BerryNet-upstream-3.9.0/config/berrynet-buster.list000066400000000000000000000002261360632137300224150ustar00rootroot00000000000000# For details, please refer to https://github.com/DT42/BerryNet-repo deb http://repo.berrynet.org/ buster/ deb-src http://repo.berrynet.org/ buster/ BerryNet-upstream-3.9.0/config/berrynet-xenial.list000066400000000000000000000002261360632137300223710ustar00rootroot00000000000000# For details, please refer to https://github.com/DT42/BerryNet-repo deb http://repo.berrynet.org/ xenial/ deb-src http://repo.berrynet.org/ xenial/ BerryNet-upstream-3.9.0/config/berrynet.list000066400000000000000000000002301360632137300211060ustar00rootroot00000000000000# For details, please refer to https://github.com/DT42/BerryNet-repo deb http://repo.berrynet.org/ stretch/ deb-src http://repo.berrynet.org/ stretch/ BerryNet-upstream-3.9.0/config/dashboard-darknet-official.json000066400000000000000000000025441360632137300244130ustar00rootroot00000000000000{ "version": 1, "allow_edit": true, "plugins": [], "panes": [ { "title": "Camera Snapshot", "width": 1, "row": { "2": 1, "3": 1, "4": 1 }, "col": { "2": 2, "3": 1, "4": 3 }, "col_width": 1, "widgets": [ { "type": "html", "settings": { "html": "imgstr = datasources[\"Detection Result\"][\"msg\"][\"bytes\"]\ns = \"\"\nreturn s", "height": 4 } } ] }, { "title": "Inference Result", "width": 1, "row": { "2": 1, "3": 1 }, "col": { "2": 1, "3": 2 }, "col_width": 1, "widgets": [ { "type": "html", "settings": { "html": "s = datasources[\"Detection Result\"][\"msg\"][\"annotations\"].map(function(r) {\n return (r[\"label\"] + \": \" + r[\"confidence\"] + \"
\")\n}).join().replace(/,/g, \"\")\nconsole.log(s)\nreturn s\n", "height": 4 } } ] } ], "datasources": [ { "name": "Detection Result", "type": "paho_mqtt", "settings": { "server": "localhost", "port": 3000, "use_ssl": false, "client_id": "freeboard_darknetres", "username": "", "password": "", "topic": "berrynet/engine/darknet/result", "json_data": true, "name": "Detection Result" } } ], "columns": 3 }BerryNet-upstream-3.9.0/config/dashboard-darknet.json000066400000000000000000000025771360632137300226470ustar00rootroot00000000000000{ "version": 1, "allow_edit": true, "plugins": [], "panes": [ { "title": "Camera Snapshot", "width": 1, "row": { "2": 1, "3": 1, "4": 1 }, "col": { "2": 2, "3": 1, "4": 3 }, "col_width": "1", "widgets": [ { "type": "html", "settings": { "html": "imgstr = datasources[\"Detection Result\"][\"msg\"][\"bytes\"]\ns = \"\"\nreturn s\n\n", "height": 4 } } ] }, { "title": "Inference Result", "width": 1, "row": { "2": 1, "3": 1 }, "col": { "2": 1, "3": 2 }, "col_width": 1, "widgets": [ { "type": "html", "settings": { "html": "s = datasources[\"Detection Result\"][\"msg\"][\"annotations\"].map(function(r) { \n return (r[\"label\"] + \": \" + r[\"confidence\"] + \"
\")\n}).join().replace(/,/g, \"\")\nconsole.log(s)\nreturn s", "height": 4 } } ] } ], "datasources": [ { "name": "Detection Result", "type": "paho_mqtt", "settings": { "server": "localhost", "port": 3000, "use_ssl": false, "client_id": "freeboard_darknetres", "topic": "berrynet/engine/darknet/result", "json_data": true, "username": "", "password": "", "name": "Detection Result" } } ], "columns": 3 } BerryNet-upstream-3.9.0/config/dashboard-movidius.json000066400000000000000000000025301360632137300230430ustar00rootroot00000000000000{ "version": 1, "allow_edit": true, "plugins": [], "panes": [ { "title": "Camera Snapshot", "width": 1, "row": { "2": 1, "3": 1, "4": 1 }, "col": { "2": 2, "3": 1, "4": 3 }, "col_width": "1", "widgets": [ { "type": "html", "settings": { "html": "imgstr = datasources[\"Detection Result\"][\"berrynet/engine/mvmobilenetssd/result\"][\"bytes\"]\ns = \"\"\nreturn s\n\n", "height": 4 } } ] }, { "title": "Inference Result", "width": 1, "row": { "2": 1, "3": 1 }, "col": { "2": 1, "3": 2 }, "col_width": 1, "widgets": [ { "type": "html", "settings": { "html": "s = datasources[\"Detection Result\"][\"berrynet/engine/mvmobilenetssd/result\"][\"annotations\"].map(function(r) { \n return (r[\"label\"] + \": \" + r[\"confidence\"] + \"
\")\n}).join().replace(/,/g, \"\")\nconsole.log(s)\nreturn s", "height": 4 } } ] } ], "datasources": [ { "name": "Detection Result", "type": "paho_mqtt_js", "settings": { "server": "localhost", "port": 3000, "client_id": "freeboard_darknetres", "topics": "berrynet/engine/mvmobilenetssd/result" } } ], "columns": 3 }BerryNet-upstream-3.9.0/config/dashboard-mqtt.json000066400000000000000000000051661360632137300222010ustar00rootroot00000000000000{ "version": 1, "allow_edit": true, "plugins": [], "panes": [ { "title": "Camera Snapshot", "width": 1, "row": { "2": 1, "3": 1, "4": 1 }, "col": { "2": 2, "3": 1, "4": 3 }, "col_width": "1", "widgets": [ { "type": "picture", "settings": { "src": "Your browser does not support the HTML5 canvas tag.\n\n\n", "refresh": 30 } } ] }, { "title": "Inference Result", "width": 1, "row": { "2": 1, "3": 1 }, "col": { "2": 1, "3": 2 }, "col_width": 1, "widgets": [ { "type": "html", "settings": { "html": "datasources[\"Inference Result\"][\"berrynet/dashboard/inferenceResult\"]", "height": 4 } } ] }, { "title": "MQTT Client Logs", "width": 1, "row": { "2": 11, "3": 11 }, "col": { "2": 1, "3": 1 }, "col_width": "2", "widgets": [ { "type": "html", "settings": { "html": "datasources[\"MQTT Client Logs\"][\"berrynet/dashboard/log\"]", "height": 4 } } ] } ], "datasources": [ { "name": "Inference Result", "type": "paho_mqtt_js", "settings": { "server": "localhost", "port": 3000, "client_id": "freeboard_ifresult", "topics": "berrynet/dashboard/inferenceResult", "name": "Inference Result" } }, { "name": "MQTT Client Logs", "type": "paho_mqtt_js", "settings": { "server": "localhost", "port": 3000, "client_id": "freeboard_aaaaalog", "topics": "berrynet/dashboard/log", "name": "MQTT Client Logs" } } ], "columns": 3 }BerryNet-upstream-3.9.0/config/dashboard-ovclassifier.json000066400000000000000000000026101360632137300236740ustar00rootroot00000000000000{ "version": 1, "allow_edit": true, "plugins": [], "panes": [ { "title": "Camera Snapshot", "width": 1, "row": { "2": 1, "3": 1, "4": 1 }, "col": { "2": 2, "3": 1, "4": 3 }, "col_width": "1", "widgets": [ { "type": "html", "settings": { "html": "imgstr = datasources[\"Classifier Result\"][\"msg\"][\"bytes\"]\ns = \"\"\nreturn s\n\n", "height": 4 } } ] }, { "title": "Inference Result", "width": 1, "row": { "2": 1, "3": 1 }, "col": { "2": 1, "3": 2 }, "col_width": 1, "widgets": [ { "type": "html", "settings": { "html": "s = datasources[\"Classifier Result\"][\"msg\"][\"annotations\"].map(function(r) { \n return (r[\"label\"] + \": \" + r[\"confidence\"] + \"
\")\n}).join().replace(/,/g, \"\")\nconsole.log(s)\nreturn s", "height": 4 } } ] } ], "datasources": [ { "name": "Classifier Result", "type": "paho_mqtt", "settings": { "server": "localhost", "port": 3000, "use_ssl": false, "client_id": "freeboard_darknetres", "topic": "berrynet/engine/ovclassifier/result", "json_data": true, "username": "", "password": "", "name": "Classifier Result" } } ], "columns": 3 } BerryNet-upstream-3.9.0/config/dashboard-ovdetector.json000066400000000000000000000025761360632137300233740ustar00rootroot00000000000000{ "version": 1, "allow_edit": true, "plugins": [], "panes": [ { "title": "Camera Snapshot", "width": 1, "row": { "2": 1, "3": 1, "4": 1 }, "col": { "2": 2, "3": 1, "4": 3 }, "col_width": "1", "widgets": [ { "type": "html", "settings": { "html": "imgstr = datasources[\"Detector Result\"][\"msg\"][\"bytes\"]\ns = \"\"\nreturn s\n\n", "height": 4 } } ] }, { "title": "Inference Result", "width": 1, "row": { "2": 1, "3": 1 }, "col": { "2": 1, "3": 2 }, "col_width": 1, "widgets": [ { "type": "html", "settings": { "html": "s = datasources[\"Detector Result\"][\"msg\"][\"annotations\"].map(function(r) { \n return (r[\"label\"] + \": \" + r[\"confidence\"] + \"
\")\n}).join().replace(/,/g, \"\")\nconsole.log(s)\nreturn s", "height": 4 } } ] } ], "datasources": [ { "name": "Detector Result", "type": "paho_mqtt", "settings": { "server": "localhost", "port": 3000, "use_ssl": false, "client_id": "freeboard_darknetres", "topic": "berrynet/engine/ovdetector/result", "json_data": true, "username": "", "password": "", "name": "Detector Result" } } ], "columns": 3 } BerryNet-upstream-3.9.0/config/dashboard-tflitedetector.json000066400000000000000000000026061360632137300242310ustar00rootroot00000000000000{ "version": 1, "allow_edit": true, "plugins": [], "panes": [ { "title": "Camera Snapshot", "width": 1, "row": { "2": 1, "3": 1, "4": 1 }, "col": { "2": 2, "3": 1, "4": 3 }, "col_width": "1", "widgets": [ { "type": "html", "settings": { "html": "imgstr = datasources[\"Detection Result\"][\"msg\"][\"bytes\"]\ns = \"\"\nreturn s\n\n", "height": 4 } } ] }, { "title": "Inference Result", "width": 1, "row": { "2": 1, "3": 1 }, "col": { "2": 1, "3": 2 }, "col_width": 1, "widgets": [ { "type": "html", "settings": { "html": "s = datasources[\"Detection Result\"][\"msg\"][\"annotations\"].map(function(r) { \n return (r[\"label\"] + \": \" + r[\"confidence\"] + \"
\")\n}).join().replace(/,/g, \"\")\nconsole.log(s)\nreturn s", "height": 4 } } ] } ], "datasources": [ { "name": "Detection Result", "type": "paho_mqtt", "settings": { "server": "localhost", "port": 3000, "use_ssl": false, "client_id": "freeboard_darknetres", "topic": "berrynet/engine/tflitedetector/result", "json_data": true, "username": "", "password": "", "name": "Detection Result" } } ], "columns": 3 } BerryNet-upstream-3.9.0/config/dashboard.json000066400000000000000000000034471360632137300212160ustar00rootroot00000000000000{ "version": 1, "allow_edit": true, "plugins": [], "panes": [ { "title": "Camera Snapshot", "width": 1, "row": { "3": 1, "4": 1 }, "col": { "3": 1, "4": 3 }, "col_width": "1", "widgets": [ { "type": "picture", "settings": { "src": "datasources[\"Camera Snapshot\"][\"berrynet/dashboard/snapshot\"]", "refresh": 30 } } ] }, { "title": "Inference Result", "width": 1, "row": { "3": 1 }, "col": { "3": 2 }, "col_width": 1, "widgets": [ { "type": "html", "settings": { "html": "datasources[\"Inference Result\"][\"berrynet/dashboard/inferenceResult\"]", "height": 4 } } ] }, { "title": "MQTT Client Logs", "width": 1, "row": { "3": 11 }, "col": { "3": 1 }, "col_width": "2", "widgets": [ { "type": "html", "settings": { "html": "datasources[\"MQTT Client Logs\"][\"berrynet/dashboard/log\"]", "height": 4 } } ] } ], "datasources": [ { "name": "Camera Snapshot", "type": "paho_mqtt_js", "settings": { "server": "localhost", "port": 3000, "client_id": "freeboard_snapshot", "topics": "berrynet/dashboard/snapshot", "name": "Camera Snapshot" } }, { "name": "Inference Result", "type": "paho_mqtt_js", "settings": { "server": "localhost", "port": 3000, "client_id": "freeboard_ifresult", "topics": "berrynet/dashboard/inferenceResult", "name": "Inference Result" } }, { "name": "MQTT Client Logs", "type": "paho_mqtt_js", "settings": { "server": "localhost", "port": 3000, "client_id": "freeboard_aaaaalog", "topics": "berrynet/dashboard/log", "name": "MQTT Client Logs" } } ], "columns": 3 } BerryNet-upstream-3.9.0/config/etc/000077500000000000000000000000001360632137300171375ustar00rootroot00000000000000BerryNet-upstream-3.9.0/config/etc/mosquitto/000077500000000000000000000000001360632137300212035ustar00rootroot00000000000000BerryNet-upstream-3.9.0/config/etc/mosquitto/conf.d/000077500000000000000000000000001360632137300223525ustar00rootroot00000000000000BerryNet-upstream-3.9.0/config/etc/mosquitto/conf.d/berrynet.conf000066400000000000000000000001671360632137300250570ustar00rootroot00000000000000# Listen on port 1883 and websockets # default listener port 1883 # extra listener listener 3000 protocol websockets BerryNet-upstream-3.9.0/config/intel-openvino-2019.list000066400000000000000000000000701360632137300226150ustar00rootroot00000000000000deb https://apt.repos.intel.com/openvino/2019/ all main BerryNet-upstream-3.9.0/config/supervisor/000077500000000000000000000000001360632137300206055ustar00rootroot00000000000000BerryNet-upstream-3.9.0/config/supervisor/conf.d/000077500000000000000000000000001360632137300217545ustar00rootroot00000000000000BerryNet-upstream-3.9.0/config/supervisor/conf.d/berrynet-darknet.conf000066400000000000000000000012131360632137300261000ustar00rootroot00000000000000[program:darknet-service] command=python3 /usr/lib/python3/dist-packages/berrynet/service/darknet_service.py --model_package tinyyolovoc --service_name detector --draw --debug stdout_logfile=/var/log/berrynet/darknet-service-stdout.log stdout_logfile_maxbytes=1048576 stderr_logfile=/var/log/berrynet/darknet-service-stderr.log stderr_logfile_maxbytes=1048576 priority=10 [program:camera] command=python3 /usr/lib/python3/dist-packages/berrynet/client/camera.py --fps 0.5 stdout_logfile=/var/log/berrynet/camera-stdout.log stdout_logfile_maxbytes=1048576 stderr_logfile=/var/log/berrynet/camera-stderr.log stderr_logfile_maxbytes=1048576 priority=30 BerryNet-upstream-3.9.0/config/supervisor/conf.d/berrynet-movidius.conf000066400000000000000000000017231360632137300263150ustar00rootroot00000000000000[program:movidius-service] command=su -c "python3 /home/pi/codes/BerryNet/berrynet/service/movidius_service.py --service_name MobileNetSSD --model_package mobilenet-ssd-movidius-1.0.0 --debug" pi stdout_logfile=/var/log/berrynet/movidius-service-stdout.log stdout_logfile_maxbytes=1048576 stderr_logfile=/var/log/berrynet/movidius-service-stderr.log stderr_logfile_maxbytes=1048576 priority=10 [program:fbdashboard] command=su -c "DISPLAY=:0 python3 /home/pi/codes/BerryNet/berrynet/client/fbdashboard.py" pi stdout_logfile=/var/log/berrynet/fbdashboard-stdout.log stdout_logfile_maxbytes=1048576 stderr_logfile=/var/log/berrynet/fbdashboard-stderr.log stderr_logfile_maxbytes=1048576 priority=30 [program:camera] command=su -c "python3 /home/pi/codes/BerryNet/berrynet/client/camera.py --fps 7" pi stdout_logfile=/var/log/berrynet/camera-stdout.log stdout_logfile_maxbytes=1048576 stderr_logfile=/var/log/berrynet/camera-stderr.log stderr_logfile_maxbytes=1048576 priority=40 BerryNet-upstream-3.9.0/config/supervisor/conf.d/berrynet-tflite.conf000066400000000000000000000011131360632137300257360ustar00rootroot00000000000000[program:tflite-service] command=bn_tflite --service detector --service_name tflitedetector --model_package mobilenet-ssd-coco-tflite-2.0.0 --num_threads 4 --draw --debug stdout_logfile=/var/log/berrynet/tflite-service-stdout.log stdout_logfile_maxbytes=1048576 stderr_logfile=/var/log/berrynet/tflite-service-stderr.log stderr_logfile_maxbytes=1048576 priority=10 [program:camera] command=bn_camera --fps 6 stdout_logfile=/var/log/berrynet/camera-stdout.log stdout_logfile_maxbytes=1048576 stderr_logfile=/var/log/berrynet/camera-stderr.log stderr_logfile_maxbytes=1048576 priority=30 BerryNet-upstream-3.9.0/configure000077500000000000000000000253301360632137300170310ustar00rootroot00000000000000#!/bin/bash # # Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . # One-click IoT gateway deployment script. set -e LOG="$PWD/berrynet-install.log" DISTRIBUTIONID=`lsb_release -i -s` CODENAME=`lsb_release -c -s` INSTALL_TENSORFLOW="Y" INSTALL_OPENVINO="N" INSTALL_DARKNET="N" INSTALL_CAFFE2="N" install_opencv() { # OpenCV sources # x86 Ubuntu 16.04: PPA # Raspbian: BerryNet repo if [ "$DISTRIBUTIONID" = "Ubuntu" ]; then sudo add-apt-repository -yu ppa:timsc/opencv-3.4 fi sudo apt install -y python3-opencv } install_nodejs() { # v10.x is LTS, if you want the latest feature, change to "setup_11.x". curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash - sudo apt install -y nodejs } install_system_dependencies() { sudo apt update if [ "$CODENAME" = "buster" ]; then sudo apt install -y \ supervisor else sudo apt install -y \ apache2 \ curl \ dirmngr \ fswebcam \ git \ imagemagick \ libkrb5-dev \ libyaml-dev \ libzmq3-dev \ lsb-release \ mosquitto \ mosquitto-clients \ python3-dev \ python3-opengl \ python3-pip \ supervisor \ wget sudo -H pip3 install --timeout 60 cython sudo -H pip3 install --timeout 60 logzero sudo -H pip3 install --timeout 60 paho-mqtt sudo -H pip3 install --timeout 60 PyOpenGL sudo -H pip3 install --timeout 60 PyOpenGL-accelerate sudo -H pip3 install --timeout 60 watchdog install_opencv install_nodejs fi } install_berrynet_repository() { curl -sL https://raw.githubusercontent.com/DT42/BerryNet-repo/master/setup.sh | sudo -E bash - } install_configs() { # supervisor sudo cp config/supervisor/conf.d/berrynet-tflite.conf /etc/supervisor/conf.d/ sudo mkdir -p /var/log/berrynet # mosquitto sudo cp config/etc/mosquitto/conf.d/berrynet.conf /etc/mosquitto/conf.d if [ "$DISTRIBUTIONID" = "Raspbian" ]; then # Make RPi camera to show at /dev/videoN sudo cp config/bcm2835-v4l2.conf /etc/modules-load.d fi } install_berrynet_py() { sudo apt install -y berrynet # FIXME: Freeboard dependency #sudo npm install -g mime } install_berrynet_js() { local working_dir="/usr/local/berrynet" sudo mkdir -p $working_dir sudo cp -a \ broker.js \ camera.js \ config.js \ data_collector.js \ inference \ journal.js \ localimg.js \ mail.js \ line.js \ package.json \ $working_dir sudo cp berrynet-manager /usr/local/bin # FIXME: image dir should be created by program mkdir -p /usr/local/berrynet/inference/image # install npm dependencies pushd $working_dir > /dev/null sudo npm install --unsafe-perm popd > /dev/null } install_model() { local model_name="$1" echo "Install model $model_name" sudo apt install -y $model_name } download_classifier_model_caffe2() { sh ./utils/install-caffe2-models.sh } install_tensorflow() { if [ "$DISTRIBUTIONID" = "Ubuntu" ]; then sudo -H pip3 install tensorflow elif [ "$DISTRIBUTIONID" = "Raspbian" ]; then case $CODENAME in "buster") # Unsatisfied dependencies in Buster, and wheels will be installed # python3-tensorboard none # python3-wrapt 1.10.11-1+b1 # python3-gast none # python3-tensorflow-estimator none # python3-astor 0.5-1 # python3-absl-py none # python3-google-pasta none # python3-setuptools 40.8.0-1 sudo apt install -y \ python3-numpy \ python3-termcolor \ python3-six \ python3-keras-applications \ python3-protobuf \ python3-keras-preprocessing \ python3-wheel \ python3-grpcio \ python3-werkzeug \ python3-markdown \ python3-h5py TENSORFLOW_PKGNAME="tensorflow-1.15.0-cp37-cp37m-linux_armv7l.whl" if [ ! -e "/tmp/$TENSORFLOW_PKGNAME" ]; then wget -O /tmp/$TENSORFLOW_PKGNAME \ https://github.com/PINTO0309/Tensorflow-bin/raw/master/$TENSORFLOW_PKGNAME else echo "$TENSORFLOW_PKGNAME has existed, skip to download it." fi sudo -H pip3 install /tmp/$TENSORFLOW_PKGNAME ;; "stretch") TENSORFLOW_PKGNAME="tensorflow-1.15.0-cp35-cp35m-linux_armv7l.whl" if [ ! -e "/tmp/$TENSORFLOW_PKGNAME" ]; then wget -O /tmp/$TENSORFLOW_PKGNAME \ https://github.com/PINTO0309/Tensorflow-bin/raw/master/$TENSORFLOW_PKGNAME else echo "$TENSORFLOW_PKGNAME has existed, skip to download it." fi sudo -H pip3 install /tmp/$TENSORFLOW_PKGNAME ;; *) echo "ERROR: Fail to install TensorFlow, unknown Raspbian codename $CODENAME" exit 1 esac fi } install_openvino_repository() { echo 'Adding the OpenVINO GPG key to your keyring...' curl -sL https://apt.repos.intel.com/openvino/2019/GPG-PUB-KEY-INTEL-OPENVINO-2019 | sudo apt-key add - sudo curl -sL -o /etc/apt/sources.list.d/intel-openvino-2019.list \ https://raw.githubusercontent.com/DT42/BerryNet/master/config/intel-openvino-2019.list sudo apt update } install_openvino() { # OpenVINO 2019R2.1 if [ "$DISTRIBUTIONID" = "Ubuntu" ]; then if [ "$CODENAME" = "xenial" ]; then sudo apt install intel-openvino-runtime-ubuntu16-2019.2.242 elif [ "$CODENAMe" = "bionic" ]; then sudo apt install intel-openvino-runtime-ubuntu18-2019.2.242 else echo "ERROR: OpenVINO on Ubuntu $CODENAME is not supported by Intel." fi elif [ "$DISTRIBUTIONID" = "Raspbian" ]; then sudo apt install -y openvino-rpi fi } install_darknet () { # For x86, we use pure Darknet. # For Raspberry Pi, we use pure Darknet + NNPACK. # # To understand how Darknet NNPACK packages are built, please refer to # https://github.com/DT42/BerryNet/blob/master/doc/darknet-nnpack.md sudo apt install -y darknet libdarknet } #install_darknet() { # local peachpy_version="0.0.1" # local confu_version="cc90068" # local ninja_version="v1.8.2" # local nnpack_darknet_version="1ecda10" # local darknet_nnpack_version="fa5bddc" # # # build dependencies # pip3 install --user PeachPy==$peachpy_version # pip3 install --user git+https://github.com/Maratyszcza/confu@$confu_version # # pushd /tmp > /dev/null # git clone https://github.com/ninja-build/ninja.git # pushd ninja > /dev/null # git reset --hard $ninja_version # ./configure.py --bootstrap # popd > /dev/null # popd > /dev/null # # sudo apt install -y clang # # pushd /tmp > /dev/null # git clone https://github.com/thomaspark-pkj/NNPACK-darknet.git # pushd NNPACK-darknet > /dev/null # git reset --hard $nnpack_darknet_version # $HOME/.local/bin/confu setup # python ./configure.py --backend auto # /tmp/ninja/ninja # sudo cp lib/{libgoogletest-core.a,libnnpack.a,libpthreadpool.a} /usr/lib/ # sudo cp include/nnpack.h /usr/include/ # sudo cp deps/pthreadpool/include/pthreadpool.h /usr/include/ # popd > /dev/null # popd > /dev/null # # # build detection backend (darknet) # pushd inference > /dev/null # git clone https://github.com/thomaspark-pkj/darknet-nnpack.git darknet # pushd darknet > /dev/null # git reset --hard $darknet_nnpack_version # patch -p 1 < ../../patch/01-detection-backend.patch # make -j # popd > /dev/null # popd > /dev/null # # cp utils/darknet/detectord.py inference/darknet # mkdir inference/darknet/utils # cp utils/darknet/utils/localrun.sh inference/darknet/utils #} install_caffe2() { if [ "$DISTRIBUTIONID" = "Ubuntu" ]; then sh ./utils/install-caffe2-ubuntu.sh elif [ "$DISTRIBUTIONID" = "Raspbian" ]; then sh ./utils/install-caffe2-raspbian.sh fi } update_system_service() { sudo service mosquitto restart sudo supervisorctl reload sudo a2enconf berrynet-dashboard } install_system_dependencies 2>&1 | tee -a $LOG install_berrynet_repository 2>&1 | tee -a $LOG install_berrynet_py 2>&1 | tee -a $LOG install_configs 2>&1 | tee -a $LOG # FIXME: Raspbian 20190408 breaks some dependencies of BerryNet JS. # Disable temporaily before this issue is fixed. #install_berrynet_js 2>&1 | tee -a $LOG if [ "$INSTALL_TENSORFLOW" = "Y" ]; then install_tensorflow 2>&1 | tee -a $LOG #install_model inception install_model mobilenet-1.0-224-quantized-tflite 2>&1 | tee -a $LOG install_model mobilenet-ssd-coco-tflite 2>&1 | tee -a $LOG else echo "Not install TensorFlow" >> $LOG fi if [ "$INSTALL_OPENVINO" = "Y" ]; then install_openvino_repository 2>&1 | tee -a $LOG install_openvino 2>&1 | tee -a $LOG install_model mobilenet-1.0-224-fp16-openvino 2>&1 | tee -a $LOG install_model mobilenet-ssd-openvino 2>&1 | tee -a $LOG else echo "Not install OpenVINO" >> $LOG fi if [ "$INSTALL_DARKNET" = "Y" ]; then install_darknet 2>&1 | tee -a $LOG install_model tinyyolovoc 2>&1 | tee -a $LOG else echo "Not install Darknet NNPACK" >> $LOG fi if [ "$INSTALL_CAFFE2" = "Y" ]; then install_caffe2 2>&1 | tee -a $LOG download_classifier_model_caffe2 2>&1 | tee -a $LOG else echo "Not install Caffe2" >> $LOG fi update_system_service 2>&1 | tee -a $LOG { echo "Installation is completed successfully!" echo "" echo "If there is any issue, please open an issue on" echo "" echo " https://github.com/DT42/BerryNet/issues" echo "" echo "and attach these logs:" echo "" echo " $LOG" echo " /usr/local/berrynet/npm-debug.log" echo "" echo "We are happy to check and fix it, thank you!" } | tee -a $LOG BerryNet-upstream-3.9.0/data_collector.js000066400000000000000000000074651360632137300204500ustar00rootroot00000000000000// Copyright 2017 DT42 // // This file is part of BerryNet. // // BerryNet is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // BerryNet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BerryNet. If not, see . 'use strict'; const fs = require('fs'); const mqtt = require('mqtt'); const path = require('path'); const config = require('./config'); const broker = config.brokerHost; const client = mqtt.connect(broker); const topicActionLog = config.topicActionLog; const topicActionInference = config.topicActionInference; const topicDashboardSnapshot = config.topicDashboardSnapshot; const topicJSONInferenceResult = config.topicJSONInferenceResult; const storageDirPath = config.storageDirPath; /** * Log wrapper to publish log message via MQTT and display on console. * @param {string} m Log message. */ function log(m) { client.publish(topicActionLog, m); console.log(m); } /** * Save published MQTT binary data as an image file. * @param {object} b The binary data published via MQTT. * @param {string} filepath The file path of the saved image. */ function saveBufferToImage(b, filepath) { fs.writeFile(filepath, b, (e) => { if (e) log(`log client: cannot save buffer to image.`); else log(`log client: saved buffer to image successfully.`); }); } /** * Get time string in ISO format. * @return {string} Time string. */ function getTimeString() { const d = new Date(); return d.toISOString(); } /** * Save snapshot, detection image, and detection JSON to data directory. * @param {string} topic Subscribed MQTT topic. * @param {object} message Snapshot binary | 'snapshot.jpg' | detection JSON. */ function callbackSaveData(topic, message) { if (topic == topicActionInference) { console.log('Get ' + topicActionInference); // NOTE: topicActionInference always happens prior other topics. callbackSaveData.timeString = getTimeString(); console.log(callbackSaveData.timeString); const snapshotImage = path.join( storageDirPath, callbackSaveData.timeString + '.jpg'); saveBufferToImage(message, snapshotImage); } else if (topic == topicDashboardSnapshot) { console.log('Get ' + topicDashboardSnapshot); const detectionImage = path.join( storageDirPath, callbackSaveData.timeString + '-detection.jpg'); /* fs.readFile(config.snapshot, (err, data) => { fs.writeFile(detectionImage, data, (e) => { if (e) log('Failed to save detection image.'); }); }); */ fs.createReadStream(config.snapshot) .pipe(fs.createWriteStream(detectionImage)); } else if (topic == topicJSONInferenceResult) { console.log('Get ' + topicJSONInferenceResult); const detectionJSON = path.join( storageDirPath, callbackSaveData.timeString + '-detection.json'); fs.writeFile(detectionJSON, message, (e) => { if (e) log('Failed to save detection JSON.'); }); } else { console.log('Unsubscribed topic ' + topic); } } fs.mkdir(storageDirPath, (e) => { if (e) log('Failed to create data storage dir.'); }); client.on('connect', () => { client.subscribe(topicActionLog); client.subscribe(topicActionInference); client.subscribe(topicDashboardSnapshot); client.subscribe(topicJSONInferenceResult); log(`log client: connected to ${broker} successfully.`); }); client.on('message', callbackSaveData); BerryNet-upstream-3.9.0/doc/000077500000000000000000000000001360632137300156645ustar00rootroot00000000000000BerryNet-upstream-3.9.0/doc/STYLE_GUIDE.md000066400000000000000000000001211360632137300200150ustar00rootroot00000000000000[We follow the Node.js Style Guide](https://github.com/felixge/node-style-guide) BerryNet-upstream-3.9.0/doc/darknet-nnpack.md000066400000000000000000000041051360632137300211060ustar00rootroot00000000000000# Get darknet-nnpack and NNPack-darknet Sources * https://github.com/digitalbrain79/darknet-nnpack * https://github.com/digitalbrain79/NNPACK-darknet * When running ninja and make on RPi3, add `-j 3` parameter to prevent system from being blocked. # Link NNPack and pthreadpool libraries Because NNPACK-darknet only generates static libraries (.a). 1. Modify build.ninja and add -fPIC (and -shared?) to cflags, still only create .a. 1. But it's okay because the key is `-fPIC`. Compiler can combine static libraries and object files if static libraries contain PIC object files. 1. [Patch](https://github.com/DT42/darknet-nnpack/blob/debian/debian/patches/01-use-nnpack-rpi3.patch) darknet-nnpack source and Makefile. * I patched C code directly because the Darknet library users will have consistent API, and do not need to initialize NNPack and pthreadpool by themselves. * You can initialize NNPack and pthreadpool in Python ([example](https://github.com/NTUEE-ESLab/2017Fall-IntelligentSecurityGuard/blob/master/replace/darknet.py#L110) to initialize NNPack only). * Simpler than adding `-Wl,--whole-archive /usr/lib/libnnpack.a /usr/lib/libpthreadpool.a -Wl,--no-whole-archive` to darknet-nnpack Makefile in NNPACK section. References * Issue discussion * https://github.com/digitalbrain79/darknet-nnpack/issues/17 * https://github.com/Maratyszcza/NNPACK/issues/70 * Link .a to .so * https://stackoverflow.com/questions/2649735/how-to-link-static-library-into-dynamic-library-in-gcc * ftp://ftp.gnu.org/old-gnu/Manuals/ld-2.9.1/html_node/ld_3.html # Verification Run [darknet_npinput_rpi.py](https://github.com/DT42/darknet-numpy/blob/master/darknet_npinput_rpi.py) which loads libdarknet and model from system filepaths. # Further Optimization Sources * https://github.com/shizukachan/darknet-nnpack * https://github.com/shizukachan/NNPACK * Known issues: https://gitlab.com/bafu/nnpack-bin/issues/1 # Upstream NNPACK (drop) Steps 1. $ pip3 install --user --upgrade confu # update from v0.0.1 to v0.0.3, use pip3 instead of pip 1. $ sudo apt install clog BerryNet-upstream-3.9.0/doc/ipcam.md000066400000000000000000000017671360632137300173120ustar00rootroot00000000000000# Setup General Purpose IP Camera Steps to connect your IP camera to BerryNet: 1. Get snapshot URL of the IP camera. The [camera connection database](https://www.ispyconnect.com/sources.aspx) can generate snapshot URL if your IP camera is supported. The key is that the IP camera supports retrieving snapshots via HTTP. For example, my IP camera provides the interface to retrieve snapshot: ``` http:///cgi-bin/encoder?USER=&PWD=&Channel=1&SNAPSHOT ``` 1. Configure BerryNet 1. Edit `config.ipcameraSnapshot` in `/usr/local/berrynet/config.js`. 2. Restart BerryNet. # Get Nest Camera's Snapshot URL Follow the [quick start guide](https://codelabs.developers.google.com/codelabs/wwn-api-quickstart/#0) to get snapshot URL. The high-level steps are: 1. Create a "product" (the concept is like a project, we will use it for personal usage). 1. Get access token from Nest cloud service. 1. Get snapshot URL with the access token Nest cloud service. BerryNet-upstream-3.9.0/docker/000077500000000000000000000000001360632137300163665ustar00rootroot00000000000000BerryNet-upstream-3.9.0/docker/Dockerfile000066400000000000000000000011321360632137300203550ustar00rootroot00000000000000# We start from Debian Stretch. Can be rebase to Raspbian because they are # similar FROM debian:stretch LABEL maintainer="dev@dt42.io" LABEL project="Berrynet" LABEL version="3.5.1" # Update apt RUN apt-get update # Install dependencies RUN apt-get install -y git sudo wget lsb-release software-properties-common # Install build-essential RUN apt-get install -y build-essential # Install systemd RUN apt-get install -y systemd systemd-sysv # Install python RUN apt-get install -y python python3 # Install BerryNet RUN git clone https://github.com/DT42/BerryNet.git RUN cd BerryNet; ./configure BerryNet-upstream-3.9.0/examples/000077500000000000000000000000001360632137300167355ustar00rootroot00000000000000BerryNet-upstream-3.9.0/examples/run-darknet-detector.sh000066400000000000000000000044231360632137300233350ustar00rootroot00000000000000#!/bin/bash # # Copyright 2019 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . # Example: Run Darknet detector. set -e SCRIPT_NAME=$0 COMMAND=$1 usage() { echo -e "Usage:\n\t$ bash $SCRIPT_NAME start|stop" exit 1 } kill_script() { local script_name=$1 local ext=${script_name##*.} local interpreter="" if [ "$ext" == "py" ]; then interpreter="python3" elif [ "$ext" == "js" ]; then interpreter="nodejs" else interpreter="bash" fi local process_id=$(ps aux | grep $script_name | grep $interpreter | awk '{print $2}') echo "Terminate $script_name (pid $process_id)" kill -9 $process_id } example_start() { # Run Freeboard echo -n "Run Dashboard..." pushd /usr/lib/berrynet/dashboard > /dev/null nodejs server.js >> /tmp/berrynet-example.log & popd > /dev/null echo "done" # Run Darknet detector echo -n "Run Darknet detector..." sleep 1 python3 /usr/lib/python3/dist-packages/berrynet/service/darknet_service.py \ --service_name detector \ --model_package tinyyolovoc-20170816 \ --draw \ --debug >> /tmp/berrynet-example.log 2>&1 & echo "done" # Run camera client echo -n "Run Camera..." sleep 1 python3 /usr/lib/python3/dist-packages/berrynet/client/camera.py \ --fps 0.5 >> /tmp/berrynet-example.log 2>&1 & echo "done" } example_stop() { kill_script "camera.py" kill_script "darknet_service.py" kill_script "server.js" } main() { local cmd=$1 if [ "$cmd" == "start" ]; then example_start elif [ "$cmd" == "stop" ]; then example_stop else usage fi } main $COMMAND BerryNet-upstream-3.9.0/examples/run-openvino-classifier.sh000066400000000000000000000045621360632137300240610ustar00rootroot00000000000000#!/bin/bash # # Copyright 2019 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . # Example: Run OpenVINO classifier on general x86 notebook. # # For more details, please refer to Medium XXX. set -e SCRIPT_NAME=$0 COMMAND=$1 usage() { echo -e "Usage:\n\t$ bash $SCRIPT_NAME start|stop" exit 1 } kill_script() { local script_name=$1 local process_id=$(ps aux | grep $script_name | grep Sl | awk '{print $2}') echo "Terminate $script_name (pid $process_id)" kill -9 $process_id } example_start() { # Run Freeboard echo -n "Run Dashboard..." pushd /usr/lib/berrynet/dashboard > /dev/null nodejs server.js >> /tmp/berrynet-example.log & popd > /dev/null echo "done" # Run OpenVINO classifier echo -n "Run OpenVINO classifier..." MODELPKG_DIRPATH="/usr/share/dlmodels/mobilenet-1.0-224-openvino-1" source /opt/intel/computer_vision_sdk_2018.5.445/bin/setupvars.sh sleep 1 python3 /usr/lib/python3/dist-packages/berrynet/service/openvino_service.py \ --model $MODELPKG_DIRPATH/mobilenet_v1_1.0_224_frozen.xml \ --label $MODELPKG_DIRPATH/imagenet_slim_labels.txt \ --service_name ovclassifier \ --num_top_predictions 3 \ --debug >> /tmp/berrynet-example.log 2>&1 & echo "done" # Run camera client echo -n "Run Camera..." sleep 1 python3 /usr/lib/python3/dist-packages/berrynet/client/camera.py \ --fps 5 >> /tmp/berrynet-example.log 2>&1 & echo "done" } example_stop() { kill_script "camera.py" kill_script "openvino_service.py" kill_script "server.js" } main() { local cmd=$1 if [ "$cmd" == "start" ]; then example_start elif [ "$cmd" == "stop" ]; then example_stop else usage fi } main $COMMAND BerryNet-upstream-3.9.0/inference/000077500000000000000000000000001360632137300170555ustar00rootroot00000000000000BerryNet-upstream-3.9.0/inference/agent.js000066400000000000000000000131441360632137300205140ustar00rootroot00000000000000// Copyright 2017 DT42 // // This file is part of BerryNet. // // BerryNet is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // BerryNet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BerryNet. If not, see . 'use strict'; const fs = require('fs'); const path = require('path'); const moment = require('moment'); const mqtt = require('mqtt'); const im = require('imagemagick'); const config = require('../config'); const broker = config.brokerHost; const client = mqtt.connect(broker); const topicActionLog = config.topicActionLog; const topicActionInference = config.topicActionInference; const topicDashboardSnapshot = config.topicDashboardSnapshot; const topicDashboardInferenceResult = config.topicDashboardInferenceResult; const topicJSONInferenceResult = config.topicJSONInferenceResult; const topicNotifyLINE = config.topicNotifyLINE; const inferenceEngine = config.inferenceEngine; function log(m) { client.publish(topicActionLog, m); console.log(m); } function saveBufferToImage(b, filepath) { fs.writeFile(filepath, b, (e) => { if (e) log(`inference client: cannot save buffer to image.`); else log(`inference client: saved buffer to image ${filepath} successfully.`); }); } const parseDarknet = function(str) { const elements = str.split(' '); // label might consists of multiple words, e.g. cell phone. const label = elements.slice(0, elements.length - 5).join(' '); let [confidence, x, y, width, height] = elements.slice(elements.length - 5); let result = { label: label, confidence: parseFloat(confidence), top: parseInt(y), bottom: parseInt(y) + parseInt(height), left: parseInt(x), right: parseInt(x) + parseInt(width) }; return result } const darknetToJSON = function(data) { let dataStrList = data.toString().replace(/\n$/, '').split('\n'); let jsonResult = []; for (let i in dataStrList) { let item = `${dataStrList[i]}`; jsonResult.push(parseDarknet(item)); } return jsonResult; }; client.on('connect', () => { client.subscribe(topicActionInference); log(`inference client: connected to ${broker} successfully.`); }); client.on('message', (t, m) => { const size = m.length; const now = moment().format('YYYYMMDD-HHmmss'); const inference_server_img_dir = __dirname + '/image'; const snapshot = `snapshot-${now}.jpg`; const snapshot_path = path.join(inference_server_img_dir, snapshot); const donefile_path = snapshot_path + '.done'; const resultfile_path = snapshot_path + '.txt'; const resultdonefile_path = snapshot_path + '.txt.done'; const dashboard_image_path = __dirname + '/../dashboard/www/freeboard/snapshot.jpg'; log(`inference client: on topic ${t}, received ${size} bytes.`); // Save snapshot and create its done file. Classifier/detector will // be triggered after snapshot done file is created. saveBufferToImage(m, snapshot_path); fs.closeSync(fs.openSync(donefile_path, 'w')); log('Image done file ' + donefile_path + ' is ready.'); // Listen to classifier/detector's result done file. When result done // file (.txt.done) is created, result is available. var watcher = fs.watch(inference_server_img_dir, (eventType, filename) => { if (eventType === 'rename') { if (filename === (snapshot + '.txt.done')) { fs.readFile(resultfile_path, (err, result) => { if (err) throw err watcher.close(); if (inferenceEngine === 'classifier') { fs.writeFile(dashboard_image_path, m, (err, written, buffer) => { console.log('Written snapshot to dashboard image directory: ' + dashboard_image_path); client.publish(topicDashboardSnapshot, 'snapshot.jpg'); }) client.publish(topicDashboardInferenceResult, result.toString().replace(/(\n)+/g, '
')); } else if (inferenceEngine === 'detector') { console.log('Snapshot is created by detector, only notify dashboard to update.'); client.publish(topicDashboardSnapshot, 'snapshot.jpg'); client.publish(topicDashboardInferenceResult, result.toString().replace(/(\n)+/g, '
')); client.publish(topicJSONInferenceResult, JSON.stringify(darknetToJSON(result))); // Delete intermediate files. // // Note: Data collector will not be affected. It retrieves data from // * topicActionInference: contains snapshot raw data // * topicDashboardSnapshot: to copy snapshot with bounding boxes // * topicDashboardInferenceResult: contains inference result string fs.unlink(snapshot_path, (e) => {}); fs.unlink(resultfile_path, (e) => {}); fs.unlink(resultdonefile_path, (e) => {}); } else { console.log('Unknown owner ' + inferenceEngine); } client.publish(topicNotifyLINE, dashboard_image_path); }) } else { console.log('rename event for ' + filename + ', but it is not inference result done file.'); } } else { console.log(eventType + ' event for ' + filename + ', ignore it.'); } }); }); BerryNet-upstream-3.9.0/inference/classify_caffe2_server.py000066400000000000000000000167661360632137300240600ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Simple image classification server with Inception. The server monitors image_dir and run inferences on new images added to the directory. Every image file should come with another empty file with '.done' suffix to signal readiness. Inference result of a image can be read from the '.txt' file of that image after '.txt.done' is spotted. This is an example the server expects clients to do. Note the order. # cp cat.jpg /run/image_dir # touch /run/image_dir/cat.jpg.done Clients should wait for appearance of 'cat.jpg.txt.done' before getting result from 'cat.jpg.txt'. """ from __future__ import print_function import os import sys import time from caffe2.proto import caffe2_pb2 import numpy as np import skimage.io import skimage.transform import threading import multiprocessing import Queue import signal from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from caffe2.python import core, workspace import urllib2 image_dir = '/run/image_dir' image_queue = Queue.Queue() sess = None threads = [] def logging(*args): print("[%08.3f]" % time.time(), ' '.join(args)) def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) def crop_center(img,cropx,cropy): y,x,c = img.shape startx = x//2-(cropx//2) starty = y//2-(cropy//2) return img[starty:starty+cropy,startx:startx+cropx] def rescale(img, input_height, input_width): aspect = img.shape[1]/float(img.shape[0]) if(aspect>1): # landscape orientation - wide image res = int(aspect * input_height) imgScaled = skimage.transform.resize(img, (input_width, res)) if(aspect<1): # portrait orientation - tall image res = int(input_width/aspect) imgScaled = skimage.transform.resize(img, (res, input_height)) if(aspect == 1): imgScaled = skimage.transform.resize(img, (input_width, input_height)) return imgScaled def server(labels): """Infinite loop serving inference requests""" global image_queue, sess CAFFE2_ROOT = "/caffe2" CAFFE_MODELS = "/caffe2/caffe2/python/models" MODEL = 'squeezenet', 'exec_net.pb', 'predict_net.pb', 'ilsvrc_2012_mean.npy', 227 codes = "https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac071eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes" logging(threading.current_thread().getName(), "is running") CAFFE2_ROOT = os.path.expanduser(CAFFE2_ROOT) CAFFE_MODELS = os.path.expanduser(CAFFE_MODELS) MEAN_FILE = os.path.join(CAFFE_MODELS, MODEL[0], MODEL[3]) if not os.path.exists(MEAN_FILE): mean = 128 else: mean = np.load(MEAN_FILE).mean(1).mean(1) mean = mean[:, np.newaxis, np.newaxis] INPUT_IMAGE_SIZE = MODEL[4] INIT_NET = os.path.join(CAFFE_MODELS, MODEL[0], MODEL[1]) PREDICT_NET = os.path.join(CAFFE_MODELS, MODEL[0], MODEL[2]) while True: input_name = image_queue.get() img = skimage.img_as_float(skimage.io.imread(input_name)).astype(np.float32) img = rescale(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE) img = crop_center(img, INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE) img = img.swapaxes(1, 2).swapaxes(0, 1) img = img[(2, 1, 0), :, :] img = img * 255 - mean img = img[np.newaxis, :, :, :].astype(np.float32) with open(INIT_NET, 'rb') as f: init_net = f.read() with open(PREDICT_NET, 'rb') as f: predict_net = f.read() p = workspace.Predictor(init_net, predict_net) # run the net and return prediction results = p.run([img]) results = np.asarray(results) results = np.delete(results, 1) index = 0 highest = 0 arr = np.empty((0,2), dtype=object) arr[:,0] = int(10) arr[:,1:] = float(10) for i, r in enumerate(results): # imagenet index begins with 1! i=i+1 arr = np.append(arr, np.array([[i,r]]), axis=0) if (r > highest): highest = r index = i response = urllib2.urlopen(codes) output_name = input_name+'.txt' output_done_name = output_name+'.done' output = open(output_name, 'w') for line in response: code, result = line.partition(":")[::2] if (code.strip() == str(index)): human_string = result.strip()[1:-2] score = highest print("%s (score = %.5f)" % (human_string, score), file=output) output.close() touch(output_done_name) logging(input_name, " classified!") class EventHandler(PatternMatchingEventHandler): def process(self, event): """ event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file """ # the file will be processed there global image_queue _msg = event.src_path image_queue.put(_msg.rstrip('.done')) os.remove(_msg) logging(_msg, event.event_type) # ignore all other types of events except 'modified' def on_created(self, event): self.process(event) def main(_): """Called by Tensorflow""" # Create a server thread for each CPU core cpu_count = multiprocessing.cpu_count() for i in xrange(cpu_count/4): threads.append(threading.Thread(target=server, name='Server thread %d' % i, args=({},))) for t in threads: t.start() for t in threads: t.join() if __name__ == '__main__': global sess, threads pid = str(os.getpid()) pidfile = "/tmp/classify_server.pid" if os.path.isfile(pidfile): logging("%s already exists, exiting" % pidfile) sys.exit(1) with open(pidfile, 'w') as f: f.write(pid) # workaround the issue that SIGINT cannot be received (fork a child to # avoid blocking the main process in Thread.join() child_pid = os.fork() if child_pid == 0: # child # observer handles event in a different thread observer = Observer() observer.schedule(EventHandler(['*.jpg.done']), path=image_dir) observer.start() # Create a server thread for each CPU core cpu_count = multiprocessing.cpu_count() for i in xrange(cpu_count/4): threads.append(threading.Thread(target=server, name='Server thread %d' % i, args=({},))) for t in threads: t.start() for t in threads: t.join() else: # parent try: os.wait() except KeyboardInterrupt: os.kill(child_pid, signal.SIGKILL) os.unlink(pidfile) BerryNet-upstream-3.9.0/inference/classify_caffe_server.py000066400000000000000000000226421360632137300237640ustar00rootroot00000000000000#!/usr/bin/env python3 # # Copyright 2018 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Simple image classification server with Inception. The server monitors image_dir and run inferences on new images added to the directory. Every image file should come with another empty file with '.done' suffix to signal readiness. Inference result of a image can be read from the '.txt' file of that image after '.txt.done' is spotted. This is an example the server expects clients to do. Note the order. # cp cat.jpg /run/image_dir # touch /run/image_dir/cat.jpg.done Clients should wait for appearance of 'cat.jpg.txt.done' before getting result from 'cat.jpg.txt'. """ from __future__ import print_function import os import sys import time import numpy as np import threading import multiprocessing import queue import signal from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler import caffe import hashlib import urllib.request import tempfile import shutil image_queue = queue.Queue() sess = None threads = [] image_dir = '/run/image_dir' caffe_classifier = None caffe_labels = [] model_meta_file = '/usr/share/doc/caffe-doc/models/bvlc_reference_caffenet/readme.md' label_file = '/tmp/synset_words.txt' pretrained_model = None def logging(*args): print("[%08.3f]" % time.time(), ' '.join(args)) def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) def load_labels(filename): """Read in labels, one label per line.""" return [line.rstrip() for line in open(filename)] def read_model_meta_file(meta_file): """Read model meta file. The meta file is inside caffe-doc package""" # We believe we shouldn't read this file for downloading and checking # model. Instead we should package some model if there is free one. url = None sha1sum = None filename = None for line in open(meta_file): l1 = line.rstrip() if (l1.startswith("sha1:")): sha1sum = l1[len("sha1:"):].strip() if (l1.startswith("caffemodel_url:")): url = l1[len("caffemodel_url:"):].strip() if (l1.startswith("caffemodel:")): filename = l1[len("caffemodel:"):].strip() if ((sha1sum != None) and (url != None) and (filename != None)): break if ((url != None) and (sha1sum != None) and (filename != None)): return {'url': url, 'sha1sum': sha1sum, 'filename': filename} return None def sha1sum(filename): """calculate sha1sum""" BUF_SIZE=1024 sha1 = hashlib.sha1() with open(filename, 'rb') as f: while True: data = f.read(BUF_SIZE) if not data: break sha1.update(data) return sha1.hexdigest() def download_model(): """Download pretrained model""" # Downloading model from network isn't good for Debian. We need to package # the model. global pretrained_model meta_data = read_model_meta_file(model_meta_file) if (meta_data is None): logging('Cannot load %s'%(meta_data)) return None # FIXME: using /tmp/ will be in-secure. pretrained_model = os.path.join('/','tmp',meta_data['filename']) if (os.path.isfile(pretrained_model)): sha1 = sha1sum(pretrained_model) if (sha1 != meta_data['sha1sum']): logging('Model %s SHA1 is not equal to %s'%(pretrained_model, meta_data['sha1sum'])) pretrained_model = None return None else: logging('Model already exists') pass else: logging('Downloading model file from %s'%(meta_data['url'])) urllib.request.urlretrieve(meta_data['url'], pretrained_model) logging('Checking SHA1...') sha1 = sha1sum(pretrained_model) if (sha1 != meta_data['sha1sum']): logging('Model %s SHA1 is not equal to %s'%(pretrained_model, meta_data['sha1sum'])) pretrained_model = None return None else: logging('Model downloaded') pass return None def download_label(): """Download label file""" # Using the scripts inside caffe Debian package to download label file. # This could also be wrong. Why we don't package the label file? global label_file if (os.path.isfile(label_file)): logging("Label file exists"); pass else: logging("Label file not exists. Downloading..."); tmpdir = tempfile.mkdtemp() s1 = shutil.copy2(os.path.join('/', 'usr', 'share', 'doc', 'caffe-doc', 'data', 'ilsvrc12', 'get_ilsvrc_aux.sh'), tmpdir) os.system('sh \'%s\''%(s1)); # FIXME: using /tmp/ will be in-secure. shutil.copy2(os.path.join(tmpdir, 'synset_words.txt'), '/tmp') def create_classifier(pretrained_model): """Creates a model from saved caffemodel file and returns a classifier.""" # Creates model from saved .caffemodel. # The following file are shipped inside caffe-doc Debian package model_def = os.path.join("/", "usr", "share", "doc", "caffe-doc", "models","bvlc_reference_caffenet", "deploy.prototxt") image_dims = [ 256, 256 ] # The following file are shipped inside python3-caffe-cpu Debian package mean = np.load(os.path.join('/', 'usr', 'lib', 'python3', 'dist-packages', 'caffe', 'imagenet', 'ilsvrc_2012_mean.npy')) channel_swap = [2, 1, 0] raw_scale = 255.0 caffe.set_mode_cpu() classifier = caffe.Classifier(model_def, pretrained_model, image_dims=image_dims, mean=mean, raw_scale=raw_scale, channel_swap=channel_swap) return classifier def server(labels): """Infinite loop serving inference requests""" global image_queue, sess logging(threading.current_thread().getName(), "is running") while True: input_name = image_queue.get() if (input_name.endswith('npy')): inputs = np.load(input_name) else: inputs = [caffe.io.load_image(input_name)] predictions = caffe_classifier.predict(inputs, False) # make tuples predictions_list = predictions[0].tolist() data = zip(predictions_list, caffe_labels) output_name = input_name+'.txt' output_done_name = output_name+'.done' output = open(output_name, 'wt') for d in sorted(data, reverse=True): human_string = d[1] score = d[0] print("%s (score = %.5f)" % (human_string, score), file=output) if (score < 0.00001): break output.close() touch(output_done_name) logging(input_name, " classified!") class EventHandler(PatternMatchingEventHandler): def process(self, event): """ event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file """ # the file will be processed there global image_queue _msg = event.src_path image_queue.put(_msg.rstrip('.done')) os.remove(_msg) logging(_msg, event.event_type) # ignore all other types of events except 'modified' def on_created(self, event): self.process(event) if __name__ == '__main__': pid = str(os.getpid()) pidfile = "/tmp/classify_server.pid" if os.path.isfile(pidfile): logging("%s already exists, exiting" % pidfile) sys.exit(1) with open(pidfile, 'w') as f: f.write(pid) # Please read /usr/share/doc/caffe-doc/models/bvlc_reference_caffenet/readme.md download_model() download_label() caffe_labels = load_labels(label_file) caffe_classifier = create_classifier(pretrained_model) # workaround the issue that SIGINT cannot be received (fork a child to # avoid blocking the main process in Thread.join() child_pid = os.fork() if child_pid == 0: # child # observer handles event in a different thread observer = Observer() observer.schedule(EventHandler(['*.jpg.done']), path=image_dir) observer.start() # Create a server thread for each CPU core cpu_count = multiprocessing.cpu_count() for i in range(1): threads.append(threading.Thread(target=server, name='Server thread %d' % i, args=({},))) for t in threads: t.start() for t in threads: t.join() else: # parent try: os.wait() except KeyboardInterrupt: os.kill(child_pid, signal.SIGKILL) os.unlink(pidfile) BerryNet-upstream-3.9.0/inference/classify_movidius_server.py000066400000000000000000000135211360632137300245530ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Simple image classification server with Inception. The server monitors image_dir and run inferences on new images added to the directory. Every image file should come with another empty file with '.done' suffix to signal readiness. Inference result of a image can be read from the '.txt' file of that image after '.txt.done' is spotted. This is an example the server expects clients to do. Note the order. # cp cat.jpg /run/image_dir # touch /run/image_dir/cat.jpg.done Clients should wait for appearance of 'cat.jpg.txt.done' before getting result from 'cat.jpg.txt'. """ from __future__ import print_function import argparse import json import multiprocessing import os import signal import sys import threading import time import cv2 import movidius as mv import numpy as np import Queue from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler image_queue = Queue.Queue() threads = [] mvng = None graph_filepath = '' labels_filepath = '' def logging(*args): print("[%08.3f]" % time.time(), ' '.join(args)) def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) def generalize_inference_result(ncs_classifications): """Result format conversion from NCS classification to generic format. param list ncs_classifications: [(label, confidence), ...] return dict r: generic inference result format """ r = { 'annotations': [] } conf_digits = 2 for label, confidence in ncs_classifications: r['annotations'].append({ 'type': 'classification', 'label': label, 'confidence': round(float(confidence), conf_digits) }) return r def server(): """Infinite loop serving inference requests""" global image_queue global mvng logging(threading.current_thread().getName(), "is running") while True: input_name = image_queue.get() image_data = cv2.imread(input_name).astype(np.float32) image_data = mv.process_inceptionv3_input(image_data) output = mvng.inference(image_data) inceptionv3_outputs = mv.process_inceptionv3_output(output, mvng.get_labels()) output_name = input_name + '.txt' output_done_name = output_name + '.done' inference_result = generalize_inference_result(inceptionv3_outputs) logging(json.dumps(inference_result, indent=4)) with open(output_name, 'w') as f: json.dump(inference_result, f, indent=4) #with open(output_name, 'w') as f: # for i in inceptionv3_outputs: # print("%s (score = %.5f)" % (i[0], i[1]), file=f) touch(output_done_name) logging(input_name, " classified!") class EventHandler(PatternMatchingEventHandler): def process(self, event): """ event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file """ # the file will be processed there global image_queue _msg = event.src_path image_queue.put(_msg.rstrip('.done')) os.remove(_msg) logging(_msg, event.event_type) # ignore all other types of events except 'modified' def on_created(self, event): self.process(event) def main(args): global threads # Create a server thread for each CPU core cpu_count = multiprocessing.cpu_count() for i in xrange(cpu_count/4): threads.append( threading.Thread(target=server, name='Server thread %d' % i)) for t in threads: t.start() for t in threads: t.join() def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--model', required=True, help='Model file path') ap.add_argument('--label', required=True, help='Label file path') ap.add_argument('--image_dir', required=True, help='Path to image file') ap.add_argument('--num_top_predictions', default=5, help='Display this many predictions') return vars(ap.parse_args()) if __name__ == '__main__': args = parse_args() mvng = mv.MovidiusNeuralGraph(args['model'], args['label']) pid = str(os.getpid()) pidfile = "/tmp/classify_movidius_server.pid" if os.path.isfile(pidfile): logging("%s already exists, exiting" % pidfile) sys.exit(1) with open(pidfile, 'w') as f: f.write(pid) logging("model filepath: ", args['model']) logging("label filepath: ", args['label']) logging("image_dir: ", args['image_dir']) # workaround the issue that SIGINT cannot be received (fork a child to # avoid blocking the main process in Thread.join() child_pid = os.fork() if child_pid == 0: # child # observer handles event in a different thread observer = Observer() observer.schedule(EventHandler(['*.jpg.done']), path=args['image_dir']) observer.start() main(args) else: # parent try: os.wait() except KeyboardInterrupt: os.kill(child_pid, signal.SIGKILL) os.unlink(pidfile) BerryNet-upstream-3.9.0/inference/classify_server.py000066400000000000000000000153261360632137300226410ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Simple image classification server with Inception. The server monitors image_dir and run inferences on new images added to the directory. Every image file should come with another empty file with '.done' suffix to signal readiness. Inference result of a image can be read from the '.txt' file of that image after '.txt.done' is spotted. This is an example the server expects clients to do. Note the order. # cp cat.jpg /run/image_dir # touch /run/image_dir/cat.jpg.done Clients should wait for appearance of 'cat.jpg.txt.done' before getting result from 'cat.jpg.txt'. """ from __future__ import print_function import os import sys import time import numpy as np import threading import multiprocessing import tensorflow as tf import Queue import signal from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler FLAGS = tf.app.flags.FLAGS image_queue = Queue.Queue() sess = None threads = [] # classify_image_graph_def.pb: # Binary representation of the GraphDef protocol buffer. # imagenet_synset_to_human_label_map.txt: # Map from synset ID to a human readable string. # imagenet_2012_challenge_label_map_proto.pbtxt: # Text representation of a protocol buffer mapping a label to synset ID. tf.app.flags.DEFINE_string( 'model_dir', 'model', """Path to output_graph.pb and output_labels.txt.""") tf.app.flags.DEFINE_string('image_dir', 'image', """Path to image file.""") tf.app.flags.DEFINE_string('output_layer', 'softmax:0', """Name of the result operation""") tf.app.flags.DEFINE_string('input_layer', 'DecodeJpeg/contents:0', """Name of the input operation""") tf.app.flags.DEFINE_integer('num_top_predictions', 5, """Display this many predictions.""") def logging(*args): print("[%08.3f]" % time.time(), ' '.join(args)) def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) def load_labels(filename): """Read in labels, one label per line.""" return [line.rstrip() for line in tf.gfile.FastGFile(filename)] def create_graph(): """Creates a graph from saved GraphDef file and returns a saver.""" # Creates graph from saved graph_def.pb. with tf.gfile.FastGFile(os.path.join( FLAGS.model_dir, 'output_graph.pb'), 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') def server(labels): """Infinite loop serving inference requests""" global image_queue, sess logging(threading.current_thread().getName(), "is running") with sess.as_default(): # Some useful tensors: # 'softmax:0': A tensor containing the normalized prediction across # 1000 labels. # 'pool_3:0': A tensor containing the next-to-last layer containing 2048 # float description of the image. # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG # encoding of the image. while True: input_name = image_queue.get() image_data = tf.gfile.FastGFile(input_name, 'rb').read() predictions = sess.run(FLAGS.output_layer, {FLAGS.input_layer: image_data}) predictions = np.squeeze(predictions) top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1] output_name = input_name+'.txt' output_done_name = output_name+'.done' output = open(output_name, 'w') for node_id in top_k: human_string = labels[node_id] score = predictions[node_id] print("%s (score = %.5f)" % (human_string, score), file=output) output.close() touch(output_done_name) logging(input_name, " classified!") class EventHandler(PatternMatchingEventHandler): def process(self, event): """ event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file """ # the file will be processed there global image_queue _msg = event.src_path image_queue.put(_msg.rstrip('.done')) os.remove(_msg) logging(_msg, event.event_type) # ignore all other types of events except 'modified' def on_created(self, event): self.process(event) def main(_): """Called by Tensorflow""" global sess, threads # Creates graph from saved GraphDef. create_graph() # Reuse the same session for all threads processing requests sess = tf.Session() # Creates node ID --> English string lookup. labels = load_labels(os.path.join(FLAGS.model_dir, 'output_labels.txt')) # Create a server thread for each CPU core cpu_count = multiprocessing.cpu_count() for i in xrange(cpu_count/4): threads.append(threading.Thread(target=server, name='Server thread %d' % i, args=(labels,))) for t in threads: t.start() for t in threads: t.join() if __name__ == '__main__': pid = str(os.getpid()) pidfile = "/tmp/classify_server.pid" if os.path.isfile(pidfile): logging("%s already exists, exiting" % pidfile) sys.exit(1) with open(pidfile, 'w') as f: f.write(pid) logging("model_dir: ", FLAGS.model_dir) logging("image_dir: ", FLAGS.image_dir) # workaround the issue that SIGINT cannot be received (fork a child to # avoid blocking the main process in Thread.join() child_pid = os.fork() if child_pid == 0: # child # observer handles event in a different thread observer = Observer() observer.schedule(EventHandler(['*.jpg.done']), path=FLAGS.image_dir) observer.start() tf.app.run() else: # parent try: os.wait() except KeyboardInterrupt: os.kill(child_pid, signal.SIGKILL) os.unlink(pidfile) BerryNet-upstream-3.9.0/inference/darkflow_engine.py000066400000000000000000000113061360632137300225660ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Darkflow inference engine. """ from __future__ import print_function import argparse import logging import cv2 from darkflow.net.build import TFNet from engineservice import EngineService from engineservice import DLEngine from dlmodelmgr import DLModelManager # FIXME: Make these variables configurable SystemSnapshot = '/usr/local/berrynet/dashboard/www/freeboard/snapshot.jpg' class DarkflowEngine(DLEngine): def __init__(self, model, label, config): super(DarkflowEngine, self).__init__() self.engine_options = { 'model': config, 'load': model, #'model': "cfg/tiny-yolo.cfg", #'load': "bin/tiny-yolo.weights", 'verbalise': True, "threshold": 0.1 } def create(self): self.tfnet = TFNet(self.engine_options) def inference(self, tensor): return self.tfnet.return_predict(tensor) def save_cache(self): #with open(self.cache['model_output_filepath'], 'w') as f: # f.write(str(self.cache['model_output'])) drawBoundingBoxes(self.cache['model_input'], #self.cache['model_output_filepath'] + '.jpg', SystemSnapshot, self.cache['model_output'], self.tfnet.meta['colors']) def drawBoundingBoxes(imageData, imageOutputPath, inferenceResults, colorMap): """Draw bounding boxes on an image. imageData: image data in numpy array format imageOutputPath: output image file path inferenceResults: Darkflow inference results colorMap: Bounding box color candidates, list of RGB tuples. """ # TODO: return raw data instead of save image for res in inferenceResults: left = res['topleft']['x'] top = res['topleft']['y'] right = res['bottomright']['x'] bottom = res['bottomright']['y'] colorIndex = res['coloridx'] color = colorMap[colorIndex] label = res['label'] confidence = res['confidence'] imgHeight, imgWidth, _ = imageData.shape thick = int((imgHeight + imgWidth) // 300) cv2.rectangle(imageData,(left, top), (right, bottom), color, thick) cv2.putText(imageData, label, (left, top - 12), 0, 1e-3 * imgHeight, color, thick//3) cv2.imwrite(imageOutputPath, imageData) logging.debug('Save bounding box result image to {}'.format(imageOutputPath)) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--model', help='Model file path') ap.add_argument('--label', help='Label file path') ap.add_argument('--model_package', default='', help='Model package "name-version" naming') ap.add_argument('--image_dir', required=True, help='Path to image file') ap.add_argument('--service_name', required=True, help='Engine service name used as PID filename') ap.add_argument('--num_top_predictions', default=5, help='Display this many predictions') return vars(ap.parse_args()) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) args = parse_args() if args['model_package'] != '': dlmm = DLModelManager() meta = dlmm.get_model_meta(args['model_package']) args['model'] = meta['model'] args['label'] = meta['label'] args['config'] = meta['config']['graph'] logging.debug('model filepath: ' + args['model']) logging.debug('label filepath: ' + args['label']) logging.debug('image_dir: ' + args['image_dir']) darkflow_engine = DarkflowEngine(args['model'], args['label'], args['config']) engine_service = EngineService(args['service_name'], darkflow_engine) engine_service.run(args) # this code block works #import cv2 #input_tensor = cv2.imread('/tmp/berrynet/dog.jpg') #tensor = darkflow_engine.process_input(input_tensor) #output = darkflow_engine.inference(tensor) #output = darkflow_engine.process_output(output) BerryNet-upstream-3.9.0/inference/detect_movidius_server.py000066400000000000000000000126741360632137300242160ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Simple image classification server with Inception. The server monitors image_dir and run inferences on new images added to the directory. Every image file should come with another empty file with '.done' suffix to signal readiness. Inference result of a image can be read from the '.txt' file of that image after '.txt.done' is spotted. This is an example the server expects clients to do. Note the order. # cp cat.jpg /run/image_dir # touch /run/image_dir/cat.jpg.done Clients should wait for appearance of 'cat.jpg.txt.done' before getting result from 'cat.jpg.txt'. """ from __future__ import print_function import argparse import multiprocessing import os import signal import sys import threading import time from datetime import datetime import cv2 import movidius as mv import numpy as np import Queue from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler image_queue = Queue.Queue() threads = [] mvng = None SystemSnapshot = '/usr/local/berrynet/dashboard/www/freeboard/snapshot.jpg' def logging(*args): print("[%08.3f]" % time.time(), ' '.join(args)) def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) def server(): """Infinite loop serving inference requests""" global image_queue global mvng logging(threading.current_thread().getName(), "is running") while True: input_name = image_queue.get() image_data = cv2.imread(input_name) processed_data = mv.process_yolo_input(image_data) t_start = datetime.now() output = mvng.inference(processed_data) t_end = datetime.now() t_inference = t_end - t_start logging('inference time: {} ms'.format(t_inference.total_seconds() * 1000)) interpreted_output = mv.interpret_yolo_output(output, image_data.shape[1], image_data.shape[0]) yolo_outputs = mv.process_yolo_output(image_data, interpreted_output, SystemSnapshot) output_name = input_name + '.txt' output_done_name = output_name + '.done' mv.save_yolo_output_text(output_name, yolo_outputs) touch(output_done_name) logging(input_name, " detected!") class EventHandler(PatternMatchingEventHandler): def process(self, event): """ event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file """ # the file will be processed there global image_queue _msg = event.src_path image_queue.put(_msg.rstrip('.done')) os.remove(_msg) logging(_msg, event.event_type) # ignore all other types of events except 'modified' def on_created(self, event): self.process(event) def main(args): global threads # Create a server thread for each CPU core cpu_count = multiprocessing.cpu_count() for i in xrange(cpu_count/4): threads.append( threading.Thread(target=server, name='Server thread %d' % i)) for t in threads: t.start() for t in threads: t.join() def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--model', required=True, help='Model file path') ap.add_argument('--label', required=True, help='Label file path') ap.add_argument('--image_dir', required=True, help='Path to image file') ap.add_argument('--num_top_predictions', default=5, help='Display this many predictions') return vars(ap.parse_args()) if __name__ == '__main__': args = parse_args() mvng = mv.MovidiusNeuralGraph(args['model'], args['label']) pid = str(os.getpid()) pidfile = "/tmp/detect_movidius_server.pid" if os.path.isfile(pidfile): logging("%s already exists, exiting" % pidfile) sys.exit(1) with open(pidfile, 'w') as f: f.write(pid) logging("model filepath: ", args['model']) logging("label filepath: ", args['label']) logging("image_dir: ", args['image_dir']) # workaround the issue that SIGINT cannot be received (fork a child to # avoid blocking the main process in Thread.join() child_pid = os.fork() if child_pid == 0: # child # observer handles event in a different thread observer = Observer() observer.schedule(EventHandler(['*.jpg.done']), path=args['image_dir']) observer.start() main(args) else: # parent try: os.wait() except KeyboardInterrupt: os.kill(child_pid, signal.SIGKILL) os.unlink(pidfile) BerryNet-upstream-3.9.0/inference/detect_movidius_server_cv.py000066400000000000000000000101441360632137300246740ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Simple image classification server with Inception. The server monitors image_dir and run inferences on new images added to the directory. Every image file should come with another empty file with '.done' suffix to signal readiness. Inference result of a image can be read from the '.txt' file of that image after '.txt.done' is spotted. This is an example the server expects clients to do. Note the order. # cp cat.jpg /run/image_dir # touch /run/image_dir/cat.jpg.done Clients should wait for appearance of 'cat.jpg.txt.done' before getting result from 'cat.jpg.txt'. """ from __future__ import print_function import argparse import os import sys import time from datetime import datetime import cv2 import movidius as mv import numpy as np mvng = None def logging(*args): print("[%08.3f]" % time.time(), ' '.join(args)) def run(mvng): """Infinite loop serving inference requests""" logging('detection service is running') capture = cv2.VideoCapture(0) while True: t_start = datetime.now() status, image_data = capture.read() t_end = datetime.now() t_capture = t_end - t_start logging('capture time: {} ms'.format(t_capture.total_seconds() * 1000)) t_start = datetime.now() processed_data = mv.process_yolo_input(image_data) t_end = datetime.now() t_preprocess = t_end - t_start logging('preprocess time: {} ms'.format(t_preprocess.total_seconds() * 1000)) t_start = datetime.now() output = mvng.inference(processed_data) t_end = datetime.now() t_inference = t_end - t_start logging('inference time: {} ms'.format(t_inference.total_seconds() * 1000)) t_start = datetime.now() interpreted_output = mv.interpret_yolo_output(output, image_data.shape[1], image_data.shape[0]) yolo_outputs = mv.process_yolo_output(image_data, interpreted_output, '/tmp/yolo_resutl.jpg') t_end = datetime.now() t_postprocess = t_end - t_start logging('postprocess time: {} ms'.format(t_postprocess.total_seconds() * 1000)) #output_name = input_name + '.txt' #mv.save_yolo_output_text(output_name, yolo_outputs) #logging(input_name, " detected!") def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--model', required=True, help='Model file path') ap.add_argument('--label', required=True, help='Label file path') ap.add_argument('--image_dir', required=True, help='Path to image file') #ap.add_argument('--num_top_predictions', default=5, # help='Display this many predictions') return vars(ap.parse_args()) if __name__ == '__main__': args = parse_args() mvng = mv.MovidiusNeuralGraph(args['model'], args['label']) logging("model filepath: ", args['model']) logging("label filepath: ", args['label']) logging("image_dir: ", args['image_dir']) # workaround the issue that SIGINT cannot be received (fork a child to # avoid blocking the main process in Thread.join() child_pid = os.fork() if child_pid == 0: # child run(mvng) else: # parent try: os.wait() except KeyboardInterrupt: os.kill(child_pid, signal.SIGKILL) os.unlink(pidfile) BerryNet-upstream-3.9.0/inference/detection_server.py000066400000000000000000000133331360632137300227760ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Simple image detection server with Tiny-YOLO. The server monitors image_dir and run inferences on new images added to the directory. Every image file should come with another empty file with '.done' suffix to signal readiness. Inference result of a image can be read from the '.txt' file of that image after '.txt.done' is spotted. This is an example the server expects clients to do. Note the order. # cp cat.jpg /run/image_dir # touch /run/image_dir/cat.jpg.done Clients should wait for appearance of 'cat.jpg.txt.done' before getting result from 'cat.jpg.txt'. """ from __future__ import print_function import logging import multiprocessing import os import Queue import signal import sys import threading import time import cv2 import numpy as np from os.path import join as pjoin from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from darkflow.net.build import TFNet image_queue = Queue.Queue() # FIXME: Make these variables configurable ImageDir = '../image' SystemSnapshot = '../../dashboard/www/freeboard/snapshot.jpg' def _logging(*args): print("[%08.3f]" % time.time(), ' '.join(args)) def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) def drawBoundingBoxes(imageData, imageOutputPath, inferenceResults, colorMap): """Draw bounding boxes on an image. imageData: image data in numpy array format imageOutputPath: output image file path inferenceResults: Darkflow inference results colorMap: Bounding box color candidates, list of RGB tuples. """ # TODO: return raw data instead of save image for res in inferenceResults: left = res['topleft']['x'] top = res['topleft']['y'] right = res['bottomright']['x'] bottom = res['bottomright']['y'] colorIndex = res['coloridx'] color = colorMap[colorIndex] label = res['label'] confidence = res['confidence'] imgHeight, imgWidth, _ = imageData.shape thick = int((imgHeight + imgWidth) // 300) cv2.rectangle(imageData,(left, top), (right, bottom), color, thick) cv2.putText(imageData, label, (left, top - 12), 0, 1e-3 * imgHeight, color, thick//3) cv2.imwrite(imageOutputPath, imageData) logging.debug('Save bounding box result image to {}'.format(imageOutputPath)) def server(tfnet): """Infinite loop serving inference requests""" global image_queue _logging(threading.current_thread().getName(), "is running") while True: input_name = image_queue.get() _logging('input image ' + input_name) imgcv = cv2.imread(input_name) _logging('start inference') result = tfnet.return_predict(imgcv) _logging('inference result: {}'.format(result)) # overwrite existing input snapshot by the result image with # bounding boxes. drawBoundingBoxes(imgcv, SystemSnapshot, result, tfnet.meta['colors']) logging.debug('System snapshot path: %s' % pjoin(os.getcwd(), SystemSnapshot)) output_name = input_name+'.txt' output_done_name = output_name+'.done' with open(output_name, 'w') as f: f.write(str(result)) touch(output_done_name) _logging(input_name, " classified!") class EventHandler(PatternMatchingEventHandler): def process(self, event): """ event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file """ # the file will be processed there global image_queue _msg = event.src_path image_queue.put(_msg.rstrip('.done')) os.remove(_msg) _logging(_msg, event.event_type) # ignore all other types of events except 'modified' def on_created(self, event): self.process(event) def main(): options = { "model": "cfg/tiny-yolo.cfg", "load": "bin/tiny-yolo.weights", 'verbalise': True, #"threshold": 0.1 } tfnet = TFNet(options) _logging('model dir: {}'.format(options['load'])) _logging('config dir: {}'.format(options['model'])) server(tfnet) if __name__ == '__main__': logging.basicConfig(filename='/tmp/dlDetector.log', level=logging.DEBUG) pid = str(os.getpid()) pidfile = "/tmp/detection_server.pid" if os.path.isfile(pidfile): _logging("%s already exists, exiting" % pidfile) sys.exit(1) with open(pidfile, 'w') as f: f.write(pid) # workaround the issue that SIGINT cannot be received (fork a child to # avoid blocking the main process in Thread.join() child_pid = os.fork() if child_pid == 0: # child # observer handles event in a different thread observer = Observer() observer.schedule(EventHandler(['*.jpg.done']), ImageDir) observer.start() main() else: # parent try: os.wait() except KeyboardInterrupt: os.kill(child_pid, signal.SIGKILL) os.unlink(pidfile) BerryNet-upstream-3.9.0/inference/dlmodelmgr.py000066400000000000000000000037001360632137300215550ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """ DL Model Manager, following the DLModelBox model package speccification. """ from __future__ import print_function import argparse import json import logging import os class DLModelManager(object): def __init__(self): self.basedir = '/var/lib/dlmodels' def get_model_names(self): return os.listdir(self.basedir) def get_model_meta(self, modelname): meta_filepath = os.path.join(self.basedir, modelname, 'meta.json') with open(meta_filepath, 'r') as f: meta = json.load(f) meta['model'] = os.path.join(self.basedir, modelname, meta['model']) meta['label'] = os.path.join(self.basedir, modelname, meta['label']) for k, v in meta['config'].items(): meta['config'][k] = os.path.join(self.basedir, modelname, meta['config'][k]) return meta def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--modelname', help='Model package name (without version)') return vars(ap.parse_args()) if __name__ == '__main__': args = parse_args() logging.debug('model package name: ', args['modelname']) dlmm = DLModelManager() for name in dlmm.get_model_names(): print(dlmm.get_model_meta(name)) BerryNet-upstream-3.9.0/inference/engineservice.py000066400000000000000000000146401360632137300222620ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Engine service is a bridge between incoming data and inference engine. """ from __future__ import print_function import argparse import logging import multiprocessing import os import signal import sys import threading import time import cv2 import numpy as np import Queue from dlmodelmgr import DLModelManager from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class DLEngine(object): def __init__(self): self.model_input_cache = [] self.model_output_cache = [] self.cache = { 'model_input': [], 'model_output': '', 'model_output_filepath': '' } def create(self): # Workaround to posepone TensorFlow initialization. # If TF is initialized in __init__, and pass an engine instance # to engine service, TF session will stuck in run(). pass def process_input(self, tensor): return tensor def inference(self, tensor): output = None return output def process_output(self, output): return output def cache_data(self, key, value): self.cache[key] = value def save_cache(self): with open(self.cache['model_output_filepath'], 'w') as f: f.write(str(self.cache['model_output'])) class EventHandler(PatternMatchingEventHandler): def process(self, event): """ event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file """ # the file will be processed there _msg = event.src_path self.image_queue.put(_msg.rstrip('.done')) os.remove(_msg) logging.debug(_msg + ' ' + event.event_type) # ignore all other types of events except 'modified' def on_created(self, event): self.process(event) class EngineService(object): def __init__(self, service_name, engine): self.service_name = service_name self.engine = engine self.image_queue = Queue.Queue() self.event_handler = EventHandler(['*.jpg.done']) # NOTE: Increase object reference count (share memory) # instead of object creation. self.event_handler.image_queue = self.image_queue def touch(self, fname, times=None): with open(fname, 'a'): os.utime(fname, times) def server(self): """Infinite loop serving inference requests""" logging.info(threading.current_thread().getName() + " is running") self.engine.create() while True: input_name = self.image_queue.get() image_data = cv2.imread(input_name).astype(np.float32) self.engine.cache_data('model_input', image_data) image_data = self.engine.process_input(image_data) output = self.engine.inference(image_data) model_outputs = self.engine.process_output(output) self.engine.cache_data('model_output', model_outputs) output_name = input_name + '.txt' output_done_name = output_name + '.done' self.engine.cache_data('model_output_filepath', output_name) self.engine.save_cache() self.touch(output_done_name) logging.debug(input_name + " classified!") def run(self, args): self.record_pid() # workaround the issue that SIGINT cannot be received (fork a child to # avoid blocking the main process in Thread.join() child_pid = os.fork() if child_pid == 0: # child # observer handles event in a different thread observer = Observer() observer.schedule(self.event_handler, path=args['image_dir']) observer.start() self.server() else: # parent try: os.wait() except KeyboardInterrupt: os.kill(child_pid, signal.SIGKILL) self.erase_pid() def record_pid(self): """Write a PID pidfile /tmp/.pid. """ pid = str(os.getpid()) pidfile = '/tmp/{}.pid'.format(self.service_name) if os.path.isfile(pidfile): logging.critical("%s already exists, exiting" % pidfile) sys.exit(1) with open(pidfile, 'w') as f: f.write(pid) def erase_pid(self): pidfile = '/tmp/{}.pid'.format(self.service_name) os.unlink(pidfile) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--model', help='Model file path') ap.add_argument('--label', help='Label file path') ap.add_argument('--model_package', default='', help='Model package name') ap.add_argument('--image_dir', required=True, help='Path to image file') ap.add_argument('--service_name', required=True, help='Engine service name used as PID filename') ap.add_argument('--num_top_predictions', default=5, help='Display this many predictions') return vars(ap.parse_args()) if __name__ == '__main__': import movidius as mv logging.basicConfig(level=logging.DEBUG) args = parse_args() if args['model_package'] != '': dlmm = DLModelManager() meta = dlmm.get_model_meta(args['model_package']) args['model'] = meta['model'] args['label'] = meta['label'] logging.debug('model filepath: ' + args['model']) logging.debug('label filepath: ' + args['label']) logging.debug('image_dir: ' + args['image_dir']) mvng = mv.MovidiusNeuralGraph(args['model'], args['label']) engine_service = EngineService(args['service_name'], mvng) engine_service.run(args) BerryNet-upstream-3.9.0/inference/movidius.py000066400000000000000000000237521360632137300212770ustar00rootroot00000000000000#!/usr/bin/python # # Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . import os import cv2 import numpy as np from mvnc import mvncapi as mvnc from skimage.transform import resize class MovidiusNeuralGraph(object): def __init__(self, graph_filepath, label_filepath): # mvnc.SetGlobalOption(mvnc.GlobalOption.LOGLEVEL, 2) devices = mvnc.EnumerateDevices() if len(devices) == 0: raise Exception('No devices found') self.device = mvnc.Device(devices[0]) self.device.OpenDevice() # Load graph with open(graph_filepath, mode='rb') as f: graphfile = f.read() self.graph = self.device.AllocateGraph(graphfile) # Load labels self.labels = [] with open(label_filepath, 'r') as f: for line in f: label = line.split('\n')[0] if label != 'classes': self.labels.append(label) f.close() def __exit__(self, exc_type, exc_value, traceback): self.graph.DeallocateGraph() self.device.CloseDevice() def inference(self, data): self.graph.LoadTensor(data.astype(np.float16), 'user object') output, userobj = self.graph.GetResult() return output def get_graph(self): return self.graph def get_labels(self): return self.labels def process_inceptionv3_input(img): image_size = 299 mean = 128 std = 1.0/128 dx, dy, dz = img.shape delta = float(abs(dy - dx)) if dx > dy: # crop the x dimension img = img[int(0.5*delta):dx-int(0.5*delta), 0:dy] else: img = img[0:dx, int(0.5*delta):dy-int(0.5*delta)] img = cv2.resize(img, (image_size, image_size)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for i in range(3): img[:, :, i] = (img[:, :, i] - mean) * std return img def process_inceptionv3_output(output, labels): top_inds = output.argsort()[::-1][:5] return [(labels[top_inds[i]], output[top_inds[i]]) for i in range(5)] def print_inceptionv3_output(output, labels): top_inds = output.argsort()[::-1][:5] for i in range(5): print(top_inds[i], labels[top_inds[i]], output[top_inds[i]]) def interpret_yolo_output(output, img_width, img_height): output = output.astype(np.float32) classes = [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train','tvmonitor' ] threshold = 0.2 iou_threshold = 0.5 num_class = 20 num_box = 2 grid_size = 7 probs = np.zeros((7, 7, 2, 20)) class_probs = (np.reshape(output[0:980], (7, 7, 20))) #.copy() scales = (np.reshape(output[980:1078], (7, 7, 2))) #.copy() boxes = (np.reshape(output[1078:], (7, 7, 2, 4))) #.copy() offset = np.transpose( np.reshape(np.array([np.arange(7)] * 14), (2, 7, 7)), (1, 2, 0) ) #boxes.setflags(write=1) boxes[:, :, :, 0] += offset boxes[:, :, :, 1] += np.transpose(offset, (1, 0, 2)) boxes[:, :, :, 0:2] = boxes[:, :, :, 0:2] / 7.0 boxes[:, :, :, 2] = np.multiply(boxes[:, :, :, 2], boxes[:, :, :, 2]) boxes[:, :, :, 3] = np.multiply(boxes[:, :, :, 3], boxes[:, :, :, 3]) boxes[:, :, :, 0] *= img_width boxes[:, :, :, 1] *= img_height boxes[:, :, :, 2] *= img_width boxes[:, :, :, 3] *= img_height for i in range(2): for j in range(20): probs[:, :, i, j] = np.multiply(class_probs[:, :, j], scales[:, :, i]) #print (probs) filter_mat_probs = np.array(probs >= threshold, dtype='bool') filter_mat_boxes = np.nonzero(filter_mat_probs) boxes_filtered = boxes[filter_mat_boxes[0], filter_mat_boxes[1], filter_mat_boxes[2]] probs_filtered = probs[filter_mat_probs] classes_num_filtered = np.argmax(probs, axis=3)[filter_mat_boxes[0], filter_mat_boxes[1], filter_mat_boxes[2]] argsort = np.array(np.argsort(probs_filtered))[::-1] boxes_filtered = boxes_filtered[argsort] probs_filtered = probs_filtered[argsort] classes_num_filtered = classes_num_filtered[argsort] for i in range(len(boxes_filtered)): if probs_filtered[i] == 0: continue for j in range(i + 1, len(boxes_filtered)): if iou(boxes_filtered[i], boxes_filtered[j]) > iou_threshold: probs_filtered[j] = 0.0 filter_iou = np.array(probs_filtered > 0.0, dtype='bool') boxes_filtered = boxes_filtered[filter_iou] probs_filtered = probs_filtered[filter_iou] classes_num_filtered = classes_num_filtered[filter_iou] result = [] for i in range(len(boxes_filtered)): result.append([classes[classes_num_filtered[i]], boxes_filtered[i][0], boxes_filtered[i][1], boxes_filtered[i][2], boxes_filtered[i][3], probs_filtered[i]]) return result def iou(box1, box2): tb = (min(box1[0] + 0.5 * box1[2], box2[0] + 0.5 * box2[2]) - max(box1[0] - 0.5 * box1[2], box2[0] - 0.5 * box2[2])) lr = (min(box1[1] + 0.5 * box1[3], box2[1] + 0.5 * box2[3]) - max(box1[1] - 0.5 * box1[3], box2[1] - 0.5 * box2[3])) if tb < 0 or lr < 0: intersection = 0 else: intersection = tb*lr return intersection / (box1[2] * box1[3] + box2[2] * box2[3] - intersection) def process_yolo_output(img, results, img_filepath): img_width = img.shape[1] img_height = img.shape[0] img_cp = img.copy() print_yolo_output(results) # draw bounding boxes on input image for i in range(len(results)): x = int(results[i][1]) y = int(results[i][2]) w = int(results[i][3]) // 2 h = int(results[i][4]) // 2 xmin = x - w xmax = x + w ymin = y - h ymax = y + h if xmin < 0: xmin = 0 if ymin < 0: ymin = 0 if xmax > img_width: xmax = img_width if ymax > img_height: ymax = img_height cv2.rectangle(img_cp, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2) cv2.rectangle(img_cp, (xmin, ymin - 20), (xmax, ymin), (125, 125, 125), -1) cv2.putText(img_cp,results[i][0] + ' : %.2f' % results[i][5], (xmin + 5, ymin - 7), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1) save_yolo_output_image(img_filepath, img_cp) return results def process_yolo_input(rgb_data): from datetime import datetime input_dim = (448, 448) t_start = datetime.now() tmp_data = rgb_data.copy() t_end = datetime.now() t_pass = t_end - t_start print('copy: {} ms'.format(t_pass.total_seconds() * 1000)) t_start = datetime.now() #tmp_data = resize(tmp_data / 255.0, input_dim, 1) # ~270 ms tmp_data = cv2.resize(tmp_data / 255.0, input_dim) # ~65 ms t_end = datetime.now() t_pass = t_end - t_start print('resize: {} ms'.format(t_pass.total_seconds() * 1000)) t_start = datetime.now() tmp_data[:, :, (2, 1, 0)] # BGR2RGB t_end = datetime.now() t_pass = t_end - t_start print('BGR2RGB: {} ms'.format(t_pass.total_seconds() * 1000)) t_start = datetime.now() input_data = tmp_data.astype(np.float16) t_end = datetime.now() t_pass = t_end - t_start print('astype: {} ms'.format(t_pass.total_seconds() * 1000)) return input_data def save_yolo_output_text(text_filepath, output): with open(text_filepath, 'w') as f: f.write(str(output)) def save_yolo_output_image(image_filepath, image_data): cv2.imwrite(image_filepath, image_data) def print_yolo_output(output): for i in range(len(output)): x = int(output[i][1]) y = int(output[i][2]) #w = int(output[i][3]) // 2 #h = int(output[i][4]) // 2 print('\tclass = {label}'.format(label=output[i][0])) print('\t[x, y, w, h] = [{x}, {y}, {w}, {h}]'.format( x=str(x), y=str(y), w=str(int(output[i][3])), h=str(int(output[i][4])))) print('\tconfidence = {conf}'.format(conf=str(output[i][5]))) if __name__ == '__main__': graph_filepath = '' # model filepath label_filepath = '' # label filepath path_to_images = '' # image dirpath image_filenames = [os.path.join(path_to_images, image_name) for image_name in []] # image filename list movidius = MovidiusNeuralGraph(graph_filepath, label_filepath) labels = movidius.get_labels() print(''.join(['*' for i in range(79)])) print('inception-v3 on NCS') for image_filename in image_filenames: img = cv2.imread(image_filename).astype(np.float32) img = process_inceptionv3_input(img) print(''.join(['*' for i in range(79)])) print('Start download to NCS...') output = movidius.inference(img) print_inceptionv3_output(output, labels) print(''.join(['*' for i in range(79)])) print('Finished') BerryNet-upstream-3.9.0/inference/movidius_engine.py000066400000000000000000000056271360632137300226250ustar00rootroot00000000000000# Copyright 2017 DT42 # # This file is part of BerryNet. # # BerryNet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # BerryNet is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BerryNet. If not, see . """Movidius inference engine. """ from __future__ import print_function import argparse import logging import movidius as mv from engineservice import EngineService from engineservice import DLEngine from dlmodelmgr import DLModelManager class MovidiusEngine(DLEngine): def __init__(self, model, label): super(MovidiusEngine, self).__init__() self.mvng = mv.MovidiusNeuralGraph(model, label) def process_input(self, tensor): return mv.process_inceptionv3_input(tensor) def inference(self, tensor): return self.mvng.inference(tensor) def process_output(self, output): return mv.process_inceptionv3_output( output, self.mvng.get_labels()) def save_cache(self): with open(self.cache['model_output_filepath'], 'w') as f: for i in self.cache['model_output']: print("%s (score = %.5f)" % (i[0], i[1]), file=f) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--model', help='Model file path') ap.add_argument('--label', help='Label file path') ap.add_argument('--model_package', default='', help='Model package "name-version" naming') ap.add_argument('--image_dir', required=True, help='Path to image file') ap.add_argument('--service_name', required=True, help='Engine service name used as PID filename') ap.add_argument('--num_top_predictions', default=5, help='Display this many predictions') return vars(ap.parse_args()) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) args = parse_args() if args['model_package'] != '': dlmm = DLModelManager() meta = dlmm.get_model_meta(args['model_package']) args['model'] = meta['model'] args['label'] = meta['label'] logging.debug('model filepath: ' + args['model']) logging.debug('label filepath: ' + args['label']) logging.debug('image_dir: ' + args['image_dir']) movidius_engine = MovidiusEngine(args['model'], args['label']) engine_service = EngineService(args['service_name'], movidius_engine) engine_service.run(args) BerryNet-upstream-3.9.0/inference/yoloutils.py000066400000000000000000000160251360632137300214760ustar00rootroot00000000000000import os import sys import time from datetime import datetime import cv2 import numpy as np from mvnc import mvncapi as mvnc from skimage.transform import resize def interpret_yolo_output(output, img_width, img_height): output = output.astype(np.float32) classes = [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train','tvmonitor' ] threshold = 0.2 iou_threshold = 0.5 num_class = 20 num_box = 2 grid_size = 7 probs = np.zeros((7, 7, 2, 20)) class_probs = (np.reshape(output[0:980], (7, 7, 20))) #.copy() scales = (np.reshape(output[980:1078], (7, 7, 2))) #.copy() boxes = (np.reshape(output[1078:], (7, 7, 2, 4))) #.copy() offset = np.transpose( np.reshape(np.array([np.arange(7)] * 14), (2, 7, 7)), (1, 2, 0) ) #boxes.setflags(write=1) boxes[:, :, :, 0] += offset boxes[:, :, :, 1] += np.transpose(offset, (1, 0, 2)) boxes[:, :, :, 0:2] = boxes[:, :, :, 0:2] / 7.0 boxes[:, :, :, 2] = np.multiply(boxes[:, :, :, 2], boxes[:, :, :, 2]) boxes[:, :, :, 3] = np.multiply(boxes[:, :, :, 3], boxes[:, :, :, 3]) boxes[:, :, :, 0] *= img_width boxes[:, :, :, 1] *= img_height boxes[:, :, :, 2] *= img_width boxes[:, :, :, 3] *= img_height for i in range(2): for j in range(20): probs[:, :, i, j] = np.multiply(class_probs[:, :, j], scales[:, :, i]) #print (probs) filter_mat_probs = np.array(probs >= threshold, dtype='bool') filter_mat_boxes = np.nonzero(filter_mat_probs) boxes_filtered = boxes[filter_mat_boxes[0], filter_mat_boxes[1], filter_mat_boxes[2]] probs_filtered = probs[filter_mat_probs] classes_num_filtered = np.argmax(probs, axis=3)[filter_mat_boxes[0], filter_mat_boxes[1], filter_mat_boxes[2]] argsort = np.array(np.argsort(probs_filtered))[::-1] boxes_filtered = boxes_filtered[argsort] probs_filtered = probs_filtered[argsort] classes_num_filtered = classes_num_filtered[argsort] for i in range(len(boxes_filtered)): if probs_filtered[i] == 0: continue for j in range(i + 1, len(boxes_filtered)): if iou(boxes_filtered[i], boxes_filtered[j]) > iou_threshold: probs_filtered[j] = 0.0 filter_iou = np.array(probs_filtered > 0.0, dtype='bool') boxes_filtered = boxes_filtered[filter_iou] probs_filtered = probs_filtered[filter_iou] classes_num_filtered = classes_num_filtered[filter_iou] result = [] for i in range(len(boxes_filtered)): result.append([classes[classes_num_filtered[i]], boxes_filtered[i][0], boxes_filtered[i][1], boxes_filtered[i][2], boxes_filtered[i][3], probs_filtered[i]]) return result def iou(box1, box2): tb = (min(box1[0] + 0.5 * box1[2], box2[0] + 0.5 * box2[2]) - max(box1[0] - 0.5 * box1[2], box2[0] - 0.5 * box2[2])) lr = (min(box1[1] + 0.5 * box1[3], box2[1] + 0.5 * box2[3]) - max(box1[1] - 0.5 * box1[3], box2[1] - 0.5 * box2[3])) if tb < 0 or lr < 0: intersection = 0 else: intersection = tb*lr return intersection / (box1[2] * box1[3] + box2[2] * box2[3] - intersection) def process_yolo_output(img, results): img_width = img.shape[1] img_height = img.shape[0] img_cp = img.copy() print_yolo_output(results) # draw bounding boxes on input image for i in range(len(results)): x = int(results[i][1]) y = int(results[i][2]) w = int(results[i][3]) // 2 h = int(results[i][4]) // 2 xmin = x - w xmax = x + w ymin = y - h ymax = y + h if xmin < 0: xmin = 0 if ymin < 0: ymin = 0 if xmax > img_width: xmax = img_width if ymax > img_height: ymax = img_height cv2.rectangle(img_cp, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2) cv2.rectangle(img_cp, (xmin, ymin - 20), (xmax, ymin), (125, 125, 125), -1) cv2.putText(img_cp,results[i][0] + ' : %.2f' % results[i][5], (xmin + 5, ymin - 7), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1) cv2.imwrite('/tmp/yolo_result.jpg', img_cp) def process_yolo_input(rgb_data): input_dim = (448, 448) tmp_data = rgb_data.copy() tmp_data = resize(tmp_data / 255.0, input_dim, 1) tmp_data[:, :, (2, 1, 0)] # BGR2RGB input_data = tmp_data.astype(np.float16) return input_data def print_yolo_output(output): for i in range(len(output)): x = int(output[i][1]) y = int(output[i][2]) #w = int(output[i][3]) // 2 #h = int(output[i][4]) // 2 print('\tclass = {label}'.format(label=output[i][0])) print('\t[x, y, w, h] = [{x}, {y}, {w}, {h}]'.format( x=str(x), y=str(y), w=str(int(output[i][3])), h=str(int(output[i][4])))) print('\tconfidence = {conf}'.format(conf=str(results[i][5]))) if __name__ == '__main__': if len(sys.argv) != 2: print ("YOLOv1 Tiny example: python3 py_examples/yolo_example.py images/dog.jpg") sys.exit() network_blob='/home/pi/codes/yoloNCS/graph' # configuration NCS mvnc.SetGlobalOption(mvnc.GlobalOption.LOG_LEVEL, 2) devices = mvnc.EnumerateDevices() if len(devices) == 0: print('No devices found') quit() device = mvnc.Device(devices[0]) device.OpenDevice() opt = device.GetDeviceOption(mvnc.DeviceOption.OPTIMISATION_LIST) # load blob with open(network_blob, mode='rb') as f: blob = f.read() graph = device.AllocateGraph(blob) graph.SetGraphOption(mvnc.GraphOption.ITERATIONS, 1) iterations = graph.GetGraphOption(mvnc.GraphOption.ITERATIONS) # image preprocess img = cv2.imread(sys.argv[1]) input_data = process_yolo_input(img) # start MOD start = datetime.now() graph.LoadTensor(input_data, 'user object') out, userobj = graph.GetResult() end = datetime.now() elapsedTime = end-start print('total time is " milliseconds', elapsedTime.total_seconds()*1000) # fc27 instead of fc12 for yolo_small results = interpret_yolo_output(out, img.shape[1], img.shape[0]) #print (results) #cv2.imshow('YOLO detection',img_cv) process_yolo_output(img, results) #cv2.waitKey(10000) graph.DeallocateGraph() device.CloseDevice() BerryNet-upstream-3.9.0/journal.js000066400000000000000000000041711360632137300171320ustar00rootroot00000000000000// Copyright 2017 DT42 // // This file is part of BerryNet. // // BerryNet is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // BerryNet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BerryNet. If not, see . 'use strict'; const fs = require('fs'); const moment = require('moment'); const mqtt = require('mqtt'); const config = require('./config'); const broker = config.brokerHost; const client = mqtt.connect(broker); const topicActionLog = config.topicActionLog; const topicNotifyEmail = config.topicNotifyEmail; const topicDashboardLog = config.topicDashboardLog; const topicDashboardSnapshot = config.topicDashboardSnapshot; const snapshot = config.snapshot; let logs = []; function log(m) { client.publish(topicActionLog, m); console.log(m); } function saveBufferToImage(b, filepath) { fs.writeFile(filepath, b, (e) => { if (e) log(`log client: cannot save buffer to image.`); else log(`log client: saved buffer to image successfully.`); }); } client.on('connect', () => { client.subscribe(topicActionLog); client.subscribe(topicNotifyEmail); log(`log client: connected to ${broker} successfully.`); }); client.on('message', (t, m) => { // secretly save a copy of the image if (t === topicNotifyEmail) { const filename = 'snapshot.jpg'; saveBufferToImage(m, snapshot); client.publish(topicDashboardSnapshot, filename); return; } // less stackoverflowy if (String(m).match(/^log/)) return; const now = moment().format('YYYY-MM-DD HH:mm:ss'); logs.push(`[${now}] ` + m); if (logs.length > 10) logs.unshift(); client.publish(topicDashboardLog, [].concat(logs).reverse().join('
')); }); BerryNet-upstream-3.9.0/line.js000066400000000000000000000053511360632137300164100ustar00rootroot00000000000000// Copyright 2017 DT42 // // This file is part of BerryNet. // // BerryNet is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // BerryNet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BerryNet. If not, see . 'use strict'; const mqtt = require('mqtt'); const line = require('@line/bot-sdk'); const imgur = require('imgur'); const config = require('./config'); const broker = config.brokerHost; const client = mqtt.connect(broker); const topicActionLog = config.topicActionLog; const topicNotifyLINE = config.topicNotifyLINE; const topicDashboardInferenceResult = config.topicDashboardInferenceResult; const targetUserID = config.LINETargetUserID; // create LINE SDK config const LINEConfig = { channelAccessToken: config.LINEChannelAccessToken, channelSecret: config.LINEChannelSecret, }; // create LINE SDK client const LINEClient = new line.Client(LINEConfig); function log(m) { client.publish(topicActionLog, m); console.log(m); } client.on('connect', () => { client.subscribe(topicNotifyLINE); client.subscribe(topicDashboardInferenceResult); log(`client connected to ${broker} successfully.`); }); client.on('message', (t, m) => { const size = m.length; log(`client on topic ${t}, received ${size} bytes.`) if (t === topicDashboardInferenceResult) { const result = m.toString(); LINEClient.pushMessage(targetUserID, { type: 'text', text: result }); return; } // save image to file and upload it to imgur for display in LINE message const snapshot_path = m.toString(); imgur.uploadFile(snapshot_path) .then((json) => { var imgurLink = json.data.link; imgurLink = imgurLink.replace('http:\/\/', 'https:\/\/'); log(`An image has been uploaded to imgur. link: ${imgurLink}`); // Image can only be delivered via 'https://' URL, 'http://' doesn't work LINEClient.pushMessage(targetUserID, { type: 'image', originalContentUrl: imgurLink, previewImageUrl: imgurLink }) .then((v) => { log(`A message sent to ${targetUserID} successfully.`); }) .catch((err) => { log(`An error occurred, ${err}.`); }); }) .catch((err) => { log(`An error occurred. ${err}`); }); }); BerryNet-upstream-3.9.0/linev3.js000066400000000000000000000066541360632137300166700ustar00rootroot00000000000000// Copyright 2017 DT42 Inc. // // This file is part of BerryNet. // // BerryNet is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // BerryNet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BerryNet. If not, see . 'use strict'; const mqtt = require('mqtt'); const line = require('@line/bot-sdk'); const imgur = require('imgur'); const config = require('./config'); const broker = config.brokerHost; const client = mqtt.connect(broker); const topicActionLog = config.topicActionLog; const topicInferenceResult = 'berrynet/engine/darknet/result' //const topicInferenceResult = 'berrynet/data/rgbimage' const targetUserID = config.LINETargetUserID; // create LINE SDK config const LINEConfig = { channelAccessToken: config.LINEChannelAccessToken, channelSecret: config.LINEChannelSecret, }; // create LINE SDK client const LINEClient = new line.Client(LINEConfig); function log(m) { client.publish(topicActionLog, m) console.log(m) } /** * Debugging utility to display inference result content. * * @param {Object} result Inference result in JSON format */ function debugPrintInferenceResult(result) { // modify result will cause side effect because of calling by reference const b64str = result["bytes"] delete result["bytes"] result["annotations"] = { "type": "detection", "label": "dog", "confidence": 0.95, "left": 10, "top": 10, "right": 50, "bottom": 50 } console.log(result) result["bytes"] = b64str } /** * Send text and image in the inference result to LINE client. * * @param {Object} result Inference result in JSON format */ function notifyLine(result) { //debugPrintInferenceResult(result) // Send base64-encoded image in result imgur.uploadBase64(result["bytes"]) .then((json) => { var imgurLink = json.data.link; imgurLink = imgurLink.replace('http:\/\/', 'https:\/\/') log(`An image has been uploaded to imgur. link: ${imgurLink}`) // Image can only be delivered via 'https://' URL, 'http://' doesn't work LINEClient.pushMessage(targetUserID, { type: 'image', originalContentUrl: imgurLink, previewImageUrl: imgurLink }) .then((v) => { log(`A message sent to ${targetUserID} successfully.`) }) .catch((err) => { log(`An error occurred, ${err}.`) }); }) .catch((err) => { log(`An error occurred. ${err}`) }) // Send annotations in result LINEClient.pushMessage(targetUserID, { type: 'text', text: JSON.stringify(result["annotations"]) }) } client.on('connect', () => { client.subscribe(topicInferenceResult) log(`client connected to ${broker} successfully.`) }) client.on('message', (t, m) => { const size = m.length log(`client on topic ${t}, received ${size} bytes.`) notifyLine(JSON.parse(m.toString())) }) BerryNet-upstream-3.9.0/localimg.js000066400000000000000000000036201360632137300172450ustar00rootroot00000000000000// Copyright 2017 DT42 // // This file is part of BerryNet. // // BerryNet is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // BerryNet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BerryNet. If not, see . // Read a local image and send it to inference server. // // subscribe // dt42/localimg // publish // dt42/inference // dt42/log // // $ node localimg.js // $ mosquitto_pub -h localhost -t dt42/localimg -m 'use strict'; const mqtt = require('mqtt'); const fs = require('fs'); const config = require('./config'); const broker = config.brokerHost; const client = mqtt.connect(broker); const topicEventLocalImage = config.topicEventLocalImage; const topicActionLog = config.topicActionLog; const topicActionInference = config.topicActionInference; function log(m) { client.publish(topicActionLog, m); console.log(m); } client.on('connect', () => { client.subscribe(topicEventLocalImage); log(`localimg client: connected to ${broker} successfully.`); }); client.on('message', (t, m) => { log(`camera client: on topic ${t}, received message ${m}.`); const imgurl = m.toString(); // Take a local image as snapshot. The snapshot will be displayed // on dashboard. fs.readFile(imgurl, function(err, data) { if (err) { log('localimg client: cannot get image.'); } else { log('localimg client: publishing image.'); client.publish(topicActionInference, data); } }); }); BerryNet-upstream-3.9.0/mail.js000066400000000000000000000042561360632137300164060ustar00rootroot00000000000000// Copyright 2017 DT42 // // This file is part of BerryNet. // // BerryNet is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // BerryNet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with BerryNet. If not, see . // Usage: // ./mail.js // This app assumes the user uses gmail. // You may need to configure "Allow Less Secure Apps" in your Gmail account. 'use strict'; const assert = require('assert'); const emailjs = require('emailjs'); const moment = require('moment'); const mqtt = require('mqtt'); assert(process.argv.length == 5); const broker = 'mqtt://localhost'; const client = mqtt.connect(broker); const mail_topic = 'dt42/mail'; const log_topic = 'dt42/log'; const args = process.argv.slice(2); const account = args[0]; const password = args[1]; const recipient = args[2]; function log(m) { client.publish(log_topic, m); console.log(m); } const server = emailjs.server.connect({ user: `${account}`, password: password, host: 'smtp.gmail.com', ssl: true, }); client.on('connect', () => { client.subscribe(mail_topic); log(`mail client: connected to ${broker} successfully.`); }); client.on('message', (t, m) => { const size = m.length; log(`mail client: on topic ${t}, received ${size} bytes.`) const now = moment().format('YYYY-MM-DD-HH-mm-ss'); server.send({ from: `<${account}>`, to: `<${recipient}>`, subject: `DT42 MQTT Snapshot at ${now}`, text: ' ', attachment: [{ name: 'snapshot.jpg', data: m, }], }, (e, m) => { if (e) { log(`mail client: an error occurred, ${e}.`); return; } if (m) log(`mail client: mail sent to ${recipient} successfully.`); }); }); BerryNet-upstream-3.9.0/package.json000066400000000000000000000011101360632137300173760ustar00rootroot00000000000000{ "name": "BerryNet", "version": "2.0.0", "description": "Deep learning gateway on Raspberry Pi", "main": "index.js", "author": "DT42", "license": "GPLv3", "dependencies": { "ascoltatori": "^3.1.0", "emailjs": "^1.0.8", "@line/bot-sdk": "^1.0.0", "imgur": "^0.2.1", "imagemagick": "^0.1.3", "mocha": "^3.2.0", "mosca": "^2.2.0", "mqtt": "^2.0.1", "opencv": "^6.0.0", "pino": "^2.13.0", "prompt": "^1.0.0", "request": "^2.79.0" }, "devDependencies": { "eslint": "^6.5.1", "eslint-config-google": "^0.7.1" } } BerryNet-upstream-3.9.0/patch/000077500000000000000000000000001360632137300162165ustar00rootroot00000000000000BerryNet-upstream-3.9.0/patch/01-detection-backend.patch000066400000000000000000000163451360632137300230310ustar00rootroot00000000000000diff --git a/Makefile b/Makefile index 7ba6b25..31950ce 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ GPU=0 CUDNN=0 -OPENCV=0 +OPENCV=1 NNPACK=1 ARM_NEON=1 DEBUG=0 diff --git a/examples/coco.c b/examples/coco.c index a07906e..170af71 100644 --- a/examples/coco.c +++ b/examples/coco.c @@ -342,7 +342,7 @@ void test_coco(char *cfgfile, char *weightfile, char *filename, float thresh) printf("%s: Predicted in %f seconds.\n", input, sec(clock()-time)); get_detection_boxes(l, 1, 1, thresh, probs, boxes, 0); if (nms) do_nms_sort(boxes, probs, l.side*l.side*l.n, l.classes, nms); - draw_detections(im, l.side*l.side*l.n, thresh, boxes, probs, coco_classes, alphabet, 80); + draw_detections(im, l.side*l.side*l.n, thresh, boxes, probs, coco_classes, alphabet, 80, 0); save_image(im, "prediction"); show_image(im, "predictions"); free_image(im); diff --git a/examples/detector.c b/examples/detector.c index 3c4a107..f2de3cc 100644 --- a/examples/detector.c +++ b/examples/detector.c @@ -581,6 +581,9 @@ void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filenam list *options = read_data_cfg(datacfg); char *name_list = option_find_str(options, "names", "data/names.list"); char **names = get_labels(name_list); + char done[256]; + FILE *done_signal = NULL; + memset(done, 0, 256); image **alphabet = load_alphabet(); network net = parse_network_cfg(cfgfile); @@ -621,6 +624,7 @@ void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filenam //resize_network(&net, sized.w, sized.h); #endif layer l = net.layers[net.n-1]; + sprintf(done, "%s.txt.done", input); box *boxes = calloc(l.w*l.h*l.n, sizeof(box)); float **probs = calloc(l.w*l.h*l.n, sizeof(float *)); @@ -634,7 +638,7 @@ void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filenam get_region_boxes(l, im.w, im.h, net.w, net.h, thresh, probs, boxes, 0, 0, hier_thresh, 1); if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); //else if (nms) do_nms_sort(boxes, probs, l.w*l.h*l.n, l.classes, nms); - draw_detections(im, l.w*l.h*l.n, thresh, boxes, probs, names, alphabet, l.classes); + draw_detections(im, l.w*l.h*l.n, thresh, boxes, probs, names, alphabet, l.classes, input); if(outfile){ save_image(im, outfile); } @@ -650,11 +654,13 @@ void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filenam cvDestroyAllWindows(); #endif } + done_signal = fopen(done, "w"); free_image(im); free_image(sized); free(boxes); free_ptrs((void **)probs, l.w*l.h*l.n); + fclose(done_signal); if (filename) break; } #ifdef NNPACK diff --git a/examples/yolo.c b/examples/yolo.c index 5b3fd16..9e74736 100644 --- a/examples/yolo.c +++ b/examples/yolo.c @@ -309,7 +309,7 @@ void test_yolo(char *cfgfile, char *weightfile, char *filename, float thresh) get_detection_boxes(l, 1, 1, thresh, probs, boxes, 0); if (nms) do_nms_sort(boxes, probs, l.side*l.side*l.n, l.classes, nms); //draw_detections(im, l.side*l.side*l.n, thresh, boxes, probs, voc_names, alphabet, 20); - draw_detections(im, l.side*l.side*l.n, thresh, boxes, probs, voc_names, alphabet, 20); + draw_detections(im, l.side*l.side*l.n, thresh, boxes, probs, voc_names, alphabet, 20, 0); save_image(im, "predictions"); show_image(im, "predictions"); diff --git a/include/darknet.h b/include/darknet.h index b6b9402..2de7cc0 100644 --- a/include/darknet.h +++ b/include/darknet.h @@ -695,7 +695,7 @@ float box_iou(box a, box b); void do_nms(box *boxes, float **probs, int total, int classes, float thresh); data load_all_cifar10(); box_label *read_boxes(char *filename, int *n); -void draw_detections(image im, int num, float thresh, box *boxes, float **probs, char **names, image **labels, int classes); +void draw_detections(image im, int num, float thresh, box *boxes, float **probs, char **names, image **labels, int classes, char* result_file); matrix network_predict_data(network net, data test); image **load_alphabet(); diff --git a/src/demo.c b/src/demo.c index 9dc4946..0030d0d 100644 --- a/src/demo.c +++ b/src/demo.c @@ -77,7 +77,7 @@ void *detect_in_thread(void *ptr) printf("\nFPS:%.1f\n",fps); printf("Objects:\n\n"); image display = buff[(buff_index+2) % 3]; - draw_detections(display, demo_detections, demo_thresh, boxes, probs, demo_names, demo_alphabet, demo_classes); + draw_detections(display, demo_detections, demo_thresh, boxes, probs, demo_names, demo_alphabet, demo_classes, 0); demo_index = (demo_index + 1)%demo_frame; running = 0; diff --git a/src/image.c b/src/image.c index 83ed382..c1b5b2a 100644 --- a/src/image.c +++ b/src/image.c @@ -190,24 +190,33 @@ image **load_alphabet() return alphabets; } -void draw_detections(image im, int num, float thresh, box *boxes, float **probs, char **names, image **alphabet, int classes) +void draw_detections(image im, int num, float thresh, box *boxes, float **probs, char **names, image **alphabet, int classes, char* result_file) { int i; - + FILE *predict_result = NULL; + char result_txt[256]; + memset(result_txt, 0, 256); + if (result_file != NULL) { + sprintf(result_txt, "%s.txt", result_file); + predict_result = fopen(result_txt, "wa"); + if (!predict_result) { + printf("%s: Predict result file opened error\n", result_txt); + return; + } + } for(i = 0; i < num; ++i){ int class = max_index(probs[i], classes); float prob = probs[i][class]; if(prob > thresh){ - int width = im.h * .006; + int width = im.h * .012; if(0){ width = pow(prob, 1./2.)*10+1; alphabet = 0; } - //printf("%d %s: %.0f%%\n", i, names[class], prob*100); - printf("%s: %.0f%%\n", names[class], prob*100); + printf("%s %.0f%%\n", names[class], prob*100); int offset = class*123457 % classes; float red = get_color(2,offset,classes); float green = get_color(1,offset,classes); @@ -232,6 +241,12 @@ void draw_detections(image im, int num, float thresh, box *boxes, float **probs, if(bot > im.h-1) bot = im.h-1; draw_box_width(im, left, top, right, bot, width, red, green, blue); + // output: label, accuracy, x, y, width, height + if (predict_result) + fprintf(predict_result, "%s %.2f %d %d %d %d\n", + names[class], prob, left, top, right - left, bot - top); + printf("%s %.2f %d %d %d %d\n", + names[class], prob, left, top, right - left, bot - top); if (alphabet) { image label = get_label(alphabet, names[class], (im.h*.03)/10); draw_label(im, top + width, left, label, rgb); @@ -239,6 +254,8 @@ void draw_detections(image im, int num, float thresh, box *boxes, float **probs, } } } + if (predict_result) + fclose(predict_result); } void transpose_image(image im) BerryNet-upstream-3.9.0/patch/darkflow/000077500000000000000000000000001360632137300200275ustar00rootroot00000000000000BerryNet-upstream-3.9.0/patch/darkflow/darkflow-app-example.patch000066400000000000000000000012611360632137300250700ustar00rootroot00000000000000diff --git a/darkflow/net/flow.py b/darkflow/net/flow.py index a5b8ceb..bb60704 100644 --- a/darkflow/net/flow.py +++ b/darkflow/net/flow.py @@ -90,7 +90,8 @@ def return_predict(self, im): "y": tmpBox[2]}, "bottomright": { "x": tmpBox[1], - "y": tmpBox[3]} + "y": tmpBox[3]}, + "coloridx": tmpBox[5] }) return boxesInfo @@ -142,4 +143,4 @@ def predict(self): # Timing self.say('Total time = {}s / {} inps = {} ips'.format( - last, len(inp_feed), len(inp_feed) / last)) \ No newline at end of file + last, len(inp_feed), len(inp_feed) / last)) BerryNet-upstream-3.9.0/patch/ui-berrynet-theme.patch000066400000000000000000000025671360632137300226160ustar00rootroot00000000000000diff --git a/index.html b/index.html index b5877e9..196aaba 100755 --- a/index.html +++ b/index.html @@ -8,9 +8,12 @@ +