You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
3.7 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import os
import sys
import cv2 as cv
import numpy as np
import requests
import imageWorking
import neuralNetwork
import ontologyWorking
url = 'http://kb.athene.tech/api/1.0/ontology/'
def analyze_base(ontology_uid: str, image: np.ndarray, queries: list[str]) -> tuple[2]:
'''
Базовая функция анализа файла и вывода результатов обработки.
@param ontology_uid: УИД онтологии.
@param image: Изображение.
'''
if not ontologyWorking.is_ontology_exists(ontology_uid, url):
raise Exception(f'Онтология с uid {ontology_uid} не существует')
if image is None:
raise Exception(f'Изображение не указано')
model = neuralNetwork.load_model()
# Распознавание изображения.
results = model.predict(source=image)
# Создание аксиом онтологии на основе результатов распознавания.
object_properties = list()
data_properties = list()
for res in results:
classes = res.boxes.cls.int()
conf = res.boxes.conf
boxes = res.boxes.xywh
request = ontologyWorking.get_request_data(model.names, classes, conf, boxes)
object_properties += request[0]
data_properties += request[1]
# Формирование данных для запроса к сервису работы с онтологиями.
data = {
'data':
{
'objectPropertyAssertions': object_properties,
'dataPropertyAssertions': data_properties
}
}
params = '&'.join([f'names={query}' for query in queries])
# Выполнение запроса.
response = requests.post(url + f'{ontology_uid}/query/multi?{params}', json=data).json()
return results, response
def analyze_file(ontology_uid: str, image_path: str) -> None:
'''
Анализирует файл и выводит результат в консоль.
@param ontology_uid: УИД онтологии.
@param image_path: Путь до изображения.
'''
if not os.path.isfile(image_path):
raise Exception(f'Изображение {image_path} не существует')
image = imageWorking.get_image_file_as_array(image_path)
queries = [ 'QueryGetNotEmpty', 'QueryGetCheck', 'QueryGetEmpty' ]
# Распознавание изображения.
results, response = analyze_base(ontology_uid, image, queries)
result = {
'QueryGetNotEmpty': '',
'QueryGetCheck': '',
'QueryGetEmpty': ''
}
if response['error']:
raise Exception(response['error'])
for query in response['response']:
result[query] = [resultSQWRL['name']['value'] for resultSQWRL in response['response'][query]['rows']]
print(f'Запрос выполнен')
# Вывод результата.
print()
print('Результат:')
if result['QueryGetNotEmpty']:
print('Аудитория занята')
elif result['QueryGetCheck']:
print('Аудиторию необходимо проверить')
elif result['QueryGetEmpty']:
print('Аудитория пустая')
else:
print('Неизвестное состояние')
# Вывод изображения.
cv.imshow('result', results[0].plot())
cv.waitKey(0)
cv.destroyAllWindows()
# Точка входа в приложение.
if __name__ == '__main__':
if len(sys.argv) != 3:
print(f'Запуск: {sys.argv[0]} <Ontology UID> <Image path>')
exit(1)
analyze_file(sys.argv[1], sys.argv[2])