From 8bba4e72d669fb34ae33e0aed3d525a4815b9101 Mon Sep 17 00:00:00 2001 From: Vladislav Moiseev Date: Sun, 9 Jul 2023 00:02:26 +0400 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=B7=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=BA=D0=B0?= =?UTF-8?q?=20=D1=81=D0=B2=D0=BE=D0=B8=D1=85=20=D0=BE=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BB=D0=BE=D0=B3=D0=B8=D0=B9,=20=D0=BD=D0=B5=D0=BC=D0=BD?= =?UTF-8?q?=D0=BE=D0=B3=D0=BE=20=D0=BA=D1=80=D0=B0=D1=81=D0=BE=D1=82=D1=8B?= =?UTF-8?q?=20=D0=B2=20webapp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ontologyWorking.py | 51 +++++++++++++++++++++++++++++++++++------- src/webApp.py | 32 +++++++++++++++++--------- static/index.html | 23 +++++++++++++------ 3 files changed, 80 insertions(+), 26 deletions(-) diff --git a/src/ontologyWorking.py b/src/ontologyWorking.py index 196c455..e369600 100644 --- a/src/ontologyWorking.py +++ b/src/ontologyWorking.py @@ -11,13 +11,39 @@ def is_ontology_exists(ontology_uid: str, url: str) -> bool: @param ontology_uid: УИД онтологии. @param url: Базовый URL сервиса. ''' - list_ontologies = requests.get(url).json()['response']['items'] + list_ontologies = requests.get(url).json() + list_ontologies = list_ontologies['response']['items'] for onto in list_ontologies: if onto['uid'] == ontology_uid: return True return False +def upload_ontology(name: str, file_buf) -> str: + """ + Загружает файл. + :param name: Имя файла. + :param file_buf: Содержимое файла. + :return: УИД загруженной онтологии. + """ + files = {'file': file_buf} + response = requests.post(f'{url}?name={name}', files=files) + response = response.json() + return response['response']['uid'] + + +def delete_ontology(ontology_uid: str) -> bool: + """ + Загружает файл. + :param name: Имя файла. + :param file_buf: Содержимое файла. + :return: УИД загруженной онтологии. + """ + response = requests.delete(url + ontology_uid) + response = response.json() + return False if response['error'] else True + + def rename_entity(list_names: dict) -> dict: ''' Нормализация названий объектов. @@ -52,16 +78,24 @@ def get_request_data(entities: dict, objects: np.ndarray, confs: np.ndarray, box for entity_idx, entity in enumerate(entities): if (entity_idx in objects): - object_properties.append({'domain': entity, 'property': 'locatedIn', 'range': classroom}) + object_properties.append( + {'domain': entity, 'property': 'locatedIn', 'range': classroom}) else: - object_properties.append({'domain': entity, 'property': 'notLocatedIn', 'range': classroom}) + object_properties.append( + {'domain': entity, 'property': 'notLocatedIn', 'range': classroom}) for object_idx, object in enumerate(objects): conf = confs[object_idx] box = boxes[object_idx] entity = entities[object.item()] - data_properties.append({'domain': entity, 'property': 'hasArea', 'value': get_entity_square(float(box[2]), float(box[3]))}) - data_properties.append({'domain': entity, 'property': 'hasConfidence', 'value': float(conf)}) + data_properties.append( + {'domain': entity, + 'property': 'hasArea', + 'value': get_entity_square(float(box[2]), float(box[3]))}) + data_properties.append( + {'domain': entity, + 'property': 'hasConfidence', + 'value': float(conf)}) return object_properties, data_properties @@ -86,8 +120,9 @@ def analyze(ontology_uid: str, object_properties: list, data_properties: list, q } } params = '&'.join([f'names={query}' for query in queries]) - + # Выполнение запроса. - response = requests.post(url + f'{ontology_uid}/query/multi?{params}', json=data).json() - + response = requests.post( + url + f'{ontology_uid}/query/multi?{params}', json=data).json() + return response diff --git a/src/webApp.py b/src/webApp.py index 8b62c26..ff31882 100644 --- a/src/webApp.py +++ b/src/webApp.py @@ -4,13 +4,16 @@ from flask import Flask, redirect, request import numpy from imageWorking import get_image_buf_as_array from main import analyze_base +from ontologyWorking import delete_ontology, upload_ontology + +app = Flask(__name__, static_folder="../static", static_url_path="/") -app = Flask(__name__, static_folder = "../static", static_url_path = "/") @app.route("/") def main(): return redirect('index.html') + @app.route("/analyze", methods=["POST"]) def analyze(): # Первоначальные проверки. @@ -19,27 +22,34 @@ def analyze(): 'success': False, 'error': 'Укажите изображение', } + + ontology_uid = '5cc5570b-6ed9-3b33-9db4-bdb8ecb9f890' + remove_ontology = False if 'ontology' in request.files and request.files['ontology'].filename != '': - return { - 'success': False, - 'error': 'Загрузка онтологии ещё не реализована', - } + ontology_uid = upload_ontology( + request.files['ontology'].filename, request.files['ontology']) + remove_ontology = True # Подготовка исходного изображения. - image_source = request.files['image'].read(); + image_source = request.files['image'].read() image_source = numpy.fromstring(image_source, numpy.uint8) image_source = get_image_buf_as_array(image_source) - + # Подготовка прочих данных и выполнение запроса. - queries = request.form['queries'].split(',') if request.form['queries'] is not None else [ ] - results, response = analyze_base('5cc5570b-6ed9-3b33-9db4-bdb8ecb9f890', image_source, queries) - + queries = request.form['queries'].split( + ',') if request.form['queries'] is not None else [] + results, response = analyze_base(ontology_uid, image_source, queries) + + # Если требуется, чистим за собой. + if remove_ontology: + delete_ontology(ontology_uid) + # Подготовка изображения с ответом. image_result = results[0].plot() image_result = cv.cvtColor(image_result, cv.COLOR_BGR2RGB) image_result = cv.imencode(".jpg", image_result)[1] image_result = base64.b64encode(image_result).decode("utf-8") - + # Вывод ответа. return { 'success': True, diff --git a/static/index.html b/static/index.html index fd3635f..f77a8c0 100644 --- a/static/index.html +++ b/static/index.html @@ -26,19 +26,28 @@
-

Загрузите изображение в поле ниже, чтобы проверить, на фотография пустая или заполненная аудитория.

+

Загрузите изображение и, если требуется, собственную онтологию для анализа.

-
- +
+
-
+
- + +
Для анализа заполненности аудиторий оставьте это поле пустым.
-
+
- + +
Для анализа заполненности аудиторий не изменяйте это поле.