pax_global_header00006660000000000000000000000064140076625260014522gustar00rootroot0000000000000052 comment=7079e49418b1ef0a55764762699140451c5a13fa BerryNet-3.10.2/000077500000000000000000000000001400766252600133375ustar00rootroot00000000000000BerryNet-3.10.2/.eslintrc.yaml000066400000000000000000000001351400766252600161230ustar00rootroot00000000000000env: node: true es6: true extends: google rules: comma-dangle: [2, only-multiline] BerryNet-3.10.2/.github/000077500000000000000000000000001400766252600146775ustar00rootroot00000000000000BerryNet-3.10.2/.github/FUNDING.yml000066400000000000000000000013571400766252600165220ustar00rootroot00000000000000# 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-3.10.2/.github/ISSUE_TEMPLATE/000077500000000000000000000000001400766252600170625ustar00rootroot00000000000000BerryNet-3.10.2/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000011461400766252600215560ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve title: "[Bug Report] " labels: '' assignees: '' --- **Description** A clear and concise description of what the bug is. **Steps to Reproduce** 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** * Expected: A clear and concise description of what you expected to happen. * Actual: A clear and concise description of what actually happened. **Logs** If applicable, add logs or screenshots to help explain your problem. **Environment** * BerryNet: [e.g. v0.6.2, beta2, etc.] * OS: [e.g. Ubuntu 20.04] BerryNet-3.10.2/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000007671400766252600226210ustar00rootroot00000000000000--- name: Feature request about: Create a new Feature request to help the project become better. title: "[FR] " labels: '' assignees: '' --- **Concept** If we provide [Feature] **Reason/Hypothesis** We can help [who] to [Benefit] or solve [Problem] because we know [who] are [Fact about our target]. **More Description (if any)** Put more description here to support the concept **Suggested Implementation (if any)** Put some suggested implementation here if you already have some ideas in mind BerryNet-3.10.2/.github/workflows/000077500000000000000000000000001400766252600167345ustar00rootroot00000000000000BerryNet-3.10.2/.github/workflows/docker.yml000066400000000000000000000043301400766252600207260ustar00rootroot00000000000000name: Docker Image CI on: push: branches: - "*" pull_request: branches: - master env: RC_NAME: dt42/berrynet jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@master # need to set dockerhub password in GitHub secrets # - name: Login to docker hub # uses: actions-hub/docker/login@master # env: # DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} # DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} # - name: Pull cache # run: | # docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} # docker pull ${RC_NAME}:cache - name: Build image if: always() run: | docker build --cache-from ${RC_NAME}:cache -t ${RC_NAME} -f docker/Dockerfile . docker tag ${RC_NAME} ${RC_NAME}:${GITHUB_SHA} docker tag ${RC_NAME} ${RC_NAME}:cache # need to set dockerhub password in GitHub secrets # - name: Push to docker registry # uses: actions-hub/docker@master # if: (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/prod') && success() # with: # args: push ${RC_NAME}:${GITHUB_SHA} # - name: Push Cache to docker registry # uses: actions-hub/docker@master # if: always() # with: # args: push ${RC_NAME}:cache test: env: POETRY_VIRTUALENVS_CREATE: false runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.7 uses: actions/setup-python@v1 with: python-version: 3.7 - name: Install dependencies run: | python3 -m pip install --upgrade pip pip install poetry poetry install python3 setup.py install - name: Download inception models run: | wget "https://storage.googleapis.com/download.tensorflow.org/models/inception_v3_2016_08_28_frozen.pb.tar.gz" -O berrynet/engine/inception_v3_2016_08_28_frozen.pb.tar.gz tar -zxvf berrynet/engine/inception_v3_2016_08_28_frozen.pb.tar.gz -C berrynet/engine - name: Test with pytest run: | python3 -m unittest BerryNet-3.10.2/.github/workflows/main.yml000066400000000000000000000036271400766252600204130ustar00rootroot00000000000000name: CI on: release: types: [published] jobs: build: runs-on: ubuntu-latest steps: - name: Checkout source uses: actions/checkout@v2 - name: Build Debian Package run: | echo Add other actions to build, echo test, and deploy your project. echo GITHUB_SHA is $GITHUB_SHA echo GITHUB_REF is $GITHUB_REF sudo apt-get -y update sudo apt-get -y install git-buildpackage sudo apt-get -y install build-essential devscripts sudo apt-get -y install lsb-release sudo apt-get -y install debhelper dh-apache2 dh-python git python3 python3-setuptools sudo apt-get -y install pristine-tar sudo apt-get -y install p7zip-full lsb_release -a curl -sL https://raw.githubusercontent.com/DT42/BerryNet-repo/master/setup.sh | sudo -E bash sudo apt-get -y install freeboard git remote add github1 https://github.com/grandpaul/BerryNet.git git remote update git branch -a git checkout github1/upstream -b upstream git checkout github1/pristine-tar -b pristine-tar git checkout github1/debian/sid -b debian/sid echo gbp buildpackage --no-sign OLDPWD=`pwd` echo OLDPWD is $OLDPWD sleep 30; uscan --verbose VER1=`ls ../berrynet_*.orig.tar.gz | sed 's/.*berrynet_//' | sed 's/.orig.tar.gz//'` echo VER1 is $VER1 cd ../berrynet-$VER1; debuild --no-sign; cd $OLDPWD ls .. 7z a -snl debpackage.7z ../*.dsc ../*.debian.tar.xz ../*.orig.tar.gz ../*.deb ../*.changes ../*.build ../*.buildinfo ../berrynet-*.tar.gz - name: Upload to release uses: JasonEtco/upload-to-release@master with: args: debpackage.7z application/x-7z-compressed env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} BerryNet-3.10.2/.gitignore000066400000000000000000000002351400766252600153270ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__ *.pyc # Distribution / packaging build dist *.egg-info # Environments env venv .vscode # Others *.swp BerryNet-3.10.2/.gitlab-ci.yml000066400000000000000000000033311400766252600157730ustar00rootroot00000000000000# 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-3.10.2/.gitmodules000066400000000000000000000001531400766252600155130ustar00rootroot00000000000000[submodule "inference/darkflow"] path = inference/darkflow url = https://github.com/thtrieu/darkflow.git BerryNet-3.10.2/AUTHORS000066400000000000000000000005541400766252600144130ustar00rootroot00000000000000# 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-3.10.2/BACKERS.md000066400000000000000000000011161400766252600147320ustar00rootroot00000000000000

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-3.10.2/CONTRIBUTING.md000066400000000000000000000003041400766252600155650ustar00rootroot00000000000000We 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-3.10.2/LICENSE.txt000066400000000000000000001045131400766252600151660ustar00rootroot00000000000000 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-3.10.2/README.md000066400000000000000000000210621400766252600146170ustar00rootroot00000000000000

BerryNet Logo

Deep Learning Gateway on Raspberry Pi And Other Edge Devices

