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
+13
View File
@@ -0,0 +1,13 @@
{
"mcp": {
"servers": {
"my-mcp-server": {
"type": "stdio",
"command": "uvx",
"args": [
"opencv-mcp-server"
]
}
}
}
}
+1
View File
@@ -13,6 +13,7 @@ RUN useradd --create-home --shell /usr/sbin/nologin appuser
WORKDIR /srv/app
COPY --from=builder /install /usr/local
COPY app ./app
COPY openapi.yaml ./openapi.yaml
# Непривилегированный пользователь; томов с данными нет — состояние
# процесса только конфигурация из окружения (FR-006, NFR-008).
+8
View File
@@ -81,6 +81,14 @@ export APP_API_KEY=dev-key
.venv/bin/python -m pytest # 64 теста: UT-01..18 + IT-01..17 (docs/08)
```
### OpenAPI (импорт в основной сервис)
Машиночитаемая копия контракта — [`openapi.yaml`](openapi.yaml) в корне
(OpenAPI 3.0.3: multipart-схемы, повторяемая часть `reference`, единый
формат ошибок, apiKey-схема `X-API-Key`). Живой сервис отдаёт её на
`/openapi.json`, интерактивная Swagger-UI — `/docs`. Для генерации Java-клиента:
`openapi-generator-cli generate -i openapi.yaml -g java -o gen/`.
### Структура
```
+26
View File
@@ -8,7 +8,9 @@ import logging
import time
import uuid
from contextlib import asynccontextmanager
from pathlib import Path
import yaml
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
@@ -24,6 +26,11 @@ logger = logging.getLogger("opencv")
# для /features: сама image-часть проверяется точно после разбора.
_FEATURES_BODY_SLACK_BYTES = 1024 * 1024
# Спецификация — рукописный файл по контракту docs/05: автогенерация FastAPI
# не видит multipart-части, разбираемые вручную. Отдаётся на /openapi.json и
# рендерится в /docs.
_OPENAPI_SPEC_PATH = Path(__file__).resolve().parent.parent / "openapi.yaml"
def create_app(config: Config | None = None) -> FastAPI:
config = config or Config.from_env()
@@ -45,6 +52,7 @@ def create_app(config: Config | None = None) -> FastAPI:
app.state.config = config
app.state.cv = CvService(config)
app.state.ready = False
_install_openapi(app)
app.include_router(router)
app.include_router(health_router)
@@ -97,6 +105,24 @@ def create_app(config: Config | None = None) -> FastAPI:
return app
def _install_openapi(app: FastAPI) -> None:
"""Отдаёт /openapi.json и /docs из openapi.yaml.
Multipart-контракт разбирается вручную (starlette request.form), поэтому
автогенерация FastAPI пуста — спецификация поддерживается как файл.
"""
if not _OPENAPI_SPEC_PATH.exists():
logger.warning("openapi.yaml не найден: /docs отдаст пустую автогенерацию")
return
with _OPENAPI_SPEC_PATH.open(encoding="utf-8") as fh:
spec = yaml.safe_load(fh)
def custom_openapi():
return spec
app.openapi = custom_openapi # type: ignore[method-assign]
def _body_limit(path: str, config: Config) -> int | None:
if path == "/api/v1/verify":
return config.verify_max_body_bytes
+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-символов)
+1
View File
@@ -5,3 +5,4 @@ opencv-python-headless>=4.10,<5
numpy>=1.26,<3
Pillow>=10
python-multipart>=0.0.9
PyYAML>=6
+95
View File
@@ -0,0 +1,95 @@
"""Тесты OpenAPI-спецификации: файл валиден и синхронен с сервисом.
Спецификация — рукописная копия контракта docs/05 (автогенерация FastAPI не
видит multipart-части, разбираемые вручную), поэтому фиксируется тестами.
"""
from __future__ import annotations
from pathlib import Path
import pytest
import yaml
from fastapi.testclient import TestClient
SPEC_PATH = Path(__file__).resolve().parents[2] / "openapi.yaml"
@pytest.fixture(scope="module")
def spec() -> dict:
return yaml.safe_load(SPEC_PATH.read_text(encoding="utf-8"))
class TestSpecFile:
def test_version_and_paths(self, spec):
assert spec["openapi"].startswith("3.")
paths = spec["paths"]
for path in ("/api/v1/features", "/api/v1/verify", "/api/v1/profiles", "/health", "/ready"):
assert path in paths, path
def test_security_scheme(self, spec):
scheme = spec["components"]["securitySchemes"]["ApiKeyAuth"]
assert scheme["type"] == "apiKey"
assert scheme["in"] == "header"
assert scheme["name"] == "X-API-Key"
assert spec["security"] == [{"ApiKeyAuth": []}]
def test_health_and_ready_without_auth(self, spec):
# диагностика переопределяет глобальную безопасность
assert spec["paths"]["/health"]["get"]["security"] == []
assert spec["paths"]["/ready"]["get"]["security"] == []
def test_verify_reference_is_repeated_part(self, spec):
schema = spec["paths"]["/api/v1/verify"]["post"]["requestBody"]["content"][
"multipart/form-data"
]["schema"]
reference = schema["properties"]["reference"]
assert reference["type"] == "array"
assert reference["minItems"] == 1
assert reference["maxItems"] == 32 # MAX_REFERENCES_PER_REQUEST по умолчанию
def test_features_response_headers(self, spec):
headers = spec["paths"]["/api/v1/features"]["post"]["responses"]["200"]["headers"]
for name in (
"X-Feature-Format-Version",
"X-Algo-Id",
"X-Keypoints-Count",
"X-Image-Width",
"X-Image-Height",
):
assert name in headers, name
def test_error_schema_codes(self, spec):
codes = set(spec["components"]["schemas"]["Error"]["properties"]["code"]["enum"])
# все коды из таблицы docs/05 §5.3
assert codes == {
"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",
}
def test_settings_match_validation_ranges(self, spec):
comparison = spec["components"]["schemas"]["ComparisonSettings"]["properties"]
assert comparison["lowe_ratio"]["minimum"] == 0.5
assert comparison["lowe_ratio"]["maximum"] == 0.95
extraction = spec["components"]["schemas"]["ExtractionSettings"]["properties"]
assert extraction["max_image_size"] == {
"type": "integer", "minimum": 320, "maximum": 8192,
"description": extraction["max_image_size"]["description"],
}
class TestSpecServed:
def test_openapi_json_serves_file_spec(self, client: TestClient):
"""Живой сервис отдаёт /openapi.json из openapi.yaml, а не автогенерацию."""
response = client.get("/openapi.json")
assert response.status_code == 200
served = response.json()
assert served["paths"].keys() == yaml.safe_load(SPEC_PATH.read_text())["paths"].keys()
assert "/api/v1/verify" in served["paths"]
assert served["components"]["securitySchemes"]["ApiKeyAuth"]["name"] == "X-API-Key"
def test_docs_ui_available(self, client: TestClient):
response = client.get("/docs")
assert response.status_code == 200
assert "swagger" in response.text.lower()