pax_global_header 0000666 0000000 0000000 00000000064 14007662526 0014522 g ustar 00root root 0000000 0000000 52 comment=7079e49418b1ef0a55764762699140451c5a13fa
BerryNet-3.10.2/ 0000775 0000000 0000000 00000000000 14007662526 0013337 5 ustar 00root root 0000000 0000000 BerryNet-3.10.2/.eslintrc.yaml 0000664 0000000 0000000 00000000135 14007662526 0016123 0 ustar 00root root 0000000 0000000 env:
node: true
es6: true
extends: google
rules:
comma-dangle: [2, only-multiline]
BerryNet-3.10.2/.github/ 0000775 0000000 0000000 00000000000 14007662526 0014677 5 ustar 00root root 0000000 0000000 BerryNet-3.10.2/.github/FUNDING.yml 0000664 0000000 0000000 00000001357 14007662526 0016522 0 ustar 00root root 0000000 0000000 # 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/ 0000775 0000000 0000000 00000000000 14007662526 0017062 5 ustar 00root root 0000000 0000000 BerryNet-3.10.2/.github/ISSUE_TEMPLATE/bug_report.md 0000664 0000000 0000000 00000001146 14007662526 0021556 0 ustar 00root root 0000000 0000000 ---
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.md 0000664 0000000 0000000 00000000767 14007662526 0022621 0 ustar 00root root 0000000 0000000 ---
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/ 0000775 0000000 0000000 00000000000 14007662526 0016734 5 ustar 00root root 0000000 0000000 BerryNet-3.10.2/.github/workflows/docker.yml 0000664 0000000 0000000 00000004330 14007662526 0020726 0 ustar 00root root 0000000 0000000 name: 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.yml 0000664 0000000 0000000 00000003627 14007662526 0020413 0 ustar 00root root 0000000 0000000 name: 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/.gitignore 0000664 0000000 0000000 00000000235 14007662526 0015327 0 ustar 00root root 0000000 0000000 # 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.yml 0000664 0000000 0000000 00000003331 14007662526 0015773 0 ustar 00root root 0000000 0000000 # 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/.gitmodules 0000664 0000000 0000000 00000000153 14007662526 0015513 0 ustar 00root root 0000000 0000000 [submodule "inference/darkflow"]
path = inference/darkflow
url = https://github.com/thtrieu/darkflow.git
BerryNet-3.10.2/AUTHORS 0000664 0000000 0000000 00000000554 14007662526 0014413 0 ustar 00root root 0000000 0000000 # 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.md 0000664 0000000 0000000 00000001116 14007662526 0014732 0 ustar 00root root 0000000 0000000
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.md 0000664 0000000 0000000 00000000304 14007662526 0015565 0 ustar 00root root 0000000 0000000 We 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.txt 0000664 0000000 0000000 00000104513 14007662526 0015166 0 ustar 00root root 0000000 0000000 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.md 0000664 0000000 0000000 00000021062 14007662526 0014617 0 ustar 00root root 0000000 0000000 
Deep Learning Gateway on Raspberry Pi And Other Edge Devices

[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: 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: 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: 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: 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-manager 0000775 0000000 0000000 00000003412 14007662526 0016527 0 ustar 00root root 0000000 0000000 #! /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/ 0000775 0000000 0000000 00000000000 14007662526 0015171 5 ustar 00root root 0000000 0000000 BerryNet-3.10.2/berrynet/__init__.py 0000664 0000000 0000000 00000000514 14007662526 0017302 0 ustar 00root root 0000000 0000000 import 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/ 0000775 0000000 0000000 00000000000 14007662526 0016432 5 ustar 00root root 0000000 0000000 BerryNet-3.10.2/berrynet/bndyda/__init__.py 0000664 0000000 0000000 00000000000 14007662526 0020531 0 ustar 00root root 0000000 0000000 BerryNet-3.10.2/berrynet/bndyda/bnpipeline.py 0000664 0000000 0000000 00000041414 14007662526 0021135 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000011671 14007662526 0022525 0 ustar 00root root 0000000 0000000 import 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.py 0000664 0000000 0000000 00000005277 14007662526 0022456 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000036534 14007662526 0020624 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000004243 14007662526 0022707 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000002267 14007662526 0020326 0 ustar 00root root 0000000 0000000 #!/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/ 0000775 0000000 0000000 00000000000 14007662526 0016447 5 ustar 00root root 0000000 0000000 BerryNet-3.10.2/berrynet/client/__init__.py 0000664 0000000 0000000 00000000000 14007662526 0020546 0 ustar 00root root 0000000 0000000 BerryNet-3.10.2/berrynet/client/camera.py 0000664 0000000 0000000 00000016426 14007662526 0020262 0 ustar 00root root 0000000 0000000 #!/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.py 0000664 0000000 0000000 00000005245 14007662526 0020756 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000010375 14007662526 0022006 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000024273 14007662526 0022505 0 ustar 00root root 0000000 0000000 #!/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.py 0000664 0000000 0000000 00000006127 14007662526 0022637 0 ustar 00root root 0000000 0000000 #!/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.py 0000664 0000000 0000000 00000024424 14007662526 0021266 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000020252 14007662526 0020113 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000006474 14007662526 0020673 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000025340 14007662526 0021471 0 ustar 00root root 0000000 0000000 #!/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/ 0000775 0000000 0000000 00000000000 14007662526 0016124 5 ustar 00root root 0000000 0000000 BerryNet-3.10.2/berrynet/comm/__init__.py 0000664 0000000 0000000 00000003345 14007662526 0020242 0 ustar 00root root 0000000 0000000 #!/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.py 0000664 0000000 0000000 00000006365 14007662526 0020141 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000003717 14007662526 0017701 0 ustar 00root root 0000000 0000000 # 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/ 0000775 0000000 0000000 00000000000 14007662526 0016436 5 ustar 00root root 0000000 0000000 BerryNet-3.10.2/berrynet/engine/__init__.py 0000664 0000000 0000000 00000003252 14007662526 0020551 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000004655 14007662526 0021413 0 ustar 00root root 0000000 0000000 # 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.py 0000664 0000000 0000000 00000013453 14007662526 0021773 0 ustar 00root root 0000000 0000000 # 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.jpg 0000664 0000000 0000000 00000463756 14007662526 0021623 0 ustar 00root root 0000000 0000000 JFIF H H SFile source: http://commons.wikimedia.org/wiki/File:American_Bird_Grasshopper.jpgXICC_PROFILE HLino mntrRGB XYZ 1 acspMSFT IEC sRGB -HP cprt P 3desc lwtpt bkpt rXYZ gXYZ , bXYZ @ dmnd T pdmdd vued L view $lumi meas $tech 0 rTRC <