Немного унифицирована работа с запросами к KB

pull/5/head
Vladislav Moiseev 1 year ago
parent 52335870fd
commit d70592fc64

@ -3,14 +3,11 @@ 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]:
'''
@ -18,8 +15,6 @@ def analyze_base(ontology_uid: str, image: np.ndarray, queries: list[str]) -> tu
@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()
@ -38,19 +33,10 @@ def analyze_base(ontology_uid: str, image: np.ndarray, queries: list[str]) -> tu
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()
# Выполнение запроса к сервису работы с онтологиями
response = ontologyWorking.analyze(ontology_uid, object_properties, data_properties, queries)
return results, response

@ -2,15 +2,18 @@ import numpy as np
import requests
def is_ontology_exists(uid: str, url: str) -> bool:
url = 'http://kb.athene.tech/api/1.0/ontology/'
def is_ontology_exists(ontology_uid: str, url: str) -> bool:
'''
Проверяет, существует ли онтология в сервисе.
@param uid: УИД онтологии.
@param ontology_uid: УИД онтологии.
@param url: Базовый URL сервиса.
'''
list_ontologies = requests.get(url).json()['response']['items']
for onto in list_ontologies:
if onto['uid'] == uid:
if onto['uid'] == ontology_uid:
return True
return False
@ -61,3 +64,30 @@ def get_request_data(entities: dict, objects: np.ndarray, confs: np.ndarray, box
data_properties.append({'domain': entity, 'property': 'hasConfidence', 'value': float(conf)})
return object_properties, data_properties
def analyze(ontology_uid: str, object_properties: list, data_properties: list, queries: list[str]) -> tuple[2]:
'''
Базовая функция анализа.
@param ontology_uid: УИД онтологии.
@param object_properties: Объектные свойства.
@param data_properties: Свойства данных.
@param queries: Список запросов для запуска.
'''
if not is_ontology_exists(ontology_uid, url):
raise Exception(f'Онтология с uid {ontology_uid} не существует')
# Формирование данных для запроса к сервису работы с онтологиями.
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 response

@ -31,7 +31,7 @@ def analyze():
image_source = get_image_buf_as_array(image_source)
# Подготовка прочих данных и выполнение запроса.
queries = [ 'QueryGetNotEmpty', 'QueryGetCheck', 'QueryGetEmpty' ]
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)
# Подготовка изображения с ответом.

@ -5,6 +5,8 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Анализ аудиторий</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
</head>
<body>
<p>
@ -20,12 +22,22 @@
<label for="ontology">Онтология предметной области</label>
<input type="file" name="ontology" id="ontology" />
</div>
<div>
<label for="queries">Набор запросов для запуска</label>
<input
type="text"
name="queries"
id="queries"
value="QueryGetNotEmpty,QueryGetCheck,QueryGetEmpty"
/>
</div>
<div>
<button type="submit">Отправить</button>
</div>
</form>
<img src="" alt="Результат" id="imgslot" />
<img src="none.png" alt="Результат" id="imgslot" />
<div id="queriesResult"></div>
<script>
document
@ -36,12 +48,37 @@
fetch("/analyze", { method: "POST", body: data })
.then((res) => res.json())
.then((data) => {
debugger;
const img = document.getElementById("imgslot");
const queriesResult = document.getElementById("queriesResult");
img.src = "none.png";
if (data.image) {
document.getElementById("imgslot").src =
"data:image/jpg;base64," + data.image;
img.src = "data:image/jpg;base64," + data.image;
}
queriesResult.innerHTML = "";
if (data.data && data.data.response) {
for (const [query, result] of Object.entries(
data.data.response
)) {
// Отрисовка результата запросов.
const markup = `
<h1>${query}</h1>
<table class="table table-bordered table-striped">
<tr>
${result.columns.map((column) => `<th>${column}</th>`).join("")}
</tr>
${result.rows.map(
(row) =>
`<tr>${Object.entries(row)
.map(([key, value]) => `<td>${value.value}</td>`)
.join("")}</tr>`
)}
</table>
`;
queriesResult.innerHTML += markup;
}
}
console.log(data);
});
});
</script>

Loading…
Cancel
Save