This commit is contained in:
2026-09-29 23:33:19 +03:00
parent da32158789
commit e47a45dc93
7 changed files with 667 additions and 0 deletions
+523
View File
@@ -0,0 +1,523 @@
openapi: 3.0.3
info:
title: open_cv — stateless CV-сервис
version: 1.0.0
description: |
Микросервис компьютерного зрения: извлекает SIFT-признаки зданий
(`POST /api/v1/features`) и верифицирует фотографии по готовым признакам
эталонов (`POST /api/v1/verify`). Stateless: сервис ничего не хранит —
фотографии и блобы признаков принадлежат основному сервису и S3.
Это машиночитаемая копия контракта `docs/05-rest-api.md` для импорта
(openapi-generator, Postman, Insomnia и т.п.). Каждый ответ несёт
заголовок `X-Trace-Id` — идентификатор запроса для разбора инцидентов.
Правила входных данных (кратко):
* изображения — JPEG/PNG/WebP, фактический формат определяется при
декодировании, не по расширению; EXIF-ориентация применяется сервером;
* части `reference` различаются по бинарной сигнатуре: zip-магика `PK` —
блоб `.npz`, сигнатуры JPEG/PNG/WebP — изображение (отладочный режим,
признаки извлекаются на лету); смешивание допустимо;
* `settings` — form-часть с JSON-строкой ≤ 4 КБ; строгая валидация:
неизвестные ключи/профили и значения вне диапазонов отвергаются.
servers:
- url: http://localhost:8000
description: Локальная разработка (uvicorn / docker compose)
security:
- ApiKeyAuth: []
tags:
- name: features
description: Извлечение признаков — один раз на эталонное фото
- name: verify
description: Верификация пробы по блобам/изображениям эталонов
- name: profiles
description: Каталог профилей настроек распознавания
- name: service
description: Диагностика (без авторизации)
paths:
/api/v1/features:
post:
tags: [features]
operationId: extractFeatures
summary: Извлечь признаки из изображения
description: |
Возвращает блоб признаков `.npz` — непрозрачен для вызывающего:
сохраните как есть (в S3 рядом с оригиналом фото) и передавайте
обратно в `/verify` без разборки и модификаций.
Семантика `settings`: применяются эффективные параметры **извлечения**
(профиль + `extraction`), их отпечаток — в заголовке `X-Algo-Id`;
секция **`comparison`** записывается в блоб и применяется как значения
по умолчанию при каждом `/verify` с этим эталоном.
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [image]
properties:
image:
type: string
format: binary
description: JPEG/PNG/WebP, ≤ MAX_IMAGE_MB (по умолчанию 20 МБ), ≥ 640×480 после EXIF-ориентации
settings:
$ref: '#/components/schemas/RequestSettings'
encoding:
image:
contentType: application/octet-stream
settings:
contentType: application/json
responses:
'200':
description: Блоб признаков `.npz` (бинарное тело)
headers:
X-Feature-Format-Version:
description: Версия формата блоба (для управления пересчётом эталонов)
schema: {type: integer, example: 1}
X-Algo-Id:
description: Отпечаток эффективных параметров извлечения
schema: {type: string, example: 'sift-v1:a3f9c2f6'}
X-Keypoints-Count:
description: Число ключевых точек
schema: {type: integer, example: 4127}
X-Image-Width:
description: Ширина оригинала после EXIF-ориентации
schema: {type: integer, example: 1400}
X-Image-Height:
description: Высота оригинала после EXIF-ориентации
schema: {type: integer, example: 900}
content:
application/octet-stream:
schema: {type: string, format: binary}
'400':
description: |
IMAGE_DECODE_FAILED — файл не декодируется как изображение;
IMAGE_TOO_SMALL — разрешение < 640×480;
UNKNOWN_PROFILE — неизвестный профиль в settings.
content:
application/json:
schema: {$ref: '#/components/schemas/ErrorResponse'}
'401': {$ref: '#/components/responses/Unauthorized'}
'403': {$ref: '#/components/responses/Forbidden'}
'413': {$ref: '#/components/responses/PayloadTooLarge'}
'415': {$ref: '#/components/responses/UnsupportedMediaType'}
'422':
description: INVALID_SETTINGS — некорректный JSON, неизвестный ключ или значение вне диапазона в settings
content:
application/json:
schema: {$ref: '#/components/schemas/ErrorResponse'}
'500': {$ref: '#/components/responses/Internal'}
/api/v1/verify:
post:
tags: [verify]
operationId: verifyPhoto
summary: Верифицировать фото пробы по эталонам
description: |
Сравнивает пробу с каждым эталоном; итог — пара с максимальным
`confidence` (при равенстве — с большим `inliers`). Значения
`uncertain` — «недостаточно признаков, нужна ручная проверка»:
трактовка — бизнес-решение вызывающего сервиса. Результат
детерминирован (NFR-009), автоповтор запроса бессмысленен.
Приоритет параметров сравнения: запрос → блоб → профиль → env.
Эффективные пороги возвращаются в `details.thresholds`.
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [probe, reference]
properties:
probe:
type: string
format: binary
description: Фото пробы — JPEG/PNG/WebP, ≤ MAX_IMAGE_MB, ≥ 640×480
reference:
type: array
items: {type: string, format: binary}
minItems: 1
maxItems: 32
description: |
Эталоны (1…MAX_REFERENCES_PER_REQUEST, по умолчанию 32):
блоб `.npz` из ответа /features **или** изображение
JPEG/PNG/WebP — отладочный режим, признаки извлекаются на
лету (каждое стоит полного извлечения). Тип определяется по
бинарной сигнатуре. Порядок частей задаёт индексы
(`best_reference_index`, 0-based); смешивание допустимо.
Суммарный запрос ≤ VERIFY_MAX_BODY_MB (64 МБ).
settings:
$ref: '#/components/schemas/RequestSettings'
encoding:
probe:
contentType: application/octet-stream
reference:
contentType: application/octet-stream
settings:
contentType: application/json
responses:
'200':
description: Вердикт, уверенность и метрики лучшей пары
content:
application/json:
schema: {$ref: '#/components/schemas/VerifyResponse'}
'400':
description: |
FEATURE_BLOB_INVALID — блоб не является корректным .npz признаков
(структура/массивы/лимиты); FEATURE_FORMAT_UNSUPPORTED —
format_version блоба не поддерживается, эталоны требуют пересчёта
через POST /api/v1/features (в details — reference_index);
TOO_MANY_REFERENCES — число эталонов превышает лимит;
IMAGE_DECODE_FAILED — проба/эталон не декодируются или содержимое
reference не распознано; IMAGE_TOO_SMALL — разрешение < 640×480.
content:
application/json:
schema: {$ref: '#/components/schemas/ErrorResponse'}
'401': {$ref: '#/components/responses/Unauthorized'}
'403': {$ref: '#/components/responses/Forbidden'}
'413': {$ref: '#/components/responses/PayloadTooLarge'}
'415': {$ref: '#/components/responses/UnsupportedMediaType'}
'422':
description: |
VALIDATION_ERROR — отсутствует часть probe или все reference;
INVALID_SETTINGS — некорректный JSON/ключ/значение в settings.
content:
application/json:
schema: {$ref: '#/components/schemas/ErrorResponse'}
'500': {$ref: '#/components/responses/Internal'}
/api/v1/profiles:
get:
tags: [profiles]
operationId: listProfiles
summary: Каталог профилей настроек
description: |
Профили, доступные для поля `settings.profile` (FR-009). В
`extraction`/`comparison` профиля указаны только отличия от базовых
значений; незаполненные поля наследуются от env-умолчаний (блок
`defaults`). Состав каталога версионируется вместе с релизами open_cv.
responses:
'200':
description: Список профилей
content:
application/json:
schema: {$ref: '#/components/schemas/ProfilesResponse'}
'401': {$ref: '#/components/responses/Unauthorized'}
'403': {$ref: '#/components/responses/Forbidden'}
'500': {$ref: '#/components/responses/Internal'}
/health:
get:
tags: [service]
operationId: health
summary: Процесс жив
security: []
responses:
'200':
description: OK
content:
application/json:
schema: {$ref: '#/components/schemas/StatusResponse'}
'500': {$ref: '#/components/responses/Internal'}
/ready:
get:
tags: [service]
operationId: ready
summary: Готовность (конфигурация валидна, CV-ядро инициализировано)
security: []
responses:
'200':
description: Готов
content:
application/json:
schema: {$ref: '#/components/schemas/StatusResponse'}
'503':
description: Неготовен (причины — в reasons)
content:
application/json:
schema: {$ref: '#/components/schemas/UnreadyResponse'}
'500': {$ref: '#/components/responses/Internal'}
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
description: Значение переменной окружения APP_API_KEY. Отсутствие — 401, несовпадение — 403.
responses:
Unauthorized:
description: UNAUTHORIZED — заголовок X-API-Key отсутствует
content:
application/json:
schema: {$ref: '#/components/schemas/ErrorResponse'}
Forbidden:
description: FORBIDDEN — неверный API-ключ
content:
application/json:
schema: {$ref: '#/components/schemas/ErrorResponse'}
PayloadTooLarge:
description: PAYLOAD_TOO_LARGE — тело запроса сверх лимита (MAX_IMAGE_MB / VERIFY_MAX_BODY_MB)
content:
application/json:
schema: {$ref: '#/components/schemas/ErrorResponse'}
UnsupportedMediaType:
description: UNSUPPORTED_MEDIA_TYPE — формат изображения не JPEG/PNG/WebP
content:
application/json:
schema: {$ref: '#/components/schemas/ErrorResponse'}
Internal:
description: INTERNAL — внутренняя ошибка; детали в логах по trace_id
content:
application/json:
schema: {$ref: '#/components/schemas/ErrorResponse'}
schemas:
RequestSettings:
type: object
description: |
Настройки распознавания (FR-008). Передаются как form-часть `settings`
с JSON-строкой ≤ 4 КБ. Профиль покрывает тип объекта, переопределения —
тюнинг конкретного объекта. В /verify секция `extraction` применяется
только к эталонам-изображениям отладочного режима.
additionalProperties: false
properties:
profile:
type: string
enum: [facade, monument, repetitive]
description: Именованный пресет (каталог — GET /api/v1/profiles)
extraction:
$ref: '#/components/schemas/ExtractionSettings'
comparison:
$ref: '#/components/schemas/ComparisonSettings'
ExtractionSettings:
type: object
description: Параметры извлечения — входят в отпечаток algo_id; format_version не меняют
additionalProperties: false
properties:
max_image_size:
type: integer
minimum: 320
maximum: 8192
description: Длинная сторона приведённого изображения, px (по умолчанию 1600)
max_keypoints:
type: integer
minimum: 100
maximum: 65536
description: Потолок ключевых точек; дополнительно ограничен сервисным SIFT_MAX_KEYPOINTS
clahe_clip_limit:
type: number
minimum: 0.5
maximum: 10.0
description: Контраст CLAHE (по умолчанию 2.0)
clahe_tile_grid:
type: array
minItems: 2
maxItems: 2
items: {type: integer, minimum: 1, maximum: 16}
description: Сетка тайлов CLAHE [w, h] (по умолчанию [8, 8])
ComparisonSettings:
type: object
description: Параметры сравнения — применяются к запросу без пересчёта эталонов
additionalProperties: false
properties:
geometry_model:
type: string
enum: [homography, fundamental]
description: Геометрическая модель RANSAC — плоские фасады / объёмные объекты
lowe_ratio:
type: number
minimum: 0.5
maximum: 0.95
description: Коэффициент теста Лоу (по умолчанию 0.75)
ransac_reproj_threshold:
type: number
minimum: 1.0
maximum: 15.0
description: Порог RANSAC, px (по умолчанию 5.0)
match_inliers_min:
type: integer
minimum: 5
maximum: 1000
description: Порог match по числу инлаеров (по умолчанию 50)
match_inliers_ratio_min:
type: number
minimum: 0.05
maximum: 0.95
description: Порог match по доле инлаеров (по умолчанию 0.30)
match_coverage_min:
type: number
minimum: 0.0
maximum: 0.5
description: Минимальное покрытие площади пробы (по умолчанию 0.05)
uncertain_inliers_min:
type: integer
minimum: 1
maximum: 500
description: Нижняя граница зоны uncertain (по умолчанию 20)
VerifyResponse:
type: object
required: [verdict, is_match, confidence, details, probe_sha256, processing_ms]
properties:
verdict:
type: string
enum: [match, uncertain, no_match]
is_match:
type: boolean
description: true только при verdict = match
confidence:
type: number
format: float
minimum: 0
maximum: 1
description: Нормированная уверенность; при uncertain обычно 0.2–0.5
details:
$ref: '#/components/schemas/VerifyDetails'
probe_sha256:
type: string
description: SHA-256 файла пробы (hex, 64 символа) — для аудита основного сервиса
processing_ms:
type: integer
description: Время обработки на сервере
VerifyDetails:
type: object
required: [references_compared, best_reference_index, metrics, thresholds]
properties:
references_compared:
type: integer
best_reference_index:
type: integer
minimum: 0
description: Индекс части reference (0-based, в порядке следования в запросе)
metrics:
$ref: '#/components/schemas/PairMetrics'
thresholds:
$ref: '#/components/schemas/ComparisonThresholds'
PairMetrics:
type: object
required: [good_matches, inliers, inlier_ratio, coverage]
properties:
good_matches:
type: integer
description: Число пар после теста Лоу
inliers:
type: integer
description: Число инлаеров RANSAC
inlier_ratio:
type: number
format: float
description: inliers / good_matches
coverage:
type: number
format: float
description: Доля площади пробы под выпуклой оболочкой инлаеров
ComparisonThresholds:
type: object
description: Эффективные пороги сравнения лучшей пары (с учётом профиля, настроек блоба и переопределений запроса)
required: [inliers_match, inlier_ratio_match, coverage_min, inliers_uncertain_min]
properties:
inliers_match: {type: integer, example: 50}
inlier_ratio_match: {type: number, example: 0.3}
coverage_min: {type: number, example: 0.05}
inliers_uncertain_min: {type: integer, example: 20}
geometry_model: {type: string, enum: [homography, fundamental]}
lowe_ratio: {type: number, example: 0.75}
ransac_reproj_threshold: {type: number, example: 5.0}
ProfilesResponse:
type: object
required: [profiles]
properties:
profiles:
type: array
items: {$ref: '#/components/schemas/Profile'}
defaults:
type: object
description: Базовые значения (env-умолчания), от которых наследуются незаполненные поля профилей
properties:
extraction: {type: object, additionalProperties: true}
comparison: {type: object, additionalProperties: true}
Profile:
type: object
required: [name, description, extraction, comparison]
properties:
name:
type: string
example: monument
description:
type: string
extraction:
type: object
additionalProperties: true
description: Только отличия от базовых значений
comparison:
type: object
additionalProperties: true
description: Только отличия от базовых значений
StatusResponse:
type: object
required: [status]
properties:
status: {type: string, example: ok}
UnreadyResponse:
type: object
required: [status, reasons]
properties:
status: {type: string, example: unavailable}
reasons:
type: array
items: {type: string}
ErrorResponse:
type: object
required: [error]
properties:
error:
$ref: '#/components/schemas/Error'
Error:
type: object
required: [code, message, details, trace_id]
properties:
code:
type: string
enum:
- IMAGE_DECODE_FAILED
- FEATURE_BLOB_INVALID
- FEATURE_FORMAT_UNSUPPORTED
- TOO_MANY_REFERENCES
- UNKNOWN_PROFILE
- IMAGE_TOO_SMALL
- UNAUTHORIZED
- FORBIDDEN
- PAYLOAD_TOO_LARGE
- UNSUPPORTED_MEDIA_TYPE
- VALIDATION_ERROR
- INVALID_SETTINGS
- INTERNAL
message:
type: string
description: Человекочитаемое описание (локализовано на русском)
details:
type: object
additionalProperties: true
description: Структура зависит от кода (например, reference_index для ошибок блоба)
trace_id:
type: string
description: Идентификатор запроса (12 hex-символов)