![Docker Image CI](https://github.com/DT42/BerryNet/workflows/Docker%20Image%20CI/badge.svg) [Supporting BerryNet](community/donation) * [Become a backer or sponsor on Open Collective](https://opencollective.com/berrynet). * [One-time donation via PayPal or crypto-currencies](community/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 [installation guide](https://dt42.io/berrynet-doc/tutorials/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 RPi (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 [Slack](https://join.slack.com/t/berrynet/shared_invite/enQtODg5MjA0ODExMjUzLWIwMDNkZWExZGE2Njc1ZDljMmFiOWJlZDdmZmEwYmQ4YTJiNzg2NDc1NTJhMDVkMzhmNzA3YTU0ZTc4M2JiNTE) or [Telegram Group](https://t.me/berrynetdev) for questions, suggestions, or any idea discussion. BerryNet-3.10.2/berrynet-manager000077500000000000000000000034121400766252600165270ustar00rootroot00000000000000#! /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-3.10.2/berrynet/000077500000000000000000000000001400766252600151715ustar00rootroot00000000000000BerryNet-3.10.2/berrynet/__init__.py000066400000000000000000000005141400766252600173020ustar00rootroot00000000000000import 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-3.10.2/berrynet/bndyda/000077500000000000000000000000001400766252600164325ustar00rootroot00000000000000BerryNet-3.10.2/berrynet/bndyda/__init__.py000066400000000000000000000000001400766252600205310ustar00rootroot00000000000000BerryNet-3.10.2/berrynet/bndyda/bnpipeline.py000066400000000000000000000414141400766252600211350ustar00rootroot00000000000000# 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 . """Pipeline service with relay engine (default engine). """ import cv2 import argparse import json import logging import os import sys import time from datetime import datetime import numpy as np from berrynet import logger from berrynet.bndyda.launcher_berrynet import BerryNetPipelineLauncher from berrynet.comm import payload from berrynet.engine import DLEngine from berrynet.service import EngineService from dyda_utils import tools class PipelineEngine(DLEngine): def __init__(self, config, dyda_config_path='', warmup_size=(480, 640, 3), disable_warmup=False, benchmark=False, verbosity=0): self.launcher = BerryNetPipelineLauncher( config, dyda_config_path=dyda_config_path, verbosity=verbosity, benchmark=benchmark) self.pipeline_config = tools.parse_json(config) if not disable_warmup: self.warmup(shape=warmup_size) # def process_input(self, tensor): # return tensor def inference(self, tensor, meta={}, base_name=None): """ Args: tensor: Image data in BGR format (numpy array) Returns: Dictionary following generic inference spec and pipeline spec (by project). """ return self.launcher.run(tensor, meta=meta, base_name=base_name) # return { # 'annotations': { # 'label': 'dt42', # 'confidence': 0.99 # } # } def process_output(self, output): return output def get_dl_component_config(self, pipeline_config): """Get pipeline def list containing only DL components Args: pipeline_config: pipeline config JSON object Returns: List of DL components definitions """ dl_comp_config = [] try: pipeline_def = pipeline_config['pipeline_def'] except KeyError: logger.warning('Invalid pipeline config') pipeline_def = [] for comp_config in pipeline_def: if ('classifier' in comp_config['name'] or 'detector' in comp_config['name']): dl_comp_config.append(comp_config) return dl_comp_config def warmup(self, shape=(480, 640, 3), iteration=5): """Warmup pipeline engine Use all-zero numpy array as input to warmup pipeline engine. Args: meta: Metadata of image data shape: Warmup image shape in (w, h, c) format iteration: How many times to feed in warmup image Returns: N/A """ logger.debug('Warmup shape: {}'.format(shape)) input_data = [np.zeros(shape=shape, dtype=np.uint8)] * iteration # FIXME: get engines programatically dl_comp_config = self.get_dl_component_config(self.pipeline_config) for comp_config in dl_comp_config: t_start = time.time() comp_name = comp_config['name'] inst = self.launcher.pipeline.pipeline[comp_name]['instance'] inst.input_data = input_data inst.main_process() t_duration = time.time() - t_start logger.debug('Warmup {0} costs {1} sec'.format(comp_name, t_duration)) def duration(t): return (datetime.now() - t).microseconds / 1000 class PipelineDummyEngine(DLEngine): def inference(self, tensor, meta={}): output = None return output class PipelineService(EngineService): def __init__(self, service_name, engine, comm_config, pid=None, pipeline_config_path=None, disable_engine=False, disable_warmup=False, warmup_size=(480, 640, 3)): super().__init__(service_name, engine, comm_config) self.pipeline_config_path = pipeline_config_path self.dyda_config_path = '' self.warmup_size = warmup_size self.disable_engine = disable_engine if not os.path.exists('/tmp/dlbox-pipeline'): os.mkdir('/tmp/dlbox-pipeline') self.counter = 0 self.pid = pid logger.debug('Pipeline result topic: berrynet/engine/pipeline/result') def inference(self, pl): logger.debug('Disable engine: {}'.format(self.disable_engine)) if self.disable_engine: self.dummy_inference(pl) else: self.dl_inference(pl) def dl_inference(self, pl): def empty_inference_result(count): return [ { 'channel': i, 'annotations': [] } for i in range(count)] t = datetime.now() base_name = None logger.debug('counter #{}'.format(self.counter)) logger.debug('payload size: {}'.format(len(pl))) logger.debug('payload type: {}'.format(type(pl))) # Unify the type of input payload to a list, so that # bnpipeline can process the input in the same way. # # If the payload is # - a list of items: keep the list # - a single item: convert to a list with an item mqtt_payload = payload.deserialize_payload(pl.decode('utf-8')) if isinstance(mqtt_payload, list): jpg_json = mqtt_payload else: jpg_json = [mqtt_payload] logger.info('Convert input type from {0} to {1}'.format( type(mqtt_payload), type(jpg_json))) jpg_bytes_list = [ payload.destringify_jpg(img['bytes']) for img in jpg_json] metas = [img.get('meta', {}) for img in jpg_json] logger.debug('destringify_jpg: {} ms'.format(duration(t))) t = datetime.now() bgr_arrays = [ payload.jpg2bgr(jpg_bytes) for jpg_bytes in jpg_bytes_list] logger.debug('jpg2bgr: {} ms'.format(duration(t))) t = datetime.now() # FIXME: Galaxy pipeline may or may not use a list as input, so we # check the length here and then choose whether to send a list or not. # We may drop it when Galaxy Pipline unite their input. if len(bgr_arrays) > 1: image_data = self.engine.process_input(bgr_arrays) else: image_data = self.engine.process_input(bgr_arrays[0]) # FIXME: Galaxy pipeline doesn't support multiple metadata for multiple # images at the moment (which will be needed), so we provide the first # metadata here. This commit should be revert when Galaxy pipeline # support it: https://gitlab.com/DT42/galaxy42/dt42-trainer/issues/120 meta_data = metas[0] try: logger.debug(meta_data) output = self.engine.inference(image_data, meta=meta_data, base_name=base_name) model_outputs = self.engine.process_output(output) except IndexError as e: # FIXME: workaround for pipeline # Pipeline throw IndexError when there's no results, see: # https://gitlab.com/DT42/galaxy42/dt42-trainer/issues/86 # So we catch the exeception, and produce a dummy result # to hook. This workaround should be removed after the issue # has been fixed. model_outputs = empty_inference_result(len(jpg_json)) logger.warning(('inference results are empty because ' 'pipeline raised IndexError')) if model_outputs is None: model_outputs = empty_inference_result(len(jpg_json)) logger.warning(('inference results are empty because ' 'severe error happened in pipeline')) 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.send_result(self.generalize_result(jpg_json, model_outputs)) self.counter += 1 def dummy_inference(self, pl): logger.debug('dummy_inference is called') def switch_mode(self, pl): """Switch pipeline service between inference and non-inference modes If Pipeline service receives berrynet/data/mode topic with "inference" in payload, service will switch to inference mode; If "idle" or "learning" in payload, service will switch to non-inference mode. Pipeline service will create pipeline engine and listen to specified topics only in inference mode. Args: pl: MQTT message payload valid value: {'inference', 'idle', 'learning'} Returns: N/A """ mode = pl.decode('utf-8') if mode == 'inference': self.disable_engine = False self.engine = PipelineEngine( self.pipeline_config_path, dyda_config_path=self.dyda_config_path, disable_warmup=self.disable_warmup, warmup_size=self.warmup_size) else: self.disable_engine = True self.engine = PipelineDummyEngine() def deploy(self, pl): """Deploy newly retrained model for pipeline engine New dyda config filepath is in the payload. Args: pl: MQTT message payload w/ new dyda config filepath. Returns: N/A """ dyda_config_path = pl.decode('utf-8') self.dyda_config_path = dyda_config_path self.comm.send('berrynet/data/deployed', '') logger.info(('New model has been deployed, ' 'dyda config: {}'.format(self.dyda_config_path))) def generalize_result(self, eng_input, eng_output): # Pipeline returns None if any error happened if eng_output is None: eng_output = {} # If pipeline generate multiple outputs simultaneously # # In this case, the format of engine output is # # { # 'annotations': {...}, # 'bytes': '...' # } if all(key in eng_output.keys() for key in ['annotations', 'bytes']): logger.debug('Pipeline output type: multiple') logger.debug('eng_input type = {0}, len = {1}'.format(type(eng_input), len(eng_input))) # FIXME: Re-cap why eng_input is a list and only contains 1 item. eng_input = eng_input[0] try: eng_input['annotations'] = eng_output['annotations'] logger.debug('output image type: {0}, len: {1}'.format(type(eng_output['bytes']), len(eng_output['bytes']))) pipeline_img = eng_output['bytes'][0] retval, jpg_bytes = cv2.imencode('.jpg', pipeline_img) eng_input['bytes'] = payload.stringify_jpg(jpg_bytes) except Exception as e: logger.critical(e) else: logger.debug('Pipeline output type: simple') # FIXME: Workaround for spec incompatibility # DLBox spec use 'image_blob', but BerryNet use 'bytes', so we have to # do a convert here if isinstance(eng_output, list): inf_output = eng_output[0] else: inf_output = eng_output if len(eng_input) > 1: for i in range(len(eng_input)): try: retval, jpg_bytes = cv2.imencode('.jpg', inf_output) eng_input[i]['bytes'] = payload.stringify_jpg(jpg_bytes) #eng_input[i].pop('bytes') except Exception as e: print(e) else: try: eng_input, = eng_input retval, jpg_bytes = cv2.imencode('.jpg', inf_output) eng_input['bytes'] = payload.stringify_jpg(jpg_bytes) #eng_input.pop('bytes') except Exception as e: print(e) return eng_input def send_result(self, generalized_result): # NOTE: There are numpy float in pipeline output, so we use # tools.dump_json instead of payload.serialize_payload if self.pid is None: self.comm.send( 'berrynet/engine/pipeline/result', tools.dump_json(generalized_result)) else: self.comm.send( 'berrynet/engine/pipeline/result/{}'.format(self.pid), tools.dump_json(generalized_result)) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--pipeline-id', help=('Indicate pipeline ID which will be attached ' 'to result topic (optional)')) ap.add_argument('--pipeline-config', help='File contains the definition ' 'of pipeline application') ap.add_argument('--debug', action='store_true', help='Debug mode toggle') ap.add_argument('--benchmark', action='store_true', help='Benchmark mode toggle') ap.add_argument('--broker-ip', default='localhost', help='MQTT broker IP') ap.add_argument('--topic-config', default=None, help='Path of the MQTT topic subscription JSON.') ap.add_argument('--topic', nargs=2, action='append', default=None, help=('Two params in " " format. ' 'It can be declared multiple times.')) ap.add_argument('--disable-engine', action='store_true', help='Service disable engine initially') ap.add_argument('--disable-warmup', action='store_true', help='Skip warming up pipeline by black image') ap.add_argument('-v', '--verbosity', action='count', default=0, help='Output verbosity') ap.add_argument('-w', '--warmup-size', nargs=2, type=int, default=(640, 480), help='Warmup image\'s size, in format "w h", ' 'e.g., "640 480"') return vars(ap.parse_args()) def main(): # Process CLI arguments args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args['topic_config']: with open(args['topic_config']) as f: topic_config = json.load(f) else: topic_config = {} topic_config['berrynet/data/mode'] = 'self.switch_mode' topic_config['berrynet/data/deploy'] = 'self.deploy' if args['topic'] is not None: for t, h in args['topic']: topic_config[t] = h w, h = args['warmup_size'] # Setup pipeline service if args['disable_engine']: eng = PipelineDummyEngine() else: eng = PipelineEngine(args['pipeline_config'], disable_warmup=args['disable_warmup'], verbosity=args['verbosity'], benchmark=args['benchmark'], warmup_size=(h, w, 3)) comm_config = { 'subscribe': topic_config, 'broker': { 'address': args['broker_ip'], 'port': 1883 } } engine_service = PipelineService( 'pipeline service', eng, comm_config, pid=args['pipeline_id'], pipeline_config_path=args['pipeline_config'], disable_engine=args['disable_engine'], disable_warmup=args['disable_warmup'], warmup_size=(h, w, 3)) engine_service.run(args) if __name__ == '__main__': main() BerryNet-3.10.2/berrynet/bndyda/launcher_berrynet.py000066400000000000000000000116711400766252600225250ustar00rootroot00000000000000import argparse import json import logging from os.path import join as pjoin import cv2 from dyda.pipelines import pipeline as dydapl logger = logging.getLogger('launcher') class BerryNetPipelineLauncher(object): def __init__(self, config, dyda_config_path='', output_dirpath='', verbosity=0, benchmark=False, lab_flag=False): self.pipeline = dydapl.Pipeline( config, dyda_config_path=dyda_config_path, parent_result_folder=output_dirpath, verbosity=verbosity, lab_flag=lab_flag) self.benchmark = benchmark def run(self, bitmap, meta={}, base_name=None): """Run pipeline. Args: bitmap: Image data in BGR format (numpy array) Returns: Dictionary with contents or empty list. """ self.pipeline.run(bitmap, external_meta=meta, benchmark=self.benchmark, base_name=base_name) try: # You can get pipeline output(s) in two ways: # # 1. Simple (and single) output from pipeline.output. # - 100% available # - Data type is dynamic (it might be a JSON object, an image, etc.) # # 2. Multiple outputs from components defined in pipeline config. # - Currently it is used in the scenario that # you want to have JSON result and image simultaneously. # - final_json_output and final_img_output are component name, # not component types. We are considering to define them as standard. if all(key in self.pipeline.pipeline.keys() for key in ['final_json_output', 'final_img_output']): logger.debug('Pipeline output type: multiple (launcher_berrynet)') output = { 'annotations': self.pipeline.pipeline['final_json_output']['output']['annotations'], 'bytes': self.pipeline.pipeline['final_img_output']['output'] } else: logger.debug('Pipeline output type: simple (launcher_berrynet)') output = self.pipeline.output except Exception as e: logger.critical(e) return output def get_args(argv=None): """ Prepare auguments for running the script. """ parser = argparse.ArgumentParser( description='Pipeline.' ) parser.add_argument( '-i', '--input', type=str, default=( '/home/shared/customer_data/acti/201711-ACTi-A/' '20171207_recording/acti_2017-12-07-1701/frame'), help='Input folder for ') parser.add_argument( '-o', '--output', type=str, default='/home/shared/DT42/test_data/' 'test_auto_labeler_with_tracker/results/', help='Output folder for output_metadata') parser.add_argument( '--lab_flag', dest='lab_flag', action='store_true', default=False, help='True to enable related lab process.' ) parser.add_argument( '-p', '--pipeline_config', type=str, default='/home/lab/dyda/pipeline.config', help='File contains the definition of pipeline application.' ) parser.add_argument( '-t', '--dyda_config', type=str, default='', help='File contains the component definitions.' ) parser.add_argument( "-v", "--verbosity", action="count", default=0, help="increase output verbosity" ) return parser.parse_args(argv) def main(): """ Example for testing pipeline. """ args = get_args() log_level = logging.WARNING if args.verbosity == 1: log_level = logging.INFO elif args.verbosity >= 2: log_level = logging.DEBUG formatter = logging.Formatter('[launcher] %(levelname)s %(message)s') console = logging.StreamHandler() console.setFormatter(formatter) logger.setLevel(log_level) logger.addHandler(console) logger.debug('lab_flag is %r' % args.lab_flag) pipeline = BerryNetPipelineLauncher( config=args.pipeline_config, dyda_config_path=args.dyda_config, output_dirpath=args.output, verbosity=args.verbosity, lab_flag=args.lab_flag ) logger.debug('Running Reader and Selector for frames') source_dirpath = args.input input_number = 100 for i in range(input_number): input_data = pjoin(source_dirpath, '00000{}.png'.format(570 + i)) ext_data = cv2.imread(input_data) output_data = pipeline.run(ext_data) logger.debug('===== frame #{} ====='.format(i)) logger.debug('input: {}'.format(input_data)) if (len(output_data) > 0): with open('output_{}.json'.format(i), 'w') as f: json.dump(output_data, f, indent=4) if __name__ == "__main__": main() BerryNet-3.10.2/berrynet/bndyda/output_processor.py000066400000000000000000000052771400766252600224560ustar00rootroot00000000000000# 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 self.comm_config['subscribe']['berrynet/engine/mockup/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 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.' ) return vars(ap.parse_args()) def main(): args = parse_args() comm_config = { 'subscribe': {}, 'broker': { 'address': 'localhost', 'port': 1883 } } dc_service = DataCollectorService(comm_config, args['data_dirpath']) dc_service.run(args) if __name__ == '__main__': main() BerryNet-3.10.2/berrynet/bndyda/pipeline.py000066400000000000000000000365341400766252600206240ustar00rootroot00000000000000# 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 . """Pipeline service with relay engine (default engine). """ import argparse import json import logging import os import sys import time from datetime import datetime import paho.mqtt.publish as publish import activation.verify import numpy as np import cv2 from berrynet import logger from berrynet.comm import payload from berrynet.engine import DLEngine from berrynet.service import EngineService from dt42lab.core import tools from bntrainer.launcher_berrynet import BerryNetPipelineLauncher class PipelineEngine(DLEngine): def __init__(self, config, trainer_config_path='', warmup_size=(480, 640, 3), disable_warmup=False, benchmark=False, verbosity=0): self.launcher = BerryNetPipelineLauncher( config, trainer_config_path=trainer_config_path, verbosity=verbosity, benchmark=benchmark) self.pipeline_config = tools.parse_json(config) if not disable_warmup: self.warmup(shape=warmup_size) # def process_input(self, tensor): # return tensor def inference(self, tensor, meta={}, base_name=None): """ Args: tensor: Image data in BGR format (numpy array) Returns: Dictionary following generic inference spec and pipeline spec (by project). """ return self.launcher.run(tensor, meta=meta, base_name=base_name) # return { # 'annotations': { # 'label': 'dt42', # 'confidence': 0.99 # } # } def process_output(self, output): return output def get_dl_component_config(self, pipeline_config): """Get pipeline def list containing only DL components Args: pipeline_config: pipeline config JSON object Returns: List of DL components definitions """ dl_comp_config = [] try: pipeline_def = pipeline_config['pipeline_def'] except KeyError: logger.warning('Invalid pipeline config') pipeline_def = [] for comp_config in pipeline_def: if ('classifier' in comp_config['name'] or 'detector' in comp_config['name']): dl_comp_config.append(comp_config) return dl_comp_config def warmup(self, shape=(480, 640, 3), iteration=5): """Warmup pipeline engine Use all-zero numpy array as input to warmup pipeline engine. Args: meta: Metadata of image data shape: Warmup image shape in (w, h, c) format iteration: How many times to feed in warmup image Returns: N/A """ logger.debug('Warmup shape: {}'.format(shape)) input_data = [np.zeros(shape=shape, dtype=np.uint8)] * iteration # FIXME: get engines programatically dl_comp_config = self.get_dl_component_config(self.pipeline_config) for comp_config in dl_comp_config: t_start = time.time() comp_name = comp_config['name'] inst = self.launcher.pipeline.pipeline[comp_name]['instance'] inst.input_data = input_data inst.main_process() t_duration = time.time() - t_start logger.debug('Warmup {0} costs {1} sec'.format(comp_name, t_duration)) def duration(t): return (datetime.now() - t).microseconds / 1000 class PipelineDummyEngine(DLEngine): def inference(self, tensor, meta={}): output = None return output class PipelineService(EngineService): def __init__(self, service_name, engine, comm_config, pipeline_config_path=None, disable_engine=False, disable_warmup=False, warmup_size=(480, 640, 3), output_broker_ip="localhost", output_mqtt_topic='berrynet/engine/pipeline/result'): super().__init__(service_name, engine, comm_config) self.pipeline_config_path = pipeline_config_path self.trainer_config_path = '' self.warmup_size = warmup_size self.disable_engine = disable_engine self.output_broker_ip = output_broker_ip self.output_mqtt_topic = output_mqtt_topic if not os.path.exists('/tmp/dlbox-pipeline'): os.mkdir('/tmp/dlbox-pipeline') self.counter = 0 logger.debug('Pipeline result topic: {}'.format( self.output_mqtt_topic)) def inference(self, pl): if self.disable_engine: self.dummy_inference(pl) else: self.dl_inference(pl) def dl_inference(self, pl): def empty_inference_result(count): return [ { 'channel': i, 'annotations': [] } for i in range(count)] t = datetime.now() base_name = None logger.debug('counter #{}'.format(self.counter)) 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_list = [ payload.destringify_jpg(img['bytes']) for img in jpg_json] metas = [img.get('meta', {}) for img in jpg_json] logger.debug('destringify_jpg: {} ms'.format(duration(t))) t = datetime.now() bgr_arrays = [ payload.jpg2bgr(jpg_bytes) for jpg_bytes in jpg_bytes_list] logger.debug('jpg2bgr: {} ms'.format(duration(t))) t = datetime.now() image_data = self.engine.process_input(bgr_arrays) # FIXME: Galaxy pipeline doesn't support multiple metadata for multiple # images at the moment (which will be needed), so we provide the first # metadata here. This commit should be revert when Galaxy pipeline # support it: https://gitlab.com/DT42/galaxy42/dt42-trainer/issues/120 meta_data = metas[0] try: logger.debug(meta_data) output = self.engine.inference(image_data, meta=meta_data, base_name=base_name) model_outputs = self.engine.process_output(output) except IndexError as e: # FIXME: workaround for pipeline # Pipeline throw IndexError when there's no results, see: # https://gitlab.com/DT42/galaxy42/dt42-trainer/issues/86 # So we catch the exeception, and produce a dummy result # to hook. This workaround should be removed after the issue # has been fixed. model_outputs = empty_inference_result(len(jpg_json)) logger.warning(('inference results are empty because ' 'pipeline raised IndexError')) if model_outputs is None: model_outputs = empty_inference_result(len(jpg_json)) logger.warning(('inference results are empty because ' 'severe error happened in pipeline')) if isinstance(model_outputs, dict): model_outputs = [model_outputs] 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.send_result(self.generalize_result(jpg_json, model_outputs), self.output_mqtt_topic) self.counter += 1 def dummy_inference(self, pl): logger.debug('dummy_inference is called') def switch_mode(self, pl): """Switch pipeline service between inference and non-inference modes If Pipeline service receives berrynet/data/mode topic with "inference" in payload, service will switch to inference mode; If "idle" or "learning" in payload, service will switch to non-inference mode. Pipeline service will create pipeline engine and listen to specified topics only in inference mode. Args: pl: MQTT message payload valid value: {'inference', 'idle', 'learning'} Returns: N/A """ mode = pl.decode('utf-8') if mode == 'inference': self.disable_engine = False else: self.disable_engine = True def deploy(self, pl): """Deploy newly retrained model for pipeline engine New trainer config filepath is in the payload. Args: pl: MQTT message payload w/ new trainer config filepath. Returns: N/A """ trainer_config_path = pl.decode('utf-8') self.trainer_config_path = trainer_config_path self.comm.send('berrynet/data/deployed', '') logger.info(('New model has been deployed, ' 'trainer config: {}'.format(self.trainer_config_path))) def generalize_result(self, eng_inputs, eng_outputs): # Pipeline returns None if any error happened if eng_outputs is None: eng_outputs = [{}] if len(eng_inputs) != len(eng_outputs): logger.warning('Input length != output length: {} != {}'.format( len(eng_inputs), len(eng_outputs))) # We guarantee len of inputs will always be 1 (at least now), so # it's safer to access eng_inputs by index than to eng_outputs c_id = int(eng_inputs[0]['meta']['channel_id']) eng_outputs = [eng_outputs[c_id]] # FIXME: Workaround for spec incompatibility # DLBox spec use 'image_blob', but BerryNet use 'bytes', so we have to # do a convert here for eng_in, eng_out in list(zip(eng_inputs, eng_outputs)): if isinstance(eng_out, np.ndarray): r, result_img = cv2.imencode('.jpg', eng_out) eng_in['bytes'] = payload.stringify_jpg(result_img) else: try: eng_in.update(eng_out) except KeyError as e: logger.exception( '{} ({}): {}'.format(e.__class__, e.__doc__, e)) eng_in['image_blob'] = eng_in.pop('bytes') return eng_inputs def send_result( self, generalized_result, topic='berrynet/engine/pipeline/result'): # NOTE: There are numpy float in pipeline output, so we use # tools.dump_json instead of payload.serialize_payload for r in generalized_result: try: c_id = r.get('channel', None) or r['meta']['channel_id'] topic += '/{}'.format(c_id) except KeyError: logger.warn( 'No channel id found, set topic to {}'.format(topic)) logger.debug('output topic: {}'.format(topic)) publish.single(topic, payload=tools.dump_json(generalized_result), hostname=self.output_broker_ip) def parse_args(): ap = argparse.ArgumentParser() ap.add_argument('--pipeline-config', help='File contains the definition ' 'of pipeline application') ap.add_argument('--debug', action='store_true', help='Debug mode toggle') ap.add_argument('--benchmark', action='store_true', help='Benchmark mode toggle') ap.add_argument('--broker-ip', '--input-broker-ip', default='localhost', help='MQTT broker IP') ap.add_argument('--output-broker-ip', default='localhost', help='Result output MQTT broker IP') ap.add_argument('--output-mqtt-topic', default='berrynet/engine/pipeline/result', help='Result output MQTT topic') ap.add_argument('--topic-config', default=None, help='Path of the MQTT topic subscription JSON.') ap.add_argument('--topic', nargs=2, action='append', default=None, help=('Two params in " " format. ' 'It can be declared multiple times.')) ap.add_argument('--disable-engine', action='store_true', help='Service disable engine initially') ap.add_argument('--disable-warmup', action='store_true', help='Skip warming up pipeline by black image') ap.add_argument('-v', '--verbosity', action='count', default=0, help='Output verbosity') ap.add_argument('-w', '--warmup-size', nargs=2, type=int, default=(640, 480), help='Warmup image\'s size, in format "w h", ' 'e.g., "640 480"') return vars(ap.parse_args()) def main(): result = activation.verify.check_license() if not result: sys.exit(1) # Process CLI arguments args = parse_args() if args['debug']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args['topic_config']: with open(args['topic_config']) as f: topic_config = json.load(f) else: topic_config = {} topic_config['berrynet/data/mode'] = 'self.switch_mode' topic_config['berrynet/data/deploy'] = 'self.deploy' if args['topic'] is not None: for t, h in args['topic']: topic_config[t] = h w, h = args['warmup_size'] # Setup pipeline service if args['disable_engine']: eng = PipelineDummyEngine() else: eng = PipelineEngine(args['pipeline_config'], disable_warmup=args['disable_warmup'], verbosity=args['verbosity'], benchmark=args['benchmark'], warmup_size=(h, w, 3)) comm_config = { 'subscribe': topic_config, 'broker': { 'address': args['broker_ip'], 'port': 1883 } } engine_service = PipelineService( 'pipeline service', eng, comm_config, pipeline_config_path=args['pipeline_config'], disable_engine=args['disable_engine'], disable_warmup=args['disable_warmup'], warmup_size=(h, w, 3), output_broker_ip=args['output_broker_ip'], output_mqtt_topic=args['output_mqtt_topic']) engine_service.run(args) if __name__ == '__main__': main() BerryNet-3.10.2/berrynet/bndyda/pipeline_restarter.py000066400000000000000000000042431400766252600227070ustar00rootroot00000000000000# 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 . """Pipeline service restarter. Restart pipeline service after received config update notification. """ import argparse import logging import subprocess from berrynet import logger from berrynet.comm import Communicator class PipelineRestarterService(object): def __init__(self, service_name, comm_config): self.service_name = service_name self.comm_config = comm_config self.comm_config['subscribe']['dlboxapi/config/update'] = \ self.restart_pipeline self.comm = Communicator(self.comm_config, debug=True) def restart_pipeline(self, pl): logger.debug('Restart pipeline') subprocess.call('dlbox-manager restart dlbox-pipeline.service', shell=True) def run(self, args): """Infinite loop serving pipeline restart requests""" self.comm.run() 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) comm_config = { 'subscribe': {}, 'broker': { 'address': 'localhost', 'port': 1883 } } engine_service = PipelineRestarterService( 'pipeline service restarter', comm_config) engine_service.run(args) if __name__ == '__main__': main() BerryNet-3.10.2/berrynet/bndyda/warmup.py000066400000000000000000000022671400766252600203260ustar00rootroot00000000000000#!/usr/bin/python3 """This script will block until the specified file appears or the timeout expires. The first argument is the timeout in seconds. The second argument is the filepath.""" import os import time import sys def logging(*args): """add a prefix to print() output""" print("wait_for_warmup:", ' '.join(args), flush=True) def wait_for_warmup(warmup_file, max_wait_sec): """wait for warmup_file to appear until max_wait_sec timeout""" counter = 0 msg = warmup_file while True: if os.access(warmup_file, os.F_OK): msg += " is detected!" break if counter >= max_wait_sec: msg += " didn't show up!" break counter += 1 time.sleep(1) msg += " Time elapsed = %d" % counter logging(msg) def main(): """Program starts here""" warmup_file = '/tmp/pipeline.warmup.done' max_wait_sec = 60 for i in range(len(sys.argv)): arg = sys.argv[i] if i == 1: max_wait_sec = int(arg) elif i == 2: warmup_file = arg if max_wait_sec > 0: wait_for_warmup(warmup_file, max_wait_sec) if __name__ == '__main__': main() BerryNet-3.10.2/berrynet/client/000077500000000000000000000000001400766252600164475ustar00rootroot00000000000000BerryNet-3.10.2/berrynet/client/__init__.py000066400000000000000000000000001400766252600205460ustar00rootroot00000000000000BerryNet-3.10.2/berrynet/client/camera.py000066400000000000000000000164261400766252600202620ustar00rootroot00000000000000#!/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 json 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('--topic', default='berrynet/data/rgbimage', help='The topic to send the captured frames.' ) 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('--hash', action='store_true', help='Add md5sum of a captured frame into the result.' ) ap.add_argument('--meta', type=str, default='{}', help='Metadata field for stringified JSON data.' ) 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 metadata = json.loads(args.get('meta', '{}')) if args['mode'] == 'stream': counter = 0 fail_counter = 0 # Check input stream source if args['stream_src'].isdigit(): # source is a physically connected camera stream_source = int(args['stream_src']) else: # source is an IP camera stream_source = args['stream_src'] capture = cv2.VideoCapture(stream_source) 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 =====') if stream_source.isdigit(): stream_source_uri = '/dev/video{}'.format(stream_source) else: stream_source_uri = stream_source logger.debug('Stream Source: {}'.format(stream_source_uri)) logger.debug('Camera FPS: {}'.format(cam_fps)) logger.debug('Output FPS: {}'.format(out_fps)) logger.debug('Interval: {}'.format(interval)) logger.debug('Send MQTT Topic: {}'.format(args['topic'])) #logger.debug('Warmup Counter: {}'.format(warmup_counter)) logger.debug('====================================') while True: status, im = capture.read() # To verify whether the input source is alive, you should use the # return value of capture.read(). It will not work by capturing # exception of a capture instance, or by checking the return value # of capture.isOpened(). # # Two reasons: # 1. If a dead stream is alive again, capture will not notify # that input source is dead. # # 2. If you check capture.isOpened(), it will keep retruning # True if a stream is dead afterward. So you can not use # the capture return value (capture status) to determine # whether a stream is alive or not. if (status is True): 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, args['hash'], metadata) comm.send(args['topic'], mqtt_payload) logger.debug('send: {} ms'.format(duration(t))) else: pass else: fail_counter += 1 logger.critical('ERROR: Failure #{} happened when reading frame'.format(fail_counter)) # Re-create capture. capture.release() logger.critical('Re-create a capture and reconnect to {} after 5s'.format(stream_source)) time.sleep(5) capture = cv2.VideoCapture(stream_source) 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, args['hash'], metadata) logger.debug('payload: {} ms'.format(duration(t))) logger.debug('payload size: {}'.format(len(mqtt_payload))) # Client publishes payload t = datetime.now() comm.send(args['topic'], 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-3.10.2/berrynet/client/dashboard.py000066400000000000000000000052451400766252600207560ustar00rootroot00000000000000# 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-3.10.2/berrynet/client/data_collector.py000066400000000000000000000103751400766252600220060ustar00rootroot00000000000000# 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-3.10.2/berrynet/client/data_collector_ui.py000066400000000000000000000242731400766252600225050ustar00rootroot00000000000000#!/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-3.10.2/berrynet/client/dyda_config_update.py000066400000000000000000000061271400766252600226370ustar00rootroot00000000000000#!/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 tempfile import tarfile import time import sys from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload class DydaConfigUpdateClient(object): def __init__(self, comm_config, debug=False): self.comm_config = comm_config for topic, functor in self.comm_config['subscribe'].items(): self.comm_config['subscribe'][topic] = self.handleResult self.comm = Communicator(self.comm_config, debug=True) def sendConfig(self, payloadID): self.comm.send(self.comm_config['publish'], payloadID) def handleResult(self, pl): try: payload_json = payload.deserialize_payload(pl.decode('utf-8')) print(payload_json) self.comm.stop_nb() sys.exit(0) except Exception as e: logger.info(e) def run(self, args): """Infinite loop serving inference requests""" self.comm.start_nb() self.sendConfig(args['payload']) time.sleep(1) 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('--debug', action='store_true', help='Debug mode toggle' ) ap.add_argument( '--payload', required=True, help='payload ID' ) ap.add_argument( '--topic', default='berrynet/manager/aikea/config', help='topic to listen for the result' ) ap.add_argument( '--publish', default='berrynet/config/aikea/update', help='topic to publish' ) 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': { args['topic']: None }, 'publish': args['publish'], 'broker': { 'address': args['broker_ip'], 'port': args['broker_port'] } } config_client = DydaConfigUpdateClient(comm_config, args['debug']) config_client.run(args) if __name__ == '__main__': main() BerryNet-3.10.2/berrynet/client/fbdashboard.py000066400000000000000000000244241400766252600212660ustar00rootroot00000000000000# 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-3.10.2/berrynet/client/gmail.py000066400000000000000000000202521400766252600201130ustar00rootroot00000000000000# 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-3.10.2/berrynet/client/snapshot.py000066400000000000000000000064741400766252600206730ustar00rootroot00000000000000# 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-3.10.2/berrynet/client/telegram_bot.py000066400000000000000000000253401400766252600214710ustar00rootroot00000000000000#!/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 tempfile import tarfile import time 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) # NOTE: Maybe change the hard-coding topic to parameter in the future. self.comm_config['subscribe']['berrynet/data/rgbimage'] = self.single_shot 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 = [] self.shot = False self.single_shot_chat_id = None 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 == '': if len(payload_json['annotations']) > 0: logger.debug("Send photo to %s" % u) self.updater.bot.send_photo(chat_id = u, photo=jpg_file_descriptor) else: logger.debug("Does not detect any object, no action") 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 single_shot(self, pl): """Capture an image from camera client and send to the client. """ if self.shot is True: try: payload_json = payload.deserialize_payload(pl.decode('utf-8')) # WORKAROUND: Support customized camera client. # # Original camera client sends an `obj` in payload, # Customized camera client sends an `[obj]` in payload. # # We are unifying the rules. Before that, checking the type # as workaround. if type(payload_json) is list: logger.debug('WORDAROUND: receive and unpack [obj]') payload_json = payload_json[0] jpg_bytes = payload.destringify_jpg(payload_json["bytes"]) jpg_file_descriptor = io.BytesIO(jpg_bytes) logger.info('Send single shot') self.updater.bot.send_photo(chat_id=self.single_shot_chat_id, photo=jpg_file_descriptor) except Exception as e: logger.info(e) self.shot = False else: logger.debug('Single shot is disabled, do nothing.') def run(self, args): """Infinite loop serving inference requests""" self.comm.start_nb() self.connect_telegram(args) def connect_telegram(self, args): try: self.updater.dispatcher.add_handler( telegram.ext.CommandHandler('help', self.handler_help)) self.updater.dispatcher.add_handler( telegram.ext.CommandHandler('hi', self.handler_hi)) 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.dispatcher.add_handler( telegram.ext.CommandHandler('shot', self.handler_shot)) if (args["has_getlog"]): self.updater.dispatcher.add_handler( telegram.ext.CommandHandler('getlog', self.handler_getlog)) 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:\n\n' 'help - Display help message.\n' 'hi - Test Telegram client.\n' 'camera - Start camera.\n' 'stop - Stop camera.\n' 'shot - Take a shot from camera.')) def handler_hi(self, update, context): logger.info("Received command `hi`") update.message.reply_text( 'Hi, {}'.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 handler_shot(self, update, context): logger.info("Received command `shot`, chat id: %s" % update.message.chat_id) # Register the chat-id for receiving images self.shot = True self.single_shot_chat_id = update.message.chat_id logger.debug('Enable single shot.') def handler_getlog(self, update, context): logger.info("Received command `getlog`, chat id: %s" % update.message.chat_id) # Create temporary tar.xz file tmpTGZ1 = tempfile.NamedTemporaryFile(suffix=".tar.xz") tmpTGZ = tarfile.open(fileobj=tmpTGZ1, mode="w:xz") tmpTGZPath = tmpTGZ1.name # Traverse /var/log varlogDir = os.path.abspath(os.path.join(os.sep, "var", "log")) for root, dirs, files in os.walk(varlogDir): for file in files: fullPath = os.path.join(root, file) # Check if the file is a regular file if not os.path.isfile(fullPath): continue # Check if the file is accessable if not os.access(fullPath, os.R_OK): continue # Pack the file tmpTGZ.add(name = fullPath, recursive=False) tmpTGZ.close() self.updater.bot.send_document(chat_id = update.message.chat_id, document = open(tmpTGZPath, 'rb'), filename=time.strftime('berrynet-varlog_%Y%m%d_%H%M%S.tar.xz')) 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' ) ap.add_argument('--has-getlog', action='store_true', help='Enable getlog command' ) 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-3.10.2/berrynet/comm/000077500000000000000000000000001400766252600161245ustar00rootroot00000000000000BerryNet-3.10.2/berrynet/comm/__init__.py000066400000000000000000000033451400766252600202420ustar00rootroot00000000000000#!/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-3.10.2/berrynet/comm/payload.py000066400000000000000000000063651400766252600201410ustar00rootroot00000000000000# 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 hashlib 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 generate_bytes_md5sum(content_bytes): content_b64 = base64.b64encode(content_bytes) return hashlib.md5(content_b64).hexdigest() def serialize_payload(json_object): return json.dumps(json_object) def serialize_jpg(jpg_bytes, md5sum=False, meta={}): """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) obj['meta'] = meta if md5sum: obj['md5sum'] = generate_bytes_md5sum(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-3.10.2/berrynet/dlmodelmgr.py000066400000000000000000000037171400766252600177010ustar00rootroot00000000000000# 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-3.10.2/berrynet/engine/000077500000000000000000000000001400766252600164365ustar00rootroot00000000000000BerryNet-3.10.2/berrynet/engine/__init__.py000066400000000000000000000032521400766252600205510ustar00rootroot00000000000000# 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-3.10.2/berrynet/engine/caffe_engine.py000066400000000000000000000046551400766252600214130ustar00rootroot00000000000000# 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-3.10.2/berrynet/engine/darknet_engine.py000066400000000000000000000134531400766252600217730ustar00rootroot00000000000000# 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-3.10.2/berrynet/engine/grace_hopper.jpg000066400000000000000000004637561400766252600216230ustar00rootroot00000000000000JFIFHHSFile source: http://commons.wikimedia.org/wiki/File:American_Bird_Grasshopper.jpg XICC_PROFILE HLinomntrRGB XYZ  1acspMSFTIEC sRGB-HP cprtP3desclwtptbkptrXYZgXYZ,bXYZ@dmndTpdmddvuedLview$lumimeas $tech0 rTRC< gTRC< bTRC< textCopyright (c) 1998 Hewlett-Packard CompanydescsRGB IEC61966-2.1sRGB IEC61966-2.1XYZ QXYZ XYZ o8XYZ bXYZ $descIEC http://www.iec.chIEC http://www.iec.chdesc.IEC 61966-2.1 Default RGB colour space - sRGB.IEC 61966-2.1 Default RGB colour space - sRGBdesc,Reference Viewing Condition in IEC61966-2.1,Reference Viewing Condition in IEC61966-2.1view_. \XYZ L VPWmeassig CRT curv #(-27;@EJOTY^chmrw| %+28>ELRY`gnu| &/8AKT]gqz !-8COZfr~ -;HUcq~ +:IXgw'7HYj{+=Oat 2FZn  % : O d y  ' = T j " 9 Q i  * C \ u & @ Z t .Id %A^z &Ca~1Om&Ed#Cc'Ij4Vx&IlAe@e Ek*Qw;c*R{Gp@j>i  A l !!H!u!!!"'"U"""# #8#f###$$M$|$$% %8%h%%%&'&W&&&''I'z''( (?(q(())8)k))**5*h**++6+i++,,9,n,,- -A-v--..L.../$/Z///050l0011J1112*2c223 3F3334+4e4455M555676r667$7`7788P8899B999:6:t::;-;k;;<' >`>>?!?a??@#@d@@A)AjAAB0BrBBC:C}CDDGDDEEUEEF"FgFFG5G{GHHKHHIIcIIJ7J}JK KSKKL*LrLMMJMMN%NnNOOIOOP'PqPQQPQQR1R|RSS_SSTBTTU(UuUVV\VVWDWWX/X}XYYiYZZVZZ[E[[\5\\]']x]^^l^__a_``W``aOaabIbbcCcc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xORk9#i[1B(a6zbrLb7&`;V2ՒF`7sD9;6Z!lc8>&mp0*Ιש R෠yCU.SҖtϏ [5Lk;‘pH~mh hC 'W{Cn'F/c::QN{5/.xɬ\zQnڭynG.Riױܫ毌Nb9$a9&iiRsjߖފ @kLR,)!S[](cOGғ Y`@ȭ˦}ËX!Qp=ˍ]4!6b y-5'Ɔ#-:1rfE47^ڼWO/5%wb/0ҒhC9'ҵH" k{TIjTIRS9ukxBP!?&UuQʳdKZ;`{C &կ`ey/h6Zj+*x&GtQTzj.튩ͥ |٫T]&nyT 'Phd\~dVjsv0F* 6bjٷ<ڹk"Jb4Wap)V5$\֧qC,D2iq6ȓLHxU}*I{r+Dح"]2b~PR^DCfy\o_5EkZ`,5ۨn~ Lrd$Vy1\ǭ< 41|b #rծΔ-9|nQu>G8Omt%v٨e g$T:i-U:>/J4Ԇ+{M4 8\VVl"O,zy=_K;pn3lv`$>wJ)r@]qHې)b-((Ҟ&$U֓{aj Օ4v Vhizvˏj|s-7f`ʪh&l;VZQqѵeY6'iVu!p2Y)][V?aqkH;V"@PSD$p*¬+!)ȫc!*$+5iY=\Zt;r*`>X4!P kevbh ԑi6; Th5vi 撖W9:I&FkT`jaXXQڈ⤋j#(5l3t[)D,L{XtQ(0AZ%bp+5b/a0Hj2b΃֪+r\)=|F}˃ X]5GfF-cn3kEj܋¡WAV'&jD|iKuQPpEj񐽅B'+dqPҔ҅C5HkGj쐗 /sަ-#>U44aW+Q);svHTj)o3KI],(KV-nAi;0=}YMjv}FjF=膔qM&Ȗ O=^ TK>m4C͟61UT~{Sis)[ 28J WU4;EU(BerryNet-3.10.2/berrynet/engine/movidius.py000066400000000000000000000136721400766252600206600ustar00rootroot00000000000000#!/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-3.10.2/berrynet/engine/movidius_engine.py000066400000000000000000000043761400766252600222060ustar00rootroot00000000000000# 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-3.10.2/berrynet/engine/openvino_engine.py000066400000000000000000000421201400766252600221710ustar00rootroot00000000000000# 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': # Since OpenVINO 2020.1, cpu_extension content has been merged # into MKLDNN plugin and it is used automatically. # # We do not need to call these functions below anymore: # 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') plugin_dirs = '/opt/intel/openvino/deployment_tools/inference_engine/lib/intel64' self.plugin = IEPlugin(device=device, plugin_dirs=plugin_dirs) 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-3.10.2/berrynet/engine/tensorflow_engine.py000066400000000000000000000071261400766252600225450ustar00rootroot00000000000000# 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-3.10.2/berrynet/engine/tflite_engine.py000066400000000000000000000233271400766252600216330ustar00rootroot00000000000000import 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, num_threads=num_threads) 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.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_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, num_threads=num_threads) 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) 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_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-3.10.2/berrynet/engine/tfliteyolov4_engine.py000066400000000000000000000203631400766252600230050ustar00rootroot00000000000000import 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 TFLiteYoloV4DetectorEngine(DLEngine): def __init__(self, model, labels, threshold=0.1, 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, (416, 416)) frame = np.expand_dims(frame, axis=0) if self.input_dtype == np.float32: frame = (1.0 / 255.0) * frame frame = frame.astype('float32') else: # default data type returned by cv2.imread is np.unit8 pass return frame def filter_boxes(self, box_xywh, scores, score_threshold=0.4, input_shape = tf.constant([416,416])): scores_max = tf.math.reduce_max(scores, axis=-1) mask = scores_max >= score_threshold class_boxes = tf.boolean_mask(box_xywh, mask) pred_conf = tf.boolean_mask(scores, mask) class_boxes = tf.reshape(class_boxes, [tf.shape(scores)[0], -1, tf.shape(class_boxes)[-1]]) pred_conf = tf.reshape(pred_conf, [tf.shape(scores)[0], -1, tf.shape(pred_conf)[-1]]) box_xy, box_wh = tf.split(class_boxes, (2, 2), axis=-1) input_shape = tf.cast(input_shape, dtype=tf.float32) box_yx = box_xy[..., ::-1] box_hw = box_wh[..., ::-1] box_mins = (box_yx - (box_hw / 2.)) / input_shape box_maxes = (box_yx + (box_hw / 2.)) / input_shape boxes = tf.concat([ box_mins[..., 0:1], # y_min box_mins[..., 1:2], # x_min box_maxes[..., 0:1], # y_max box_maxes[..., 1:2] # x_max ], axis=-1) # return tf.concat([boxes, pred_conf], axis=-1) return (boxes, pred_conf) 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 pred = [self.interpreter.get_tensor(self.output_details[i]['index']) for i in range(len(self.output_details))] boxes, pred_conf = self.filter_boxes(pred[0], pred[1], score_threshold=0.25, input_shape=tf.constant([416, 416])) boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression( boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)), scores=tf.reshape( pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])), max_output_size_per_class=50, max_total_size=50, iou_threshold=0.45, score_threshold=0.25 ) return { 'boxes': boxes, 'classes': classes, 'scores': scores, 'num': valid_detections } def process_output(self, output): # get results boxes = np.squeeze(output['boxes'][0]) classes = np.squeeze(output['classes'][0]).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 def parse_argsr(): parser = ArgumentParser() parser.add_argument( "-e", "--engine", help=("Classifier or Detector engine. " "classifier, or detector is acceptable. " "(detector by default)"), default="detector", 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 tfliteyolov4_engine.py -m yolov4-tiny-*.tflite \ # --labels coco.names -i dog.jpg --debug args = parse_argsr() if args.debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if args.engine == 'detector': engine = TFLiteYoloV4DetectorEngine( 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-3.10.2/berrynet/service/000077500000000000000000000000001400766252600166315ustar00rootroot00000000000000BerryNet-3.10.2/berrynet/service/__init__.py000066400000000000000000000054741400766252600207540ustar00rootroot00000000000000# 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-3.10.2/berrynet/service/darknet_service.py000066400000000000000000000103471400766252600223600ustar00rootroot00000000000000# 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-3.10.2/berrynet/service/dyda_config_update.py000066400000000000000000000100001400766252600230020ustar00rootroot00000000000000#!/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 subprocess import tempfile import tarfile import time import sys import configparser from berrynet import logger from berrynet.comm import Communicator from berrynet.comm import payload class DydaConfigUpdateService(object): def __init__(self, comm_config, debug=False): self.comm_config = comm_config for topic, functor in self.comm_config['subscribe'].items(): self.comm_config['subscribe'][topic] = self.handleConfig self.comm = Communicator(self.comm_config, debug=True) idlistConfig = configparser.ConfigParser() idlistConfig.read(self.comm_config['idlist']) self.idlist = idlistConfig["ID"] def sendConfig(self, jsonPayload): self.comm.send(self.comm_config['publish'], jsonPayload) def handleConfig(self, pl): payload_json = "" try: id=pl.decode('utf-8') if (id in self.idlist): configFilename = self.idlist[id] f = open(configFilename) payload_json = payload.deserialize_payload(f.read()) self.sendConfig(payload.serialize_payload(payload_json)) else: logger.warning("ID %s is not in idlist"%(id)) return except Exception as e: logger.info(e) # output config file with open(self.comm_config['configfile'], 'w') as configfile: configfile.write(payload.serialize_payload(payload_json)) configfile.close() # restart service subprocess.run(["supervisorctl", "restart", "bnpipeline-bndyda"]) 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('--debug', action='store_true', help='Debug mode toggle' ) ap.add_argument( '--topic', default='berrynet/config/aikea/update', help='topic to listen for the result' ) ap.add_argument( '--publish', default='berrynet/manager/aikea/config', help='topic to publish' ) ap.add_argument( '--configfile', default='/var/lib/berrynet/dyda.config', help='config file path for dyda' ) ap.add_argument( '--idlist', required=True, help='list of id and config file' ) 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': { args['topic']: None }, 'publish': args['publish'], 'broker': { 'address': args['broker_ip'], 'port': args['broker_port'] }, 'configfile': args['configfile'], 'idlist': args['idlist'] } config_service = DydaConfigUpdateService(comm_config, args['debug']) config_service.run(args) if __name__ == '__main__': main() BerryNet-3.10.2/berrynet/service/mockup_service.py000066400000000000000000000051701400766252600222240ustar00rootroot00000000000000# 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-3.10.2/berrynet/service/movidius_service.py000066400000000000000000000135471400766252600225740ustar00rootroot00000000000000# 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-3.10.2/berrynet/service/openvino_service.py000066400000000000000000000202321400766252600225570ustar00rootroot00000000000000# 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-3.10.2/berrynet/service/tensorflow_service.py000066400000000000000000000077131400766252600231350ustar00rootroot00000000000000# 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-3.10.2/berrynet/service/tflite_service.py000066400000000000000000000175651400766252600222300ustar00rootroot00000000000000# 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.", type=int) 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-3.10.2/berrynet/service/tfliteyolov4_service.py000066400000000000000000000130501400766252600233660ustar00rootroot00000000000000# 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.tfliteyolov4_engine import TFLiteYoloV4DetectorEngine from berrynet.service import EngineService from berrynet.utils import draw_bb from berrynet.utils import generate_class_color class TFLiteYoloV4DetectorService(EngineService): def __init__(self, service_name, engine, comm_config, draw=False): super(TFLiteYoloV4DetectorService, 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/tfliteyolov4detector/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. ' '(detector by default)'), default='detector', type=str) ap.add_argument( '--service_name', default='tfliteyolov4_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 TFLiteYoloV4 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'] == 'detector': engine = TFLiteYoloV4DetectorEngine( model = args['model'], labels = args['label'], num_threads = args['num_threads']) service_functor = TFLiteYoloV4DetectorService 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-3.10.2/berrynet/utils.py000066400000000000000000000140521400766252600167050ustar00rootroot00000000000000# 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-3.10.2/berrynetjs/000077500000000000000000000000001400766252600155265ustar00rootroot00000000000000BerryNet-3.10.2/berrynetjs/broker.js000066400000000000000000000027041400766252600173530ustar00rootroot00000000000000// 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-3.10.2/berrynetjs/camera.js000066400000000000000000000126201400766252600173150ustar00rootroot00000000000000// 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-3.10.2/berrynetjs/client.js000066400000000000000000000005771400766252600173530ustar00rootroot00000000000000var 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-3.10.2/berrynetjs/config.js000066400000000000000000000047011400766252600173330ustar00rootroot00000000000000// 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-3.10.2/berrynetjs/data_collector.js000066400000000000000000000074651400766252600210570ustar00rootroot00000000000000// 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-3.10.2/berrynetjs/journal.js000066400000000000000000000041711400766252600175410ustar00rootroot00000000000000// 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-3.10.2/berrynetjs/line.js000066400000000000000000000053511400766252600170170ustar00rootroot00000000000000// 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-3.10.2/berrynetjs/linev3.js000066400000000000000000000066541400766252600172770ustar00rootroot00000000000000// 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-3.10.2/berrynetjs/localimg.js000066400000000000000000000036201400766252600176540ustar00rootroot00000000000000// 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-3.10.2/berrynetjs/mail.js000066400000000000000000000042561400766252600170150ustar00rootroot00000000000000// 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-3.10.2/berrynetjs/package.json000066400000000000000000000011101400766252600200050ustar00rootroot00000000000000{ "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-3.10.2/config/000077500000000000000000000000001400766252600146045ustar00rootroot00000000000000BerryNet-3.10.2/config/bcm2835-v4l2.conf000066400000000000000000000001121400766252600173150ustar00rootroot00000000000000# BerryNet supports accessing RPi camera access via OpenCV. bcm2835_v4l2 BerryNet-3.10.2/config/berrynet-bionic.list000066400000000000000000000002261400766252600205740ustar00rootroot00000000000000# 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-3.10.2/config/berrynet-buster.list000066400000000000000000000002261400766252600206350ustar00rootroot00000000000000# 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-3.10.2/config/berrynet-focal.list000066400000000000000000000002241400766252600204130ustar00rootroot00000000000000# For details, please refer to https://github.com/DT42/BerryNet-repo deb http://repo.berrynet.org/ focal/ deb-src http://repo.berrynet.org/ focal/ BerryNet-3.10.2/config/berrynet-xenial.list000066400000000000000000000002261400766252600206110ustar00rootroot00000000000000# 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-3.10.2/config/berrynet.list000066400000000000000000000002301400766252600173260ustar00rootroot00000000000000# 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-3.10.2/config/dashboard-darknet-official.json000066400000000000000000000025441400766252600226330ustar00rootroot00000000000000{ "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-3.10.2/config/dashboard-darknet.json000066400000000000000000000025771400766252600210670ustar00rootroot00000000000000{ "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-3.10.2/config/dashboard-movidius.json000066400000000000000000000025301400766252600212630ustar00rootroot00000000000000{ "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-3.10.2/config/dashboard-mqtt.json000066400000000000000000000051661400766252600204210ustar00rootroot00000000000000{ "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-3.10.2/config/dashboard-ovclassifier.json000066400000000000000000000026101400766252600221140ustar00rootroot00000000000000{ "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-3.10.2/config/dashboard-ovdetector.json000066400000000000000000000025761400766252600216140ustar00rootroot00000000000000{ "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-3.10.2/config/dashboard-tflitedetector.json000066400000000000000000000026061400766252600224510ustar00rootroot00000000000000{ "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-3.10.2/config/dashboard.json000066400000000000000000000034471400766252600174360ustar00rootroot00000000000000{ "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-3.10.2/config/dyda-idlist.ini000066400000000000000000000001551400766252600175150ustar00rootroot00000000000000[ID] 1=../dyda/dyda/pipelines/configs/validator.config 2=../dyda/dyda/pipelines/configs/training_yolo.config BerryNet-3.10.2/config/etc/000077500000000000000000000000001400766252600153575ustar00rootroot00000000000000BerryNet-3.10.2/config/etc/mosquitto/000077500000000000000000000000001400766252600174235ustar00rootroot00000000000000BerryNet-3.10.2/config/etc/mosquitto/conf.d/000077500000000000000000000000001400766252600205725ustar00rootroot00000000000000BerryNet-3.10.2/config/etc/mosquitto/conf.d/berrynet.conf000066400000000000000000000001671400766252600232770ustar00rootroot00000000000000# Listen on port 1883 and websockets # default listener port 1883 # extra listener listener 3000 protocol websockets BerryNet-3.10.2/config/intel-openvino-2019.list000066400000000000000000000000701400766252600210350ustar00rootroot00000000000000deb https://apt.repos.intel.com/openvino/2019/ all main BerryNet-3.10.2/config/intel-openvino-2020.list000066400000000000000000000000701400766252600210250ustar00rootroot00000000000000deb https://apt.repos.intel.com/openvino/2020/ all main BerryNet-3.10.2/config/supervisor/000077500000000000000000000000001400766252600170255ustar00rootroot00000000000000BerryNet-3.10.2/config/supervisor/conf.d/000077500000000000000000000000001400766252600201745ustar00rootroot00000000000000BerryNet-3.10.2/config/supervisor/conf.d/berrynet-darknet.conf000066400000000000000000000012131400766252600243200ustar00rootroot00000000000000[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-3.10.2/config/supervisor/conf.d/berrynet-movidius.conf000066400000000000000000000017231400766252600245350ustar00rootroot00000000000000[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-3.10.2/config/supervisor/conf.d/berrynet-tflite.conf000066400000000000000000000011131400766252600241560ustar00rootroot00000000000000[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-3.10.2/configure000077500000000000000000000245231400766252600152540ustar00rootroot00000000000000#!/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-get 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-get install -y nodejs } install_system_dependencies() { sudo apt-get update if [ "$CODENAME" = "buster" ]; then sudo apt-get install -y \ supervisor else sudo apt-get 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 fi 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 } 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-get 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-get 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-get 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://s3.amazonaws.com/pypi.berrynet.org/$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 or unsupported 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/2020/GPG-PUB-KEY-INTEL-OPENVINO-2020 | sudo apt-key add - sudo curl -sL -o /etc/apt/sources.list.d/intel-openvino-2020.list \ https://raw.githubusercontent.com/DT42/BerryNet/master/config/intel-openvino-2020.list sudo apt-get update } install_openvino() { if [ "$DISTRIBUTIONID" = "Ubuntu" ]; then let OPENVINO_VERSION="2020.1.023" if [ "$CODENAME" = "xenial" ]; then sudo apt-get install intel-openvino-runtime-ubuntu16-$OPENVINO_VERSION elif [ "$CODENAMe" = "bionic" ]; then sudo apt-get install intel-openvino-runtime-ubuntu18-$OPENVINO_VERSION else echo "ERROR: OpenVINO on Ubuntu $CODENAME is not supported by Intel." fi elif [ "$DISTRIBUTIONID" = "Raspbian" ]; then sudo apt-get 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-get 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-get 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-3.10.2/doc/000077500000000000000000000000001400766252600141045ustar00rootroot00000000000000BerryNet-3.10.2/doc/STYLE_GUIDE.md000066400000000000000000000001211400766252600162350ustar00rootroot00000000000000[We follow the Node.js Style Guide](https://github.com/felixge/node-style-guide) BerryNet-3.10.2/doc/darknet-nnpack.md000066400000000000000000000041051400766252600173260ustar00rootroot00000000000000# 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-3.10.2/doc/ipcam.md000066400000000000000000000017671400766252600155320ustar00rootroot00000000000000# 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-3.10.2/docker/000077500000000000000000000000001400766252600146065ustar00rootroot00000000000000BerryNet-3.10.2/docker/Dockerfile000066400000000000000000000021611400766252600166000ustar00rootroot00000000000000# We start from Debian Buster. Can be rebase to Raspbian because they are # similar FROM debian:buster LABEL maintainer="dev@dt42.io" LABEL project="Berrynet" LABEL version="3.7.0" # 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 curl # Install systemd RUN apt-get install -y systemd systemd-sysv # Install python RUN apt-get install -y python3 python3-dev # Install python libs RUN apt-get install -y python3-wheel python3-setuptools python3-pip RUN apt-get install -y python3-paho-mqtt python3-logzero python3-astor RUN apt-get install -y python3-opengl python3-six python3-grpcio RUN apt-get install -y python3-keras-applications python3-keras-preprocessing RUN apt-get install -y python3-protobuf python3-termcolor python3-numpy # Install daemons RUN apt-get install -y mosquitto mosquitto-clients RUN apt-get install -y apache2 # Install tensorflow RUN pip3 install tensorflow # Install BerryNet RUN git clone https://github.com/DT42/BerryNet.git RUN cd BerryNet; ./configure BerryNet-3.10.2/docker/Dockerfile.focal000066400000000000000000000023261400766252600176660ustar00rootroot00000000000000# We start from Debian Buster. Can be rebase to Raspbian because they are # similar FROM ubuntu:focal LABEL maintainer="dev@dt42.io" LABEL project="Berrynet" LABEL version="3.7.0" ENV TZ=Europe/London # Update apt RUN apt-get update RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 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 curl # Install systemd RUN apt-get install -y systemd systemd-sysv # Install python RUN apt-get install -y python3 python3-dev # Install python libs RUN apt-get install -y python3-wheel python3-setuptools python3-pip RUN apt-get install -y python3-paho-mqtt python3-logzero python3-astor RUN apt-get install -y python3-opengl python3-six python3-grpcio RUN apt-get install -y python3-keras-applications python3-keras-preprocessing RUN apt-get install -y python3-protobuf python3-termcolor python3-numpy # Install daemons RUN apt-get install -y mosquitto mosquitto-clients RUN apt-get install -y apache2 # Install tensorflow RUN pip3 install tensorflow # Install BerryNet RUN git clone https://github.com/DT42/BerryNet.git RUN cd BerryNet; ./configure BerryNet-3.10.2/examples/000077500000000000000000000000001400766252600151555ustar00rootroot00000000000000BerryNet-3.10.2/examples/run-darknet-detector.sh000066400000000000000000000044231400766252600215550ustar00rootroot00000000000000#!/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-3.10.2/examples/run-openvino-classifier.sh000066400000000000000000000045621400766252600223010ustar00rootroot00000000000000#!/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-3.10.2/inference/000077500000000000000000000000001400766252600152755ustar00rootroot00000000000000BerryNet-3.10.2/inference/agent.js000066400000000000000000000131441400766252600167340ustar00rootroot00000000000000// 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-3.10.2/inference/classify_caffe2_server.py000066400000000000000000000167661400766252600223000ustar00rootroot00000000000000# 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-3.10.2/inference/classify_caffe_server.py000066400000000000000000000226421400766252600222040ustar00rootroot00000000000000#!/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-3.10.2/inference/classify_movidius_server.py000066400000000000000000000135211400766252600227730ustar00rootroot00000000000000# 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-3.10.2/inference/classify_server.py000066400000000000000000000153261400766252600210610ustar00rootroot00000000000000# 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-3.10.2/inference/darkflow/000077500000000000000000000000001400766252600171065ustar00rootroot00000000000000BerryNet-3.10.2/inference/darkflow_engine.py000066400000000000000000000113061400766252600210060ustar00rootroot00000000000000# 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-3.10.2/inference/detect_movidius_server.py000066400000000000000000000126741400766252600224360ustar00rootroot00000000000000# 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-3.10.2/inference/detect_movidius_server_cv.py000066400000000000000000000101441400766252600231140ustar00rootroot00000000000000# 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-3.10.2/inference/detection_server.py000066400000000000000000000133331400766252600212160ustar00rootroot00000000000000# 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-3.10.2/inference/dlmodelmgr.py000066400000000000000000000037001400766252600177750ustar00rootroot00000000000000# 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-3.10.2/inference/engineservice.py000066400000000000000000000146401400766252600205020ustar00rootroot00000000000000# 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-3.10.2/inference/movidius.py000066400000000000000000000237521400766252600175170ustar00rootroot00000000000000#!/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-3.10.2/inference/movidius_engine.py000066400000000000000000000056271400766252600210450ustar00rootroot00000000000000# 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-3.10.2/inference/yoloutils.py000066400000000000000000000160251400766252600177160ustar00rootroot00000000000000import 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-3.10.2/patch/000077500000000000000000000000001400766252600144365ustar00rootroot00000000000000BerryNet-3.10.2/patch/01-detection-backend.patch000066400000000000000000000163451400766252600212510ustar00rootroot00000000000000diff --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-3.10.2/patch/darkflow/000077500000000000000000000000001400766252600162475ustar00rootroot00000000000000BerryNet-3.10.2/patch/darkflow/darkflow-app-example.patch000066400000000000000000000012611400766252600233100ustar00rootroot00000000000000diff --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-3.10.2/patch/ui-berrynet-theme.patch000066400000000000000000000025671400766252600210360ustar00rootroot00000000000000diff --git a/index.html b/index.html index b5877e9..196aaba 100755 --- a/index.html +++ b/index.html @@ -8,9 +8,12 @@ +