mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
fix(search): preview matched video chunks on hover (#540)
* fix(search): preview matched video chunks on hover * fix(search): show chunk covers before hover * fix(search): reuse sprites for whole-video matches
This commit is contained in:
@@ -2,6 +2,7 @@ import { prisma, Prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { imageSearchRequestSchema } from '@shumai/dtos'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { imageEmbeddingService } from './image-embedding'
|
||||
import { searchService } from './search'
|
||||
|
||||
@@ -14,12 +15,13 @@ async function insertEmbedding(
|
||||
embedding: number[],
|
||||
startTime: number | null = null,
|
||||
endTime: number | null = null,
|
||||
sprite?: PrismaJson.VideoChunkSprite,
|
||||
) {
|
||||
const column = embedding.length === 768 ? Prisma.sql`embedding_768` : Prisma.sql`embedding`
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, ${column}, start_time, end_time, created_at, updated_at)
|
||||
INSERT INTO asset_embeddings (id, asset_id, ${column}, start_time, end_time, sprite, created_at, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${assetId}, ${JSON.stringify(embedding)}::vector,
|
||||
${startTime}, ${endTime}, NOW(), NOW())
|
||||
${startTime}, ${endTime}, ${sprite ? JSON.stringify(sprite) : null}::jsonb, NOW(), NOW())
|
||||
`
|
||||
}
|
||||
|
||||
@@ -80,8 +82,10 @@ describe('image search', () => {
|
||||
await prisma.asset.update({ where: { id: deleted.id }, data: { isDeleted: true } })
|
||||
|
||||
await insertEmbedding(source.id, vector(1536, 1))
|
||||
await insertEmbedding(video.id, vector(1536, 1), 4, 12)
|
||||
await insertEmbedding(video.id, vector(1536, 0, 1), 12, 20)
|
||||
const firstSprite = { key: 'files/video/chunk-4-12.webp', columns: 5, rows: 2, frameCount: 8 }
|
||||
const secondSprite = { ...firstSprite, key: 'files/video/chunk-12-20.webp' }
|
||||
await insertEmbedding(video.id, vector(1536, 1), 4, 12, firstSprite)
|
||||
await insertEmbedding(video.id, vector(1536, 0, 1), 12, 20, secondSprite)
|
||||
await insertEmbedding(image.id, vector(1536, 1, 1))
|
||||
await insertEmbedding(deleted.id, vector(1536, 1))
|
||||
await insertEmbedding(audio.id, vector(1536, 1))
|
||||
@@ -93,13 +97,25 @@ describe('image search', () => {
|
||||
imageSearchRequestSchema.parse({ ...request, first: 2 }),
|
||||
)
|
||||
expect(first.data.map((item) => item.id)).toEqual([video.id, image.id])
|
||||
expect(first.data[0]).toMatchObject({ startTime: 4, endTime: 12 })
|
||||
expect(first.data[0]).toMatchObject({
|
||||
startTime: 4,
|
||||
endTime: 12,
|
||||
matchedSprite: { url: expect.stringContaining(firstSprite.key) },
|
||||
})
|
||||
expect(first.data[1].matchedSprite).toBeUndefined()
|
||||
expect(first.pageInfo).toMatchObject({ total: 3, cursor: expect.any(String) })
|
||||
const next = await searchService.searchByImage(
|
||||
root.id,
|
||||
imageSearchRequestSchema.parse({ ...request, first: 2, after: first.pageInfo.cursor }),
|
||||
)
|
||||
expect(next.data).toMatchObject([{ id: video.id, startTime: 12, endTime: 20 }])
|
||||
expect(next.data).toMatchObject([
|
||||
{
|
||||
id: video.id,
|
||||
startTime: 12,
|
||||
endTime: 20,
|
||||
matchedSprite: { url: expect.stringContaining(secondSprite.key) },
|
||||
},
|
||||
])
|
||||
expect(next.pageInfo.cursor).toBeUndefined()
|
||||
|
||||
const images = await searchService.searchByImage(
|
||||
@@ -129,6 +145,60 @@ describe('image search', () => {
|
||||
expect(result.data.map((item) => item.id)).toEqual([image.id])
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ startTime: 0, endTime: 10, stored: true, useFullSprite: true },
|
||||
{ startTime: 0, endTime: 10, stored: false, useFullSprite: false },
|
||||
{ startTime: 0, endTime: 5, stored: true, useFullSprite: false },
|
||||
{ startTime: 5, endTime: 10, stored: true, useFullSprite: false },
|
||||
])(
|
||||
'picks the preview for $startTime–$endTime when full sprite availability is $stored',
|
||||
async ({ startTime, endTime, stored, useFullSprite }) => {
|
||||
const { root, source, file } = await createProjectAssets()
|
||||
const video = await file('result.mp4', 'video/mp4')
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const fullKey = `files/${video.id}/sprite.webp`
|
||||
const chunkKey = `files/${video.id}/chunk.webp`
|
||||
await prisma.asset.update({
|
||||
where: { id: video.id },
|
||||
data: {
|
||||
media: {
|
||||
duration: 10,
|
||||
proxyType: 'video',
|
||||
sprite: { key: fullKey, frames: 100, tileX: 10, tileY: 10 },
|
||||
} as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
if (stored) await s3Service.putObject(bucket, fullKey, 'sprite', 6, 'image/webp')
|
||||
try {
|
||||
await insertEmbedding(source.id, vector(1536, 1))
|
||||
await insertEmbedding(video.id, vector(1536, 1), startTime, endTime, {
|
||||
key: chunkKey,
|
||||
columns: 5,
|
||||
rows: 2,
|
||||
frameCount: 10,
|
||||
})
|
||||
|
||||
const result = await searchService.searchByImage(
|
||||
root.id,
|
||||
imageSearchRequestSchema.parse({ sourceAssetId: source.id }),
|
||||
)
|
||||
expect(result.data).toHaveLength(1)
|
||||
expect(result.data[0]).toMatchObject({
|
||||
startTime,
|
||||
endTime,
|
||||
preview: { spriteUrl: expect.stringContaining(fullKey) },
|
||||
})
|
||||
if (useFullSprite) {
|
||||
expect(result.data[0].matchedSprite).toBeUndefined()
|
||||
} else {
|
||||
expect(result.data[0].matchedSprite?.url).toContain(chunkKey)
|
||||
}
|
||||
} finally {
|
||||
if (stored) await s3Service.deleteObject(bucket, fullKey)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it('limits an uploaded-image search to the folder and applies metadata filters', async () => {
|
||||
const { team, subfolder, source, file } = await createProjectAssets()
|
||||
const match = await file('approved.png', 'image/png', subfolder.id)
|
||||
|
||||
@@ -8,6 +8,7 @@ import { textEmbeddingService } from './text-embedding'
|
||||
|
||||
import { AssetType } from '@shumai/db'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
|
||||
describe('SearchService', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -805,6 +806,22 @@ describe('SearchService', () => {
|
||||
)
|
||||
`
|
||||
|
||||
const sprite = { key: 'files/video-a/chunk-0-10.webp', columns: 5, rows: 2, frameCount: 7 }
|
||||
await prisma.assetEmbedding.update({ where: { id: 'chunk-a1' }, data: { sprite } })
|
||||
const unsignedKey = 'files/video-b/chunk-5-15.webp'
|
||||
await prisma.assetEmbedding.update({
|
||||
where: { id: 'chunk-b1' },
|
||||
data: { sprite: { ...sprite, key: unsignedKey } },
|
||||
})
|
||||
const presign = s3Service.presign.bind(s3Service)
|
||||
const signSprite = vi
|
||||
.spyOn(s3Service, 'presign')
|
||||
.mockImplementation((bucket, key, method) =>
|
||||
key === unsignedKey
|
||||
? Promise.reject(new Error('Signing failed'))
|
||||
: presign(bucket, key, method),
|
||||
)
|
||||
|
||||
// Mock the embedding generation
|
||||
// Our query vector points along the first dimension [1, 0, 0...]
|
||||
const queryVector = Array(1536).fill(0)
|
||||
@@ -838,17 +855,26 @@ describe('SearchService', () => {
|
||||
expect(result.data[0].id).toBe(videoAssetA.id)
|
||||
expect(result.data[0].startTime).toBe(0)
|
||||
expect(result.data[0].endTime).toBe(10)
|
||||
expect(result.data[0].matchedSprite).toEqual({
|
||||
url: expect.stringContaining(sprite.key),
|
||||
columns: 5,
|
||||
rows: 2,
|
||||
frameCount: 7,
|
||||
})
|
||||
|
||||
// 2nd: Chunk B1
|
||||
expect(result.data[1].id).toBe(videoAssetB.id)
|
||||
expect(result.data[1].startTime).toBe(5)
|
||||
expect(result.data[1].endTime).toBe(15)
|
||||
expect(result.data[1].matchedSprite).toBeUndefined()
|
||||
|
||||
// 3rd: Chunk A2
|
||||
expect(result.data[2].id).toBe(videoAssetA.id)
|
||||
expect(result.data[2].startTime).toBe(10)
|
||||
expect(result.data[2].endTime).toBe(20)
|
||||
expect(result.data[2].matchedSprite).toBeUndefined()
|
||||
|
||||
signSprite.mockRestore()
|
||||
mockGenerateEmbedding.mockRestore()
|
||||
})
|
||||
|
||||
|
||||
@@ -2,6 +2,9 @@ import { prisma } from '@shumai/db'
|
||||
import { Prisma, AssetType } from '@shumai/db'
|
||||
import { AssetService, assetService } from '@shumai/core/src/asset/asset'
|
||||
import type { AssetInfo, ImageSearchRequest, SearchRequest } from '@shumai/dtos'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { hasStoredVideoSprite, isFullVideoRange } from '@shumai/core/src/transcode/video-sprite'
|
||||
import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@shumai/core/src/pagination'
|
||||
import { generateSearchNgrams } from '@shumai/core/src/utils/ngram'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
@@ -416,25 +419,68 @@ export class SearchService {
|
||||
const offset = req.after ? decodeCursor(req.after) : 0
|
||||
const resultQuery = builder
|
||||
.select(
|
||||
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", ${distance} as "distance"`,
|
||||
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", ae.sprite,
|
||||
a.media -> 'duration' as "videoDuration", a.media #>> '{sprite,key}' as "fullSpriteKey",
|
||||
${distance} as "distance"`,
|
||||
)
|
||||
.orderBy(visual ? Prisma.sql`distance ASC, ae.id ASC` : Prisma.sql`distance ASC`)
|
||||
.limit(limit + 1)
|
||||
.offset(offset)
|
||||
.build()
|
||||
|
||||
const matches =
|
||||
await this.prismaClient.$queryRaw<
|
||||
{ assetId: string; startTime: number | null; endTime: number | null }[]
|
||||
>(resultQuery)
|
||||
const matches = await this.prismaClient.$queryRaw<
|
||||
{
|
||||
assetId: string
|
||||
startTime: number | null
|
||||
endTime: number | null
|
||||
sprite: PrismaJson.VideoChunkSprite | null
|
||||
videoDuration: unknown
|
||||
fullSpriteKey: string | null
|
||||
}[]
|
||||
>(resultQuery)
|
||||
const page = matches.slice(0, limit)
|
||||
const assetIds = [...new Set(page.map((match) => match.assetId))]
|
||||
const infos = await this.assetSvc.listAssetsByIds(assetIds, req.previewFormat)
|
||||
const byId = new Map(infos.map((item) => [item.id, item]))
|
||||
const data = page.flatMap(({ assetId, startTime, endTime }) => {
|
||||
const item = byId.get(assetId)
|
||||
return item ? [{ ...item, startTime, endTime }] : []
|
||||
})
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const results = await Promise.all(
|
||||
page.map(
|
||||
async ({
|
||||
assetId,
|
||||
startTime,
|
||||
endTime,
|
||||
sprite,
|
||||
videoDuration,
|
||||
fullSpriteKey,
|
||||
}): Promise<AssetInfo | undefined> => {
|
||||
const item = byId.get(assetId)
|
||||
if (!item) return
|
||||
const match = { ...item, startTime, endTime }
|
||||
if (!sprite) return match
|
||||
|
||||
// A stack or symlink can get its preview from a different asset.
|
||||
if (
|
||||
item.type === AssetType.file &&
|
||||
item.preview?.spriteUrl &&
|
||||
fullSpriteKey &&
|
||||
isFullVideoRange(startTime, endTime, videoDuration) &&
|
||||
(await hasStoredVideoSprite(bucket, fullSpriteKey))
|
||||
) {
|
||||
return match
|
||||
}
|
||||
|
||||
const { key, ...layout } = sprite
|
||||
try {
|
||||
const url = await s3Service.presign(bucket, key, 'GET')
|
||||
return { ...match, matchedSprite: { ...layout, url } }
|
||||
} catch (err) {
|
||||
logger.warn({ err, assetId, key }, 'Failed to sign video chunk sprite')
|
||||
return match
|
||||
}
|
||||
},
|
||||
),
|
||||
)
|
||||
const data = results.filter((item) => item !== undefined)
|
||||
|
||||
const counts = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countQuery)
|
||||
const total = Number(counts[0]?.count ?? 0)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import sharp from 'sharp'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { composeVideoChunkSprite } from './video-chunk-sprite'
|
||||
|
||||
describe('composeVideoChunkSprite', () => {
|
||||
it('fills tiles in frame order and counts only the tiles with frames', async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'chunk-sprite-test-'))
|
||||
try {
|
||||
const colors = ['red', 'red', 'red', 'red', 'red', 'blue']
|
||||
const frames = await Promise.all(
|
||||
colors.map(async (background, index) => {
|
||||
const frame = join(directory, `frame-${index}.png`)
|
||||
await sharp({ create: { width: 48, height: 32, channels: 3, background } }).toFile(frame)
|
||||
return frame
|
||||
}),
|
||||
)
|
||||
|
||||
const sprite = await composeVideoChunkSprite(frames)
|
||||
expect(sprite).toMatchObject({ columns: 5, rows: 2, frameCount: 6 })
|
||||
const { data, info } = await sharp(sprite!.image).raw().toBuffer({ resolveWithObject: true })
|
||||
expect(info).toMatchObject({ width: 240, height: 64, channels: 3 })
|
||||
const pixel = (x: number, y: number) => (y * info.width + x) * info.channels
|
||||
expect(data[pixel(24, 16)]).toBeGreaterThan(200)
|
||||
expect(data[pixel(24, 48) + 2]).toBeGreaterThan(200)
|
||||
expect(data[pixel(72, 48) + 2]).toBeLessThan(10)
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('omits preview metadata when the chunk contains no frames', async () => {
|
||||
await expect(composeVideoChunkSprite([])).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import { mkdtemp, readdir, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
import type { SpriteLayout } from '@shumai/dtos'
|
||||
import sharp from 'sharp'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const MAX_TILE_SIDE = 240
|
||||
const MAX_COLUMNS = 5
|
||||
const MAX_SAMPLED_FRAMES = 15
|
||||
|
||||
export async function composeVideoChunkSprite(
|
||||
frames: string[],
|
||||
): Promise<(SpriteLayout & { image: Buffer }) | undefined> {
|
||||
if (!frames.length) return
|
||||
|
||||
const { width, height } = await sharp(frames[0]).metadata()
|
||||
const scale = Math.min(1, MAX_TILE_SIDE / Math.max(width, height))
|
||||
const tileWidth = Math.max(1, Math.round(width * scale))
|
||||
const tileHeight = Math.max(1, Math.round(height * scale))
|
||||
const frameCount = frames.length
|
||||
const columns = Math.min(MAX_COLUMNS, frameCount)
|
||||
const rows = Math.ceil(frameCount / columns)
|
||||
const tiles = await Promise.all(
|
||||
frames.map(async (frame, index) => ({
|
||||
input: await sharp(frame)
|
||||
.resize(tileWidth, tileHeight, { fit: 'contain', background: 'black' })
|
||||
.png()
|
||||
.toBuffer(),
|
||||
left: (index % columns) * tileWidth,
|
||||
top: Math.floor(index / columns) * tileHeight,
|
||||
})),
|
||||
)
|
||||
const image = await sharp({
|
||||
create: {
|
||||
width: columns * tileWidth,
|
||||
height: rows * tileHeight,
|
||||
channels: 3,
|
||||
background: 'black',
|
||||
},
|
||||
})
|
||||
.composite(tiles)
|
||||
.webp()
|
||||
.toBuffer()
|
||||
return { image, columns, rows, frameCount }
|
||||
}
|
||||
|
||||
export async function sampleVideoChunkSprite(
|
||||
clip: string,
|
||||
duration: number,
|
||||
signal?: AbortSignal,
|
||||
): ReturnType<typeof composeVideoChunkSprite> {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'video-chunk-sprite-'))
|
||||
try {
|
||||
const fps = Math.min(1, MAX_SAMPLED_FRAMES / duration)
|
||||
await execFileAsync(
|
||||
'ffmpeg',
|
||||
[
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-i',
|
||||
clip,
|
||||
'-vf',
|
||||
`fps=${fps}:round=up,scale=w='min(iw,240)':h='min(ih,240)':force_original_aspect_ratio=decrease`,
|
||||
'-frames:v',
|
||||
String(MAX_SAMPLED_FRAMES),
|
||||
join(dir, 'frame_%04d.jpg'),
|
||||
],
|
||||
{ signal },
|
||||
)
|
||||
const files = (await readdir(dir)).sort()
|
||||
return await composeVideoChunkSprite(files.map((file) => join(dir, file)))
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
|
||||
export function isFullVideoRange(
|
||||
startTime: number | null,
|
||||
endTime: number | null,
|
||||
duration: unknown,
|
||||
): boolean {
|
||||
return (
|
||||
startTime === 0 &&
|
||||
typeof duration === 'number' &&
|
||||
Number.isFinite(duration) &&
|
||||
duration > 0 &&
|
||||
endTime === duration
|
||||
)
|
||||
}
|
||||
|
||||
export async function hasStoredVideoSprite(bucket: string, key: string): Promise<boolean> {
|
||||
const size = await s3Service.getObjectSize(bucket, key).catch(() => 0)
|
||||
return size > 0
|
||||
}
|
||||
Reference in New Issue
Block a user