move to dinoV2

This commit is contained in:
a.ilin
2026-10-07 15:44:37 +03:00
parent 258234b2e2
commit 1155fbaae2
7 changed files with 49 additions and 133 deletions
+2 -14
View File
@@ -113,27 +113,15 @@ export async function updatePhotoSortOrder(
return resp.data return resp.data
} }
/** Перезапустить извлечение признаков через сервис open_cv. */ /** Проверить распознавание тестовым фото по всей коллекции эталонов, визит не фиксируется. */
export async function recalcPhotoFeatures(
attractionId: string,
photoId: string,
): Promise<Photo> {
const resp = await http.post<Photo>(
`/admin/attractions/${attractionId}/photos/${photoId}/features`,
)
return resp.data
}
/** Проверить эталон тестовым фото: /verify по этому эталону, визит не фиксируется. */
export async function verifyReferencePhoto( export async function verifyReferencePhoto(
attractionId: string, attractionId: string,
photoId: string,
file: File, file: File,
): Promise<PhotoVerifyResponse> { ): Promise<PhotoVerifyResponse> {
const form = new FormData() const form = new FormData()
form.append('photo', file) form.append('photo', file)
const resp = await http.post<PhotoVerifyResponse>( const resp = await http.post<PhotoVerifyResponse>(
`/admin/attractions/${attractionId}/photos/${photoId}/verify`, `/admin/attractions/${attractionId}/photos/verify`,
form, form,
{ headers: { 'Content-Type': 'multipart/form-data' } }, { headers: { 'Content-Type': 'multipart/form-data' } },
) )
+1 -9
View File
@@ -36,8 +36,6 @@ export interface UpdateAreaRequest {
// ---------- Достопримечательности ---------- // ---------- Достопримечательности ----------
export type CvProfile = 'facade' | 'monument' | 'repetitive'
export interface Attraction { export interface Attraction {
id: string id: string
areaId: string areaId: string
@@ -53,14 +51,12 @@ export interface Attraction {
longitude: number | null longitude: number | null
address: string | null address: string | null
facts: string[] | null facts: string[] | null
cvProfile: CvProfile
photoCount: number photoCount: number
} }
export interface CreateAttractionRequest { export interface CreateAttractionRequest {
areaId: string areaId: string
name: string name: string
cvProfile: CvProfile
about?: string about?: string
latitude?: number latitude?: number
longitude?: number longitude?: number
@@ -70,7 +66,6 @@ export interface CreateAttractionRequest {
export interface UpdateAttractionRequest { export interface UpdateAttractionRequest {
name?: string name?: string
cvProfile?: CvProfile
about?: string about?: string
latitude?: number latitude?: number
longitude?: number longitude?: number
@@ -85,9 +80,6 @@ export interface Photo {
/** Presigned GET URL (TTL 1 час) — не кэшировать надолго. */ /** Presigned GET URL (TTL 1 час) — не кэшировать надолго. */
photoUrl: string photoUrl: string
sortOrder: number sortOrder: number
featureFormatVersion: number
algoId: string
keypointsCount: number
/** UTC, ISO-8601 без зоны. */ /** UTC, ISO-8601 без зоны. */
createdAt: string createdAt: string
} }
@@ -96,7 +88,7 @@ export type PhotoVerifyVerdict = 'match' | 'uncertain' | 'no_match'
export interface PhotoVerifyResponse { export interface PhotoVerifyResponse {
verdict: PhotoVerifyVerdict verdict: PhotoVerifyVerdict
/** 0..1 из open_cv /verify. */ /** 0..1 из dinoV2 /verify. */
confidence: number confidence: number
} }
@@ -37,7 +37,6 @@ import { notifyApiError, notifySuccess } from '@/api/errors'
import { notify } from '@/api/notify' import { notify } from '@/api/notify'
import type { Attraction } from '@/api/types' import type { Attraction } from '@/api/types'
import { useIsMobile } from '@/hooks/useIsMobile' import { useIsMobile } from '@/hooks/useIsMobile'
import { cvProfileMeta } from '@/utils/format'
import { CameraUpload } from '@/components/CameraUpload' import { CameraUpload } from '@/components/CameraUpload'
import { import {
AttractionForm, AttractionForm,
@@ -234,11 +233,6 @@ export function AttractionDetailPage() {
<Card title="Карточка"> <Card title="Карточка">
<Descriptions column={{ xs: 1, md: 2 }} bordered size="small"> <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
<Descriptions.Item label="Название">{attraction.name}</Descriptions.Item> <Descriptions.Item label="Название">{attraction.name}</Descriptions.Item>
<Descriptions.Item label="CV-профиль">
<Tag color={cvProfileMeta[attraction.cvProfile].color}>
{cvProfileMeta[attraction.cvProfile].label}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="Адрес">{attraction.address ?? '—'}</Descriptions.Item> <Descriptions.Item label="Адрес">{attraction.address ?? '—'}</Descriptions.Item>
<Descriptions.Item label="Координаты"> <Descriptions.Item label="Координаты">
{attraction.latitude != null && attraction.longitude != null {attraction.latitude != null && attraction.longitude != null
+2 -16
View File
@@ -1,13 +1,11 @@
import type { FormInstance } from 'antd' import type { FormInstance } from 'antd'
import { Button, Form, Input, InputNumber, Select, Space } from 'antd' import { Button, Form, Input, InputNumber, Space } from 'antd'
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons' import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'
import type { CreateAttractionRequest, CvProfile, UpdateAttractionRequest } from '@/api/types' import type { CreateAttractionRequest, UpdateAttractionRequest } from '@/api/types'
import { useIsMobile } from '@/hooks/useIsMobile' import { useIsMobile } from '@/hooks/useIsMobile'
import { cvProfileOptions } from '@/utils/format'
export interface AttractionFormValues { export interface AttractionFormValues {
name: string name: string
cvProfile: CvProfile
about?: string about?: string
address?: string address?: string
latitude?: number | null latitude?: number | null
@@ -17,7 +15,6 @@ export interface AttractionFormValues {
export interface AttractionFormInitialValues { export interface AttractionFormInitialValues {
name: string name: string
cvProfile: CvProfile
about?: string | null about?: string | null
address?: string | null address?: string | null
latitude?: number | null latitude?: number | null
@@ -39,7 +36,6 @@ export function toCreateRequest(
return { return {
areaId, areaId,
name: v.name.trim(), name: v.name.trim(),
cvProfile: v.cvProfile,
about: v.about?.trim() || undefined, about: v.about?.trim() || undefined,
address: v.address?.trim() || undefined, address: v.address?.trim() || undefined,
latitude: v.latitude ?? undefined, latitude: v.latitude ?? undefined,
@@ -56,7 +52,6 @@ export function toUpdateRequest(v: AttractionFormValues): UpdateAttractionReques
const request: UpdateAttractionRequest = {} const request: UpdateAttractionRequest = {}
const name = v.name?.trim() const name = v.name?.trim()
if (name) request.name = name if (name) request.name = name
if (v.cvProfile) request.cvProfile = v.cvProfile
const about = v.about?.trim() const about = v.about?.trim()
if (about) request.about = about if (about) request.about = about
const address = v.address?.trim() const address = v.address?.trim()
@@ -84,7 +79,6 @@ export function AttractionForm({
initialValues={ initialValues={
initialValues && { initialValues && {
name: initialValues.name, name: initialValues.name,
cvProfile: initialValues.cvProfile,
about: initialValues.about ?? undefined, about: initialValues.about ?? undefined,
address: initialValues.address ?? undefined, address: initialValues.address ?? undefined,
latitude: initialValues.latitude ?? undefined, latitude: initialValues.latitude ?? undefined,
@@ -100,14 +94,6 @@ export function AttractionForm({
> >
<Input maxLength={255} placeholder="Например, Дом со шпилем" /> <Input maxLength={255} placeholder="Например, Дом со шпилем" />
</Form.Item> </Form.Item>
<Form.Item
name="cvProfile"
label="CV-профиль распознавания"
rules={[{ required: true, message: 'Выберите профиль' }]}
extra="Влияет на алгоритм сопоставления фотографий."
>
<Select options={cvProfileOptions} />
</Form.Item>
<Form.Item name="about" label="Описание"> <Form.Item name="about" label="Описание">
<Input.TextArea rows={3} maxLength={4000} /> <Input.TextArea rows={3} maxLength={4000} />
</Form.Item> </Form.Item>
+1 -11
View File
@@ -1,6 +1,6 @@
import { useState } from 'react' import { useState } from 'react'
import { keepPreviousData, useMutation, useQuery } from '@tanstack/react-query' import { keepPreviousData, useMutation, useQuery } from '@tanstack/react-query'
import { Button, Empty, Form, Modal, Space, Table, Tag, Typography } from 'antd' import { Button, Empty, Form, Modal, Space, Table, Typography } from 'antd'
import type { ColumnsType } from 'antd/es/table' import type { ColumnsType } from 'antd/es/table'
import { useNavigate, useSearchParams } from 'react-router-dom' import { useNavigate, useSearchParams } from 'react-router-dom'
import { createAttraction, fetchAttractions } from '@/api/attractions' import { createAttraction, fetchAttractions } from '@/api/attractions'
@@ -8,7 +8,6 @@ import { notifyApiError, notifySuccess } from '@/api/errors'
import type { Attraction } from '@/api/types' import type { Attraction } from '@/api/types'
import { AreaTreeSelect } from '@/components/AreaTreeSelect' import { AreaTreeSelect } from '@/components/AreaTreeSelect'
import { useIsMobile } from '@/hooks/useIsMobile' import { useIsMobile } from '@/hooks/useIsMobile'
import { cvProfileMeta } from '@/utils/format'
import { import {
AttractionForm, AttractionForm,
toCreateRequest, toCreateRequest,
@@ -66,15 +65,6 @@ export function AttractionListPage() {
), ),
}, },
{ title: 'Адрес', dataIndex: 'address', key: 'address', render: (v) => v ?? '—' }, { title: 'Адрес', dataIndex: 'address', key: 'address', render: (v) => v ?? '—' },
{
title: 'CV-профиль',
dataIndex: 'cvProfile',
key: 'cvProfile',
width: 180,
render: (v: Attraction['cvProfile']) => (
<Tag color={cvProfileMeta[v].color}>{cvProfileMeta[v].label}</Tag>
),
},
{ {
title: 'Координаты', title: 'Координаты',
key: 'coords', key: 'coords',
+42 -65
View File
@@ -18,7 +18,6 @@ import {
import { import {
CameraOutlined, CameraOutlined,
DeleteOutlined, DeleteOutlined,
ExperimentOutlined,
SafetyCertificateOutlined, SafetyCertificateOutlined,
SaveOutlined, SaveOutlined,
UploadOutlined, UploadOutlined,
@@ -27,7 +26,6 @@ import type { UploadProps } from 'antd'
import { import {
deletePhoto, deletePhoto,
fetchPhotos, fetchPhotos,
recalcPhotoFeatures,
updatePhotoSortOrder, updatePhotoSortOrder,
uploadPhoto, uploadPhoto,
verifyReferencePhoto, verifyReferencePhoto,
@@ -93,29 +91,19 @@ export function PhotoGallery({
onError: (e) => notifyApiError(e, 'Не удалось изменить позицию'), onError: (e) => notifyApiError(e, 'Не удалось изменить позицию'),
}) })
const recalcMutation = useMutation({
mutationFn: (photoId: string) => recalcPhotoFeatures(attractionId, photoId),
onSuccess: (photo) => {
setPhotos((prev) => prev.map((p) => (p.id === photo.id ? photo : p)))
notifySuccess('Признаки пересчитаны', `Keypoints: ${photo.keypointsCount}`)
},
onError: (e) => notifyApiError(e, 'Не удалось пересчитать признаки'),
})
const verifyMutation = useMutation({ const verifyMutation = useMutation({
mutationFn: ({ photoId, file }: { photoId: string; file: File }) => mutationFn: ({ file }: { file: File }) => verifyReferencePhoto(attractionId, file),
verifyReferencePhoto(attractionId, photoId, file),
onSuccess: (result) => { onSuccess: (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}`)
} else if (result.verdict === 'uncertain') { } else if (result.verdict === 'uncertain') {
notify('info', 'Однозначного совпадения нет', `Уверенность ${confidence} — стоит переснять эталон или проверить другим снимком`) notify('info', 'Однозначного совпадения нет', `Уверенность ${confidence} — стоит переснять эталонные фото или проверить другим снимком`)
} else { } else {
notify('error', 'Эталон не распознаёт пробное фото', `Уверенность ${confidence} — эталон не подходит для распознавания`) notify('error', 'Пробное фото не распознано', `Уверенность ${confidence} — коллекция эталонов не распознаёт снимок`)
} }
}, },
onError: (e) => notifyApiError(e, 'Не удалось проверить эталон'), onError: (e) => notifyApiError(e, 'Не удалось выполнить проверку'),
}) })
const deleteMutation = useMutation({ const deleteMutation = useMutation({
@@ -164,6 +152,7 @@ export function PhotoGallery({
} }
const photos = photosQuery.data ?? [] const photos = photosQuery.data ?? []
const noPhotosYet = photos.length === 0
return ( return (
<Space direction="vertical" size="middle" style={{ width: '100%' }}> <Space direction="vertical" size="middle" style={{ width: '100%' }}>
@@ -200,7 +189,42 @@ export function PhotoGallery({
</Space> </Space>
</Space> </Space>
{photos.length === 0 ? ( <Space wrap>
<Upload
accept={ACCEPTED_TYPES}
multiple={false}
showUploadList={false}
beforeUpload={checkFileSize}
disabled={noPhotosYet}
customRequest={({ file }) => verifyMutation.mutate({ file: file as File })}
>
<Button
icon={<SafetyCertificateOutlined />}
loading={verifyMutation.isPending}
disabled={noPhotosYet}
title="Загрузить пробное фото и проверить, распознаёт ли его коллекция эталонных фото"
>
Проверить распознавание
</Button>
</Upload>
{isMobile && (
<CameraUpload
onFile={(file) => verifyMutation.mutate({ file })}
>
<Button
icon={<CameraOutlined />}
loading={verifyMutation.isPending}
disabled={noPhotosYet}
title="Снять пробное фото камерой и проверить распознавание"
/>
</CameraUpload>
)}
<Typography.Text type="secondary">
пробное фото сверяется со всеми эталонными фото достопримечательности
</Typography.Text>
</Space>
{noPhotosYet ? (
<Empty description="Эталонных фото пока нет" style={{ padding: 24 }} /> <Empty description="Эталонных фото пока нет" style={{ padding: 24 }} />
) : ( ) : (
<Row gutter={[16, 16]}> <Row gutter={[16, 16]}>
@@ -224,10 +248,6 @@ export function PhotoGallery({
{formatUtc(photo.createdAt)} UTC {formatUtc(photo.createdAt)} UTC
</Typography.Text> </Typography.Text>
</Space> </Space>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
keypoints: {photo.keypointsCount} · algo: {photo.algoId || '—'} · формат:{' '}
{photo.featureFormatVersion}
</Typography.Text>
<Space size={8} wrap> <Space size={8} wrap>
<InputNumber <InputNumber
size="small" size="small"
@@ -261,49 +281,6 @@ export function PhotoGallery({
> >
Позиция Позиция
</Button> </Button>
<Button
size="small"
icon={<ExperimentOutlined />}
loading={recalcMutation.isPending && recalcMutation.variables === photo.id}
onClick={() => recalcMutation.mutate(photo.id)}
>
Признаки
</Button>
<Upload
accept={ACCEPTED_TYPES}
multiple={false}
showUploadList={false}
beforeUpload={checkFileSize}
customRequest={({ file }) =>
verifyMutation.mutate({ photoId: photo.id, file: file as File })
}
>
<Button
size="small"
icon={<SafetyCertificateOutlined />}
loading={
verifyMutation.isPending && verifyMutation.variables?.photoId === photo.id
}
title="Загрузить пробное фото и проверить, распознает ли его этот эталон"
>
Проверить
</Button>
</Upload>
{isMobile && (
<CameraUpload
onFile={(file) => verifyMutation.mutate({ photoId: photo.id, file })}
>
<Button
size="small"
icon={<CameraOutlined />}
loading={
verifyMutation.isPending &&
verifyMutation.variables?.photoId === photo.id
}
title="Снять пробное фото камерой и проверить эталон"
/>
</CameraUpload>
)}
<Popconfirm <Popconfirm
title="Удалить это фото?" title="Удалить это фото?"
description="Единственное фото объекта в активном наборе удалить нельзя." description="Единственное фото объекта в активном наборе удалить нельзя."
+1 -12
View File
@@ -1,6 +1,6 @@
import dayjs from 'dayjs' import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc' import utc from 'dayjs/plugin/utc'
import type { CvProfile, SetStatus, Verdict } from '@/api/types' import type { SetStatus, Verdict } from '@/api/types'
dayjs.extend(utc) dayjs.extend(utc)
@@ -22,19 +22,8 @@ export const verdictMeta: Record<Verdict, { label: string; color: string }> = {
no_match: { label: 'Нет совпадения', color: 'red' }, no_match: { label: 'Нет совпадения', color: 'red' },
} }
export const cvProfileMeta: Record<CvProfile, { label: string; color: string }> = {
facade: { label: 'Фасад', color: 'blue' },
monument: { label: 'Памятник', color: 'purple' },
repetitive: { label: 'Повторяющийся объект', color: 'cyan' },
}
export const setStatusMeta: Record<SetStatus, { label: string; color: string }> = { export const setStatusMeta: Record<SetStatus, { label: string; color: string }> = {
DRAFT: { label: 'Черновик', color: 'default' }, DRAFT: { label: 'Черновик', color: 'default' },
ACTIVE: { label: 'Активен', color: 'green' }, ACTIVE: { label: 'Активен', color: 'green' },
ARCHIVED: { label: 'В архиве', color: 'default' }, ARCHIVED: { label: 'В архиве', color: 'default' },
} }
export const cvProfileOptions = (Object.keys(cvProfileMeta) as CvProfile[]).map((value) => ({
value,
label: cvProfileMeta[value].label,
}))