├── deepstack-cpu
├── Dockerfile
├── build.json
├── icon.png
├── CHANGELOG.md
├── config.json
└── README.md
├── deepstack-gpu
├── Dockerfile
├── build.json
├── icon.png
├── CHANGELOG.md
├── config.json
└── README.md
├── deepstack-trainer
├── icon.png
├── CHANGELOG.md
├── trainer
│ ├── dist
│ │ ├── img
│ │ │ ├── save.png
│ │ │ ├── avatar.png
│ │ │ ├── delete.png
│ │ │ ├── paypal.png
│ │ │ ├── paypal2.png
│ │ │ ├── boxed-bg.jpg
│ │ │ ├── boxed-bg.png
│ │ │ ├── broadlink.png
│ │ │ └── clippy.svg
│ │ ├── webfonts
│ │ │ ├── fa-solid-900.eot
│ │ │ ├── fa-solid-900.ttf
│ │ │ ├── fa-brands-400.eot
│ │ │ ├── fa-brands-400.ttf
│ │ │ ├── fa-brands-400.woff
│ │ │ ├── fa-regular-400.eot
│ │ │ ├── fa-regular-400.ttf
│ │ │ ├── fa-solid-900.woff
│ │ │ ├── fa-solid-900.woff2
│ │ │ ├── fa-brands-400.woff2
│ │ │ ├── fa-regular-400.woff
│ │ │ ├── fa-regular-400.woff2
│ │ │ └── fa-regular-400.svg
│ │ ├── css
│ │ │ └── style.css
│ │ └── js
│ │ │ └── home.js
│ ├── templates
│ │ ├── gallery.html
│ │ └── index.html
│ └── trainer.py
├── config.json
├── Dockerfile
└── README.md
├── repository.json
├── README.md
└── readme-ru.md
/deepstack-cpu/Dockerfile:
--------------------------------------------------------------------------------
1 | ARG BUILD_FROM
2 | FROM $BUILD_FROM
3 | ENV DATA_DIR=/data/database
--------------------------------------------------------------------------------
/deepstack-gpu/Dockerfile:
--------------------------------------------------------------------------------
1 | ARG BUILD_FROM
2 | FROM $BUILD_FROM
3 | ENV DATA_DIR=/data/database
--------------------------------------------------------------------------------
/deepstack-cpu/build.json:
--------------------------------------------------------------------------------
1 | {
2 | "build_from": {
3 | "amd64": "deepquestai/deepstack:cpu-2022.01.1"
4 | }
5 | }
--------------------------------------------------------------------------------
/deepstack-gpu/build.json:
--------------------------------------------------------------------------------
1 | {
2 | "build_from": {
3 | "amd64": "deepquestai/deepstack:gpu-2022.01.1"
4 | }
5 | }
--------------------------------------------------------------------------------
/deepstack-cpu/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-cpu/icon.png
--------------------------------------------------------------------------------
/deepstack-gpu/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-gpu/icon.png
--------------------------------------------------------------------------------
/deepstack-trainer/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/icon.png
--------------------------------------------------------------------------------
/deepstack-trainer/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Please reference the [release notes](https://github.com/t0mer/deepstack-trainer/releases) for changes.
2 |
--------------------------------------------------------------------------------
/deepstack-cpu/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Please reference the [release notes](https://registry.hub.docker.com/r/deepquestai/deepstack/tags) for changes.
2 |
--------------------------------------------------------------------------------
/deepstack-gpu/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Please reference the [release notes](https://registry.hub.docker.com/r/deepquestai/deepstack/tags) for changes.
2 |
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/img/save.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/img/save.png
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/img/avatar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/img/avatar.png
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/img/delete.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/img/delete.png
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/img/paypal.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/img/paypal.png
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/img/paypal2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/img/paypal2.png
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/img/boxed-bg.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/img/boxed-bg.jpg
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/img/boxed-bg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/img/boxed-bg.png
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/img/broadlink.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/img/broadlink.png
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-solid-900.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-solid-900.eot
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-solid-900.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-solid-900.ttf
--------------------------------------------------------------------------------
/repository.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Home Assistant Add-on: DeepStack",
3 | "url": "https://github.com/DivanX10/Home-Assistant-Add-on-Deepstack",
4 | "maintainer": "DivanX10"
5 | }
6 |
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-brands-400.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-brands-400.eot
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-brands-400.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-brands-400.ttf
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-brands-400.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-brands-400.woff
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-regular-400.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-regular-400.eot
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-regular-400.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-regular-400.ttf
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-solid-900.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-solid-900.woff
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-solid-900.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-solid-900.woff2
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-brands-400.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-brands-400.woff2
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-regular-400.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-regular-400.woff
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-regular-400.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DivanX10/Home-Assistant-Add-on-Deepstack/HEAD/deepstack-trainer/trainer/dist/webfonts/fa-regular-400.woff2
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/img/clippy.svg:
--------------------------------------------------------------------------------
1 |
4 |
--------------------------------------------------------------------------------
/deepstack-trainer/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "DeepStack Client (Trainer)",
3 | "version": "2.2.0-1",
4 | "url": "https://github.com/DivanX10/Home-Assistant-Add-on-Deepstack",
5 | "slug": "deepstack-trainer",
6 | "description": "DeepStack Trainer is a Flask powerd, easy to use web app, hepls us to train and test Deepstack AI",
7 | "webui": "http://[HOST]:[PORT:8080]",
8 | "arch": ["amd64"],
9 | "startup": "application",
10 | "boot": "auto",
11 | "map": ["config:rw"],
12 | "ports": {
13 | "8080/tcp": 7100
14 | },
15 | "ports_description": {
16 | "8080/tcp": "Optional. Deepstack trainer. Web interface"
17 | },
18 | "environment": {
19 | "DEEPSTACK_HOST_ADDRESS": "http://homeassistant:7000"
20 | }
21 | }
22 |
23 |
--------------------------------------------------------------------------------
/deepstack-trainer/Dockerfile:
--------------------------------------------------------------------------------
1 | # https://github.com/geerlingguy/docker-debian11-ansible
2 | #FROM divanx10/debian11-fastapi:v1
3 | FROM techblog/fastapi:latest
4 |
5 | LABEL maintainer="tomer.klein@gmail.com"
6 | ENV DEEPSTACK_HOST_ADDRESS=""
7 | ENV DEEPSTACK_API_KEY=""
8 | ENV MIN_CONFIDANCE=0.70
9 | ENV PYTHONIOENCODING=utf-8
10 | ENV LANG=C.UTF-8
11 |
12 | RUN apt update -yqq
13 |
14 | RUN apt -yqq install python3-pip
15 |
16 | RUN pip3 install --upgrade pip --no-cache-dir && \
17 | pip3 install --upgrade setuptools --no-cache-dir
18 |
19 | RUN mkdir -p /opt/trainer/photos/uploads
20 | RUN mkdir -p /opt/trainer/db
21 |
22 | COPY trainer /opt/trainer
23 |
24 | EXPOSE 8080
25 |
26 | WORKDIR /opt/trainer/
27 |
28 | ENTRYPOINT ["/usr/bin/python3", "trainer.py"]
29 |
--------------------------------------------------------------------------------
/deepstack-cpu/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "DeepStack Server (CPU)",
3 | "version": "2022.01.1",
4 | "url": "https://github.com/johnolafenwa/DeepStack",
5 | "slug": "deepstack-cpu",
6 | "description": "DeepStack is an AI API engine that serves pre-built models and custom models on multiple edge devices locally or on your private cloud",
7 | "arch": ["amd64"],
8 | "startup": "application",
9 | "boot": "auto",
10 | "webui": "http://[HOST]:[PORT:5000]",
11 | "ports": {
12 | "5000/tcp": 7000
13 | },
14 | "ports_description": {
15 | "5000/tcp": "Optional. Port of your deepstack server"
16 | },
17 | "environment": {
18 | "VISION-FACE": "True",
19 | "VISION-DETECTION": "True",
20 | "VISION-SCENE": "True",
21 | "MODELSTORE-DETECTION": "True",
22 | "TZ": ""
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/deepstack-gpu/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "DeepStack Server (GPU)",
3 | "version": "2022.01.1",
4 | "url": "https://github.com/johnolafenwa/DeepStack",
5 | "slug": "deepstack-gpu",
6 | "description": "DeepStack is an AI API engine that serves pre-built models and custom models on multiple edge devices locally or on your private cloud",
7 | "arch": ["amd64"],
8 | "startup": "application",
9 | "boot": "auto",
10 | "webui": "http://[HOST]:[PORT:5000]",
11 | "ports": {
12 | "5000/tcp": 7000
13 | },
14 | "ports_description": {
15 | "5000/tcp": "Optional. Port of your deepstack server"
16 | },
17 | "environment": {
18 | "VISION-FACE": "True",
19 | "VISION-DETECTION": "True",
20 | "VISION-SCENE": "True",
21 | "MODELSTORE-DETECTION": "True",
22 | "TZ": ""
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/templates/gallery.html:
--------------------------------------------------------------------------------
1 | {% for image in images %}
2 |
3 |
4 |
5 |
6 |
7 |
8 |

9 |
10 |
11 |
12 |

13 |
{{ image[0] }}
14 |
15 |
16 |
17 | {% endfor %}
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Home Assistant Add-on: DeepStack
2 |
3 | ### [Русская версия](https://github.com/DivanX10/Home-Assistant-Add-on-Deepstack/blob/main/readme-ru.md)
4 |
5 | ----
6 | ### [DeepStack Server](https://registry.hub.docker.com/r/deepquestai/deepstack/)
7 |
8 | ![amd64][amd64-shield]
9 |
10 | [amd64-shield]: https://img.shields.io/badge/amd64-yes-green.svg
11 |
12 |
13 | **DeepStack Server** - This is the server part of artificial intelligence, which will allow you to recognize faces and objects, and you can also create your own custom models.
14 |
15 | [DeepStack Documentation](https://docs.deepstack.cc/index.html#)
16 |
17 |
18 | ### [DeepStack Trainer](https://github.com/t0mer/deepstack-trainer)
19 |
20 | ![amd64][amd64-shield]
21 |
22 | [amd64-shield]: https://img.shields.io/badge/amd64-yes-green.svg
23 |
24 | **DeepStack Trainer** - this is the client part and has a web interface where you can train Deep Stack by uploading photos and assigning a name, as well as check the recognition of faces and objects by photo
25 |
26 | [DeepStack Trainer Documentation](https://github.com/t0mer/deepstack-trainer)
27 |
28 |
29 | ### Installation
30 |
31 | Go to the external interface of your home assistant in Settings -> Add-ons -> Store -> click on the 3 dots (top right) and add this URL to the repository:
32 |
33 | ```
34 | https://github.com/DivanX10/Home-Assistant-Add-on-Deepstack
35 | ```
36 |
37 | ### Additions in this repository
38 |
39 | DeepStack CPU: The server part for working with the processor
40 |
41 | DeepStack GPU: Server part for working with a video card
42 |
43 | DeepStack Trainer: The client part
44 |
45 |
46 | ### Integration into Home assistant
47 | [HASS-DeepStack-Face](https://github.com/robmarkcole/HASS-Deepstack-face): face recognition, registration and recognition
48 |
49 | [HASS-DeepStack-Object](https://github.com/robmarkcole/HASS-Deepstack-object): discovery of shared and custom objects
50 |
51 | [HASS-DeepStack-Scene](https://github.com/robmarkcole/HASS-Deepstack-scene): scene recognition
52 |
--------------------------------------------------------------------------------
/readme-ru.md:
--------------------------------------------------------------------------------
1 | # Home Assistant Add-on: DeepStack
2 |
3 | ### [Английская версия](https://github.com/DivanX10/Home-Assistant-Add-on-Deepstack)
4 |
5 | ### [DeepStack Server](https://registry.hub.docker.com/r/deepquestai/deepstack/)
6 |
7 | ![amd64][amd64-shield]
8 |
9 | [amd64-shield]: https://img.shields.io/badge/amd64-yes-green.svg
10 |
11 |
12 | **DeepStack Server** - это серверная часть искусственного интеллекта, который позволит вам распознавать лица и объекты, а также можно создавать свои пользовательские модел
13 |
14 | [Документация DeepStack](https://docs.deepstack.cc/index.html#)
15 |
16 |
17 | ### [DeepStack Trainer](https://github.com/t0mer/deepstack-trainer)
18 |
19 | ![amd64][amd64-shield]
20 |
21 | [amd64-shield]: https://img.shields.io/badge/amd64-yes-green.svg
22 |
23 |
24 |
25 | **DeepStack Trainer** - это клиентсякая часть и имеет веб интерфейс, где вы сможете обучать DeepStac, загружая фото и присаивая имя, а также проверить распознавание лица и объектов по фото
26 |
27 | [Документация DeepStack Trainer](https://github.com/t0mer/deepstack-trainer)
28 |
29 | ## Инструкции по Deepstack читаем [здесь](https://github.com/DivanX10/Home-Assistant-Add-on-Deepstack/wiki)
30 |
31 | ## Установка
32 |
33 | Перейдите во внешний интерфейс своего домашнего помощника в Настройки -> Дополнения -> Магазин -> нажимаем на 3 точки (справа наверху) и добавьте этот URL-адрес в репозиторий:
34 |
35 | ```
36 | https://github.com/DivanX10/Home-Assistant-Add-on-Deepstack
37 | ```
38 |
39 | ## Дополнения в этом репозитории
40 |
41 | DeepStack CPU: Серверная часть для работы с процессором
42 |
43 | DeepStack GPU: Серверная часть для работы с видеокартой
44 |
45 | DeepStack Trainer: Клиентская часть
46 |
47 |
48 | ## Интеграции в Home assistant
49 | [HASS-DeepStack-Face](https://github.com/robmarkcole/HASS-Deepstack-face): распознавание лиц, регистрация и распознавание
50 |
51 | [HASS-DeepStack-Object](https://github.com/robmarkcole/HASS-Deepstack-object): обнаружение общих и пользовательских объектов
52 |
53 | [HASS-DeepStack-Scene](https://github.com/robmarkcole/HASS-Deepstack-scene): распознавание сцен
54 |
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/css/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | height: 50em;
3 | background: #f1f1f1;
4 | }
5 |
6 | .navbar-fixed {
7 | height: auto !important;
8 | }
9 |
10 | nav {
11 | height: auto;
12 | }
13 |
14 | .mb-0 {
15 | margin-bottom: 0px;
16 | }
17 |
18 |
19 | .pt-10 {
20 | padding-top: 10em;
21 | }
22 |
23 | .tabs .indicator {
24 | background-color: #fff;
25 | }
26 |
27 | .header {
28 | margin: 1em 0em;
29 | font-weight: 600;
30 | color: #333;
31 | /* text-transform: uppercase; */
32 | }
33 | .regular
34 | {
35 | text-transform:none !important;
36 | }
37 |
38 | .btn_file {
39 | position: relative;
40 | overflow: hidden;
41 | }
42 |
43 | .btn_file input[type=file] {
44 | position: absolute;
45 | top: 0;
46 | right: 0;
47 | min-width: 100%;
48 | min-height: 100%;
49 | font-size: 100px;
50 | text-align: right;
51 | /* filter: alpha(opacity=0); */
52 | opacity: 0;
53 | outline: none;
54 | background: white;
55 | cursor: inherit;
56 | display: block;
57 | }
58 |
59 | #teach-img, #who-img, #detect-img, #scene-img {
60 | width: 450px;
61 | margin: 0 auto;
62 | display: block;
63 | }
64 |
65 |
66 | /* Photo Gallery */
67 | div.gallery {
68 | border: 1px solid #ccc;
69 | }
70 |
71 | div.gallery:hover {
72 | border: 1px solid #777;
73 | }
74 |
75 | div.gallery img {
76 | width: 100%;
77 | height: auto;
78 | }
79 |
80 | div.desc {
81 | padding: 15px;
82 | text-align: center;
83 | }
84 |
85 | * {
86 | box-sizing: border-box;
87 | }
88 |
89 | .responsive {
90 | padding: 0 6px;
91 | float: left;
92 | width: 24.99999%;
93 | }
94 |
95 | @media only screen and (max-width: 700px) {
96 | .responsive {
97 | width: 49.99999%;
98 | margin: 6px 0;
99 | }
100 | }
101 |
102 | @media only screen and (max-width: 500px) {
103 | .responsive {
104 | width: 100%;
105 | }
106 | }
107 |
108 | .clearfix:after {
109 | content: "";
110 | display: table;
111 | clear: both;
112 | }
113 |
114 | #gallery{
115 | padding: 10px;
116 | }
117 |
118 | .tabs{
119 | overflow-x:hidden !important;
120 | }
--------------------------------------------------------------------------------
/deepstack-trainer/README.md:
--------------------------------------------------------------------------------
1 | # Home assistant add-on: DeepStack Trainer - Client
2 |
3 | ### A client with a graphical interface
4 | ### Installation
5 | Install and run. You don't need to make any settings. After installing the DeepStack Trainer addon, a deepstack folder with db and photos subfolders will appear in the config folder. These folders are used to store the database and uploaded photos in Deepstack Trainer for Deepstack Server training. If you restart or turn off the Deep stack Trainer addon, the database and photos are erased and there will be no photos in the photo gallery of the Deepstack Trainer addon. To prevent this from happening, all data is copied to the deep stack folder, and after launching the addon, it is copied to the Deep stack Trainer addon. If you accidentally delete the deepstack folder, then everything will be lost. After launching the Deepstack Trainer addon, click on the web interface.
6 |
7 | ### Sources
8 | [Page of the author of DeepStack Trainer Tomer Kleinman](https://github.com/t0mer/deepstack-trainer)
9 |
10 | [DeepStack Documentation](https://docs.deepstack.cc)
11 |
12 | [Download images](https://registry.hub.docker.com/r/deepquestai/deepstack/tags)
13 |
14 | ### Integration into Home assistant
15 | [HASS-DeepStack-Face](https://github.com/robmarkcole/HASS-Deepstack-face): face recognition, registration and recognition
16 |
17 | [HASS-DeepStack-Object](https://github.com/robmarkcole/HASS-Deepstack-object): discovery of shared and custom objects
18 |
19 | [HASS-DeepStack-Scene](https://github.com/robmarkcole/HASS-Deepstack-scene): scene recognition
20 |
21 | -----
22 |
23 |
24 | Текст на русском
25 |
26 |
27 | ### Клиент c графическим интерфейсом
28 |
29 | ### Установка
30 | Устанавливаем и запускаем. Никаких настроек делать не нужно. После установки аддона DeepStack Trainer в папке config появится папка deepstack с подпапками db и photos. Эти папки служат для хранения базы и загруженных фото в Deepstack Trainer для обучения Deepstack Server. Если перезагрузить или выключить аддон Deepstack Trainer, то база и фото стираются и в галерее фото аддона Deepstack Trainer не будет фотографии. Чтобы этого не произошло, все данные копируются в папку deepstack, а после запуска аддона копируются в аддон Deepstack Trainer. Если вы случайно удалите папку deepstack, то все будет утрачено. После запуска аддона Deepstack Trainer нажимаем на веб-интерфейс.
31 |
32 | ### Источники
33 | [Документация DeepStack](https://docs.deepstack.cc)
34 |
35 | [Скачать образы](https://registry.hub.docker.com/r/deepquestai/deepstack/tags)
36 |
37 | [Википедия DeepStack by Divan](https://github.com/DivanX10/Home-Assistant-Add-on-Deepstack/wiki)
38 |
39 | ### Интеграции в Home assistant
40 | [HASS-DeepStack-Face](https://github.com/robmarkcole/HASS-Deepstack-face): распознавание лиц, регистрация и распознавание
41 |
42 | [HASS-DeepStack-Object](https://github.com/robmarkcole/HASS-Deepstack-object): обнаружение общих и пользовательских объектов
43 |
44 | [HASS-DeepStack-Scene](https://github.com/robmarkcole/HASS-Deepstack-scene): распознавание сцен
45 |
46 |
47 |
--------------------------------------------------------------------------------
/deepstack-cpu/README.md:
--------------------------------------------------------------------------------
1 | # Home assistant add-on: DeepStack CPU - Server
2 |
3 | Using a Deep Stack with a processor. The Deep Stack CPU version is slower than the GPU version.
4 |
5 | ### Installation
6 | Install and run the DeepStack addon(server). You don't need to make any settings. After launching the DeepStack addon(server), click on the web interface. If the DeepStack(server) home page has opened, then DeepStack(server) is running and ready to work. It remains to install DeepStack Trainer(client) for DeepStack training (server) and face and object recognition testing.
7 |
8 | DeepStack(server) is available on port 7000. You can access it by clicking on the web interface button
9 |
10 | 4 options have been added to DeepStack(server) and they are enabled by default:
11 | * VISION-FACE - face recognition
12 | * VISION-DETECTION - object recognition
13 | * VISION-SCENE - scene recognition
14 | * MODELSTORE-DETECTION - recognition of user models
15 |
16 |
17 | ### Sources
18 |
19 | [Deep Stack Documentation](https://docs.deepstack.cc)
20 |
21 | [Download images](https://registry.hub.docker.com/r/deepquestai/deepstack/tags)
22 |
23 |
24 | ### Integration into Home assistant
25 | [HASS-DeepStack-Face](https://github.com/robmarkcole/HASS-Deepstack-face): face recognition, registration and recognition
26 |
27 | [HASS-DeepStack-Object](https://github.com/robmarkcole/HASS-Deepstack-object): discovery of shared and custom objects
28 |
29 | [HASS-DeepStack-Scene](https://github.com/robmarkcole/HASS-Deepstack-scene): scene recognition
30 |
31 | -----
32 |
33 |
34 | Текст на русском
35 |
36 |
37 | Использование DeepStack с процессором. Версия DeepStack СPU работает медленнее, чем версия GPU.
38 |
39 | ### Установка
40 | Устанавливаем и запускаем аддон DeepStack(сервер). Никаких настроек делать не нужно. После запуска аддона DeepStack(сервер) нажимаем на веб-интерфейс. Если открылась стартовая страница DeepStack(сервер), значит DeepStack(сервер) запущен и готов к работе. Осталось установить DeepStack Trainer(клиент) для обучения DeepStack(сервер) и проверки распознавания лиц и объектов.
41 |
42 | DeepStack(сервер) доступен на порту 7000. Доступ к нему можно получить, нажав на кнопку веб-интерфейс
43 |
44 | В DeepStack(сервер) добавлены 4 опции и они по умолчанию включены:
45 | * VISION-FACE - распознавание лица
46 | * VISION-DETECTION - распознавание объектов
47 | * VISION-SCENE - распознавание сцен
48 | * MODELSTORE-DETECTION - распознавание пользовательских моделей
49 |
50 |
51 | ### Источники
52 |
53 | [Документация DeepStack](https://docs.deepstack.cc)
54 |
55 | [Скачать образы](https://registry.hub.docker.com/r/deepquestai/deepstack/tags)
56 |
57 | [Википедия DeepStack by Divan](https://github.com/DivanX10/Home-Assistant-Add-on-Deepstack/wiki)
58 |
59 |
60 | ### Интеграции в Home assistant
61 | [HASS-DeepStack-Face](https://github.com/robmarkcole/HASS-Deepstack-face): распознавание лиц, регистрация и распознавание
62 |
63 | [HASS-DeepStack-Object](https://github.com/robmarkcole/HASS-Deepstack-object): обнаружение общих и пользовательских объектов
64 |
65 | [HASS-DeepStack-Scene](https://github.com/robmarkcole/HASS-Deepstack-scene): распознавание сцен
66 |
67 |
68 |
--------------------------------------------------------------------------------
/deepstack-gpu/README.md:
--------------------------------------------------------------------------------
1 | # Home assistant add-on: DeepStack GPU - Server
2 |
3 | Using Deep Stack with NVIDIA GPUs. The Deep Stack GPU version handles requests 5-20 times faster than the CPU version if you have an NVIDIA GPU.
4 |
5 | ### Installation
6 | Install and run the DeepStack addon(server). You don't need to make any settings. After launching the DeepStack addon(server), click on the web interface. If the DeepStack(server) home page has opened, then DeepStack(server) is running and ready to work. It remains to install DeepStack Trainer(client) for DeepStack training (server) and face and object recognition testing.
7 |
8 | DeepStack(server) is available on port 7000. You can access it by clicking on the web interface button
9 |
10 | 4 options have been added to DeepStack(server) and they are enabled by default:
11 | * VISION-FACE - face recognition
12 | * VISION-DETECTION - object recognition
13 | * VISION-SCENE - scene recognition
14 | * MODELSTORE-DETECTION - recognition of user models
15 |
16 |
17 | ### Sources
18 |
19 | [Deep Stack Documentation](https://docs.deepstack.cc)
20 |
21 | [Download images](https://registry.hub.docker.com/r/deepquestai/deepstack/tags)
22 |
23 |
24 | ### Integration into Home assistant
25 | [HASS-DeepStack-Face](https://github.com/robmarkcole/HASS-Deepstack-face): face recognition, registration and recognition
26 |
27 | [HASS-DeepStack-Object](https://github.com/robmarkcole/HASS-Deepstack-object): discovery of shared and custom objects
28 |
29 | [HASS-DeepStack-Scene](https://github.com/robmarkcole/HASS-Deepstack-scene): scene recognition
30 |
31 | -----
32 |
33 |
34 | Текст на русском
35 |
36 |
37 | Использование DeepStack с графическими процессорами NVIDIA. Версия DeepStack GPU обслуживает запросы в 5-20 раз быстрее, чем версия CPU, если у вас графический процессор NVIDIA.
38 |
39 |
40 | ### Установка
41 | Устанавливаем и запускаем аддон DeepStack(сервер). Никаких настроек делать не нужно. После запуска аддона DeepStack(сервер) нажимаем на веб-интерфейс. Если открылась стартовая страница DeepStack(сервер), значит DeepStack(сервер) запущен и готов к работе. Осталось установить DeepStack Trainer(клиент) для обучения DeepStack(сервер) и проверки распознавания лиц и объектов.
42 |
43 | DeepStack(сервер) доступен на порту 7000. Доступ к нему можно получить, нажав на кнопку веб-интерфейс
44 |
45 | В DeepStack(сервер) добавлены 4 опции и они по умолчанию включены:
46 | * VISION-FACE - распознавание лица
47 | * VISION-DETECTION - распознавание объектов
48 | * VISION-SCENE - распознавание сцен
49 | * MODELSTORE-DETECTION - распознавание пользовательских моделей
50 |
51 |
52 | ### Источники
53 |
54 | [Документация DeepStack](https://docs.deepstack.cc)
55 |
56 | [Скачать образы](https://registry.hub.docker.com/r/deepquestai/deepstack/tags)
57 |
58 | [Википедия DeepStack by Divan](https://github.com/DivanX10/Home-Assistant-Add-on-Deepstack/wiki)
59 |
60 |
61 | ### Интеграции в Home assistant
62 | [HASS-DeepStack-Face](https://github.com/robmarkcole/HASS-Deepstack-face): распознавание лиц, регистрация и распознавание
63 |
64 | [HASS-DeepStack-Object](https://github.com/robmarkcole/HASS-Deepstack-object): обнаружение общих и пользовательских объектов
65 |
66 | [HASS-DeepStack-Scene](https://github.com/robmarkcole/HASS-Deepstack-scene): распознавание сцен
67 |
68 |
69 |
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/js/home.js:
--------------------------------------------------------------------------------
1 | $(document).on('change', '.btn_file :file', function () {
2 | var input = $(this),
3 | label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
4 | input.trigger('fileselect', [label]);
5 | });
6 |
7 |
8 | $(document).on('click', '.savbtn', function () {
9 | var text = $(this).parent().next('.desc').text();
10 | var id = $(this).parent().next('.desc').attr('id');
11 | Swal.fire({
12 | title: 'Do you want to save the changes?',
13 | showDenyButton: true,
14 | showCancelButton: true,
15 | confirmButtonText: 'Save',
16 | denyButtonText: `Don't save`,
17 | }).then((result) => {
18 | /* Read more about isConfirmed, isDenied below */
19 | if (result.isConfirmed) {
20 | //
21 | $.ajax({
22 | url: '/api/rename',
23 | // dataType: 'json',
24 | type: 'post',
25 | contentType: 'application/json',
26 | data: JSON.stringify({ text: text, img: id }),
27 | processData: false,
28 | success: function (data, textStatus, jQxhr) {
29 | data = JSON.parse(data)
30 | if (data.success == "true")
31 | {
32 | Swal.fire('Saved!', '', 'success');
33 | }
34 | else
35 | {
36 | Swal.fire('Changes are not saved', '', 'error');
37 | }
38 | load_gallery();
39 | },
40 | error: function (jqXhr, textStatus, errorThrown) {
41 | console.log(errorThrown);
42 | Swal.fire('Changes are not saved', '', 'error');
43 | }
44 | });
45 |
46 | } else if (result.isDenied) {
47 | Swal.fire('Changes are not saved', '', 'info');
48 | }
49 | })
50 | });
51 |
52 | $(document).on('click', '.delbtn', function () {
53 | var id = $(this).data('img');
54 | Swal.fire({
55 | title: 'Do you want to delete the image?',
56 | showDenyButton: true,
57 | showCancelButton: false,
58 | confirmButtonText: 'Delete',
59 | denyButtonText: `Don't Delete`,
60 | }).then((result) => {
61 | /* Read more about isConfirmed, isDenied below */
62 | if (result.isConfirmed) {
63 | // Swal.fire('Saved!', '', 'success')
64 | $.ajax({
65 | url: '/api/delete',
66 | // dataType: 'json',
67 | type: 'post',
68 | contentType: 'application/json',
69 | data: JSON.stringify({img: id }),
70 | processData: false,
71 | success: function (data, textStatus, jQxhr) {
72 | data = JSON.parse(data)
73 | if (data.success == "true")
74 | {
75 | Swal.fire('Image was deleted!', '', 'success');
76 |
77 | }
78 | else{
79 | Swal.fire('Image was not deleted', '', 'error');
80 | }
81 |
82 | load_gallery();
83 | },
84 | error: function (jqXhr, textStatus, errorThrown) {
85 | Swal.fire('Image was not deleted', '', 'error');
86 | }
87 | });
88 |
89 | } else if (result.isDenied) {
90 | Swal.fire('Image was not deleted', '', 'info');
91 | }
92 | })
93 | });
94 |
95 | $('.btn_file :file').on('fileselect', function (event, label) {
96 | var input = $(this).parents('.input-group').find(':text'),
97 | log = label;
98 | if (input.length) {
99 | input.val(log);
100 | } else {
101 | if (log) alert(log);
102 | }
103 | });
104 |
105 |
106 | function readURL(input, id) {
107 | if (input.files && input.files[0]) {
108 | var reader = new FileReader();
109 | reader.onload = function (e) {
110 | $(id).attr('src', e.target.result);
111 | }
112 | reader.readAsDataURL(input.files[0]);
113 | }
114 | }
115 |
116 |
117 | function Validate(pairs) {
118 | for (var pair of pairs) {
119 | if (pair[0] == 'teach_file' || pair[0] == 'who_file' || pair[0] == 'detect_file' || pair[0] == 'scene_file') {
120 | if (pair[1].name == "") {
121 | ShowError("No image is selected, Please select image and try again.");
122 | return false;
123 | }
124 |
125 | type = pair[1].type.split('/').pop().toLowerCase();
126 | if (type != "jpeg" && type != "jpg" && type != "png" && type != "bmp" && type != "gif") {
127 | ShowError('Please select a valid image file');
128 | return false;
129 | }
130 | }
131 | if (pair[0] == 'person') {
132 | if (pair[1] === "") {
133 | ShowError("Please enter person name");
134 | return false;
135 | }
136 | }
137 |
138 | }
139 | return true;
140 | }
141 |
142 | function ShowError(message) {
143 | Swal.fire({
144 | title: 'Error!',
145 | text: message,
146 | icon: 'error',
147 | confirmButtonText: 'Ok'
148 | })
149 | }
150 |
151 |
152 | function load_gallery() {
153 | $.ajax(
154 | {
155 | url: '/api/images',
156 | success: function (data) {
157 |
158 | $('#gallery').html(data)
159 | $('.desc').each(function () {
160 | this.addEventListener('input', function () {
161 | $(this).prev().find('img').show();
162 | });
163 |
164 |
165 | });
166 |
167 | },
168 | error: function (e) {
169 |
170 | }
171 | });
172 |
173 |
174 |
175 | }
176 |
177 |
178 | $(document).ready(function () {
179 |
180 |
181 | $('#gallerytab').click(function () {
182 | load_gallery();
183 | });
184 |
185 | $(".imgfile").change(function () {
186 | var action = $(this).attr('id').split("_")[0];
187 | readURL(this, '#' + action + '-img');
188 | });
189 |
190 |
191 |
192 |
193 | $('.btn-post').click(function () {
194 | var action = $(this).attr('id').split("-")[0];
195 | var form_data = new FormData($('#' + action + '-form')[0]);
196 | if (!Validate(form_data.entries())) {
197 | return;
198 | }
199 |
200 | $.ajax({
201 | type: 'POST',
202 | url: '/' + action,
203 | data: form_data,
204 | contentType: false,
205 | cache: false,
206 | processData: false,
207 | success: function (data) {
208 | try {
209 | data = JSON.parse(data)
210 | if (data.success == "false") {
211 | Swal.fire({
212 | title: 'Error!',
213 | text: data.error,
214 | icon: 'error',
215 | confirmButtonText: 'Ok'
216 | })
217 | }
218 | if (data.success == "true") {
219 | Swal.fire({
220 | title: 'Success!',
221 | text: data.message,
222 | icon: 'success',
223 | confirmButtonText: 'Ok'
224 | }).then((result) => {
225 | if (result.isConfirmed) {
226 | $('#' + action + '-img').attr('src', './img/avatar.png');
227 | $("#" + action + "-form :input").each(function () {
228 | if ($(this).is(":button")) {
229 | }
230 | else {
231 | $(this).val('');
232 | }
233 | });
234 | } else if (result.isDenied) {
235 | }
236 | })
237 | }
238 | }
239 | catch (err) {
240 | Swal.fire({
241 | title: 'Error!',
242 | text: err,
243 | icon: 'error',
244 | confirmButtonText: 'Ok'
245 | })
246 | }
247 | },
248 | });
249 | });
250 | });
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | Deepstack
11 |
12 |
13 |
14 |
15 |
16 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
83 |
84 |
85 |
86 |
115 |
144 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
199 |
200 |
201 |
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/trainer.py:
--------------------------------------------------------------------------------
1 | import os, json, requests, uvicorn, uuid
2 | import shutil, aiofiles, sqlite3, base64, subprocess
3 |
4 | from os import environ, path
5 | from loguru import logger
6 | from fastapi import FastAPI, Request, File, Form, UploadFile
7 | from fastapi.responses import UJSONResponse
8 | from fastapi.templating import Jinja2Templates
9 | from fastapi.responses import HTMLResponse
10 | from fastapi.staticfiles import StaticFiles
11 | from fastapi.responses import JSONResponse
12 |
13 |
14 |
15 | # from aiofiles import open
16 | db_path='./db/images.db'
17 | deepstack_host_address = os.getenv("DEEPSTACK_HOST_ADDRESS")
18 | deepstack_api_key = os.getenv("DEEPSTACK_API_KEY")
19 | min_confidence = os.getenv("MIN_CONFIDANCE")
20 |
21 | #создать папки
22 | create_folders='/config/deepstack/db /config/deepstack/photos/uploads'
23 |
24 | #копируем базу из аддона deepstack trainer в homeassistant
25 | copy_base_to_haos='/opt/trainer/db /config/deepstack'
26 |
27 | #копируем фото из аддона deepstack trainer в homeassistant
28 | copy_photos_to_haos='/opt/trainer/photos/uploads /config/deepstack/photos'
29 |
30 | #копируем базу из homeassistant в аддон deepstack trainer
31 | copy_base_to_docker='/config/deepstack/db/* /opt/trainer/db/'
32 |
33 | #копируем фото из homeassistant в аддон deepstack trainer
34 | copy_photos_to_docker='/config/deepstack/photos/uploads/* /opt/trainer/photos/uploads'
35 |
36 |
37 | if not min_confidence:
38 | min_confidence=0.70
39 | else:
40 | min_confidence=float(min_confidence)
41 |
42 | def teachme(person,image_file):
43 | user_image = open(image_file,"rb").read()
44 | response=""
45 | if not deepstack_api_key:
46 | response = requests.post("{}/v1/vision/face/register".format(deepstack_host_address), files={"image1":user_image},data={"userid":person}).json()
47 | else:
48 | response = requests.post("{}/v1/vision/face/register".format(deepstack_host_address), files={"image1":user_image},data={"userid":person,"api_key":deepstack_api_key}).json()
49 | if response.get('success') == False:
50 | raise Exception(response.get('error'))
51 | return response
52 |
53 | def detection(photo_path):
54 | image_data = open(photo_path,"rb").read()
55 | objects = ""
56 | response = ""
57 | if not deepstack_api_key:
58 | response = requests.post("{}/v1/vision/detection".format(deepstack_host_address),files={"image":image_data}, data={"min_confidence":min_confidence}).json()
59 | else:
60 | response = requests.post("{}/v1/vision/detection".format(deepstack_host_address),files={"image":image_data}, data={"min_confidence":min_confidence,"api_key":deepstack_api_key}).json()
61 | logger.debug(min_confidence)
62 | if response.get('success') == False:
63 | raise Exception(response.get('error'))
64 | for object in response["predictions"]:
65 | objects = objects + object["label"] + " ,"
66 | return objects
67 |
68 | def detect_scene(photo_path):
69 | image_data = open(photo_path,"rb").read()
70 | if not deepstack_api_key:
71 | response = requests.post("{}/v1/vision/scene".format(deepstack_host_address),files={"image":image_data}, data={"min_confidence":min_confidence}).json()
72 | else:
73 | response = requests.post("{}/v1/vision/scene".format(deepstack_host_address),files={"image":image_data}, data={"min_confidence":min_confidence,"api_key":deepstack_api_key}).json()
74 | if response.get('success') == False:
75 | raise Exception(response.get('error'))
76 | return str(response['label'])
77 |
78 | def getFaces(photo_path):
79 | users = ""
80 | image_data = open(photo_path,"rb").read()
81 | if not deepstack_api_key:
82 | response = requests.post("{}/v1/vision/face/recognize".format(deepstack_host_address),files={"image":image_data}, data={"min_confidence":min_confidence}).json()
83 | else:
84 | response = requests.post("{}/v1/vision/face/recognize".format(deepstack_host_address),files={"image":image_data}, data={"min_confidence":min_confidence,"api_key":deepstack_api_key}).json()
85 | if response.get('success') == False:
86 | raise Exception(response.get('error'))
87 | for user in response["predictions"]:
88 | users = users + user["userid"] + " ,"
89 | return users
90 |
91 |
92 |
93 | def allowed_file(filename):
94 | logger.info("Validating file type")
95 | return '.' in filename and \
96 | filename.rsplit('.', 1)[1].lower() in "jpg,png,gif,bmp,jpeg"
97 |
98 | def SaveImage(file, path):
99 | logger.info("Saving the image to the file system")
100 | try:
101 | with open(path, "wb") as buffer:
102 | shutil.copyfileobj(file, buffer)
103 | logger.info("File saved")
104 | except Exception as e:
105 | logger.error("Unable to save file " + str(e))
106 | raise Exception(str(e))
107 |
108 |
109 | def convertToBinaryData(filename):
110 | logger.info("Converting To Binary Data: " + filename)
111 | # Convert digital data to binary format
112 | try:
113 | with open(filename, 'rb') as file:
114 | blobData = file.read()
115 | logger.info("Data loaded successfully")
116 | return blobData
117 | except Exception as e:
118 | logger.error("Unable to blob " + str(e))
119 | raise Exception(str(e))
120 |
121 | def generate_file_name(file):
122 | try:
123 | logger.info("Renaming image name in order to avoid overwriting")
124 | file_name_without_ext=os.path.basename(file.rsplit('.', 1)[0])
125 | new_file_name = file.replace(file_name_without_ext, file_name_without_ext + "_" + str(uuid.uuid4()))
126 | return new_file_name
127 | except Exception as e:
128 | logger.error("Unable to rename " + str(e))
129 | return file
130 |
131 | ################################################################################
132 | #Когда фото сохраняется в базу, то идет перезапись базы и синхронизация файлов с последующим удалением
133 | #Когда обучаем Deepstack, то при сохранении фото, фото сохраняются в папку ХА
134 | def insertBLOB(name, photo):
135 | try:
136 | con = sqlite3.connect(db_path)
137 | cur = con.cursor()
138 | logger.info("Connected to SQLite")
139 | sqlite_insert_blob_query = """ INSERT INTO images
140 | (name, photo) VALUES (?, ?)"""
141 | data_tuple = (name, os.path.basename(photo))
142 | cur.execute(sqlite_insert_blob_query, data_tuple)
143 | con.commit()
144 | logger.info("Image and file inserted successfully as a BLOB into a table")
145 | os.system(f'cp -rf {copy_base_to_haos}')
146 | os.system(f'rsync -havuz --delete {copy_photos_to_haos}')
147 | con.close()
148 | except Exception as error:
149 | logger.error("Failed to insert blob data into sqlite table " + str(error))
150 | finally:
151 | if con:
152 | con.close()
153 | logger.info("the sqlite connection is closed")
154 |
155 |
156 | ################################################################################
157 | #Когда стартует или перезагружается аддон DeepStack Trainer, то база и фото копируются из папки ХА в аддон DeepStack Trainer
158 | def InitDB():
159 | if os.path.exists(db_path):
160 | return
161 | logger.info("Initializing Database")
162 | os.system(f'mkdir -p {create_folders}')
163 | os.system(f'cp -rf {copy_base_to_docker}')
164 | os.system(f'cp -rf {copy_photos_to_docker}')
165 | con = sqlite3.connect(db_path)
166 | cur = con.cursor()
167 | cur.execute('CREATE TABLE IF NOT EXISTS images (name TEXT NOT NULL, photo TEXT NOT NULL, dt datetime default current_timestamp);')
168 | con.commit()
169 | con.close()
170 | ################################################################################
171 |
172 | ################################################################################
173 | #Когда удаляем фото из базы, то идет перезапись базы и удаляются фото из папки
174 | def delete_image(image_file):
175 | if os.path.exists(image_file):
176 | os.remove(image_file)
177 | os.system(f'cp -rf {copy_base_to_haos}')
178 | os.system(f'rsync -havuz --delete {copy_photos_to_haos}')
179 | return True
180 | else:
181 | return False
182 | ################################################################################
183 |
184 | logger.info("Configuring app")
185 | app = FastAPI(title="Deepstack Trainer", description="Train your deepstack AI server", version="1.0.0")
186 | app.mount("/dist", StaticFiles(directory="dist"), name="dist")
187 | app.mount("/js", StaticFiles(directory="dist/js"), name="js")
188 | app.mount("/css", StaticFiles(directory="dist/css"), name="css")
189 | app.mount("/img", StaticFiles(directory="dist/img"), name="img")
190 | app.mount("/uploads", StaticFiles(directory="photos/uploads"), name="img")
191 | templates = Jinja2Templates(directory="templates/")
192 |
193 | @app.post('/teach')
194 | def teach(person: str = Form(...) ,teach_file: UploadFile = File(...)):
195 | logger.info("Start learning new face for: " + person)
196 | try:
197 | InitDB()
198 | if teach_file and allowed_file(teach_file.filename):
199 | image_file = os.path.join('./photos/uploads', generate_file_name(teach_file.filename))
200 | SaveImage(teach_file.file, image_file)
201 | logger.info("Sending the image to deepstack server")
202 | response = teachme(person,image_file)
203 | success = str(response['success']).lower()
204 | if 'message' in str(response):
205 | message = response['message']
206 | logger.info("Saving image to Database")
207 | if success=='true':
208 | insertBLOB(person,image_file)
209 | else:
210 | delete_image(image_file)
211 | return JSONResponse(content = '{"message":"'+message+'","success":"'+success+'"}')
212 | if 'error' in str(response):
213 | delete_image(image_file)
214 | error = response['error']
215 | logger.error("Unable to learn " + error)
216 | return JSONResponse(content = '{"error":"'+error+'","success":"'+success+'"}')
217 | return response
218 | except Exception as e:
219 | delete_image(image_file)
220 | error = "Aw Snap! something went wrong - " + str(e)
221 | logger.error(error)
222 | return JSONResponse(content = '{"error":"'+error+'","success":"false"}')
223 |
224 |
225 | @app.post('/who')
226 | def who(who_file: UploadFile = File(...)):
227 | logger.info("Starting face detection")
228 | try:
229 | InitDB()
230 | if who_file and allowed_file(who_file.filename):
231 | filename = who_file.filename
232 | image_file = os.path.join('./photos', filename)
233 | SaveImage(who_file.file, image_file)
234 | logger.info("sending image to Deepstack server")
235 | response = getFaces(image_file)
236 | if response == '"" ,':
237 | response='unknown'
238 | return JSONResponse(content = '{"message":"The person in the picture is ' + str(response) + '","success":"true"}')
239 | except Exception as e:
240 | logger.error("Face Detection error " + str(e) )
241 | return JSONResponse(content = '{"error":"'+ str(e) +'","success":"false"}')
242 | finally:
243 | logger.info("Deleting file to save space")
244 | delete_image(image_file)
245 |
246 | @app.post('/detect')
247 | def detect(detect_file: UploadFile = File(...)):
248 | logger.info("Starting object detection")
249 | try:
250 | InitDB()
251 | if detect_file and allowed_file(detect_file.filename):
252 | filename = detect_file.filename
253 | image_file = os.path.join('./photos', filename)
254 | logger.info("sending image to Deepstack server")
255 | SaveImage(detect_file.file, image_file)
256 | response = detection(image_file)
257 | if response == '"" ,':
258 | response='unknown'
259 | return JSONResponse(content = '{"message":"The objects in the picture are ' + str(response) + '","success":"true"}')
260 | except Exception as e:
261 | logger.error("Object Detection error " + str(e))
262 | return JSONResponse(content = '{"error":"'+ str(e) +'","success":"false"}')
263 | finally:
264 | logger.info("Deleting file to save space")
265 | delete_image(image_file)
266 |
267 | @app.post('/scene')
268 | def scene(scene_file: UploadFile = File(...)):
269 | logger.info("Starting scene detection")
270 | try:
271 | InitDB()
272 | if scene_file and allowed_file(scene_file.filename):
273 | filename = scene_file.filename
274 | image_file = os.path.join('./photos', filename)
275 | logger.info("sending image to Deepstack server")
276 | SaveImage(scene_file.file, image_file)
277 | response = detect_scene(image_file)
278 | if response == '"" ,':
279 | response='unknown'
280 | return JSONResponse(content = '{"message":"The objects in the picture are ' + str(response) + '","success":"true"}')
281 | except Exception as e:
282 | logger.error("Object Detection error " + str(e))
283 | return JSONResponse(content = '{"error":"'+ str(e) +'","success":"false"}')
284 | finally:
285 | logger.info("Deleting file to save space")
286 | delete_image(image_file)
287 |
288 | ################################################################################
289 | #Когда переименовываем фото в галерее фото, то идет перезапись базы
290 | @app.post('/api/rename')
291 | async def rename(request: Request ):
292 | data = await request.json()
293 | try:
294 | InitDB()
295 | conn = sqlite3.connect(db_path)
296 | sql = ''' UPDATE images
297 | SET name = ?
298 | WHERE photo = ?'''
299 | cur = conn.cursor()
300 | cur.execute(sql, (data['text'], data['img']))
301 | conn.commit()
302 | os.system(f'cp -rf {copy_base_to_haos}')
303 | return JSONResponse(content = '{"message":"Person renamed","success":"true"}')
304 | except Exception as e:
305 | error = "Aw Snap! something went wrong " + str(e)
306 | logger.error(error)
307 | return JSONResponse(content = '{"error":"'+error+'","success":"false"}')
308 | ################################################################################
309 |
310 |
311 |
312 | @app.post('/api/delete')
313 | async def delete(request: Request):
314 | logger.info("Deleting")
315 | data = await request.json()
316 | try:
317 | image_file = os.path.join('./photos/uploads', data['img'])
318 | logger.debug('########## ' + image_file)
319 | if delete_image(image_file) == True:
320 | InitDB()
321 | conn = sqlite3.connect(db_path)
322 | sql = 'DELETE from images WHERE photo = "' + data['img'] + '"'
323 | cur = conn.cursor()
324 | cur.execute(sql)
325 | conn.commit()
326 | return JSONResponse(content = '{"message":"Image Deleted","success":"true"}')
327 | else:
328 | return JSONResponse(content = '{"error":"Unable to delete image","success":"false"}')
329 | except Exception as e:
330 | error = "Aw Snap! something went wrong " + str(e)
331 | logger.error(error)
332 | return JSONResponse(content = '{"error":"'+error+'","success":"false"}')
333 |
334 |
335 | @app.get("/")
336 | def home(request: Request):
337 | InitDB()
338 | logger.info("loading default page")
339 | return templates.TemplateResponse('index.html', context={'request': request})
340 |
341 |
342 | @app.get("/api/images")
343 | def get_images(request: Request):
344 | try:
345 | with sqlite3.connect(db_path, check_same_thread=False) as con:
346 | cur = con.cursor()
347 | cur.execute('SELECT * FROM images order by dt')
348 | return templates.TemplateResponse('gallery.html', context={'request': request, 'images' : cur.fetchall()} )
349 | except Exception as e:
350 | logger.error("Error fetch images, " + str(e))
351 | return None
352 |
353 |
354 | # Start Application
355 | if __name__ == '__main__':
356 | InitDB()
357 | uvicorn.run(app, host="0.0.0.0", port=8080)
358 |
--------------------------------------------------------------------------------
/deepstack-trainer/trainer/dist/webfonts/fa-regular-400.svg:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
804 |
--------------------------------------------------------------------------------