This commit is contained in:
a.ilin
2026-10-12 23:46:47 +03:00
parent 1155fbaae2
commit d59fdfd517
5 changed files with 167 additions and 13 deletions
+11 -1
View File
@@ -7,6 +7,7 @@ import type {
Photo, Photo,
PhotoVerifyResponse, PhotoVerifyResponse,
UpdateAttractionRequest, UpdateAttractionRequest,
UpdateMatchThresholdsRequest,
} from '@/api/types' } from '@/api/types'
export interface AttractionListParams { export interface AttractionListParams {
@@ -41,6 +42,15 @@ export async function updateAttraction(
return resp.data return resp.data
} }
/** Полная замена границ вердикта: null в поле = сброс к глобальным значениям. */
export async function updateMatchThresholds(
id: string,
request: UpdateMatchThresholdsRequest,
): Promise<Attraction> {
const resp = await http.put<Attraction>(`/admin/attractions/${id}/match-thresholds`, request)
return resp.data
}
export async function uploadIcon(id: string, file: File): Promise<Attraction> { export async function uploadIcon(id: string, file: File): Promise<Attraction> {
const form = new FormData() const form = new FormData()
form.append('file', file) form.append('file', file)
@@ -113,7 +123,7 @@ export async function updatePhotoSortOrder(
return resp.data return resp.data
} }
/** Проверить распознавание тестовым фото по всей коллекции эталонов, визит не фиксируется. */ /** Проверить распознавание тестовым фото: итеративно по каждому эталону, визит не фиксируется. */
export async function verifyReferencePhoto( export async function verifyReferencePhoto(
attractionId: string, attractionId: string,
file: File, file: File,
+27 -1
View File
@@ -52,6 +52,9 @@ export interface Attraction {
address: string | null address: string | null
facts: string[] | null facts: string[] | null
photoCount: number photoCount: number
/** Переопределение границ вердикта; null = глобальные (gorodar.dinov2.*). */
matchThreshold: number | null
noMatchThreshold: number | null
} }
export interface CreateAttractionRequest { export interface CreateAttractionRequest {
@@ -62,6 +65,8 @@ export interface CreateAttractionRequest {
longitude?: number longitude?: number
address?: string address?: string
facts?: string[] facts?: string[]
matchThreshold?: number
noMatchThreshold?: number
} }
export interface UpdateAttractionRequest { export interface UpdateAttractionRequest {
@@ -73,6 +78,12 @@ export interface UpdateAttractionRequest {
facts?: string[] facts?: string[]
} }
/** Полная замена порогов: null = сброс к глобальным значениям. */
export interface UpdateMatchThresholdsRequest {
matchThreshold: number | null
noMatchThreshold: number | null
}
// ---------- Эталонные фото ---------- // ---------- Эталонные фото ----------
export interface Photo { export interface Photo {
@@ -86,10 +97,25 @@ export interface Photo {
export type PhotoVerifyVerdict = 'match' | 'uncertain' | 'no_match' export type PhotoVerifyVerdict = 'match' | 'uncertain' | 'no_match'
/** Результат сверки пробы с одним эталонным фото. */
export interface ReferenceMatchResult {
photoId: string
sortOrder: number
/** 0..1 — процент прохождения проверки этим эталоном. */
confidence: number
/** Прошла ли эффективный порог match. */
match: boolean
}
export interface PhotoVerifyResponse { export interface PhotoVerifyResponse {
verdict: PhotoVerifyVerdict verdict: PhotoVerifyVerdict
/** 0..1 из dinoV2 /verify. */ /** Лучший confidence по всем эталонам, 0..1. */
confidence: number confidence: number
/** Эффективные границы вердикта (с учётом переопределения достопримечательности). */
matchThreshold: number
noMatchThreshold: number
/** Проценты по каждому эталонному фото. */
references: ReferenceMatchResult[]
} }
// ---------- Наборы ---------- // ---------- Наборы ----------
+18 -1
View File
@@ -28,6 +28,7 @@ import {
fetchAttractionCard, fetchAttractionCard,
fetchAttractions, fetchAttractions,
updateAttraction, updateAttraction,
updateMatchThresholds,
uploadAudio, uploadAudio,
uploadBackground, uploadBackground,
uploadIcon, uploadIcon,
@@ -40,6 +41,7 @@ import { useIsMobile } from '@/hooks/useIsMobile'
import { CameraUpload } from '@/components/CameraUpload' import { CameraUpload } from '@/components/CameraUpload'
import { import {
AttractionForm, AttractionForm,
toMatchThresholdsRequest,
toUpdateRequest, toUpdateRequest,
type AttractionFormValues, type AttractionFormValues,
} from '@/pages/attractions/AttractionForm' } from '@/pages/attractions/AttractionForm'
@@ -82,7 +84,11 @@ export function AttractionDetailPage() {
}) })
const editMutation = useMutation({ 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) => { onSuccess: (updated) => {
notifySuccess('Карточка обновлена', updated.name) notifySuccess('Карточка обновлена', updated.name)
setMutated(updated) setMutated(updated)
@@ -242,6 +248,17 @@ export function AttractionDetailPage() {
<Descriptions.Item label="Фото" span={2}> <Descriptions.Item label="Фото" span={2}>
{attraction.photoCount} {attraction.photoCount}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="Пороги верификации" span={2}>
{attraction.matchThreshold != null || attraction.noMatchThreshold != null ? (
<>
<Tag color="green">match {attraction.matchThreshold ?? '—'}</Tag>
<Tag color="orange">no_match {attraction.noMatchThreshold ?? '—'}</Tag>
<Typography.Text type="secondary">переопределены</Typography.Text>
</>
) : (
'по умолчанию приложения'
)}
</Descriptions.Item>
<Descriptions.Item label="Описание" span={2}> <Descriptions.Item label="Описание" span={2}>
{attraction.about ?? '—'} {attraction.about ?? '—'}
</Descriptions.Item> </Descriptions.Item>
+65 -2
View File
@@ -1,7 +1,11 @@
import type { FormInstance } from 'antd' 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 { 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' import { useIsMobile } from '@/hooks/useIsMobile'
export interface AttractionFormValues { export interface AttractionFormValues {
@@ -11,6 +15,8 @@ export interface AttractionFormValues {
latitude?: number | null latitude?: number | null
longitude?: number | null longitude?: number | null
facts?: (string | undefined)[] facts?: (string | undefined)[]
matchThreshold?: number | null
noMatchThreshold?: number | null
} }
export interface AttractionFormInitialValues { export interface AttractionFormInitialValues {
@@ -20,6 +26,8 @@ export interface AttractionFormInitialValues {
latitude?: number | null latitude?: number | null
longitude?: number | null longitude?: number | null
facts?: string[] | null facts?: string[] | null
matchThreshold?: number | null
noMatchThreshold?: number | null
} }
function normalizeFacts(facts: (string | undefined)[] | undefined): string[] { function normalizeFacts(facts: (string | undefined)[] | undefined): string[] {
@@ -41,6 +49,8 @@ export function toCreateRequest(
latitude: v.latitude ?? undefined, latitude: v.latitude ?? undefined,
longitude: v.longitude ?? undefined, longitude: v.longitude ?? undefined,
facts: facts.length ? facts : 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 return request
} }
/** PUT-семантика порогов: значение — переопределить, пусто — сброс к глобальным. */
export function toMatchThresholdsRequest(v: AttractionFormValues): UpdateMatchThresholdsRequest {
return {
matchThreshold: v.matchThreshold ?? null,
noMatchThreshold: v.noMatchThreshold ?? null,
}
}
export function AttractionForm({ export function AttractionForm({
form, form,
initialValues, initialValues,
@@ -84,6 +102,8 @@ export function AttractionForm({
latitude: initialValues.latitude ?? undefined, latitude: initialValues.latitude ?? undefined,
longitude: initialValues.longitude ?? undefined, longitude: initialValues.longitude ?? undefined,
facts: initialValues.facts ?? [], facts: initialValues.facts ?? [],
matchThreshold: initialValues.matchThreshold ?? undefined,
noMatchThreshold: initialValues.noMatchThreshold ?? undefined,
} }
} }
> >
@@ -137,6 +157,49 @@ export function AttractionForm({
<InputNumber style={{ width: '100%' }} min={-180} max={180} step={0.000001} placeholder="37.618423" /> <InputNumber style={{ width: '100%' }} min={-180} max={180} step={0.000001} placeholder="37.618423" />
</Form.Item> </Form.Item>
</Space> </Space>
<Space
size="large"
style={{ display: 'flex' }}
align="start"
direction={isMobile ? 'vertical' : 'horizontal'}
>
<Form.Item
name="matchThreshold"
label="Порог match"
style={{ width: isMobile ? '100%' : 220 }}
rules={[
{
validator: (_, value: number | null | undefined) =>
value == null || (value >= 0 && value <= 1)
? Promise.resolve()
: Promise.reject(new Error('Диапазон 0…1')),
},
]}
>
<InputNumber style={{ width: '100%' }} min={0} max={1} step={0.01} placeholder="по умолчанию 0.75" />
</Form.Item>
<Form.Item
name="noMatchThreshold"
label="Порог no_match"
style={{ width: isMobile ? '100%' : 220 }}
rules={[
{
validator: (_, value: number | null | undefined) =>
value == null || (value >= 0 && value <= 1)
? Promise.resolve()
: Promise.reject(new Error('Диапазон 0…1')),
},
]}
>
<InputNumber style={{ width: '100%' }} min={0} max={1} step={0.01} placeholder="по умолчанию 0.55" />
</Form.Item>
</Space>
<Typography.Text type="secondary">
Границы вердикта распознавания (0…1): confidence ≥ порога match — совпадение,
≤ порога no_match — не совпадение. Любой порядок порогов допустим. Пустые поля —
значения приложения (0.75 / 0.55), сохранение очистки возвращает переопределение
к глобальным.
</Typography.Text>
<Form.Item label="Интересные факты" style={{ marginBottom: 0 }}> <Form.Item label="Интересные факты" style={{ marginBottom: 0 }}>
<Form.List name="facts"> <Form.List name="facts">
{(fields, { add, remove }) => ( {(fields, { add, remove }) => (
+46 -8
View File
@@ -32,13 +32,15 @@ import {
} from '@/api/attractions' } from '@/api/attractions'
import { notifyApiError, notifySuccess } from '@/api/errors' import { notifyApiError, notifySuccess } from '@/api/errors'
import { notify } from '@/api/notify' import { notify } from '@/api/notify'
import type { Photo } from '@/api/types' import type { Photo, PhotoVerifyResponse } from '@/api/types'
import { useIsMobile } from '@/hooks/useIsMobile' import { useIsMobile } from '@/hooks/useIsMobile'
import { formatUtc } from '@/utils/format' import { formatUtc } from '@/utils/format'
import { CameraUpload } from '@/components/CameraUpload' import { CameraUpload } from '@/components/CameraUpload'
const MAX_FILE_SIZE = 20 * 1024 * 1024 const MAX_FILE_SIZE = 20 * 1024 * 1024
const ACCEPTED_TYPES = 'image/jpeg,image/png,image/webp,image/svg+xml' 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({ export function PhotoGallery({
attractionId, attractionId,
@@ -52,12 +54,17 @@ export function PhotoGallery({
const [uploadSortOrder, setUploadSortOrder] = useState<number | null>(null) const [uploadSortOrder, setUploadSortOrder] = useState<number | null>(null)
/** Черновики позиций: photoId → введённое, но не сохранённое значение. */ /** Черновики позиций: photoId → введённое, но не сохранённое значение. */
const [pendingOrders, setPendingOrders] = useState<Record<string, number>>({}) const [pendingOrders, setPendingOrders] = useState<Record<string, number>>({})
/** Последняя проверка распознавания: проценты по эталонам показываем на карточках. */
const [verifyResult, setVerifyResult] = useState<PhotoVerifyResponse | null>(null)
const photosQuery = useQuery({ const photosQuery = useQuery({
queryKey: ['admin-photos', attractionId], queryKey: ['admin-photos', attractionId],
queryFn: () => fetchPhotos(attractionId), queryFn: () => fetchPhotos(attractionId),
}) })
const photosCount = photosQuery.data?.length ?? 0
const limitReached = photosCount >= MAX_REFERENCE_PHOTOS
const photosKey = ['admin-photos', attractionId] as const const photosKey = ['admin-photos', attractionId] as const
const setPhotos = (updater: (prev: Photo[]) => Photo[]) => { const setPhotos = (updater: (prev: Photo[]) => Photo[]) => {
queryClient.setQueryData<Photo[]>(photosKey, (prev) => queryClient.setQueryData<Photo[]>(photosKey, (prev) =>
@@ -94,9 +101,10 @@ export function PhotoGallery({
const verifyMutation = useMutation({ const verifyMutation = useMutation({
mutationFn: ({ file }: { file: File }) => verifyReferencePhoto(attractionId, file), mutationFn: ({ file }: { file: File }) => verifyReferencePhoto(attractionId, file),
onSuccess: (result) => { onSuccess: (result) => {
setVerifyResult(result)
const confidence = `${(result.confidence * 100).toFixed(0)} %` const confidence = `${(result.confidence * 100).toFixed(0)} %`
if (result.verdict === 'match') { if (result.verdict === 'match') {
notify('success', 'Пробное фото распознано', `Коллекция эталонов работает, уверенность ${confidence}`) notify('success', 'Пробное фото распознано', `Лучший эталон ${confidence}, порог match ${(result.matchThreshold * 100).toFixed(0)} %`)
} else if (result.verdict === 'uncertain') { } else if (result.verdict === 'uncertain') {
notify('info', 'Однозначного совпадения нет', `Уверенность ${confidence} — стоит переснять эталонные фото или проверить другим снимком`) notify('info', 'Однозначного совпадения нет', `Уверенность ${confidence} — стоит переснять эталонные фото или проверить другим снимком`)
} else { } else {
@@ -117,6 +125,10 @@ export function PhotoGallery({
}) })
const checkFileSize: UploadProps['beforeUpload'] = (file) => { const checkFileSize: UploadProps['beforeUpload'] = (file) => {
if (limitReached) {
notify('error', 'Достигнут лимит эталонных фото', `Максимум ${MAX_REFERENCE_PHOTOS} фото на достопримечательность`)
return Upload.LIST_IGNORE
}
if (file.size > MAX_FILE_SIZE) { if (file.size > MAX_FILE_SIZE) {
notify('error', 'Файл больше 20 МБ') notify('error', 'Файл больше 20 МБ')
return Upload.LIST_IGNORE return Upload.LIST_IGNORE
@@ -153,12 +165,13 @@ export function PhotoGallery({
const photos = photosQuery.data ?? [] const photos = photosQuery.data ?? []
const noPhotosYet = photos.length === 0 const noPhotosYet = photos.length === 0
const verifyByPhoto = new Map((verifyResult?.references ?? []).map((r) => [r.photoId, r]))
return ( return (
<Space direction="vertical" size="middle" style={{ width: '100%' }}> <Space direction="vertical" size="middle" style={{ width: '100%' }}>
<Space wrap> <Space wrap>
<Upload {...uploadProps}> <Upload {...uploadProps} disabled={limitReached}>
<Button type="primary" icon={<UploadOutlined />} loading={uploadMutation.isPending}> <Button type="primary" icon={<UploadOutlined />} loading={uploadMutation.isPending} disabled={limitReached}>
Загрузить фото Загрузить фото
</Button> </Button>
</Upload> </Upload>
@@ -168,7 +181,7 @@ export function PhotoGallery({
uploadMutation.mutate({ file, sortOrder: uploadSortOrder ?? undefined }) uploadMutation.mutate({ file, sortOrder: uploadSortOrder ?? undefined })
} }
> >
<Button type="primary" icon={<CameraOutlined />} loading={uploadMutation.isPending}> <Button type="primary" icon={<CameraOutlined />} loading={uploadMutation.isPending} disabled={limitReached}>
Сделать фото Сделать фото
</Button> </Button>
</CameraUpload> </CameraUpload>
@@ -187,6 +200,9 @@ export function PhotoGallery({
без позиции — следующая свободная без позиции — следующая свободная
</Typography.Text> </Typography.Text>
</Space> </Space>
<Typography.Text type={limitReached ? 'danger' : 'secondary'}>
Эталонных фото: {photos.length} из {MAX_REFERENCE_PHOTOS}
</Typography.Text>
</Space> </Space>
<Space wrap> <Space wrap>
@@ -220,15 +236,31 @@ export function PhotoGallery({
</CameraUpload> </CameraUpload>
)} )}
<Typography.Text type="secondary"> <Typography.Text type="secondary">
пробное фото сверяется со всеми эталонными фото достопримечательности пробное фото сверяется с каждым эталонным фото по отдельности — проценты
проверки появятся на фото
</Typography.Text> </Typography.Text>
{verifyResult && (
<Typography.Text type="secondary">
пороги: match {(verifyResult.matchThreshold * 100).toFixed(0)} % / no_match{' '}
{(verifyResult.noMatchThreshold * 100).toFixed(0)} %
</Typography.Text>
)}
</Space> </Space>
{noPhotosYet ? ( {noPhotosYet ? (
<Empty description="Эталонных фото пока нет" style={{ padding: 24 }} /> <Empty description="Эталонных фото пока нет" style={{ padding: 24 }} />
) : ( ) : (
<Row gutter={[16, 16]}> <Row gutter={[16, 16]}>
{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 (
<Col key={photo.id} xs={24} sm={12} lg={8} xl={6}> <Col key={photo.id} xs={24} sm={12} lg={8} xl={6}>
<Card <Card
size="small" size="small"
@@ -244,6 +276,11 @@ export function PhotoGallery({
<Space direction="vertical" size={4} style={{ width: '100%' }}> <Space direction="vertical" size={4} style={{ width: '100%' }}>
<Space size={8} wrap> <Space size={8} wrap>
<Tag color="blue">позиция {photo.sortOrder}</Tag> <Tag color="blue">позиция {photo.sortOrder}</Tag>
{refResult != null && (
<Tag color={refColor} title="Процент прохождения проверки этим эталоном">
проверка {(refResult.confidence * 100).toFixed(0)} %
</Tag>
)}
<Typography.Text type="secondary"> <Typography.Text type="secondary">
{formatUtc(photo.createdAt)} UTC {formatUtc(photo.createdAt)} UTC
</Typography.Text> </Typography.Text>
@@ -299,7 +336,8 @@ export function PhotoGallery({
</Space> </Space>
</Card> </Card>
</Col> </Col>
))} )
})}
</Row> </Row>
)} )}
</Space> </Space>