From d59fdfd51765a3937049ae282935cc8db3021a0e Mon Sep 17 00:00:00 2001 From: "a.ilin" Date: Mon, 12 Oct 2026 23:46:47 +0300 Subject: [PATCH] admin --- src/api/attractions.ts | 12 +++- src/api/types.ts | 28 +++++++- .../attractions/AttractionDetailPage.tsx | 19 +++++- src/pages/attractions/AttractionForm.tsx | 67 ++++++++++++++++++- src/pages/attractions/PhotoGallery.tsx | 54 ++++++++++++--- 5 files changed, 167 insertions(+), 13 deletions(-) diff --git a/src/api/attractions.ts b/src/api/attractions.ts index 96fae10..3612f26 100644 --- a/src/api/attractions.ts +++ b/src/api/attractions.ts @@ -7,6 +7,7 @@ import type { Photo, PhotoVerifyResponse, UpdateAttractionRequest, + UpdateMatchThresholdsRequest, } from '@/api/types' export interface AttractionListParams { @@ -41,6 +42,15 @@ export async function updateAttraction( return resp.data } +/** Полная замена границ вердикта: null в поле = сброс к глобальным значениям. */ +export async function updateMatchThresholds( + id: string, + request: UpdateMatchThresholdsRequest, +): Promise { + const resp = await http.put(`/admin/attractions/${id}/match-thresholds`, request) + return resp.data +} + export async function uploadIcon(id: string, file: File): Promise { const form = new FormData() form.append('file', file) @@ -113,7 +123,7 @@ export async function updatePhotoSortOrder( return resp.data } -/** Проверить распознавание тестовым фото по всей коллекции эталонов, визит не фиксируется. */ +/** Проверить распознавание тестовым фото: итеративно по каждому эталону, визит не фиксируется. */ export async function verifyReferencePhoto( attractionId: string, file: File, diff --git a/src/api/types.ts b/src/api/types.ts index 5989e2b..c05b170 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -52,6 +52,9 @@ export interface Attraction { address: string | null facts: string[] | null photoCount: number + /** Переопределение границ вердикта; null = глобальные (gorodar.dinov2.*). */ + matchThreshold: number | null + noMatchThreshold: number | null } export interface CreateAttractionRequest { @@ -62,6 +65,8 @@ export interface CreateAttractionRequest { longitude?: number address?: string facts?: string[] + matchThreshold?: number + noMatchThreshold?: number } export interface UpdateAttractionRequest { @@ -73,6 +78,12 @@ export interface UpdateAttractionRequest { facts?: string[] } +/** Полная замена порогов: null = сброс к глобальным значениям. */ +export interface UpdateMatchThresholdsRequest { + matchThreshold: number | null + noMatchThreshold: number | null +} + // ---------- Эталонные фото ---------- export interface Photo { @@ -86,10 +97,25 @@ export interface Photo { export type PhotoVerifyVerdict = 'match' | 'uncertain' | 'no_match' +/** Результат сверки пробы с одним эталонным фото. */ +export interface ReferenceMatchResult { + photoId: string + sortOrder: number + /** 0..1 — процент прохождения проверки этим эталоном. */ + confidence: number + /** Прошла ли эффективный порог match. */ + match: boolean +} + export interface PhotoVerifyResponse { verdict: PhotoVerifyVerdict - /** 0..1 из dinoV2 /verify. */ + /** Лучший confidence по всем эталонам, 0..1. */ confidence: number + /** Эффективные границы вердикта (с учётом переопределения достопримечательности). */ + matchThreshold: number + noMatchThreshold: number + /** Проценты по каждому эталонному фото. */ + references: ReferenceMatchResult[] } // ---------- Наборы ---------- diff --git a/src/pages/attractions/AttractionDetailPage.tsx b/src/pages/attractions/AttractionDetailPage.tsx index 392e291..2f84060 100644 --- a/src/pages/attractions/AttractionDetailPage.tsx +++ b/src/pages/attractions/AttractionDetailPage.tsx @@ -28,6 +28,7 @@ import { fetchAttractionCard, fetchAttractions, updateAttraction, + updateMatchThresholds, uploadAudio, uploadBackground, uploadIcon, @@ -40,6 +41,7 @@ import { useIsMobile } from '@/hooks/useIsMobile' import { CameraUpload } from '@/components/CameraUpload' import { AttractionForm, + toMatchThresholdsRequest, toUpdateRequest, type AttractionFormValues, } from '@/pages/attractions/AttractionForm' @@ -82,7 +84,11 @@ export function AttractionDetailPage() { }) const editMutation = useMutation({ - mutationFn: (request: AttractionFormValues) => updateAttraction(id!, toUpdateRequest(request)), + mutationFn: async (values: AttractionFormValues) => { + await updateAttraction(id!, toUpdateRequest(values)) + // Пороги — отдельным PUT: пустое поле формы сбрасывает переопределение к глобальным + return updateMatchThresholds(id!, toMatchThresholdsRequest(values)) + }, onSuccess: (updated) => { notifySuccess('Карточка обновлена', updated.name) setMutated(updated) @@ -242,6 +248,17 @@ export function AttractionDetailPage() { {attraction.photoCount} + + {attraction.matchThreshold != null || attraction.noMatchThreshold != null ? ( + <> + match {attraction.matchThreshold ?? '—'} + no_match {attraction.noMatchThreshold ?? '—'} + переопределены + + ) : ( + 'по умолчанию приложения' + )} + {attraction.about ?? '—'} diff --git a/src/pages/attractions/AttractionForm.tsx b/src/pages/attractions/AttractionForm.tsx index c2c79c6..bd260b5 100644 --- a/src/pages/attractions/AttractionForm.tsx +++ b/src/pages/attractions/AttractionForm.tsx @@ -1,7 +1,11 @@ import type { FormInstance } from 'antd' -import { Button, Form, Input, InputNumber, Space } from 'antd' +import { Button, Form, Input, InputNumber, Space, Typography } from 'antd' import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons' -import type { CreateAttractionRequest, UpdateAttractionRequest } from '@/api/types' +import type { + CreateAttractionRequest, + UpdateAttractionRequest, + UpdateMatchThresholdsRequest, +} from '@/api/types' import { useIsMobile } from '@/hooks/useIsMobile' export interface AttractionFormValues { @@ -11,6 +15,8 @@ export interface AttractionFormValues { latitude?: number | null longitude?: number | null facts?: (string | undefined)[] + matchThreshold?: number | null + noMatchThreshold?: number | null } export interface AttractionFormInitialValues { @@ -20,6 +26,8 @@ export interface AttractionFormInitialValues { latitude?: number | null longitude?: number | null facts?: string[] | null + matchThreshold?: number | null + noMatchThreshold?: number | null } function normalizeFacts(facts: (string | undefined)[] | undefined): string[] { @@ -41,6 +49,8 @@ export function toCreateRequest( latitude: v.latitude ?? undefined, longitude: v.longitude ?? undefined, facts: facts.length ? facts : undefined, + matchThreshold: v.matchThreshold ?? undefined, + noMatchThreshold: v.noMatchThreshold ?? undefined, } } @@ -63,6 +73,14 @@ export function toUpdateRequest(v: AttractionFormValues): UpdateAttractionReques return request } +/** PUT-семантика порогов: значение — переопределить, пусто — сброс к глобальным. */ +export function toMatchThresholdsRequest(v: AttractionFormValues): UpdateMatchThresholdsRequest { + return { + matchThreshold: v.matchThreshold ?? null, + noMatchThreshold: v.noMatchThreshold ?? null, + } +} + export function AttractionForm({ form, initialValues, @@ -84,6 +102,8 @@ export function AttractionForm({ latitude: initialValues.latitude ?? undefined, longitude: initialValues.longitude ?? undefined, facts: initialValues.facts ?? [], + matchThreshold: initialValues.matchThreshold ?? undefined, + noMatchThreshold: initialValues.noMatchThreshold ?? undefined, } } > @@ -137,6 +157,49 @@ export function AttractionForm({ + + + value == null || (value >= 0 && value <= 1) + ? Promise.resolve() + : Promise.reject(new Error('Диапазон 0…1')), + }, + ]} + > + + + + value == null || (value >= 0 && value <= 1) + ? Promise.resolve() + : Promise.reject(new Error('Диапазон 0…1')), + }, + ]} + > + + + + + Границы вердикта распознавания (0…1): confidence ≥ порога match — совпадение, + ≤ порога no_match — не совпадение. Любой порядок порогов допустим. Пустые поля — + значения приложения (0.75 / 0.55), сохранение очистки возвращает переопределение + к глобальным. + {(fields, { add, remove }) => ( diff --git a/src/pages/attractions/PhotoGallery.tsx b/src/pages/attractions/PhotoGallery.tsx index 0cab909..4619f76 100644 --- a/src/pages/attractions/PhotoGallery.tsx +++ b/src/pages/attractions/PhotoGallery.tsx @@ -32,13 +32,15 @@ import { } from '@/api/attractions' import { notifyApiError, notifySuccess } from '@/api/errors' import { notify } from '@/api/notify' -import type { Photo } from '@/api/types' +import type { Photo, PhotoVerifyResponse } from '@/api/types' import { useIsMobile } from '@/hooks/useIsMobile' import { formatUtc } from '@/utils/format' import { CameraUpload } from '@/components/CameraUpload' const MAX_FILE_SIZE = 20 * 1024 * 1024 const ACCEPTED_TYPES = 'image/jpeg,image/png,image/webp,image/svg+xml' +/** Лимит бэкенда: gorodar.dinov2.max-reference-photos. */ +const MAX_REFERENCE_PHOTOS = 15 export function PhotoGallery({ attractionId, @@ -52,12 +54,17 @@ export function PhotoGallery({ const [uploadSortOrder, setUploadSortOrder] = useState(null) /** Черновики позиций: photoId → введённое, но не сохранённое значение. */ const [pendingOrders, setPendingOrders] = useState>({}) + /** Последняя проверка распознавания: проценты по эталонам показываем на карточках. */ + const [verifyResult, setVerifyResult] = useState(null) const photosQuery = useQuery({ queryKey: ['admin-photos', attractionId], queryFn: () => fetchPhotos(attractionId), }) + const photosCount = photosQuery.data?.length ?? 0 + const limitReached = photosCount >= MAX_REFERENCE_PHOTOS + const photosKey = ['admin-photos', attractionId] as const const setPhotos = (updater: (prev: Photo[]) => Photo[]) => { queryClient.setQueryData(photosKey, (prev) => @@ -94,9 +101,10 @@ export function PhotoGallery({ const verifyMutation = useMutation({ mutationFn: ({ file }: { file: File }) => verifyReferencePhoto(attractionId, file), onSuccess: (result) => { + setVerifyResult(result) const confidence = `${(result.confidence * 100).toFixed(0)} %` if (result.verdict === 'match') { - notify('success', 'Пробное фото распознано', `Коллекция эталонов работает, уверенность ${confidence}`) + notify('success', 'Пробное фото распознано', `Лучший эталон ${confidence}, порог match ${(result.matchThreshold * 100).toFixed(0)} %`) } else if (result.verdict === 'uncertain') { notify('info', 'Однозначного совпадения нет', `Уверенность ${confidence} — стоит переснять эталонные фото или проверить другим снимком`) } else { @@ -117,6 +125,10 @@ export function PhotoGallery({ }) const checkFileSize: UploadProps['beforeUpload'] = (file) => { + if (limitReached) { + notify('error', 'Достигнут лимит эталонных фото', `Максимум ${MAX_REFERENCE_PHOTOS} фото на достопримечательность`) + return Upload.LIST_IGNORE + } if (file.size > MAX_FILE_SIZE) { notify('error', 'Файл больше 20 МБ') return Upload.LIST_IGNORE @@ -153,12 +165,13 @@ export function PhotoGallery({ const photos = photosQuery.data ?? [] const noPhotosYet = photos.length === 0 + const verifyByPhoto = new Map((verifyResult?.references ?? []).map((r) => [r.photoId, r])) return ( - - @@ -168,7 +181,7 @@ export function PhotoGallery({ uploadMutation.mutate({ file, sortOrder: uploadSortOrder ?? undefined }) } > - @@ -187,6 +200,9 @@ export function PhotoGallery({ без позиции — следующая свободная + + Эталонных фото: {photos.length} из {MAX_REFERENCE_PHOTOS} + @@ -220,15 +236,31 @@ export function PhotoGallery({ )} - пробное фото сверяется со всеми эталонными фото достопримечательности + пробное фото сверяется с каждым эталонным фото по отдельности — проценты + проверки появятся на фото + {verifyResult && ( + + пороги: match {(verifyResult.matchThreshold * 100).toFixed(0)} % / no_match{' '} + {(verifyResult.noMatchThreshold * 100).toFixed(0)} % + + )} {noPhotosYet ? ( ) : ( - {photos.map((photo) => ( + {photos.map((photo) => { + const refResult = verifyByPhoto.get(photo.id) + const refColor = refResult + ? refResult.match + ? 'green' + : refResult.confidence > (verifyResult?.noMatchThreshold ?? 0) + ? 'orange' + : 'red' + : undefined + return ( позиция {photo.sortOrder} + {refResult != null && ( + + проверка {(refResult.confidence * 100).toFixed(0)} % + + )} {formatUtc(photo.createdAt)} UTC @@ -299,7 +336,8 @@ export function PhotoGallery({ - ))} + ) + })} )}