admin
This commit is contained in:
+11
-1
@@ -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<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> {
|
||||
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,
|
||||
|
||||
+27
-1
@@ -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[]
|
||||
}
|
||||
|
||||
// ---------- Наборы ----------
|
||||
|
||||
@@ -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() {
|
||||
<Descriptions.Item label="Фото" span={2}>
|
||||
{attraction.photoCount}
|
||||
</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}>
|
||||
{attraction.about ?? '—'}
|
||||
</Descriptions.Item>
|
||||
|
||||
@@ -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({
|
||||
<InputNumber style={{ width: '100%' }} min={-180} max={180} step={0.000001} placeholder="37.618423" />
|
||||
</Form.Item>
|
||||
</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.List name="facts">
|
||||
{(fields, { add, remove }) => (
|
||||
|
||||
@@ -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<number | null>(null)
|
||||
/** Черновики позиций: photoId → введённое, но не сохранённое значение. */
|
||||
const [pendingOrders, setPendingOrders] = useState<Record<string, number>>({})
|
||||
/** Последняя проверка распознавания: проценты по эталонам показываем на карточках. */
|
||||
const [verifyResult, setVerifyResult] = useState<PhotoVerifyResponse | null>(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<Photo[]>(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 (
|
||||
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||
<Space wrap>
|
||||
<Upload {...uploadProps}>
|
||||
<Button type="primary" icon={<UploadOutlined />} loading={uploadMutation.isPending}>
|
||||
<Upload {...uploadProps} disabled={limitReached}>
|
||||
<Button type="primary" icon={<UploadOutlined />} loading={uploadMutation.isPending} disabled={limitReached}>
|
||||
Загрузить фото
|
||||
</Button>
|
||||
</Upload>
|
||||
@@ -168,7 +181,7 @@ export function PhotoGallery({
|
||||
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>
|
||||
</CameraUpload>
|
||||
@@ -187,6 +200,9 @@ export function PhotoGallery({
|
||||
без позиции — следующая свободная
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
<Typography.Text type={limitReached ? 'danger' : 'secondary'}>
|
||||
Эталонных фото: {photos.length} из {MAX_REFERENCE_PHOTOS}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
|
||||
<Space wrap>
|
||||
@@ -220,15 +236,31 @@ export function PhotoGallery({
|
||||
</CameraUpload>
|
||||
)}
|
||||
<Typography.Text type="secondary">
|
||||
пробное фото сверяется со всеми эталонными фото достопримечательности
|
||||
пробное фото сверяется с каждым эталонным фото по отдельности — проценты
|
||||
проверки появятся на фото
|
||||
</Typography.Text>
|
||||
{verifyResult && (
|
||||
<Typography.Text type="secondary">
|
||||
пороги: match {(verifyResult.matchThreshold * 100).toFixed(0)} % / no_match{' '}
|
||||
{(verifyResult.noMatchThreshold * 100).toFixed(0)} %
|
||||
</Typography.Text>
|
||||
)}
|
||||
</Space>
|
||||
|
||||
{noPhotosYet ? (
|
||||
<Empty description="Эталонных фото пока нет" style={{ padding: 24 }} />
|
||||
) : (
|
||||
<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}>
|
||||
<Card
|
||||
size="small"
|
||||
@@ -244,6 +276,11 @@ export function PhotoGallery({
|
||||
<Space direction="vertical" size={4} style={{ width: '100%' }}>
|
||||
<Space size={8} wrap>
|
||||
<Tag color="blue">позиция {photo.sortOrder}</Tag>
|
||||
{refResult != null && (
|
||||
<Tag color={refColor} title="Процент прохождения проверки этим эталоном">
|
||||
проверка {(refResult.confidence * 100).toFixed(0)} %
|
||||
</Tag>
|
||||
)}
|
||||
<Typography.Text type="secondary">
|
||||
{formatUtc(photo.createdAt)} UTC
|
||||
</Typography.Text>
|
||||
@@ -299,7 +336,8 @@ export function PhotoGallery({
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</Row>
|
||||
)}
|
||||
</Space>
|
||||
|
||||
Reference in New Issue
Block a user